JavascriptFunction.cpp 132 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLibraryPch.h"
  6. #include "Library/StackScriptFunction.h"
  7. #include "Types/SpreadArgument.h"
  8. #include "Language/AsmJsTypes.h"
  9. #ifdef _M_X64
  10. #include "ByteCode/PropertyIdArray.h"
  11. #include "Language/AsmJsModule.h"
  12. #endif
  13. #ifdef _M_IX86
  14. #ifdef _CONTROL_FLOW_GUARD
  15. extern "C" PVOID __guard_check_icall_fptr;
  16. #endif
  17. extern "C" void __cdecl _alloca_probe_16();
  18. #endif
  19. namespace Js
  20. {
  21. // The VS2013 linker treats this as a redefinition of an already
  22. // defined constant and complains. So skip the declaration if we're compiling
  23. // with VS2013 or below.
  24. #if !defined(_MSC_VER) || _MSC_VER >= 1900
  25. const charcount_t JavascriptFunction::DIAG_MAX_FUNCTION_STRING;
  26. #endif
  27. DEFINE_RECYCLER_TRACKER_PERF_COUNTER(JavascriptFunction);
  28. JavascriptFunction::JavascriptFunction(DynamicType * type)
  29. : DynamicObject(type), functionInfo(nullptr), constructorCache(&ConstructorCache::DefaultInstance)
  30. {
  31. Assert(this->constructorCache != nullptr);
  32. }
  33. JavascriptFunction::JavascriptFunction(DynamicType * type, FunctionInfo * functionInfo)
  34. : DynamicObject(type), functionInfo(functionInfo), constructorCache(&ConstructorCache::DefaultInstance)
  35. {
  36. Assert(this->constructorCache != nullptr);
  37. this->GetTypeHandler()->ClearHasOnlyWritableDataProperties(); // length is non-writable
  38. if (GetTypeHandler()->GetFlags() & DynamicTypeHandler::IsPrototypeFlag)
  39. {
  40. // No need to invalidate store field caches for non-writable properties here. Since this type is just being created, it cannot represent
  41. // an object that is already a prototype. If it becomes a prototype and then we attempt to add a property to an object derived from this
  42. // object, then we will check if this property is writable, and only if it is will we do the fast path for add property.
  43. // GetScriptContext()->InvalidateStoreFieldCaches(PropertyIds::length);
  44. GetLibrary()->NoPrototypeChainsAreEnsuredToHaveOnlyWritableDataProperties();
  45. }
  46. }
  47. JavascriptFunction::JavascriptFunction(DynamicType * type, FunctionInfo * functionInfo, ConstructorCache* cache)
  48. : DynamicObject(type), functionInfo(functionInfo), constructorCache(cache)
  49. {
  50. Assert(this->constructorCache != nullptr);
  51. this->GetTypeHandler()->ClearHasOnlyWritableDataProperties(); // length is non-writable
  52. if (GetTypeHandler()->GetFlags() & DynamicTypeHandler::IsPrototypeFlag)
  53. {
  54. // No need to invalidate store field caches for non-writable properties here. Since this type is just being created, it cannot represent
  55. // an object that is already a prototype. If it becomes a prototype and then we attempt to add a property to an object derived from this
  56. // object, then we will check if this property is writable, and only if it is will we do the fast path for add property.
  57. // GetScriptContext()->InvalidateStoreFieldCaches(PropertyIds::length);
  58. GetLibrary()->NoPrototypeChainsAreEnsuredToHaveOnlyWritableDataProperties();
  59. }
  60. }
  61. FunctionProxy *JavascriptFunction::GetFunctionProxy() const
  62. {
  63. Assert(functionInfo != nullptr);
  64. return functionInfo->GetFunctionProxy();
  65. }
  66. ParseableFunctionInfo *JavascriptFunction::GetParseableFunctionInfo() const
  67. {
  68. Assert(functionInfo != nullptr);
  69. return functionInfo->GetParseableFunctionInfo();
  70. }
  71. DeferDeserializeFunctionInfo *JavascriptFunction::GetDeferDeserializeFunctionInfo() const
  72. {
  73. Assert(functionInfo != nullptr);
  74. return functionInfo->GetDeferDeserializeFunctionInfo();
  75. }
  76. FunctionBody *JavascriptFunction::GetFunctionBody() const
  77. {
  78. Assert(functionInfo != nullptr);
  79. return functionInfo->GetFunctionBody();
  80. }
  81. BOOL JavascriptFunction::IsScriptFunction() const
  82. {
  83. Assert(functionInfo != nullptr);
  84. return functionInfo->HasBody();
  85. }
  86. bool JavascriptFunction::Is(Var aValue)
  87. {
  88. if (JavascriptOperators::GetTypeId(aValue) == TypeIds_Function)
  89. {
  90. return true;
  91. }
  92. return false;
  93. }
  94. JavascriptFunction* JavascriptFunction::FromVar(Var aValue)
  95. {
  96. AssertMsg(Is(aValue), "Ensure var is actually a 'JavascriptFunction'");
  97. return static_cast<JavascriptFunction *>(RecyclableObject::FromVar(aValue));
  98. }
  99. BOOL JavascriptFunction::IsStrictMode() const
  100. {
  101. FunctionProxy * proxy = this->GetFunctionProxy();
  102. return proxy && proxy->EnsureDeserialized()->GetIsStrictMode();
  103. }
  104. BOOL JavascriptFunction::IsLambda() const
  105. {
  106. return this->GetFunctionInfo()->IsLambda();
  107. }
  108. BOOL JavascriptFunction::IsConstructor() const
  109. {
  110. return this->GetFunctionInfo()->IsConstructor();
  111. }
  112. #if DBG
  113. /* static */
  114. bool JavascriptFunction::IsBuiltinProperty(Var objectWithProperty, PropertyIds propertyId)
  115. {
  116. return ScriptFunctionBase::Is(objectWithProperty)
  117. && (propertyId == PropertyIds::length || (JavascriptFunction::FromVar(objectWithProperty)->HasRestrictedProperties() && (propertyId == PropertyIds::arguments || propertyId == PropertyIds::caller)));
  118. }
  119. #endif
  120. Var JavascriptFunction::NewInstanceHelper(ScriptContext *scriptContext, RecyclableObject* function, CallInfo callInfo, Js::ArgumentReader& args, FunctionKind functionKind /* = FunctionKind::Normal */)
  121. {
  122. JavascriptLibrary* library = function->GetLibrary();
  123. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  124. // SkipDefaultNewObject function flag should have prevented the default object from
  125. // being created, except when call true a host dispatch.
  126. Var newTarget = callInfo.Flags & CallFlags_NewTarget ? args.Values[args.Info.Count] : args[0];
  127. bool isCtorSuperCall = (callInfo.Flags & CallFlags_New) && newTarget != nullptr && !JavascriptOperators::IsUndefined(newTarget);
  128. Assert(isCtorSuperCall || !(callInfo.Flags & CallFlags_New) || args[0] == nullptr
  129. || JavascriptOperators::GetTypeId(args[0]) == TypeIds_HostDispatch);
  130. JavascriptString* separator = library->GetCommaDisplayString();
  131. // Gather all the formals into a string like (fml1, fml2, fml3)
  132. JavascriptString *formals = library->GetOpenRBracketString();
  133. for (uint i = 1; i < args.Info.Count - 1; ++i)
  134. {
  135. if (i != 1)
  136. {
  137. formals = JavascriptString::Concat(formals, separator);
  138. }
  139. formals = JavascriptString::Concat(formals, JavascriptConversion::ToString(args.Values[i], scriptContext));
  140. }
  141. formals = JavascriptString::Concat(formals, library->GetNewLineCloseRBracketString());
  142. // Function body, last argument to Function(...)
  143. JavascriptString *fnBody = NULL;
  144. if (args.Info.Count > 1)
  145. {
  146. fnBody = JavascriptConversion::ToString(args.Values[args.Info.Count - 1], scriptContext);
  147. }
  148. // Create a string representing the anonymous function
  149. Assert(
  150. 0 + // "function anonymous" GetFunctionAnonymousString
  151. 0 + // "(" GetOpenRBracketString
  152. 1 + // "\n)" GetNewLineCloseRBracketString
  153. 0 // " {" GetSpaceOpenBracketString
  154. == numberLinesPrependedToAnonymousFunction); // Be sure to add exactly one line to anonymous function
  155. JavascriptString *bs = functionKind == FunctionKind::Async ?
  156. library->GetAsyncFunctionAnonymouseString() :
  157. functionKind == FunctionKind::Generator ?
  158. library->GetFunctionPTRAnonymousString() :
  159. library->GetFunctionAnonymousString();
  160. bs = JavascriptString::Concat(bs, formals);
  161. bs = JavascriptString::Concat(bs, library->GetSpaceOpenBracketString());
  162. if (fnBody != NULL)
  163. {
  164. bs = JavascriptString::Concat(bs, fnBody);
  165. }
  166. bs = JavascriptString::Concat(bs, library->GetNewLineCloseBracketString());
  167. // Bug 1105479. Get the module id from the caller
  168. ModuleID moduleID = kmodGlobal;
  169. BOOL strictMode = FALSE;
  170. JavascriptFunction *pfuncScript;
  171. FunctionInfo *pfuncInfoCache = NULL;
  172. char16 const * sourceString = bs->GetSz();
  173. charcount_t sourceLen = bs->GetLength();
  174. EvalMapString key(sourceString, sourceLen, moduleID, strictMode, /* isLibraryCode = */ false);
  175. if (!scriptContext->IsInNewFunctionMap(key, &pfuncInfoCache))
  176. {
  177. // Validate formals here
  178. scriptContext->GetGlobalObject()->ValidateSyntax(
  179. scriptContext, formals->GetSz(), formals->GetLength(),
  180. functionKind == FunctionKind::Generator, functionKind == FunctionKind::Async,
  181. &Parser::ValidateFormals);
  182. if (fnBody != NULL)
  183. {
  184. // Validate function body
  185. scriptContext->GetGlobalObject()->ValidateSyntax(
  186. scriptContext, fnBody->GetSz(), fnBody->GetLength(),
  187. functionKind == FunctionKind::Generator, functionKind == FunctionKind::Async,
  188. &Parser::ValidateSourceElementList);
  189. }
  190. pfuncScript = scriptContext->GetGlobalObject()->EvalHelper(scriptContext, sourceString, sourceLen, moduleID, fscrNil, Constants::FunctionCode, TRUE, TRUE, strictMode);
  191. // Indicate that this is a top-level function. We don't pass the fscrGlobalCode flag to the eval helper,
  192. // or it will return the global function that wraps the declared function body, as though it were an eval.
  193. // But we want, for instance, to be able to verify that we did the right amount of deferred parsing.
  194. ParseableFunctionInfo *functionInfo = pfuncScript->GetParseableFunctionInfo();
  195. Assert(functionInfo);
  196. functionInfo->SetGrfscr(functionInfo->GetGrfscr() | fscrGlobalCode);
  197. #if ENABLE_TTD
  198. if(!scriptContext->IsTTDRecordOrReplayModeEnabled())
  199. {
  200. scriptContext->AddToNewFunctionMap(key, functionInfo->GetFunctionInfo());
  201. }
  202. #else
  203. scriptContext->AddToNewFunctionMap(key, functionInfo->GetFunctionInfo());
  204. #endif
  205. }
  206. else if (pfuncInfoCache->IsCoroutine())
  207. {
  208. pfuncScript = scriptContext->GetLibrary()->CreateGeneratorVirtualScriptFunction(pfuncInfoCache->GetFunctionProxy());
  209. }
  210. else
  211. {
  212. pfuncScript = scriptContext->GetLibrary()->CreateScriptFunction(pfuncInfoCache->GetFunctionProxy());
  213. }
  214. #if ENABLE_TTD
  215. //
  216. //TODO: We may (probably?) want to use the debugger source rundown functionality here instead
  217. //
  218. if(pfuncScript != nullptr && (scriptContext->IsTTDRecordModeEnabled() || scriptContext->ShouldPerformReplayAction()))
  219. {
  220. //Make sure we have the body and text information available
  221. FunctionBody* globalBody = TTD::JsSupport::ForceAndGetFunctionBody(pfuncScript->GetParseableFunctionInfo());
  222. if(!scriptContext->TTDContextInfo->IsBodyAlreadyLoadedAtTopLevel(globalBody))
  223. {
  224. uint32 bodyIdCtr = 0;
  225. if(scriptContext->IsTTDRecordModeEnabled())
  226. {
  227. const TTD::NSSnapValues::TopLevelNewFunctionBodyResolveInfo* tbfi = scriptContext->GetThreadContext()->TTDLog->AddNewFunction(globalBody, moduleID, sourceString, sourceLen);
  228. //We always want to register the top-level load but we don't always need to log the event
  229. if(scriptContext->ShouldPerformRecordAction())
  230. {
  231. scriptContext->GetThreadContext()->TTDLog->RecordTopLevelCodeAction(tbfi->TopLevelBase.TopLevelBodyCtr);
  232. }
  233. bodyIdCtr = tbfi->TopLevelBase.TopLevelBodyCtr;
  234. }
  235. if(scriptContext->ShouldPerformReplayAction())
  236. {
  237. bodyIdCtr = scriptContext->GetThreadContext()->TTDLog->ReplayTopLevelCodeAction();
  238. }
  239. //walk global body to (1) add functions to pin set (2) build parent map
  240. scriptContext->TTDContextInfo->ProcessFunctionBodyOnLoad(globalBody, nullptr);
  241. scriptContext->TTDContextInfo->RegisterNewScript(globalBody, bodyIdCtr);
  242. if(scriptContext->ShouldPerformRecordOrReplayAction())
  243. {
  244. globalBody->GetUtf8SourceInfo()->SetSourceInfoForDebugReplay_TTD(bodyIdCtr);
  245. }
  246. if(scriptContext->ShouldPerformDebuggerAction())
  247. {
  248. scriptContext->GetThreadContext()->TTDExecutionInfo->ProcessScriptLoad(scriptContext, bodyIdCtr, globalBody, globalBody->GetUtf8SourceInfo(), nullptr);
  249. }
  250. }
  251. }
  252. #endif
  253. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_FUNCTION(pfuncScript, EtwTrace::GetFunctionId(pfuncScript->GetFunctionProxy())));
  254. if (functionKind == FunctionKind::Generator || functionKind == FunctionKind::Async)
  255. {
  256. Assert(pfuncScript->GetFunctionInfo()->IsCoroutine());
  257. auto pfuncVirt = static_cast<GeneratorVirtualScriptFunction*>(pfuncScript);
  258. auto pfuncGen = functionKind == FunctionKind::Async ?
  259. scriptContext->GetLibrary()->CreateAsyncFunction(JavascriptAsyncFunction::EntryAsyncFunctionImplementation, pfuncVirt) :
  260. scriptContext->GetLibrary()->CreateGeneratorFunction(JavascriptGeneratorFunction::EntryGeneratorFunctionImplementation, pfuncVirt);
  261. pfuncVirt->SetRealGeneratorFunction(pfuncGen);
  262. pfuncScript = pfuncGen;
  263. }
  264. return isCtorSuperCall ?
  265. JavascriptOperators::OrdinaryCreateFromConstructor(RecyclableObject::FromVar(newTarget), pfuncScript, nullptr, scriptContext) :
  266. pfuncScript;
  267. }
  268. Var JavascriptFunction::NewInstanceRestrictedMode(RecyclableObject* function, CallInfo callInfo, ...)
  269. {
  270. ScriptContext* scriptContext = function->GetScriptContext();
  271. scriptContext->CheckEvalRestriction();
  272. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  273. ARGUMENTS(args, callInfo);
  274. return NewInstanceHelper(scriptContext, function, callInfo, args);
  275. }
  276. Var JavascriptFunction::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  277. {
  278. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  279. ARGUMENTS(args, callInfo);
  280. ScriptContext* scriptContext = function->GetScriptContext();
  281. return NewInstanceHelper(scriptContext, function, callInfo, args);
  282. }
  283. Var JavascriptFunction::NewAsyncFunctionInstance(RecyclableObject* function, CallInfo callInfo, ...)
  284. {
  285. // Get called when creating a new async function through the constructor (e.g. af.__proto__.constructor)
  286. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  287. ARGUMENTS(args, callInfo);
  288. return JavascriptFunction::NewInstanceHelper(function->GetScriptContext(), function, callInfo, args, JavascriptFunction::FunctionKind::Async);
  289. }
  290. Var JavascriptFunction::NewAsyncFunctionInstanceRestrictedMode(RecyclableObject* function, CallInfo callInfo, ...)
  291. {
  292. ScriptContext* scriptContext = function->GetScriptContext();
  293. scriptContext->CheckEvalRestriction();
  294. PROBE_STACK(scriptContext, Js::Constants::MinStackDefault);
  295. ARGUMENTS(args, callInfo);
  296. return JavascriptFunction::NewInstanceHelper(scriptContext, function, callInfo, args, JavascriptFunction::FunctionKind::Async);
  297. }
  298. //
  299. // Dummy EntryPoint for Function.prototype
  300. //
  301. Var JavascriptFunction::PrototypeEntryPoint(RecyclableObject* function, CallInfo callInfo, ...)
  302. {
  303. ARGUMENTS(args, callInfo);
  304. ScriptContext* scriptContext = function->GetScriptContext();
  305. JavascriptLibrary* library = function->GetLibrary();
  306. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  307. if (callInfo.Flags & CallFlags_New)
  308. {
  309. JavascriptError::ThrowTypeError(scriptContext, VBSERR_ActionNotSupported);
  310. }
  311. return library->GetUndefined();
  312. }
  313. enum : unsigned { STACK_ARGS_ALLOCA_THRESHOLD = 8 }; // Number of stack args we allow before using _alloca
  314. // ES5 15.3.4.3
  315. //When the apply method is called on an object func with arguments thisArg and argArray the following steps are taken:
  316. // 1. If IsCallable(func) is false, then throw a TypeError exception.
  317. // 2. If argArray is null or undefined, then
  318. // a. Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and an empty list of arguments.
  319. // 3. If Type(argArray) is not Object, then throw a TypeError exception.
  320. // 4. Let len be the result of calling the [[Get]] internal method of argArray with argument "length".
  321. //
  322. // Steps 5 and 7 deleted from July 19 Errata of ES5 spec
  323. //
  324. // 5. If len is null or undefined, then throw a TypeError exception.
  325. // 6. Len n be ToUint32(len).
  326. // 7. If n is not equal to ToNumber(len), then throw a TypeError exception.
  327. // 8. Let argList be an empty List.
  328. // 9. Let index be 0.
  329. // 10. Repeat while index < n
  330. // a. Let indexName be ToString(index).
  331. // b. Let nextArg be the result of calling the [[Get]] internal method of argArray with indexName as the argument.
  332. // c. Append nextArg as the last element of argList.
  333. // d. Set index to index + 1.
  334. // 11. Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and argList as the list of arguments.
  335. // The length property of the apply method is 2.
  336. Var JavascriptFunction::EntryApply(RecyclableObject* function, CallInfo callInfo, ...)
  337. {
  338. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  339. // Ideally, we want to maintain CallFlags_Eval behavior and pass along the extra FrameDisplay parameter
  340. // but that we would be a bigger change than what we want to do in this ship cycle. See WIN8: 915315.
  341. // If eval is executed using apply it will not get the frame display and always execute in global scope.
  342. ARGUMENTS(args, callInfo);
  343. ScriptContext* scriptContext = function->GetScriptContext();
  344. Assert(!(callInfo.Flags & CallFlags_New));
  345. ///
  346. /// Check Argument[0] has internal [[Call]] property
  347. /// If not, throw TypeError
  348. ///
  349. if (args.Info.Count == 0 || !JavascriptConversion::IsCallable(args[0]))
  350. {
  351. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("Function.prototype.apply"));
  352. }
  353. Var thisVar = NULL;
  354. Var argArray = NULL;
  355. RecyclableObject* pFunc = RecyclableObject::FromVar(args[0]);
  356. if (args.Info.Count == 1)
  357. {
  358. thisVar = scriptContext->GetLibrary()->GetUndefined();
  359. }
  360. else if (args.Info.Count == 2)
  361. {
  362. thisVar = args.Values[1];
  363. }
  364. else if (args.Info.Count > 2)
  365. {
  366. thisVar = args.Values[1];
  367. argArray = args.Values[2];
  368. }
  369. return CalloutHelper<false>(pFunc, thisVar, /* overridingNewTarget = */nullptr, argArray, scriptContext);
  370. }
  371. template <bool isConstruct>
  372. Var JavascriptFunction::CalloutHelper(RecyclableObject* pFunc, Var thisVar, Var overridingNewTarget, Var argArray, ScriptContext* scriptContext)
  373. {
  374. CallFlags callFlag;
  375. if (isConstruct)
  376. {
  377. callFlag = CallFlags_New;
  378. }
  379. else
  380. {
  381. callFlag = CallFlags_Value;
  382. }
  383. Arguments outArgs(CallInfo(callFlag, 0), nullptr);
  384. Var stackArgs[STACK_ARGS_ALLOCA_THRESHOLD];
  385. if (nullptr == argArray)
  386. {
  387. outArgs.Info.Count = 1;
  388. outArgs.Values = &thisVar;
  389. }
  390. else
  391. {
  392. bool isArray = JavascriptArray::Is(argArray);
  393. TypeId typeId = JavascriptOperators::GetTypeId(argArray);
  394. bool isNullOrUndefined = (typeId == TypeIds_Null || typeId == TypeIds_Undefined);
  395. if (!isNullOrUndefined && !JavascriptOperators::IsObject(argArray)) // ES5: throw if Type(argArray) is not Object
  396. {
  397. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Function.prototype.apply"));
  398. }
  399. int64 len;
  400. JavascriptArray* arr = NULL;
  401. RecyclableObject* dynamicObject = RecyclableObject::FromVar(argArray);
  402. if (isNullOrUndefined)
  403. {
  404. len = 0;
  405. }
  406. else if (isArray)
  407. {
  408. #if ENABLE_COPYONACCESS_ARRAY
  409. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(argArray);
  410. #endif
  411. arr = JavascriptArray::FromVar(argArray);
  412. len = arr->GetLength();
  413. }
  414. else
  415. {
  416. Var lenProp = JavascriptOperators::OP_GetLength(dynamicObject, scriptContext);
  417. len = JavascriptConversion::ToLength(lenProp, scriptContext);
  418. }
  419. if (len >= CallInfo::kMaxCountArgs)
  420. {
  421. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgListTooLarge);
  422. }
  423. outArgs.Info.Count = (uint)len + 1;
  424. if (len == 0)
  425. {
  426. outArgs.Values = &thisVar;
  427. }
  428. else
  429. {
  430. if (outArgs.Info.Count > STACK_ARGS_ALLOCA_THRESHOLD)
  431. {
  432. PROBE_STACK(scriptContext, outArgs.Info.Count * sizeof(Var)+Js::Constants::MinStackDefault); // args + function call
  433. outArgs.Values = (Var*)_alloca(outArgs.Info.Count * sizeof(Var));
  434. }
  435. else
  436. {
  437. outArgs.Values = stackArgs;
  438. }
  439. outArgs.Values[0] = thisVar;
  440. Var undefined = pFunc->GetLibrary()->GetUndefined();
  441. if (isArray && arr->GetScriptContext() == scriptContext)
  442. {
  443. arr->ForEachItemInRange<false>(0, (uint)len, undefined, scriptContext,
  444. [&outArgs](uint index, Var element)
  445. {
  446. outArgs.Values[index + 1] = element;
  447. });
  448. }
  449. else
  450. {
  451. for (uint i = 0; i < len; i++)
  452. {
  453. Var element = nullptr;
  454. if (!JavascriptOperators::GetItem(dynamicObject, i, &element, scriptContext))
  455. {
  456. element = undefined;
  457. }
  458. outArgs.Values[i + 1] = element;
  459. }
  460. }
  461. }
  462. }
  463. if (isConstruct)
  464. {
  465. return JavascriptFunction::CallAsConstructor(pFunc, overridingNewTarget, outArgs, scriptContext);
  466. }
  467. else
  468. {
  469. return JavascriptFunction::CallFunction<true>(pFunc, pFunc->GetEntryPoint(), outArgs);
  470. }
  471. }
  472. Var JavascriptFunction::ApplyHelper(RecyclableObject* function, Var thisArg, Var argArray, ScriptContext* scriptContext)
  473. {
  474. return CalloutHelper<false>(function, thisArg, /* overridingNewTarget = */nullptr, argArray, scriptContext);
  475. }
  476. Var JavascriptFunction::ConstructHelper(RecyclableObject* function, Var thisArg, Var overridingNewTarget, Var argArray, ScriptContext* scriptContext)
  477. {
  478. return CalloutHelper<true>(function, thisArg, overridingNewTarget, argArray, scriptContext);
  479. }
  480. Var JavascriptFunction::EntryBind(RecyclableObject* function, CallInfo callInfo, ...)
  481. {
  482. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  483. ARGUMENTS(args, callInfo);
  484. ScriptContext* scriptContext = function->GetScriptContext();
  485. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Function_Prototype_bind);
  486. Assert(!(callInfo.Flags & CallFlags_New));
  487. ///
  488. /// Check Argument[0] has internal [[Call]] property
  489. /// If not, throw TypeError
  490. ///
  491. if (args.Info.Count == 0 || !JavascriptConversion::IsCallable(args[0]))
  492. {
  493. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("Function.prototype.bind"));
  494. }
  495. BoundFunction* boundFunc = BoundFunction::New(scriptContext, args);
  496. return boundFunc;
  497. }
  498. // ES5 15.3.4.4
  499. // Function.prototype.call (thisArg [ , arg1 [ , arg2, ... ] ] )
  500. // When the call method is called on an object func with argument thisArg and optional arguments arg1, arg2 etc, the following steps are taken:
  501. // 1. If IsCallable(func) is false, then throw a TypeError exception.
  502. // 2. Let argList be an empty List.
  503. // 3. If this method was called with more than one argument then in left to right order starting with arg1 append each argument as the last element of argList
  504. // 4. Return the result of calling the [[Call]] internal method of func, providing thisArg as the this value and argList as the list of arguments.
  505. // The length property of the call method is 1.
  506. Var JavascriptFunction::EntryCall(RecyclableObject* function, CallInfo callInfo, ...)
  507. {
  508. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  509. RUNTIME_ARGUMENTS(args, callInfo);
  510. ScriptContext* scriptContext = function->GetScriptContext();
  511. Assert(!(callInfo.Flags & CallFlags_New));
  512. ///
  513. /// Check Argument[0] has internal [[Call]] property
  514. /// If not, throw TypeError
  515. ///
  516. uint argCount = args.Info.Count;
  517. if (callInfo.Flags & CallFlags_ExtraArg)
  518. {
  519. // The last argument is the "extra". Don't consider it in the logic below.
  520. // It will either remain in place (argCount == 1) or be copied.
  521. argCount--;
  522. }
  523. if (argCount == 0 || !JavascriptConversion::IsCallable(args[0]))
  524. {
  525. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("Function.prototype.call"));
  526. }
  527. RecyclableObject *pFunc = RecyclableObject::FromVar(args[0]);
  528. if (argCount == 1)
  529. {
  530. args.Values[0] = scriptContext->GetLibrary()->GetUndefined();
  531. }
  532. else
  533. {
  534. ///
  535. /// Remove function object from the arguments and pass the rest
  536. ///
  537. for (uint i = 0; i < args.Info.Count - 1; ++i)
  538. {
  539. args.Values[i] = args.Values[i + 1];
  540. }
  541. args.Info.Count = args.Info.Count - 1;
  542. }
  543. ///
  544. /// Call the [[Call]] method on the function object
  545. ///
  546. return JavascriptFunction::CallFunction<true>(pFunc, pFunc->GetEntryPoint(), args);
  547. }
  548. Var JavascriptFunction::CallRootFunctionInScript(JavascriptFunction* func, Arguments args)
  549. {
  550. ScriptContext* scriptContext = func->GetScriptContext();
  551. if (scriptContext->GetThreadContext()->HasPreviousHostScriptContext())
  552. {
  553. ScriptContext* requestContext = scriptContext->GetThreadContext()->GetPreviousHostScriptContext()->GetScriptContext();
  554. func = JavascriptFunction::FromVar(CrossSite::MarshalVar(requestContext, func));
  555. }
  556. return func->CallRootFunction(args, scriptContext, true);
  557. }
  558. Var JavascriptFunction::CallRootFunction(RecyclableObject* obj, Arguments args, ScriptContext * scriptContext, bool inScript)
  559. {
  560. Var ret = nullptr;
  561. #ifdef FAULT_INJECTION
  562. if (Js::Configuration::Global.flags.FaultInjection >= 0)
  563. {
  564. Js::FaultInjection::pfnHandleAV = JavascriptFunction::CallRootEventFilter;
  565. __try
  566. {
  567. ret = JavascriptFunction::CallRootFunctionInternal(obj, args, scriptContext, inScript);
  568. }
  569. __finally
  570. {
  571. Js::FaultInjection::pfnHandleAV = nullptr;
  572. }
  573. //ret should never be null here
  574. Assert(ret);
  575. return ret;
  576. }
  577. #endif
  578. #ifdef DISABLE_SEH
  579. // xplat: JavascriptArrayBuffer::AllocWrapper is disabled on cross-platform
  580. // (IsValidVirtualBufferLength always returns false).
  581. // SEH and ResumeForOutOfBoundsArrayRefs are not needed.
  582. ret = JavascriptFunction::CallRootFunctionInternal(obj, args, scriptContext, inScript);
  583. #else
  584. if (scriptContext->GetThreadContext()->GetAbnormalExceptionCode() != 0)
  585. {
  586. // ensure that hosts are not doing SEH across Chakra frames, as that can lead to bad state (e.g. destructors not being called)
  587. UnexpectedExceptionHandling_fatal_error();
  588. }
  589. // mark volatile, because otherwise VC will incorrectly optimize away load in the finally block
  590. volatile uint32 exceptionCode = 0;
  591. EXCEPTION_POINTERS exceptionInfo = { 0 };
  592. __try
  593. {
  594. __try
  595. {
  596. ret = JavascriptFunction::CallRootFunctionInternal(obj, args, scriptContext, inScript);
  597. }
  598. __except (
  599. exceptionInfo = *GetExceptionInformation(),
  600. exceptionCode = GetExceptionCode(),
  601. CallRootEventFilter(exceptionCode, GetExceptionInformation()))
  602. {
  603. Assert(UNREACHED);
  604. }
  605. }
  606. __finally
  607. {
  608. // 0xE06D7363 is C++ exception code
  609. if (exceptionCode != 0 && exceptionCode != 0xE06D7363 && AbnormalTermination() && !IsDebuggerPresent())
  610. {
  611. scriptContext->GetThreadContext()->SetAbnormalExceptionCode(exceptionCode);
  612. scriptContext->GetThreadContext()->SetAbnormalExceptionRecord(&exceptionInfo);
  613. }
  614. }
  615. #endif
  616. //ret should never be null here
  617. Assert(ret);
  618. return ret;
  619. }
  620. Var JavascriptFunction::CallRootFunctionInternal(RecyclableObject* obj, Arguments args, ScriptContext * scriptContext, bool inScript)
  621. {
  622. #if DBG
  623. if (IsInAssert != 0)
  624. {
  625. // Just don't execute anything if we are in an assert
  626. Js::Throw::FatalInternalError();
  627. }
  628. #endif
  629. if (inScript)
  630. {
  631. Assert(!(args.Info.Flags & CallFlags_New));
  632. return JavascriptFunction::CallFunction<true>(obj, obj->GetEntryPoint(), args);
  633. }
  634. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  635. Js::Var varThis;
  636. if (PHASE_FORCE1(Js::EvalCompilePhase) && args.Info.Count == 0)
  637. {
  638. varThis = JavascriptOperators::OP_GetThis(scriptContext->GetLibrary()->GetUndefined(), kmodGlobal, scriptContext);
  639. args.Info.Flags = (Js::CallFlags)(args.Info.Flags | CallFlags_Eval);
  640. args.Info.Count = 1;
  641. args.Values = &varThis;
  642. }
  643. #endif
  644. Var varResult = nullptr;
  645. ThreadContext *threadContext;
  646. threadContext = scriptContext->GetThreadContext();
  647. JavascriptExceptionObject* pExceptionObject = NULL;
  648. bool hasCaller = scriptContext->GetHostScriptContext() ? !!scriptContext->GetHostScriptContext()->HasCaller() : false;
  649. Assert(scriptContext == obj->GetScriptContext());
  650. BEGIN_JS_RUNTIME_CALLROOT_EX(scriptContext, hasCaller)
  651. {
  652. scriptContext->VerifyAlive(true);
  653. try
  654. {
  655. varResult =
  656. args.Info.Flags & CallFlags_New ?
  657. CallAsConstructor(obj, /* overridingNewTarget = */nullptr, args, scriptContext) :
  658. CallFunction<true>(obj, obj->GetEntryPoint(), args);
  659. // A recent compiler bug 150148 can incorrectly eliminate catch block, temporary workaround
  660. if (threadContext == NULL)
  661. {
  662. throw JavascriptException(nullptr);
  663. }
  664. }
  665. catch (const JavascriptException& err)
  666. {
  667. pExceptionObject = err.GetAndClear();
  668. }
  669. if (pExceptionObject)
  670. {
  671. JavascriptExceptionOperators::DoThrowCheckClone(pExceptionObject, scriptContext);
  672. }
  673. }
  674. END_JS_RUNTIME_CALL(scriptContext);
  675. Assert(varResult != nullptr);
  676. return varResult;
  677. }
  678. Var JavascriptFunction::CallRootFunction(Arguments args, ScriptContext * scriptContext, bool inScript)
  679. {
  680. return JavascriptFunction::CallRootFunction(this, args, scriptContext, inScript);
  681. }
  682. #if DBG
  683. /*static*/
  684. void JavascriptFunction::CheckValidDebugThunk(ScriptContext* scriptContext, RecyclableObject *function)
  685. {
  686. Assert(scriptContext != nullptr);
  687. Assert(function != nullptr);
  688. if (scriptContext->IsScriptContextInDebugMode()
  689. && !scriptContext->IsInterpreted() && !CONFIG_FLAG(ForceDiagnosticsMode) // Does not work nicely if we change the default settings.
  690. && function->GetEntryPoint() != scriptContext->CurrentThunk
  691. && function->GetEntryPoint() != scriptContext->CurrentCrossSiteThunk
  692. && JavascriptFunction::Is(function))
  693. {
  694. JavascriptFunction *jsFunction = JavascriptFunction::FromVar(function);
  695. if (!jsFunction->IsBoundFunction()
  696. && !jsFunction->GetFunctionInfo()->IsDeferred()
  697. && (jsFunction->GetFunctionInfo()->GetAttributes() & FunctionInfo::DoNotProfile) != FunctionInfo::DoNotProfile
  698. && jsFunction->GetFunctionInfo() != &JavascriptExternalFunction::EntryInfo::WrappedFunctionThunk)
  699. {
  700. Js::FunctionProxy *proxy = jsFunction->GetFunctionProxy();
  701. if (proxy)
  702. {
  703. AssertMsg(proxy->HasValidEntryPoint(), "Function does not have valid entrypoint");
  704. }
  705. }
  706. }
  707. }
  708. #endif
  709. Var JavascriptFunction::CallAsConstructor(Var v, Var overridingNewTarget, Arguments args, ScriptContext* scriptContext, const Js::AuxArray<uint32> *spreadIndices)
  710. {
  711. Assert(v);
  712. Assert(args.Info.Flags & CallFlags_New);
  713. Assert(scriptContext);
  714. // newCount is ushort.
  715. if (args.Info.Count >= USHORT_MAX)
  716. {
  717. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgListTooLarge);
  718. }
  719. AnalysisAssert(args.Info.Count < USHORT_MAX);
  720. // Create the empty object if necessary:
  721. // - Built-in constructor functions will return a new object of a specific type, so a new empty object does not need to
  722. // be created
  723. // - If the newTarget is specified and the function is base kind then the this object will be already created. So we can
  724. // just use it instead of creating a new one.
  725. // - For user-defined constructor functions, an empty object is created with the function's prototype
  726. Var resultObject = nullptr;
  727. if (overridingNewTarget != nullptr && args.Info.Count > 0)
  728. {
  729. resultObject = args.Values[0];
  730. }
  731. else
  732. {
  733. resultObject = JavascriptOperators::NewScObjectNoCtor(v, scriptContext);
  734. }
  735. // JavascriptOperators::NewScObject should have thrown if 'v' is not a constructor
  736. RecyclableObject* functionObj = RecyclableObject::FromVar(v);
  737. Var* newValues = args.Values;
  738. CallFlags newFlags = args.Info.Flags;
  739. ushort newCount = args.Info.Count;
  740. bool thisAlreadySpecified = false;
  741. if (overridingNewTarget != nullptr)
  742. {
  743. if (ScriptFunction::Is(functionObj) && ScriptFunction::FromVar(functionObj)->GetFunctionInfo()->IsClassConstructor())
  744. {
  745. thisAlreadySpecified = true;
  746. args.Values[0] = overridingNewTarget;
  747. }
  748. else
  749. {
  750. newCount++;
  751. newFlags = (CallFlags)(newFlags | CallFlags_NewTarget | CallFlags_ExtraArg);
  752. const unsigned STACK_ARGS_ALLOCA_THRESHOLD = 8; // Number of stack args we allow before using _alloca
  753. Var stackArgs[STACK_ARGS_ALLOCA_THRESHOLD];
  754. if (newCount > STACK_ARGS_ALLOCA_THRESHOLD)
  755. {
  756. PROBE_STACK(scriptContext, newCount * sizeof(Var) + Js::Constants::MinStackDefault); // args + function call
  757. newValues = (Var*)_alloca(newCount * sizeof(Var));
  758. }
  759. else
  760. {
  761. newValues = stackArgs;
  762. }
  763. for (unsigned int i = 0; i < args.Info.Count; i++)
  764. {
  765. newValues[i] = args.Values[i];
  766. }
  767. #pragma prefast(suppress:6386, "The index is within the bounds")
  768. newValues[args.Info.Count] = overridingNewTarget;
  769. }
  770. }
  771. // Call the constructor function:
  772. // - If this is not already specified as the overriding new target in Reflect.construct a class case, then
  773. // - Pass in the new empty object as the 'this' parameter. This can be null if an empty object was not created.
  774. if (!thisAlreadySpecified)
  775. {
  776. newValues[0] = resultObject;
  777. }
  778. CallInfo newCallInfo(newFlags, newCount);
  779. Arguments newArgs(newCallInfo, newValues);
  780. if (JavascriptProxy::Is(v))
  781. {
  782. JavascriptProxy* proxy = JavascriptProxy::FromVar(v);
  783. return proxy->ConstructorTrap(newArgs, scriptContext, spreadIndices);
  784. }
  785. #if DBG
  786. if (scriptContext->IsScriptContextInDebugMode())
  787. {
  788. CheckValidDebugThunk(scriptContext, functionObj);
  789. }
  790. #endif
  791. Var functionResult;
  792. if (spreadIndices != nullptr)
  793. {
  794. functionResult = CallSpreadFunction(functionObj, newArgs, spreadIndices);
  795. }
  796. else
  797. {
  798. functionResult = CallFunction<true>(functionObj, functionObj->GetEntryPoint(), newArgs);
  799. }
  800. return
  801. FinishConstructor(
  802. functionResult,
  803. resultObject,
  804. JavascriptFunction::Is(functionObj) && functionObj->GetScriptContext() == scriptContext ?
  805. JavascriptFunction::FromVar(functionObj) :
  806. nullptr,
  807. overridingNewTarget != nullptr);
  808. }
  809. Var JavascriptFunction::FinishConstructor(
  810. const Var constructorReturnValue,
  811. Var newObject,
  812. JavascriptFunction *const function,
  813. bool hasOverridingNewTarget)
  814. {
  815. Assert(constructorReturnValue);
  816. // CONSIDER: Using constructorCache->ctorHasNoExplicitReturnValue to speed up this interpreter code path.
  817. if (JavascriptOperators::IsObject(constructorReturnValue))
  818. {
  819. newObject = constructorReturnValue;
  820. }
  821. // #3217: Cases with overriding newTarget are not what constructor cache is intended for;
  822. // Bypass constructor cache to avoid prototype mismatch/confusion.
  823. if (function && function->GetConstructorCache()->NeedsUpdateAfterCtor() && !hasOverridingNewTarget)
  824. {
  825. JavascriptOperators::UpdateNewScObjectCache(function, newObject, function->GetScriptContext());
  826. }
  827. return newObject;
  828. }
  829. Var JavascriptFunction::EntrySpreadCall(const Js::AuxArray<uint32> *spreadIndices, RecyclableObject* function, CallInfo callInfo, ...)
  830. {
  831. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  832. RUNTIME_ARGUMENTS(args, spreadIndices, function, callInfo);
  833. return JavascriptFunction::CallSpreadFunction(function, args, spreadIndices);
  834. }
  835. uint32 JavascriptFunction::GetSpreadSize(const Arguments args, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
  836. {
  837. // Work out the expanded number of arguments.
  838. uint32 totalLength = args.Info.Count - spreadIndices->count;
  839. ::Math::RecordOverflowPolicy overflow;
  840. for (unsigned i = 0; i < spreadIndices->count; ++i)
  841. {
  842. uint32 elementLength = JavascriptArray::GetSpreadArgLen(args[spreadIndices->elements[i]], scriptContext);
  843. totalLength = UInt32Math::Add(totalLength, elementLength, overflow);
  844. }
  845. if (totalLength >= CallInfo::kMaxCountArgs || overflow.HasOverflowed())
  846. {
  847. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgListTooLarge);
  848. }
  849. return totalLength;
  850. }
  851. void JavascriptFunction::SpreadArgs(const Arguments args, Arguments& destArgs, const Js::AuxArray<uint32> *spreadIndices, ScriptContext *scriptContext)
  852. {
  853. Assert(args.Values != nullptr);
  854. Assert(destArgs.Values != nullptr);
  855. CallInfo callInfo = args.Info;
  856. size_t destArgsByteSize = destArgs.Info.Count * sizeof(Var);
  857. destArgs.Values[0] = args[0];
  858. // Iterate over the arguments, spreading inline. We skip 'this'.
  859. uint32 argsIndex = 1;
  860. for (unsigned i = 1, spreadArgIndex = 0; i < callInfo.Count; ++i)
  861. {
  862. uint32 spreadIndex = spreadIndices->elements[spreadArgIndex]; // Next index to be spread.
  863. if (i < spreadIndex)
  864. {
  865. // Copy everything until the next spread index.
  866. js_memcpy_s(destArgs.Values + argsIndex,
  867. destArgsByteSize - (argsIndex * sizeof(Var)),
  868. args.Values + i,
  869. (spreadIndex - i) * sizeof(Var));
  870. argsIndex += spreadIndex - i;
  871. i = spreadIndex - 1;
  872. continue;
  873. }
  874. else if (i > spreadIndex)
  875. {
  876. // Copy everything after the last spread index.
  877. js_memcpy_s(destArgs.Values + argsIndex,
  878. destArgsByteSize - (argsIndex * sizeof(Var)),
  879. args.Values + i,
  880. (args.Info.Count - i) * sizeof(Var));
  881. break;
  882. }
  883. else
  884. {
  885. // Expand the spread element.
  886. Var instance = args[spreadIndex];
  887. if (SpreadArgument::Is(instance))
  888. {
  889. SpreadArgument* spreadedArgs = SpreadArgument::FromVar(instance);
  890. uint size = spreadedArgs->GetArgumentSpreadCount();
  891. if (size > 0)
  892. {
  893. const Var * spreadBuffer = spreadedArgs->GetArgumentSpread();
  894. js_memcpy_s(destArgs.Values + argsIndex,
  895. size * sizeof(Var),
  896. spreadBuffer,
  897. size * sizeof(Var));
  898. argsIndex += size;
  899. }
  900. }
  901. else
  902. {
  903. Assert(JavascriptOperators::IsUndefinedObject(instance));
  904. destArgs.Values[argsIndex++] = instance;
  905. }
  906. if (spreadArgIndex < spreadIndices->count - 1)
  907. {
  908. spreadArgIndex++;
  909. }
  910. }
  911. }
  912. if (argsIndex > destArgs.Info.Count)
  913. {
  914. AssertMsg(false, "The array length has changed since we allocated the destArgs buffer?");
  915. Throw::FatalInternalError();
  916. }
  917. }
  918. Var JavascriptFunction::CallSpreadFunction(RecyclableObject* function, Arguments args, const Js::AuxArray<uint32> *spreadIndices)
  919. {
  920. ScriptContext* scriptContext = function->GetScriptContext();
  921. // Work out the expanded number of arguments.
  922. uint32 actualLength = GetSpreadSize(args, spreadIndices, scriptContext);
  923. // Allocate (if needed) space for the expanded arguments.
  924. Arguments outArgs(CallInfo(args.Info.Flags, 0), nullptr);
  925. outArgs.Info.Count = actualLength;
  926. Var stackArgs[STACK_ARGS_ALLOCA_THRESHOLD];
  927. size_t outArgsSize = 0;
  928. if (outArgs.Info.Count > STACK_ARGS_ALLOCA_THRESHOLD)
  929. {
  930. PROBE_STACK(scriptContext, outArgs.Info.Count * sizeof(Var) + Js::Constants::MinStackDefault); // args + function call
  931. outArgsSize = outArgs.Info.Count * sizeof(Var);
  932. outArgs.Values = (Var*)_alloca(outArgsSize);
  933. ZeroMemory(outArgs.Values, outArgsSize);
  934. }
  935. else
  936. {
  937. outArgs.Values = stackArgs;
  938. outArgsSize = STACK_ARGS_ALLOCA_THRESHOLD * sizeof(Var);
  939. ZeroMemory(outArgs.Values, outArgsSize); // We may not use all of the elements
  940. }
  941. SpreadArgs(args, outArgs, spreadIndices, scriptContext);
  942. return JavascriptFunction::CallFunction<true>(function, function->GetEntryPoint(), outArgs);
  943. }
  944. Var JavascriptFunction::CallFunction(Arguments args)
  945. {
  946. return JavascriptFunction::CallFunction<true>(this, this->GetEntryPoint(), args);
  947. }
  948. template Var JavascriptFunction::CallFunction<true>(RecyclableObject* function, JavascriptMethod entryPoint, Arguments args);
  949. template Var JavascriptFunction::CallFunction<false>(RecyclableObject* function, JavascriptMethod entryPoint, Arguments args);
  950. #if _M_IX86
  951. #ifdef ASMJS_PLAT
  952. template <> int JavascriptFunction::CallAsmJsFunction<int>(RecyclableObject * function, JavascriptMethod entryPoint, uint argc, Var * argv)
  953. {
  954. return CallAsmJsFunctionX86Thunk(function, entryPoint, argc, argv).retIntVal;
  955. }
  956. template <> int64 JavascriptFunction::CallAsmJsFunction<int64>(RecyclableObject * function, JavascriptMethod entryPoint, uint argc, Var * argv)
  957. {
  958. return CallAsmJsFunctionX86Thunk(function, entryPoint, argc, argv).retInt64Val;
  959. }
  960. template <> float JavascriptFunction::CallAsmJsFunction<float>(RecyclableObject * function, JavascriptMethod entryPoint, uint argc, Var * argv)
  961. {
  962. return CallAsmJsFunctionX86Thunk(function, entryPoint, argc, argv).retFloatVal;
  963. }
  964. template <> double JavascriptFunction::CallAsmJsFunction<double>(RecyclableObject * function, JavascriptMethod entryPoint, uint argc, Var * argv)
  965. {
  966. return CallAsmJsFunctionX86Thunk(function, entryPoint, argc, argv).retDoubleVal;
  967. }
  968. template <> AsmJsSIMDValue JavascriptFunction::CallAsmJsFunction<AsmJsSIMDValue>(RecyclableObject * function, JavascriptMethod entryPoint, uint argc, Var * argv)
  969. {
  970. return CallAsmJsFunctionX86Thunk(function, entryPoint, argc, argv).retSimdVal;
  971. }
  972. PossibleAsmJsReturnValues JavascriptFunction::CallAsmJsFunctionX86Thunk(RecyclableObject * function, JavascriptMethod entryPoint, uint argc, Var * argv)
  973. {
  974. enum {
  975. IsFloat = 1 << AsmJsRetType::Float,
  976. IsDouble = 1 << AsmJsRetType::Double,
  977. IsInt64 = 1 << AsmJsRetType::Int64,
  978. IsSimd =
  979. 1 << AsmJsRetType::Int32x4 |
  980. 1 << AsmJsRetType::Bool32x4 |
  981. 1 << AsmJsRetType::Bool16x8 |
  982. 1 << AsmJsRetType::Bool8x16 |
  983. 1 << AsmJsRetType::Float32x4 |
  984. 1 << AsmJsRetType::Float64x2 |
  985. 1 << AsmJsRetType::Int16x8 |
  986. 1 << AsmJsRetType::Int8x16 |
  987. 1 << AsmJsRetType::Uint32x4 |
  988. 1 << AsmJsRetType::Uint16x8 |
  989. 1 << AsmJsRetType::Uint8x16,
  990. CannotUseEax = IsFloat | IsDouble | IsInt64 | IsSimd
  991. };
  992. AsmJsFunctionInfo* asmInfo = ((ScriptFunction*)function)->GetFunctionBody()->GetAsmJsFunctionInfo();
  993. Assert((uint)((ArgSlot)asmInfo->GetArgCount() + 1) == (uint)(asmInfo->GetArgCount() + 1));
  994. uint argsSize = asmInfo->GetArgByteSize();
  995. uint alignedSize = ::Math::Align<int32>(argsSize, 8);
  996. ScriptContext * scriptContext = function->GetScriptContext();
  997. PROBE_STACK_CALL(scriptContext, function, alignedSize);
  998. PossibleAsmJsReturnValues retVals;
  999. AsmJsRetType::Which retType = asmInfo->GetReturnType().which();
  1000. void *data = nullptr;
  1001. void *savedEsp = nullptr;
  1002. __asm
  1003. {
  1004. // Save ESP
  1005. mov savedEsp, esp;
  1006. mov eax, alignedSize;
  1007. // Make sure we don't go beyond guard page
  1008. cmp eax, 0x1000;
  1009. jge alloca_probe;
  1010. sub esp, eax;
  1011. jmp dbl_align;
  1012. alloca_probe :
  1013. // Use alloca to allocate more then a page size
  1014. // Alloca assumes eax, contains size, and adjust ESP while
  1015. // probing each page.
  1016. call _alloca_probe_16;
  1017. dbl_align :
  1018. and esp,-8
  1019. mov data, esp;
  1020. }
  1021. {
  1022. Var* outParam = argv + 1;
  1023. void* dest = (void*)data;
  1024. memmove(dest, outParam, argsSize);
  1025. }
  1026. // call variable argument function provided in entryPoint
  1027. __asm
  1028. {
  1029. #ifdef _CONTROL_FLOW_GUARD
  1030. // verify that the call target is valid
  1031. mov ecx, entryPoint
  1032. call[__guard_check_icall_fptr]
  1033. ; no need to restore ecx('call entryPoint' is a __cdecl call)
  1034. #endif
  1035. push function;
  1036. call entryPoint;
  1037. push edx; // save possible int64 return value
  1038. mov ecx, retType;
  1039. mov edx, 1;
  1040. shl edx, cl;
  1041. pop ecx; // restore possible int64 return value
  1042. and edx, CannotUseEax;
  1043. jz FromEax;
  1044. and edx, ~IsInt64;
  1045. jz FromEaxEcx;
  1046. and edx, ~IsFloat;
  1047. jz FromXmmWord;
  1048. and edx, ~IsDouble;
  1049. jz FromXmmDWord;
  1050. // simd
  1051. movups retVals.retSimdVal, xmm0;
  1052. jmp end
  1053. FromEax:
  1054. mov retVals.retIntVal, eax;
  1055. jmp end;
  1056. FromEaxEcx:
  1057. mov retVals.retIntVal, eax;
  1058. mov retVals.retIntVal + 4, ecx;
  1059. jmp end;
  1060. FromXmmWord:
  1061. movss retVals.retFloatVal, xmm0;
  1062. jmp end;
  1063. FromXmmDWord:
  1064. movsd retVals.retDoubleVal, xmm0;
  1065. end:
  1066. // Restore ESP
  1067. mov esp, savedEsp;
  1068. }
  1069. return retVals;
  1070. }
  1071. #endif
  1072. #ifdef __clang__
  1073. void __cdecl _alloca_probe_16()
  1074. {
  1075. // todo: fix this!!!
  1076. abort();
  1077. __asm
  1078. {
  1079. push ecx
  1080. lea ecx, [esp + 8]
  1081. sub ecx, eax
  1082. and ecx, (16 - 1)
  1083. add eax, ecx
  1084. ret
  1085. }
  1086. }
  1087. #endif
  1088. static Var LocalCallFunction(RecyclableObject* function,
  1089. JavascriptMethod entryPoint, Arguments args, bool doStackProbe)
  1090. {
  1091. Js::Var varResult;
  1092. #if DBG && ENABLE_NATIVE_CODEGEN
  1093. CheckIsExecutable(function, entryPoint);
  1094. #endif
  1095. // compute size of stack to reserve
  1096. CallInfo callInfo = args.Info;
  1097. uint argsSize = callInfo.Count * sizeof(Var);
  1098. ScriptContext * scriptContext = function->GetScriptContext();
  1099. if (doStackProbe)
  1100. {
  1101. PROBE_STACK_CALL(scriptContext, function, argsSize);
  1102. }
  1103. void *data;
  1104. void *savedEsp;
  1105. __asm {
  1106. // Save ESP
  1107. mov savedEsp, esp
  1108. mov eax, argsSize
  1109. // Make sure we don't go beyond guard page
  1110. cmp eax, 0x1000
  1111. jge alloca_probe
  1112. sub esp, eax
  1113. jmp dbl_align
  1114. alloca_probe:
  1115. // Use alloca to allocate more then a page size
  1116. // Alloca assumes eax, contains size, and adjust ESP while
  1117. // probing each page.
  1118. call _alloca_probe_16
  1119. dbl_align:
  1120. // 8-byte align frame to improve floating point perf of our JIT'd code.
  1121. and esp, -8
  1122. mov data, esp
  1123. }
  1124. {
  1125. Var* dest = (Var*)data;
  1126. Var* src = args.Values;
  1127. for(unsigned int i =0; i < callInfo.Count; i++)
  1128. {
  1129. dest[i] = src[i];
  1130. }
  1131. }
  1132. // call variable argument function provided in entryPoint
  1133. __asm
  1134. {
  1135. #ifdef _CONTROL_FLOW_GUARD
  1136. // verify that the call target is valid
  1137. mov ecx, entryPoint
  1138. call [__guard_check_icall_fptr]
  1139. ; no need to restore ecx ('call entryPoint' is a __cdecl call)
  1140. #endif
  1141. push callInfo
  1142. push function
  1143. call entryPoint
  1144. // Restore ESP
  1145. mov esp, savedEsp
  1146. // save the return value from realsum.
  1147. mov varResult, eax;
  1148. }
  1149. return varResult;
  1150. }
  1151. // clang fails to create the labels,
  1152. // when __asm op is under a template function
  1153. template <bool doStackProbe>
  1154. Var JavascriptFunction::CallFunction(RecyclableObject* function,
  1155. JavascriptMethod entryPoint, Arguments args)
  1156. {
  1157. return LocalCallFunction(function, entryPoint, args, doStackProbe);
  1158. }
  1159. #elif _M_X64
  1160. template <bool doStackProbe>
  1161. Var JavascriptFunction::CallFunction(RecyclableObject *function, JavascriptMethod entryPoint, Arguments args)
  1162. {
  1163. // compute size of stack to reserve and make sure we have enough stack.
  1164. CallInfo callInfo = args.Info;
  1165. uint argsSize = callInfo.Count * sizeof(Var);
  1166. if (doStackProbe == true)
  1167. {
  1168. PROBE_STACK_CALL(function->GetScriptContext(), function, argsSize);
  1169. }
  1170. #if DBG && ENABLE_NATIVE_CODEGEN
  1171. CheckIsExecutable(function, entryPoint);
  1172. #endif
  1173. return amd64_CallFunction(function, entryPoint, args.Info, args.Info.Count, &args.Values[0]);
  1174. }
  1175. #elif defined(_M_ARM)
  1176. extern "C"
  1177. {
  1178. extern Var arm_CallFunction(JavascriptFunction* function, CallInfo info, Var* values, JavascriptMethod entryPoint);
  1179. }
  1180. template <bool doStackProbe>
  1181. Var JavascriptFunction::CallFunction(RecyclableObject* function, JavascriptMethod entryPoint, Arguments args)
  1182. {
  1183. // compute size of stack to reserve and make sure we have enough stack.
  1184. CallInfo callInfo = args.Info;
  1185. uint argsSize = callInfo.Count * sizeof(Var);
  1186. if (doStackProbe)
  1187. {
  1188. PROBE_STACK_CALL(function->GetScriptContext(), function, argsSize);
  1189. }
  1190. #if DBG && ENABLE_NATIVE_CODEGEN
  1191. CheckIsExecutable(function, entryPoint);
  1192. #endif
  1193. Js::Var varResult;
  1194. //The ARM can pass 4 arguments via registers so handle the cases for 0 or 1 values without resorting to asm code
  1195. //(so that the asm code can assume 0 or more values will go on the stack: putting -1 values on the stack is unhealthy).
  1196. unsigned count = args.Info.Count;
  1197. if (count == 0)
  1198. {
  1199. varResult = CALL_ENTRYPOINT(function->GetScriptContext()->GetThreadContext(),
  1200. entryPoint, (JavascriptFunction*)function, args.Info);
  1201. }
  1202. else if (count == 1)
  1203. {
  1204. varResult = CALL_ENTRYPOINT(function->GetScriptContext()->GetThreadContext(),
  1205. entryPoint, (JavascriptFunction*)function, args.Info, args.Values[0]);
  1206. }
  1207. else
  1208. {
  1209. varResult = arm_CallFunction((JavascriptFunction*)function, args.Info, args.Values, entryPoint);
  1210. }
  1211. return varResult;
  1212. }
  1213. #elif defined(_M_ARM64)
  1214. extern "C"
  1215. {
  1216. extern Var arm64_CallFunction(JavascriptFunction* function, CallInfo info, Var* values, JavascriptMethod entryPoint);
  1217. }
  1218. template <bool doStackProbe>
  1219. Var JavascriptFunction::CallFunction(RecyclableObject* function, JavascriptMethod entryPoint, Arguments args)
  1220. {
  1221. // compute size of stack to reserve and make sure we have enough stack.
  1222. CallInfo callInfo = args.Info;
  1223. uint argsSize = callInfo.Count * sizeof(Var);
  1224. if (doStackProbe)
  1225. {
  1226. PROBE_STACK_CALL(function->GetScriptContext(), function, argsSize);
  1227. }
  1228. #if DBG && ENABLE_NATIVE_CODEGEN
  1229. CheckIsExecutable(function, entryPoint);
  1230. #endif
  1231. Js::Var varResult;
  1232. varResult = arm64_CallFunction((JavascriptFunction*)function, args.Info, args.Values, entryPoint);
  1233. return varResult;
  1234. }
  1235. #else
  1236. Var JavascriptFunction::CallFunction(RecyclableObject *function, JavascriptMethod entryPoint, Arguments args)
  1237. {
  1238. #if DBG && ENABLE_NATIVE_CODEGEN
  1239. CheckIsExecutable(function, entryPoint);
  1240. #endif
  1241. #if 1
  1242. Js::Throw::NotImplemented();
  1243. return nullptr;
  1244. #else
  1245. Var varResult;
  1246. switch (info.Count)
  1247. {
  1248. case 0:
  1249. {
  1250. varResult=entryPoint((JavascriptFunction*)function, args.Info);
  1251. break;
  1252. }
  1253. case 1: {
  1254. varResult=entryPoint(
  1255. (JavascriptFunction*)function,
  1256. args.Info,
  1257. args.Values[0]);
  1258. break;
  1259. }
  1260. case 2: {
  1261. varResult=entryPoint(
  1262. (JavascriptFunction*)function,
  1263. args.Info,
  1264. args.Values[0],
  1265. args.Values[1]);
  1266. break;
  1267. }
  1268. case 3: {
  1269. varResult=entryPoint(
  1270. (JavascriptFunction*)function,
  1271. args.Info,
  1272. args.Values[0],
  1273. args.Values[1],
  1274. args.Values[2]);
  1275. break;
  1276. }
  1277. case 4: {
  1278. varResult=entryPoint(
  1279. (JavascriptFunction*)function,
  1280. args.Info,
  1281. args.Values[0],
  1282. args.Values[1],
  1283. args.Values[2],
  1284. args.Values[3]);
  1285. break;
  1286. }
  1287. case 5: {
  1288. varResult=entryPoint(
  1289. (JavascriptFunction*)function,
  1290. args.Info,
  1291. args.Values[0],
  1292. args.Values[1],
  1293. args.Values[2],
  1294. args.Values[3],
  1295. args.Values[4]);
  1296. break;
  1297. }
  1298. case 6: {
  1299. varResult=entryPoint(
  1300. (JavascriptFunction*)function,
  1301. args.Info,
  1302. args.Values[0],
  1303. args.Values[1],
  1304. args.Values[2],
  1305. args.Values[3],
  1306. args.Values[4],
  1307. args.Values[5]);
  1308. break;
  1309. }
  1310. case 7: {
  1311. varResult=entryPoint(
  1312. (JavascriptFunction*)function,
  1313. args.Info,
  1314. args.Values[0],
  1315. args.Values[1],
  1316. args.Values[2],
  1317. args.Values[3],
  1318. args.Values[4],
  1319. args.Values[5],
  1320. args.Values[6]);
  1321. break;
  1322. }
  1323. case 8: {
  1324. varResult=entryPoint(
  1325. (JavascriptFunction*)function,
  1326. args.Info,
  1327. args.Values[0],
  1328. args.Values[1],
  1329. args.Values[2],
  1330. args.Values[3],
  1331. args.Values[4],
  1332. args.Values[5],
  1333. args.Values[6],
  1334. args.Values[7]);
  1335. break;
  1336. }
  1337. case 9: {
  1338. varResult=entryPoint(
  1339. (JavascriptFunction*)function,
  1340. args.Info,
  1341. args.Values[0],
  1342. args.Values[1],
  1343. args.Values[2],
  1344. args.Values[3],
  1345. args.Values[4],
  1346. args.Values[5],
  1347. args.Values[6],
  1348. args.Values[7],
  1349. args.Values[8]);
  1350. break;
  1351. }
  1352. default:
  1353. ScriptContext* scriptContext = function->type->GetScriptContext();
  1354. varResult = scriptContext->GetLibrary()->GetUndefined();
  1355. AssertMsg(false, "CallFunction call with unsupported number of arguments");
  1356. break;
  1357. }
  1358. #endif
  1359. return varResult;
  1360. }
  1361. #endif
  1362. Var JavascriptFunction::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
  1363. {
  1364. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1365. ARGUMENTS(args, callInfo);
  1366. ScriptContext* scriptContext = function->GetScriptContext();
  1367. Assert(!(callInfo.Flags & CallFlags_New));
  1368. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  1369. if (args.Info.Count == 0 || !JavascriptFunction::Is(args[0]))
  1370. {
  1371. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NeedFunction, _u("Function.prototype.toString"));
  1372. }
  1373. JavascriptFunction *pFunc = JavascriptFunction::FromVar(args[0]);
  1374. // pFunc can be from a different script context if Function.prototype.toString is invoked via .call/.apply.
  1375. // Marshal the resulting string to the current script context (that of the toString)
  1376. return CrossSite::MarshalVar(scriptContext, pFunc->EnsureSourceString());
  1377. }
  1378. JavascriptString* JavascriptFunction::GetNativeFunctionDisplayString(ScriptContext *scriptContext, JavascriptString *name)
  1379. {
  1380. return GetNativeFunctionDisplayStringCommon<JavascriptString>(scriptContext, name);
  1381. }
  1382. JavascriptString* JavascriptFunction::GetLibraryCodeDisplayString(ScriptContext *scriptContext, PCWSTR displayName)
  1383. {
  1384. return GetLibraryCodeDisplayStringCommon<JavascriptString, JavascriptString*>(scriptContext, displayName);
  1385. }
  1386. #ifdef _M_IX86
  1387. // This code is enabled by the -checkAlignment switch.
  1388. // It verifies that all of our JS frames are 8 byte aligned.
  1389. // Our alignments is based on aligning the return address of the function.
  1390. // Note that this test can fail when Javascript functions are called directly
  1391. // from helper functions. This could be fixed by making these calls through
  1392. // CallFunction(), or by having the helper 8 byte align the frame itself before
  1393. // the call. A lot of these though are not dealing with floats, so the cost
  1394. // of doing the 8 byte alignment would outweigh the benefit...
  1395. __declspec (naked)
  1396. void JavascriptFunction::CheckAlignment()
  1397. {
  1398. _asm
  1399. {
  1400. test esp, 0x4
  1401. je LABEL1
  1402. ret
  1403. LABEL1:
  1404. call Throw::InternalError
  1405. }
  1406. }
  1407. #else
  1408. void JavascriptFunction::CheckAlignment()
  1409. {
  1410. // Note: in order to enable this on ARM, uncomment/fix code in LowerMD.cpp (LowerEntryInstr).
  1411. }
  1412. #endif
  1413. BOOL JavascriptFunction::IsNativeAddress(ScriptContext * scriptContext, void * codeAddr)
  1414. {
  1415. #if ENABLE_NATIVE_CODEGEN
  1416. return scriptContext->IsNativeAddress(codeAddr);
  1417. #else
  1418. return false;
  1419. #endif
  1420. }
  1421. Js::JavascriptMethod JavascriptFunction::DeferredParse(ScriptFunction** functionRef)
  1422. {
  1423. BOOL fParsed;
  1424. return Js::ScriptFunction::DeferredParseCore(functionRef, fParsed);
  1425. }
  1426. Js::JavascriptMethod JavascriptFunction::DeferredParseCore(ScriptFunction** functionRef, BOOL &fParsed)
  1427. {
  1428. // Do the actual deferred parsing and byte code generation, passing the new entry point to the caller.
  1429. ParseableFunctionInfo* functionInfo = (*functionRef)->GetParseableFunctionInfo();
  1430. FunctionBody* funcBody = nullptr;
  1431. Assert(functionInfo);
  1432. ScriptFunctionWithInlineCache * funcObjectWithInlineCache = ScriptFunctionWithInlineCache::Is(*functionRef) ? ScriptFunctionWithInlineCache::FromVar(*functionRef) : nullptr;
  1433. if (functionInfo->IsDeferredParseFunction())
  1434. {
  1435. if (funcObjectWithInlineCache)
  1436. {
  1437. // If inline caches were populated from a function body that has been redeferred, the caches have been cleaned up,
  1438. // so clear the pointers. REVIEW: Is this a perf loss in some cases?
  1439. funcObjectWithInlineCache->ClearBorrowedInlineCacheOnFunctionObject();
  1440. }
  1441. funcBody = functionInfo->Parse(functionRef);
  1442. fParsed = funcBody->IsFunctionParsed() ? TRUE : FALSE;
  1443. #if ENABLE_PROFILE_INFO
  1444. // This is the first call to the function, ensure dynamic profile info
  1445. funcBody->EnsureDynamicProfileInfo();
  1446. #endif
  1447. }
  1448. else
  1449. {
  1450. funcBody = functionInfo->GetFunctionBody();
  1451. Assert(funcBody != nullptr);
  1452. Assert(!funcBody->IsDeferredParseFunction());
  1453. }
  1454. DebugOnly(JavascriptMethod directEntryPoint = funcBody->GetDirectEntryPoint(funcBody->GetDefaultEntryPointInfo()));
  1455. #if defined(ENABLE_SCRIPT_PROFILING) || defined(ENABLE_SCRIPT_DEBUGGING)
  1456. Assert(directEntryPoint != DefaultDeferredParsingThunk
  1457. && directEntryPoint != ProfileDeferredParsingThunk);
  1458. #else // !ENABLE_SCRIPT_PROFILING && !ENABLE_SCRIPT_DEBUGGING
  1459. Assert(directEntryPoint != DefaultDeferredParsingThunk);
  1460. #endif
  1461. JavascriptMethod thunkEntryPoint = (*functionRef)->UpdateUndeferredBody(funcBody);
  1462. if (funcObjectWithInlineCache && !funcObjectWithInlineCache->GetHasOwnInlineCaches())
  1463. {
  1464. // If the function object needs to use the inline caches from the function body, point them to the
  1465. // function body's caches. This is required in two redeferral cases:
  1466. //
  1467. // 1. We might have cleared the caches on the function object (ClearBorrowedInlineCacheOnFunctionObject)
  1468. // above if the function body was redeferred.
  1469. // 2. Another function object could have been called before and undeferred the function body, thereby creating
  1470. // new inline caches. This function object would still be pointing to the old ones and needs updating.
  1471. funcObjectWithInlineCache->SetInlineCachesFromFunctionBody();
  1472. }
  1473. return thunkEntryPoint;
  1474. }
  1475. void JavascriptFunction::ReparseAsmJsModule(ScriptFunction** functionRef)
  1476. {
  1477. ParseableFunctionInfo* functionInfo = (*functionRef)->GetParseableFunctionInfo();
  1478. Assert(functionInfo);
  1479. functionInfo->GetFunctionBody()->AddDeferParseAttribute();
  1480. functionInfo->GetFunctionBody()->ResetEntryPoint();
  1481. functionInfo->GetFunctionBody()->ResetInParams();
  1482. FunctionBody * funcBody = functionInfo->Parse(functionRef);
  1483. #if ENABLE_PROFILE_INFO
  1484. // This is the first call to the function, ensure dynamic profile info
  1485. funcBody->EnsureDynamicProfileInfo();
  1486. #endif
  1487. (*functionRef)->UpdateUndeferredBody(funcBody);
  1488. }
  1489. // Thunk for handling calls to functions that have not had byte code generated for them.
  1490. #if _M_IX86
  1491. __declspec(naked)
  1492. Var JavascriptFunction::DeferredParsingThunk(RecyclableObject* function, CallInfo callInfo, ...)
  1493. {
  1494. __asm
  1495. {
  1496. push ebp
  1497. mov ebp, esp
  1498. lea eax, [esp+8] // load the address of the function os that if we need to box, we can patch it up
  1499. push eax
  1500. call JavascriptFunction::DeferredParse
  1501. #ifdef _CONTROL_FLOW_GUARD
  1502. // verify that the call target is valid
  1503. mov ecx, eax
  1504. call[__guard_check_icall_fptr]
  1505. mov eax, ecx
  1506. #endif
  1507. pop ebp
  1508. jmp eax
  1509. }
  1510. }
  1511. #elif defined(_M_X64) || defined(_M_ARM32_OR_ARM64)
  1512. //Do nothing: the implementation of JavascriptFunction::DeferredParsingThunk is declared (appropriately decorated) in
  1513. // Library\amd64\javascriptfunctiona.asm
  1514. // Library\arm\arm_DeferredParsingThunk.asm
  1515. // Library\arm64\arm64_DeferredParsingThunk.asm
  1516. #else
  1517. Var JavascriptFunction::DeferredParsingThunk(RecyclableObject* function, CallInfo callInfo, ...)
  1518. {
  1519. Js::Throw::NotImplemented();
  1520. return nullptr;
  1521. }
  1522. #endif
  1523. ConstructorCache* JavascriptFunction::EnsureValidConstructorCache()
  1524. {
  1525. Assert(this->constructorCache != nullptr);
  1526. this->constructorCache = ConstructorCache::EnsureValidInstance(this->constructorCache, this->GetScriptContext());
  1527. return this->constructorCache;
  1528. }
  1529. void JavascriptFunction::ResetConstructorCacheToDefault()
  1530. {
  1531. Assert(this->constructorCache != nullptr);
  1532. if (!this->constructorCache->IsDefault())
  1533. {
  1534. this->constructorCache = &ConstructorCache::DefaultInstance;
  1535. }
  1536. }
  1537. // Thunk for handling calls to functions that have not had byte code generated for them.
  1538. #if _M_IX86
  1539. __declspec(naked)
  1540. Var JavascriptFunction::DeferredDeserializeThunk(RecyclableObject* function, CallInfo callInfo, ...)
  1541. {
  1542. __asm
  1543. {
  1544. push ebp
  1545. mov ebp, esp
  1546. push [esp+8]
  1547. call JavascriptFunction::DeferredDeserialize
  1548. #ifdef _CONTROL_FLOW_GUARD
  1549. // verify that the call target is valid
  1550. mov ecx, eax
  1551. call[__guard_check_icall_fptr]
  1552. mov eax, ecx
  1553. #endif
  1554. pop ebp
  1555. jmp eax
  1556. }
  1557. }
  1558. #elif (defined(_M_X64) || defined(_M_ARM32_OR_ARM64)) && defined(_MSC_VER)
  1559. //Do nothing: the implementation of JavascriptFunction::DeferredParsingThunk is declared (appropriately decorated) in
  1560. // Library\amd64\javascriptfunctiona.asm
  1561. // Library\arm\arm_DeferredParsingThunk.asm
  1562. // Library\arm64\arm64_DeferredParsingThunk.asm
  1563. #else
  1564. // xplat implement in
  1565. // Library/amd64/JavascriptFunctionA.S
  1566. #endif
  1567. Js::JavascriptMethod JavascriptFunction::DeferredDeserialize(ScriptFunction* function)
  1568. {
  1569. FunctionInfo* funcInfo = function->GetFunctionInfo();
  1570. Assert(funcInfo);
  1571. FunctionBody* funcBody = nullptr;
  1572. // If we haven't already deserialized this function, do so now
  1573. // FunctionProxies could have gotten deserialized during the interpreter when
  1574. // we tried to record the callsite info for the function which meant that it was a
  1575. // target of a call. Or we could have deserialized the function info in another JavascriptFunctionInstance
  1576. // In any case, fix up the function info if it's already been deserialized so that
  1577. // we don't hold on to the proxy for too long, and rethunk it so that it directly
  1578. // calls the default entry point the next time around
  1579. if (funcInfo->IsDeferredDeserializeFunction())
  1580. {
  1581. DeferDeserializeFunctionInfo* deferDeserializeFunction = funcInfo->GetDeferDeserializeFunctionInfo();
  1582. // This is the first call to the function, ensure dynamic profile info
  1583. // Deserialize is a no-op if the function has already been deserialized
  1584. funcBody = deferDeserializeFunction->Deserialize();
  1585. #if ENABLE_PROFILE_INFO
  1586. funcBody->EnsureDynamicProfileInfo();
  1587. #endif
  1588. }
  1589. else
  1590. {
  1591. funcBody = funcInfo->GetFunctionBody();
  1592. Assert(funcBody != nullptr);
  1593. Assert(!funcBody->IsDeferredDeserializeFunction());
  1594. }
  1595. return function->UpdateUndeferredBody(funcBody);
  1596. }
  1597. void JavascriptFunction::SetEntryPoint(JavascriptMethod method)
  1598. {
  1599. this->GetDynamicType()->SetEntryPoint(method);
  1600. }
  1601. Var JavascriptFunction::EnsureSourceString()
  1602. {
  1603. return this->GetLibrary()->GetFunctionDisplayString();
  1604. }
  1605. /*
  1606. *****************************************************************************************************************
  1607. Conditions checked by instruction decoder (In sequential order)
  1608. ******************************************************************************************************************
  1609. 1) Exception Code is AV i.e STATUS_ACCESS_VIOLATION
  1610. 2) Check if Rip is Native address
  1611. 3) Get the function object from RBP (a fixed offset from RBP) and check for the following
  1612. a. Not Null
  1613. b. Ensure that the function object is heap allocated
  1614. c. Ensure that the entrypointInfo is heap allocated
  1615. d. Ensure that the functionbody is heap allocated
  1616. e. Is a function
  1617. f. Is AsmJs Function object for asmjs
  1618. 4) Check if Array BufferLength > 0x10000 (64K), power of 2 if length is less than 2^24 or multiple of 2^24 and multiple of 0x1000(4K) for asmjs
  1619. 5) Check If the instruction is valid
  1620. a. Is one of the move instructions , i.e. mov, movsx, movzx, movsxd, movss or movsd
  1621. b. Get the array buffer register and its value for asmjs
  1622. c. Get the dst register(in case of load)
  1623. d. Calculate the number of bytes read in order to get the length of the instruction , ensure that the length should never be greater than 15 bytes
  1624. 6) Check that the Array buffer value is same as the one we passed in EntryPointInfo in asmjs
  1625. 7) Set the dst reg if the instr type is load
  1626. 8) Add the bytes read to Rip and set it as new Rip
  1627. 9) Return EXCEPTION_CONTINUE_EXECUTION
  1628. */
  1629. #if ENABLE_NATIVE_CODEGEN
  1630. #if defined(_M_IX86) || defined(_M_X64)
  1631. class ExceptionFilterHelper
  1632. {
  1633. Js::ScriptFunction* m_func = nullptr;
  1634. bool m_checkedForFunc = false;
  1635. PEXCEPTION_POINTERS exceptionInfo;
  1636. public:
  1637. ExceptionFilterHelper(PEXCEPTION_POINTERS exceptionInfo) : exceptionInfo(exceptionInfo) {}
  1638. PEXCEPTION_POINTERS GetExceptionInfo() const
  1639. {
  1640. return exceptionInfo;
  1641. }
  1642. uintptr_t GetFaultingAddress() const
  1643. {
  1644. // For AVs, the second element of ExceptionInformation array is address of inaccessible data
  1645. // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082.aspx
  1646. Assert(this->exceptionInfo->ExceptionRecord->ExceptionCode == STATUS_ACCESS_VIOLATION);
  1647. Assert(this->exceptionInfo->ExceptionRecord->NumberParameters >= 2);
  1648. return exceptionInfo->ExceptionRecord->ExceptionInformation[1];
  1649. }
  1650. Var GetIPAddress() const
  1651. {
  1652. #if _M_IX86
  1653. return (Var)exceptionInfo->ContextRecord->Eip;
  1654. #elif _M_X64
  1655. return (Var)exceptionInfo->ContextRecord->Rip;
  1656. #else
  1657. #error Not yet Implemented
  1658. #endif
  1659. }
  1660. Var* GetAddressOfFuncObj() const
  1661. {
  1662. #if _M_IX86
  1663. return (Var*)(exceptionInfo->ContextRecord->Ebp + 2 * sizeof(Var));
  1664. #elif _M_X64
  1665. return (Var*)(exceptionInfo->ContextRecord->Rbp + 2 * sizeof(Var));
  1666. #else
  1667. #error Not yet Implemented
  1668. #endif
  1669. }
  1670. Js::ScriptFunction* GetScriptFunction()
  1671. {
  1672. if (m_checkedForFunc)
  1673. {
  1674. return m_func;
  1675. }
  1676. m_checkedForFunc = true;
  1677. ThreadContext* threadContext = ThreadContext::GetContextForCurrentThread();
  1678. // AV should come from JITed code, since we don't eliminate bound checks in interpreter
  1679. if (!threadContext->IsNativeAddress(GetIPAddress()))
  1680. {
  1681. return nullptr;
  1682. }
  1683. Var* addressOfFuncObj = GetAddressOfFuncObj();
  1684. if (!addressOfFuncObj || *addressOfFuncObj == nullptr || !ScriptFunction::Is(*addressOfFuncObj))
  1685. {
  1686. return nullptr;
  1687. }
  1688. Js::ScriptFunction* func = (Js::ScriptFunction*)(*addressOfFuncObj);
  1689. RecyclerHeapObjectInfo heapObject;
  1690. Recycler* recycler = threadContext->GetRecycler();
  1691. bool isFuncObjHeapAllocated = recycler->FindHeapObject(func, FindHeapObjectFlags_NoFlags, heapObject); // recheck if this needs to be removed
  1692. bool isEntryPointHeapAllocated = recycler->FindHeapObject(func->GetEntryPointInfo(), FindHeapObjectFlags_NoFlags, heapObject);
  1693. bool isFunctionBodyHeapAllocated = recycler->FindHeapObject(func->GetFunctionBody(), FindHeapObjectFlags_NoFlags, heapObject);
  1694. // ensure that all our objects are heap allocated
  1695. if (!(isFuncObjHeapAllocated && isEntryPointHeapAllocated && isFunctionBodyHeapAllocated))
  1696. {
  1697. return nullptr;
  1698. }
  1699. m_func = func;
  1700. return m_func;
  1701. }
  1702. };
  1703. void CheckWasmMathException(int exceptionCode, ExceptionFilterHelper& helper)
  1704. {
  1705. if (CONFIG_FLAG(WasmMathExFilter) && (exceptionCode == STATUS_INTEGER_DIVIDE_BY_ZERO || exceptionCode == STATUS_INTEGER_OVERFLOW))
  1706. {
  1707. Js::ScriptFunction* func = helper.GetScriptFunction();
  1708. if (func)
  1709. {
  1710. Js::FunctionBody* funcBody = func->GetFunctionBody();
  1711. if (funcBody && funcBody->IsWasmFunction())
  1712. {
  1713. int32 code = exceptionCode == STATUS_INTEGER_DIVIDE_BY_ZERO ? WASMERR_DivideByZero : VBSERR_Overflow;
  1714. JavascriptError::ThrowWebAssemblyRuntimeError(func->GetScriptContext(), code);
  1715. }
  1716. }
  1717. }
  1718. }
  1719. // x64 specific exception filters
  1720. #ifdef _M_X64
  1721. ArrayAccessDecoder::InstructionData ArrayAccessDecoder::CheckValidInstr(BYTE* &pc, PEXCEPTION_POINTERS exceptionInfo) // get the reg operand and isLoad and
  1722. {
  1723. InstructionData instrData;
  1724. uint prefixValue = 0;
  1725. ArrayAccessDecoder::RexByteValue rexByteValue;
  1726. bool isFloat = false;
  1727. uint immBytes = 0;
  1728. uint dispBytes = 0;
  1729. bool isImmediate = false;
  1730. bool isSIB = false;
  1731. // Read first byte - check for prefix
  1732. BYTE* beginPc = pc;
  1733. if (((*pc) == 0x0F2) || ((*pc) == 0x0F3))
  1734. {
  1735. //MOVSD or MOVSS
  1736. prefixValue = *pc;
  1737. isFloat = true;
  1738. pc++;
  1739. }
  1740. else if (*pc == 0x66)
  1741. {
  1742. prefixValue = *pc;
  1743. pc++;
  1744. }
  1745. // Check for Rex Byte - After prefix we should have a rexByte if there is one
  1746. if (*pc >= 0x40 && *pc <= 0x4F)
  1747. {
  1748. rexByteValue.rexValue = *pc;
  1749. uint rexByte = *pc - 0x40;
  1750. if (rexByte & 0x8)
  1751. {
  1752. rexByteValue.isW = true;
  1753. }
  1754. if (rexByte & 0x4)
  1755. {
  1756. rexByteValue.isR = true;
  1757. }
  1758. if (rexByte & 0x2)
  1759. {
  1760. rexByteValue.isX = true;
  1761. }
  1762. if (rexByte & 0x1)
  1763. {
  1764. rexByteValue.isB = true;
  1765. }
  1766. pc++;
  1767. }
  1768. // read opcode
  1769. // Is one of the move instructions , i.e. mov, movsx, movzx, movsxd, movss or movsd
  1770. switch (*pc)
  1771. {
  1772. //MOV - Store
  1773. case 0x89:
  1774. case 0x88:
  1775. {
  1776. pc++;
  1777. instrData.isLoad = false;
  1778. break;
  1779. }
  1780. //MOVSXD
  1781. case 0x63:
  1782. //MOV - Load
  1783. case 0x8A:
  1784. case 0x8B:
  1785. {
  1786. pc++;
  1787. instrData.isLoad = true;
  1788. break;
  1789. }
  1790. case 0x0F:
  1791. {
  1792. // more than one byte opcode and hence we will read pc multiple times
  1793. pc++;
  1794. //MOVSX
  1795. if (*pc == 0xBE || *pc == 0xBF)
  1796. {
  1797. instrData.isLoad = true;
  1798. }
  1799. //MOVZX
  1800. else if (*pc == 0xB6 || *pc == 0xB7)
  1801. {
  1802. instrData.isLoad = true;
  1803. }
  1804. //MOVSS - Load
  1805. else if (*pc == 0x10 && prefixValue == 0xF3)
  1806. {
  1807. Assert(isFloat);
  1808. instrData.isLoad = true;
  1809. instrData.isFloat32 = true;
  1810. }
  1811. //MOVSS - Store
  1812. else if (*pc == 0x11 && prefixValue == 0xF3)
  1813. {
  1814. Assert(isFloat);
  1815. instrData.isLoad = false;
  1816. instrData.isFloat32 = true;
  1817. }
  1818. //MOVSD - Load
  1819. else if (*pc == 0x10 && prefixValue == 0xF2)
  1820. {
  1821. Assert(isFloat);
  1822. instrData.isLoad = true;
  1823. instrData.isFloat64 = true;
  1824. }
  1825. //MOVSD - Store
  1826. else if (*pc == 0x11 && prefixValue == 0xF2)
  1827. {
  1828. Assert(isFloat);
  1829. instrData.isLoad = false;
  1830. instrData.isFloat64 = true;
  1831. }
  1832. //MOVUPS - Load
  1833. else if (*pc == 0x10 && prefixValue == 0)
  1834. {
  1835. instrData.isLoad = true;
  1836. instrData.isSimd = true;
  1837. }
  1838. //MOVUPS - Store
  1839. else if (*pc == 0x11 && prefixValue == 0)
  1840. {
  1841. instrData.isLoad = false;
  1842. instrData.isSimd = true;
  1843. }
  1844. else
  1845. {
  1846. instrData.isInvalidInstr = true;
  1847. }
  1848. pc++;
  1849. break;
  1850. }
  1851. // Support Mov Immediates
  1852. // MOV
  1853. case 0xC6:
  1854. case 0xC7:
  1855. {
  1856. instrData.isLoad = false;
  1857. instrData.isFloat64 = false;
  1858. isImmediate = true;
  1859. if (*pc == 0xC6)
  1860. {
  1861. immBytes = 1;
  1862. }
  1863. else if (rexByteValue.isW) // For MOV, REX.W set means we have a 32 bit immediate value, which gets extended to 64 bit.
  1864. {
  1865. immBytes = 4;
  1866. }
  1867. else
  1868. {
  1869. if (prefixValue == 0x66)
  1870. {
  1871. immBytes = 2;
  1872. }
  1873. else
  1874. {
  1875. immBytes = 4;
  1876. }
  1877. }
  1878. pc++;
  1879. break;
  1880. }
  1881. default:
  1882. instrData.isInvalidInstr = true;
  1883. break;
  1884. }
  1885. // if the opcode is not a move return
  1886. if (instrData.isInvalidInstr)
  1887. {
  1888. return instrData;
  1889. }
  1890. //Read ModR/M
  1891. // Read the Src Reg and also check for SIB
  1892. // Add the isR bit to SrcReg and get the actual SRCReg
  1893. // Get the number of bytes for displacement
  1894. //get mod bits
  1895. BYTE modVal = *pc & 0xC0; // first two bits(7th and 6th bits)
  1896. modVal >>= 6;
  1897. //get the R/M bits
  1898. BYTE rmVal = (*pc) & 0x07; // last 3 bits ( 0,1 and 2nd bits)
  1899. //get the reg value
  1900. BYTE dstReg = (*pc) & 0x38; // mask reg bits (3rd 4th and 5th bits)
  1901. dstReg >>= 3;
  1902. Assert(dstReg <= 0x07);
  1903. Assert(modVal <= 0x03);
  1904. Assert(rmVal <= 0x07);
  1905. switch (modVal)
  1906. {
  1907. case 0x00:
  1908. dispBytes = 0;
  1909. break;
  1910. case 0x01:
  1911. dispBytes = 1;
  1912. break;
  1913. case 0x02:
  1914. dispBytes = 4;
  1915. break;
  1916. default:
  1917. instrData.isInvalidInstr = true;
  1918. break;
  1919. }
  1920. if (instrData.isInvalidInstr)
  1921. {
  1922. return instrData;
  1923. }
  1924. // Get the R/M value and see if SIB is present , else get the buffer reg
  1925. if (rmVal == 0x04)
  1926. {
  1927. isSIB = true;
  1928. }
  1929. else
  1930. {
  1931. instrData.bufferReg = rmVal;
  1932. }
  1933. // Get the RegByes from ModRM
  1934. instrData.dstReg = dstReg;
  1935. // increment the modrm byte
  1936. pc++;
  1937. // Check if we have SIB and in that case bufferReg should not be set
  1938. if (isSIB)
  1939. {
  1940. Assert(!instrData.bufferReg);
  1941. // Get the Base and Index Reg from SIB and ensure that Scale is zero
  1942. // We don't care about the Index reg
  1943. // Add the isB value from Rex and get the actual Base Reg
  1944. // Get the base register
  1945. // 6f. Get the array buffer register and its value
  1946. instrData.bufferReg = (*pc % 8);
  1947. pc++;
  1948. }
  1949. // check for the Rex.B value and append it to the base register
  1950. if (rexByteValue.isB)
  1951. {
  1952. instrData.bufferReg |= 1 << 3;
  1953. }
  1954. // check for the Rex.R value and append it to the dst register
  1955. if (rexByteValue.isR)
  1956. {
  1957. instrData.dstReg |= 1 << 3;
  1958. }
  1959. // Get the buffer address - this is always 64 bit GPR
  1960. switch (instrData.bufferReg)
  1961. {
  1962. case 0x0:
  1963. instrData.bufferValue = exceptionInfo->ContextRecord->Rax;
  1964. break;
  1965. case 0x1:
  1966. instrData.bufferValue = exceptionInfo->ContextRecord->Rcx;
  1967. break;
  1968. case 0x2:
  1969. instrData.bufferValue = exceptionInfo->ContextRecord->Rdx;
  1970. break;
  1971. case 0x3:
  1972. instrData.bufferValue = exceptionInfo->ContextRecord->Rbx;
  1973. break;
  1974. case 0x4:
  1975. instrData.bufferValue = exceptionInfo->ContextRecord->Rsp;
  1976. break;
  1977. case 0x5:
  1978. // RBP wouldn't point to an array buffer
  1979. instrData.bufferValue = NULL;
  1980. break;
  1981. case 0x6:
  1982. instrData.bufferValue = exceptionInfo->ContextRecord->Rsi;
  1983. break;
  1984. case 0x7:
  1985. instrData.bufferValue = exceptionInfo->ContextRecord->Rdi;
  1986. break;
  1987. case 0x8:
  1988. instrData.bufferValue = exceptionInfo->ContextRecord->R8;
  1989. break;
  1990. case 0x9:
  1991. instrData.bufferValue = exceptionInfo->ContextRecord->R9;
  1992. break;
  1993. case 0xA:
  1994. instrData.bufferValue = exceptionInfo->ContextRecord->R10;
  1995. break;
  1996. case 0xB:
  1997. instrData.bufferValue = exceptionInfo->ContextRecord->R11;
  1998. break;
  1999. case 0xC:
  2000. instrData.bufferValue = exceptionInfo->ContextRecord->R12;
  2001. break;
  2002. case 0xD:
  2003. instrData.bufferValue = exceptionInfo->ContextRecord->R13;
  2004. break;
  2005. case 0xE:
  2006. instrData.bufferValue = exceptionInfo->ContextRecord->R14;
  2007. break;
  2008. case 0xF:
  2009. instrData.bufferValue = exceptionInfo->ContextRecord->R15;
  2010. break;
  2011. default:
  2012. instrData.isInvalidInstr = true;
  2013. Assert(false);// should never reach here as validation is done before itself
  2014. return instrData;
  2015. }
  2016. // add the pc for displacement , we don't need the displacement Byte value
  2017. if (dispBytes > 0)
  2018. {
  2019. pc = pc + dispBytes;
  2020. }
  2021. instrData.instrSizeInByte = (uint)(pc - beginPc);
  2022. if (isImmediate)
  2023. {
  2024. Assert(immBytes > 0);
  2025. instrData.instrSizeInByte += immBytes;
  2026. }
  2027. // Calculate the number of bytes read in order to get the length of the instruction , ensure that the length should never be greater than 15 bytes
  2028. if (instrData.instrSizeInByte > 15)
  2029. {
  2030. // no instr size can be greater than 15
  2031. instrData.isInvalidInstr = true;
  2032. }
  2033. return instrData;
  2034. }
  2035. #if ENABLE_FAST_ARRAYBUFFER
  2036. bool ResumeForOutOfBoundsArrayRefs(int exceptionCode, ExceptionFilterHelper& helper)
  2037. {
  2038. if (exceptionCode != STATUS_ACCESS_VIOLATION)
  2039. {
  2040. return false;
  2041. }
  2042. Js::ScriptFunction* func = helper.GetScriptFunction();
  2043. if (!func)
  2044. {
  2045. return false;
  2046. }
  2047. Js::FunctionBody* funcBody = func->GetFunctionBody();
  2048. bool isWAsmJs = funcBody->GetIsAsmJsFunction();
  2049. bool isWasmOnly = funcBody->IsWasmFunction();
  2050. if (isWAsmJs)
  2051. {
  2052. // some extra checks for asm.js because we have slightly more information that we can validate
  2053. uintptr_t moduleMemory = (uintptr_t)((AsmJsScriptFunction*)func)->GetModuleMemory();
  2054. if (!moduleMemory)
  2055. {
  2056. return false;
  2057. }
  2058. ArrayBuffer* arrayBuffer = nullptr;
  2059. size_t reservationSize = 0;
  2060. #ifdef ENABLE_WASM
  2061. if (isWasmOnly)
  2062. {
  2063. WebAssemblyMemory* mem = *(WebAssemblyMemory**)(moduleMemory + WebAssemblyModule::GetMemoryOffset());
  2064. arrayBuffer = mem->GetBuffer();
  2065. reservationSize = MAX_WASM__ARRAYBUFFER_LENGTH;
  2066. }
  2067. else
  2068. #endif
  2069. {
  2070. arrayBuffer = *(ArrayBuffer**)(moduleMemory + AsmJsModuleMemory::MemoryTableBeginOffset);
  2071. reservationSize = MAX_ASMJS_ARRAYBUFFER_LENGTH;
  2072. }
  2073. if (!arrayBuffer || !arrayBuffer->GetBuffer())
  2074. {
  2075. // don't have a heap buffer for asm.js... so this shouldn't be an asm.js heap access
  2076. return false;
  2077. }
  2078. uintptr_t bufferAddr = (uintptr_t)arrayBuffer->GetBuffer();
  2079. uint bufferLength = arrayBuffer->GetByteLength();
  2080. if (!isWasmOnly && !arrayBuffer->IsValidAsmJsBufferLength(bufferLength))
  2081. {
  2082. return false;
  2083. }
  2084. uintptr_t faultingAddr = helper.GetFaultingAddress();
  2085. if (faultingAddr < bufferAddr)
  2086. {
  2087. return false;
  2088. }
  2089. if (faultingAddr >= bufferAddr + reservationSize)
  2090. {
  2091. return false;
  2092. }
  2093. }
  2094. PEXCEPTION_POINTERS exceptionInfo = helper.GetExceptionInfo();
  2095. BYTE* pc = (BYTE*)exceptionInfo->ExceptionRecord->ExceptionAddress;
  2096. ArrayAccessDecoder::InstructionData instrData = ArrayAccessDecoder::CheckValidInstr(pc, exceptionInfo);
  2097. // Check If the instruction is valid
  2098. if (instrData.isInvalidInstr)
  2099. {
  2100. return false;
  2101. }
  2102. // If we didn't find the array buffer, ignore
  2103. if (!instrData.bufferValue)
  2104. {
  2105. return false;
  2106. }
  2107. if (isWasmOnly)
  2108. {
  2109. JavascriptError::ThrowWebAssemblyRuntimeError(func->GetScriptContext(), WASMERR_ArrayIndexOutOfRange);
  2110. }
  2111. // SIMD loads/stores do bounds checks.
  2112. if (instrData.isSimd)
  2113. {
  2114. return false;
  2115. }
  2116. // Set the dst reg if the instr type is load
  2117. if (instrData.isLoad)
  2118. {
  2119. Var exceptionInfoReg = exceptionInfo->ContextRecord;
  2120. Var* exceptionInfoIntReg = (Var*)((uint64)exceptionInfoReg + offsetof(CONTEXT, Rax)); // offset in the contextRecord for RAX , the assert below checks for any change in the exceptionInfo struct
  2121. Var* exceptionInfoFloatReg = (Var*)((uint64)exceptionInfoReg + offsetof(CONTEXT, Xmm0));// offset in the contextRecord for XMM0 , the assert below checks for any change in the exceptionInfo struct
  2122. Assert((DWORD64)*exceptionInfoIntReg == exceptionInfo->ContextRecord->Rax);
  2123. Assert((uint64)*exceptionInfoFloatReg == exceptionInfo->ContextRecord->Xmm0.Low);
  2124. if (instrData.isLoad)
  2125. {
  2126. double nanVal = JavascriptNumber::NaN;
  2127. if (instrData.isFloat64)
  2128. {
  2129. double* destRegLocation = (double*)((uint64)exceptionInfoFloatReg + 16 * (instrData.dstReg));
  2130. *destRegLocation = nanVal;
  2131. }
  2132. else if (instrData.isFloat32)
  2133. {
  2134. float* destRegLocation = (float*)((uint64)exceptionInfoFloatReg + 16 * (instrData.dstReg));
  2135. *destRegLocation = (float)nanVal;
  2136. }
  2137. else
  2138. {
  2139. uint64* destRegLocation = (uint64*)((uint64)exceptionInfoIntReg + 8 * (instrData.dstReg));
  2140. *destRegLocation = 0;
  2141. }
  2142. }
  2143. }
  2144. // Add the bytes read to Rip and set it as new Rip
  2145. exceptionInfo->ContextRecord->Rip = exceptionInfo->ContextRecord->Rip + instrData.instrSizeInByte;
  2146. return true;
  2147. }
  2148. #endif
  2149. #endif
  2150. #endif
  2151. #endif
  2152. int JavascriptFunction::CallRootEventFilter(int exceptionCode, PEXCEPTION_POINTERS exceptionInfo)
  2153. {
  2154. #if ENABLE_NATIVE_CODEGEN
  2155. #if defined(_M_IX86) || defined(_M_X64)
  2156. ExceptionFilterHelper helper(exceptionInfo);
  2157. CheckWasmMathException(exceptionCode, helper);
  2158. #if ENABLE_FAST_ARRAYBUFFER
  2159. if (ResumeForOutOfBoundsArrayRefs(exceptionCode, helper))
  2160. {
  2161. return EXCEPTION_CONTINUE_EXECUTION;
  2162. }
  2163. #endif
  2164. #endif
  2165. #endif
  2166. return EXCEPTION_CONTINUE_SEARCH;
  2167. }
  2168. #if DBG
  2169. void JavascriptFunction::VerifyEntryPoint()
  2170. {
  2171. JavascriptMethod callEntryPoint = this->GetType()->GetEntryPoint();
  2172. if (this->IsCrossSiteObject())
  2173. {
  2174. Assert(CrossSite::IsThunk(callEntryPoint));
  2175. }
  2176. else if (ScriptFunction::Is(this))
  2177. {
  2178. }
  2179. else
  2180. {
  2181. JavascriptMethod originalEntryPoint = this->GetFunctionInfo()->GetOriginalEntryPoint();
  2182. Assert(callEntryPoint == originalEntryPoint || callEntryPoint == ProfileEntryThunk
  2183. || (this->GetScriptContext()->GetHostScriptContext()
  2184. && this->GetScriptContext()->GetHostScriptContext()->IsHostCrossSiteThunk(callEntryPoint))
  2185. );
  2186. }
  2187. }
  2188. #endif
  2189. /*static*/
  2190. PropertyId const JavascriptFunction::specialPropertyIds[] =
  2191. {
  2192. PropertyIds::caller,
  2193. PropertyIds::arguments
  2194. };
  2195. bool JavascriptFunction::HasRestrictedProperties() const
  2196. {
  2197. return !(
  2198. this->functionInfo->IsClassMethod() ||
  2199. this->functionInfo->IsClassConstructor() ||
  2200. this->functionInfo->IsLambda() ||
  2201. this->functionInfo->IsAsync() ||
  2202. this->IsGeneratorFunction() ||
  2203. this->IsBoundFunction() ||
  2204. this->IsStrictMode()
  2205. );
  2206. }
  2207. PropertyQueryFlags JavascriptFunction::HasPropertyQuery(PropertyId propertyId)
  2208. {
  2209. switch (propertyId)
  2210. {
  2211. case PropertyIds::caller:
  2212. case PropertyIds::arguments:
  2213. if (this->HasRestrictedProperties())
  2214. {
  2215. return PropertyQueryFlags::Property_Found;
  2216. }
  2217. break;
  2218. case PropertyIds::length:
  2219. if (this->IsScriptFunction())
  2220. {
  2221. return PropertyQueryFlags::Property_Found;
  2222. }
  2223. break;
  2224. }
  2225. return DynamicObject::HasPropertyQuery(propertyId);
  2226. }
  2227. BOOL JavascriptFunction::GetAccessors(PropertyId propertyId, Var *getter, Var *setter, ScriptContext * requestContext)
  2228. {
  2229. Assert(!this->IsBoundFunction());
  2230. Assert(propertyId != Constants::NoProperty);
  2231. Assert(getter);
  2232. Assert(setter);
  2233. Assert(requestContext);
  2234. if (this->HasRestrictedProperties())
  2235. {
  2236. switch (propertyId)
  2237. {
  2238. case PropertyIds::caller:
  2239. case PropertyIds::arguments:
  2240. if (this->GetEntryPoint() == JavascriptFunction::PrototypeEntryPoint)
  2241. {
  2242. *setter = *getter = requestContext->GetLibrary()->GetThrowTypeErrorRestrictedPropertyAccessorFunction();
  2243. return true;
  2244. }
  2245. break;
  2246. }
  2247. }
  2248. return __super::GetAccessors(propertyId, getter, setter, requestContext);
  2249. }
  2250. DescriptorFlags JavascriptFunction::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2251. {
  2252. DescriptorFlags flags;
  2253. if (GetSetterBuiltIns(propertyId, setterValue, info, requestContext, &flags))
  2254. {
  2255. return flags;
  2256. }
  2257. return __super::GetSetter(propertyId, setterValue, info, requestContext);
  2258. }
  2259. DescriptorFlags JavascriptFunction::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  2260. {
  2261. DescriptorFlags flags;
  2262. PropertyRecord const* propertyRecord;
  2263. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  2264. if (propertyRecord != nullptr && GetSetterBuiltIns(propertyRecord->GetPropertyId(), setterValue, info, requestContext, &flags))
  2265. {
  2266. return flags;
  2267. }
  2268. return __super::GetSetter(propertyNameString, setterValue, info, requestContext);
  2269. }
  2270. bool JavascriptFunction::GetSetterBuiltIns(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext, DescriptorFlags* descriptorFlags)
  2271. {
  2272. Assert(propertyId != Constants::NoProperty);
  2273. Assert(setterValue);
  2274. Assert(requestContext);
  2275. switch (propertyId)
  2276. {
  2277. case PropertyIds::caller:
  2278. case PropertyIds::arguments:
  2279. if (this->HasRestrictedProperties()) {
  2280. PropertyValueInfo::SetNoCache(info, this);
  2281. if (this->GetEntryPoint() == JavascriptFunction::PrototypeEntryPoint)
  2282. {
  2283. *setterValue = requestContext->GetLibrary()->GetThrowTypeErrorRestrictedPropertyAccessorFunction();
  2284. *descriptorFlags = Accessor;
  2285. }
  2286. else
  2287. {
  2288. *descriptorFlags = Data;
  2289. }
  2290. return true;
  2291. }
  2292. break;
  2293. }
  2294. return false;
  2295. }
  2296. BOOL JavascriptFunction::IsConfigurable(PropertyId propertyId)
  2297. {
  2298. if (DynamicObject::GetPropertyIndex(propertyId) == Constants::NoSlot)
  2299. {
  2300. switch (propertyId)
  2301. {
  2302. case PropertyIds::caller:
  2303. case PropertyIds::arguments:
  2304. if (this->HasRestrictedProperties())
  2305. {
  2306. return false;
  2307. }
  2308. break;
  2309. case PropertyIds::length:
  2310. if (this->IsScriptFunction() || this->IsBoundFunction())
  2311. {
  2312. return true;
  2313. }
  2314. break;
  2315. }
  2316. }
  2317. return DynamicObject::IsConfigurable(propertyId);
  2318. }
  2319. BOOL JavascriptFunction::IsEnumerable(PropertyId propertyId)
  2320. {
  2321. if (DynamicObject::GetPropertyIndex(propertyId) == Constants::NoSlot)
  2322. {
  2323. switch (propertyId)
  2324. {
  2325. case PropertyIds::caller:
  2326. case PropertyIds::arguments:
  2327. if (this->HasRestrictedProperties())
  2328. {
  2329. return false;
  2330. }
  2331. break;
  2332. case PropertyIds::length:
  2333. if (this->IsScriptFunction())
  2334. {
  2335. return false;
  2336. }
  2337. break;
  2338. }
  2339. }
  2340. return DynamicObject::IsEnumerable(propertyId);
  2341. }
  2342. BOOL JavascriptFunction::IsWritable(PropertyId propertyId)
  2343. {
  2344. if (DynamicObject::GetPropertyIndex(propertyId) == Constants::NoSlot)
  2345. {
  2346. switch (propertyId)
  2347. {
  2348. case PropertyIds::caller:
  2349. case PropertyIds::arguments:
  2350. if (this->HasRestrictedProperties())
  2351. {
  2352. return false;
  2353. }
  2354. break;
  2355. case PropertyIds::length:
  2356. if (this->IsScriptFunction())
  2357. {
  2358. return false;
  2359. }
  2360. break;
  2361. }
  2362. }
  2363. return DynamicObject::IsWritable(propertyId);
  2364. }
  2365. BOOL JavascriptFunction::GetSpecialPropertyName(uint32 index, JavascriptString ** propertyName, ScriptContext * requestContext)
  2366. {
  2367. uint length = GetSpecialPropertyCount();
  2368. if (index < length)
  2369. {
  2370. Assert(DynamicObject::GetPropertyIndex(specialPropertyIds[index]) == Constants::NoSlot);
  2371. *propertyName = requestContext->GetPropertyString(specialPropertyIds[index]);
  2372. return true;
  2373. }
  2374. if (index == length)
  2375. {
  2376. if (this->IsScriptFunction() || this->IsBoundFunction())
  2377. {
  2378. if (DynamicObject::GetPropertyIndex(PropertyIds::length) == Constants::NoSlot)
  2379. {
  2380. //Only for user defined functions length is a special property.
  2381. *propertyName = requestContext->GetPropertyString(PropertyIds::length);
  2382. return true;
  2383. }
  2384. }
  2385. }
  2386. return false;
  2387. }
  2388. // Returns the number of special non-enumerable properties this type has.
  2389. uint JavascriptFunction::GetSpecialPropertyCount() const
  2390. {
  2391. return this->HasRestrictedProperties() ? _countof(specialPropertyIds) : 0;
  2392. }
  2393. // Returns the list of special non-enumerable properties for the type.
  2394. PropertyId const * JavascriptFunction::GetSpecialPropertyIds() const
  2395. {
  2396. return specialPropertyIds;
  2397. }
  2398. PropertyQueryFlags JavascriptFunction::GetPropertyReferenceQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  2399. {
  2400. return JavascriptFunction::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  2401. }
  2402. JavascriptFunction* JavascriptFunction::FindCaller(BOOL* foundThis, JavascriptFunction* nullValue, ScriptContext* requestContext)
  2403. {
  2404. ScriptContext* scriptContext = this->GetScriptContext();
  2405. JavascriptFunction* funcCaller = nullValue;
  2406. JavascriptStackWalker walker(scriptContext);
  2407. if (walker.WalkToTarget(this))
  2408. {
  2409. *foundThis = TRUE;
  2410. while (walker.GetCaller(&funcCaller))
  2411. {
  2412. if (walker.IsCallerGlobalFunction())
  2413. {
  2414. // Caller is global/eval. If it's eval, keep looking.
  2415. // Otherwise, return null.
  2416. if (walker.IsEvalCaller())
  2417. {
  2418. continue;
  2419. }
  2420. funcCaller = nullValue;
  2421. }
  2422. break;
  2423. }
  2424. if (funcCaller == nullptr)
  2425. {
  2426. // We no longer return Null objects as JavascriptFunctions, so we don't have to worry about
  2427. // cross-context null objects. We do want to clean up null pointers though, since some call
  2428. // later in this function may depend on non-nullptr calls.
  2429. funcCaller = nullValue;
  2430. }
  2431. if (ScriptFunction::Is(funcCaller))
  2432. {
  2433. // If this is the internal function of a generator function then return the original generator function
  2434. funcCaller = ScriptFunction::FromVar(funcCaller)->GetRealFunctionObject();
  2435. // This function is escaping, so make sure there isn't some nested parent that has a cached scope.
  2436. if (ScriptFunction::Is(funcCaller))
  2437. {
  2438. FrameDisplay * pFrameDisplay = Js::ScriptFunction::FromVar(funcCaller)->GetEnvironment();
  2439. uint length = (uint)pFrameDisplay->GetLength();
  2440. for (uint i = 0; i < length; i++)
  2441. {
  2442. void * scope = pFrameDisplay->GetItem(i);
  2443. if (!Js::ScopeSlots::Is(scope) && Js::ActivationObjectEx::Is(scope))
  2444. {
  2445. Js::ActivationObjectEx::FromVar(scope)->InvalidateCachedScope();
  2446. }
  2447. }
  2448. }
  2449. }
  2450. }
  2451. return StackScriptFunction::EnsureBoxed(BOX_PARAM(funcCaller, nullptr, _u("caller")));
  2452. }
  2453. BOOL JavascriptFunction::GetCallerProperty(Var originalInstance, Var* value, ScriptContext* requestContext)
  2454. {
  2455. ScriptContext* scriptContext = this->GetScriptContext();
  2456. *value = nullptr;
  2457. if (this->IsStrictMode())
  2458. {
  2459. return false;
  2460. }
  2461. if (this->GetEntryPoint() == JavascriptFunction::PrototypeEntryPoint)
  2462. {
  2463. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2464. {
  2465. JavascriptFunction* accessor = requestContext->GetLibrary()->GetThrowTypeErrorRestrictedPropertyAccessorFunction();
  2466. *value = CALL_FUNCTION(scriptContext->GetThreadContext(), accessor, CallInfo(1), originalInstance);
  2467. }
  2468. return true;
  2469. }
  2470. JavascriptFunction* nullValue = (JavascriptFunction*)requestContext->GetLibrary()->GetNull();
  2471. if (this->IsLibraryCode()) // Hide .caller for builtins
  2472. {
  2473. *value = nullValue;
  2474. return true;
  2475. }
  2476. // Use a stack walker to find this function's frame. If we find it, find its caller.
  2477. BOOL foundThis = FALSE;
  2478. JavascriptFunction* funcCaller = FindCaller(&foundThis, nullValue, requestContext);
  2479. // WOOB #1142373. We are trying to get the caller in window.onerror = function(){alert(arguments.callee.caller);} case
  2480. // window.onerror is called outside of JavascriptFunction::CallFunction loop, so the caller information is not available
  2481. // in the stack to be found by the stack walker.
  2482. // As we had already walked the stack at throw time retrieve the caller information stored in the exception object
  2483. // The down side is that we can only find the top level caller at thrown time, and won't be able to find caller.caller etc.
  2484. // We'll try to fetch the caller only if we can find the function on the stack, but we can't find the caller if and we are in
  2485. // window.onerror scenario.
  2486. *value = funcCaller;
  2487. if (foundThis && funcCaller == nullValue && scriptContext->GetThreadContext()->HasUnhandledException())
  2488. {
  2489. Js::JavascriptExceptionObject* unhandledExceptionObject = scriptContext->GetThreadContext()->GetUnhandledExceptionObject();
  2490. if (unhandledExceptionObject)
  2491. {
  2492. JavascriptFunction* exceptionFunction = unhandledExceptionObject->GetFunction();
  2493. // This is for getcaller in window.onError. The behavior is different in different browsers
  2494. if (exceptionFunction
  2495. && scriptContext == exceptionFunction->GetScriptContext()
  2496. && exceptionFunction->IsScriptFunction()
  2497. && !exceptionFunction->GetFunctionBody()->GetIsGlobalFunc())
  2498. {
  2499. *value = exceptionFunction;
  2500. }
  2501. }
  2502. }
  2503. else if (foundThis && scriptContext != funcCaller->GetScriptContext())
  2504. {
  2505. HRESULT hr = scriptContext->GetHostScriptContext()->CheckCrossDomainScriptContext(funcCaller->GetScriptContext());
  2506. if (S_OK != hr)
  2507. {
  2508. *value = nullValue;
  2509. }
  2510. else
  2511. {
  2512. *value = CrossSite::MarshalVar(requestContext, funcCaller);
  2513. }
  2514. }
  2515. if (Js::JavascriptFunction::Is(*value) && Js::JavascriptFunction::FromVar(*value)->IsStrictMode())
  2516. {
  2517. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2518. {
  2519. // ES5.15.3.5.4 [[Get]] (P) -- access to the 'caller' property of strict mode function results in TypeError.
  2520. // Note that for caller coming from remote context (see the check right above) we can't call IsStrictMode()
  2521. // unless CheckCrossDomainScriptContext succeeds. If it fails we don't know whether caller is strict mode
  2522. // function or not and throw if it's not, so just return Null.
  2523. JavascriptError::ThrowTypeError(scriptContext, JSERR_AccessRestrictedProperty);
  2524. }
  2525. }
  2526. return true;
  2527. }
  2528. BOOL JavascriptFunction::GetArgumentsProperty(Var originalInstance, Var* value, ScriptContext* requestContext)
  2529. {
  2530. ScriptContext* scriptContext = this->GetScriptContext();
  2531. if (this->IsStrictMode())
  2532. {
  2533. return false;
  2534. }
  2535. if (this->GetEntryPoint() == JavascriptFunction::PrototypeEntryPoint)
  2536. {
  2537. if (scriptContext->GetThreadContext()->RecordImplicitException())
  2538. {
  2539. JavascriptFunction* accessor = requestContext->GetLibrary()->GetThrowTypeErrorRestrictedPropertyAccessorFunction();
  2540. *value = CALL_FUNCTION(scriptContext->GetThreadContext(), accessor, CallInfo(1), originalInstance);
  2541. }
  2542. return true;
  2543. }
  2544. if (!this->IsScriptFunction())
  2545. {
  2546. // builtin function do not have an argument object - return null.
  2547. *value = scriptContext->GetLibrary()->GetNull();
  2548. return true;
  2549. }
  2550. // Use a stack walker to find this function's frame. If we find it, compute its arguments.
  2551. // Note that we are currently unable to guarantee that the binding between formal arguments
  2552. // and foo.arguments[n] will be maintained after this object is returned.
  2553. JavascriptStackWalker walker(scriptContext);
  2554. if (walker.WalkToTarget(this))
  2555. {
  2556. if (walker.IsCallerGlobalFunction())
  2557. {
  2558. *value = requestContext->GetLibrary()->GetNull();
  2559. }
  2560. else
  2561. {
  2562. Var args = nullptr;
  2563. //Create a copy of the arguments and return it.
  2564. const CallInfo callInfo = walker.GetCallInfo();
  2565. args = JavascriptOperators::LoadHeapArguments(
  2566. this, callInfo.Count - 1,
  2567. walker.GetJavascriptArgs(),
  2568. scriptContext->GetLibrary()->GetNull(),
  2569. scriptContext->GetLibrary()->GetNull(),
  2570. scriptContext,
  2571. /* formalsAreLetDecls */ false);
  2572. *value = args;
  2573. }
  2574. }
  2575. else
  2576. {
  2577. *value = scriptContext->GetLibrary()->GetNull();
  2578. }
  2579. return true;
  2580. }
  2581. PropertyQueryFlags JavascriptFunction::GetPropertyQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  2582. {
  2583. BOOL result = JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext)) ? TRUE : FALSE;
  2584. if (result)
  2585. {
  2586. if (propertyId == PropertyIds::prototype)
  2587. {
  2588. PropertyValueInfo::DisableStoreFieldCache(info);
  2589. }
  2590. }
  2591. else
  2592. {
  2593. GetPropertyBuiltIns(originalInstance, propertyId, value, requestContext, &result);
  2594. }
  2595. return JavascriptConversion::BooleanToPropertyQueryFlags(result);
  2596. }
  2597. PropertyQueryFlags JavascriptFunction::GetPropertyQuery(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  2598. {
  2599. BOOL result;
  2600. PropertyRecord const* propertyRecord;
  2601. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  2602. result = JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::GetPropertyQuery(originalInstance, propertyNameString, value, info, requestContext)) ? TRUE : FALSE;
  2603. if (result)
  2604. {
  2605. if (propertyRecord != nullptr && propertyRecord->GetPropertyId() == PropertyIds::prototype)
  2606. {
  2607. PropertyValueInfo::DisableStoreFieldCache(info);
  2608. }
  2609. return JavascriptConversion::BooleanToPropertyQueryFlags(result);
  2610. }
  2611. if (propertyRecord != nullptr)
  2612. {
  2613. GetPropertyBuiltIns(originalInstance, propertyRecord->GetPropertyId(), value, requestContext, &result);
  2614. }
  2615. return JavascriptConversion::BooleanToPropertyQueryFlags(result);
  2616. }
  2617. bool JavascriptFunction::GetPropertyBuiltIns(Var originalInstance, PropertyId propertyId, Var* value, ScriptContext* requestContext, BOOL* result)
  2618. {
  2619. if (propertyId == PropertyIds::caller && this->HasRestrictedProperties())
  2620. {
  2621. *result = GetCallerProperty(originalInstance, value, requestContext);
  2622. return true;
  2623. }
  2624. if (propertyId == PropertyIds::arguments && this->HasRestrictedProperties())
  2625. {
  2626. *result = GetArgumentsProperty(originalInstance, value, requestContext);
  2627. return true;
  2628. }
  2629. if (propertyId == PropertyIds::length)
  2630. {
  2631. FunctionProxy *proxy = this->GetFunctionProxy();
  2632. if (proxy)
  2633. {
  2634. *value = TaggedInt::ToVarUnchecked(proxy->EnsureDeserialized()->GetReportedInParamsCount() - 1);
  2635. *result = true;
  2636. return true;
  2637. }
  2638. }
  2639. return false;
  2640. }
  2641. BOOL JavascriptFunction::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  2642. {
  2643. bool isReadOnly = false;
  2644. switch (propertyId)
  2645. {
  2646. case PropertyIds::caller:
  2647. if (this->HasRestrictedProperties())
  2648. {
  2649. isReadOnly = true;
  2650. }
  2651. break;
  2652. case PropertyIds::arguments:
  2653. if (this->HasRestrictedProperties())
  2654. {
  2655. isReadOnly = true;
  2656. }
  2657. break;
  2658. case PropertyIds::length:
  2659. if (this->IsScriptFunction())
  2660. {
  2661. isReadOnly = true;
  2662. }
  2663. break;
  2664. }
  2665. if (isReadOnly)
  2666. {
  2667. JavascriptError::ThrowCantAssignIfStrictMode(flags, this->GetScriptContext());
  2668. return false;
  2669. }
  2670. BOOL result = DynamicObject::SetProperty(propertyId, value, flags, info);
  2671. if (propertyId == PropertyIds::prototype || propertyId == PropertyIds::_symbolHasInstance)
  2672. {
  2673. PropertyValueInfo::SetNoCache(info, this);
  2674. InvalidateConstructorCacheOnPrototypeChange();
  2675. this->GetScriptContext()->GetThreadContext()->InvalidateIsInstInlineCachesForFunction(this);
  2676. }
  2677. return result;
  2678. }
  2679. BOOL JavascriptFunction::SetPropertyWithAttributes(PropertyId propertyId, Var value, PropertyAttributes attributes, PropertyValueInfo* info, PropertyOperationFlags flags, SideEffects possibleSideEffects)
  2680. {
  2681. BOOL result = __super::SetPropertyWithAttributes(propertyId, value, attributes, info, flags, possibleSideEffects);
  2682. if (propertyId == PropertyIds::prototype || propertyId == PropertyIds::_symbolHasInstance)
  2683. {
  2684. PropertyValueInfo::SetNoCache(info, this);
  2685. InvalidateConstructorCacheOnPrototypeChange();
  2686. this->GetScriptContext()->GetThreadContext()->InvalidateIsInstInlineCachesForFunction(this);
  2687. }
  2688. return result;
  2689. }
  2690. BOOL JavascriptFunction::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  2691. {
  2692. PropertyRecord const * propertyRecord;
  2693. this->GetScriptContext()->FindPropertyRecord(propertyNameString, &propertyRecord);
  2694. if (propertyRecord != nullptr)
  2695. {
  2696. return JavascriptFunction::SetProperty(propertyRecord->GetPropertyId(), value, flags, info);
  2697. }
  2698. else
  2699. {
  2700. return DynamicObject::SetProperty(propertyNameString, value, flags, info);
  2701. }
  2702. }
  2703. BOOL JavascriptFunction::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
  2704. {
  2705. switch (propertyId)
  2706. {
  2707. case PropertyIds::caller:
  2708. case PropertyIds::arguments:
  2709. if (this->HasRestrictedProperties())
  2710. {
  2711. JavascriptError::ThrowCantDeleteIfStrictMode(flags, this->GetScriptContext(), this->GetScriptContext()->GetPropertyName(propertyId)->GetBuffer());
  2712. return false;
  2713. }
  2714. break;
  2715. case PropertyIds::length:
  2716. if (this->IsScriptFunction())
  2717. {
  2718. JavascriptError::ThrowCantDeleteIfStrictMode(flags, this->GetScriptContext(), this->GetScriptContext()->GetPropertyName(propertyId)->GetBuffer());
  2719. return false;
  2720. }
  2721. break;
  2722. }
  2723. BOOL result = DynamicObject::DeleteProperty(propertyId, flags);
  2724. if (result && (propertyId == PropertyIds::prototype || propertyId == PropertyIds::_symbolHasInstance))
  2725. {
  2726. InvalidateConstructorCacheOnPrototypeChange();
  2727. this->GetScriptContext()->GetThreadContext()->InvalidateIsInstInlineCachesForFunction(this);
  2728. }
  2729. return result;
  2730. }
  2731. BOOL JavascriptFunction::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
  2732. {
  2733. JsUtil::CharacterBuffer<WCHAR> propertyName(propertyNameString->GetString(), propertyNameString->GetLength());
  2734. if (BuiltInPropertyRecords::caller.Equals(propertyName) || BuiltInPropertyRecords::arguments.Equals(propertyName))
  2735. {
  2736. if (this->HasRestrictedProperties())
  2737. {
  2738. JavascriptError::ThrowCantDeleteIfStrictMode(flags, this->GetScriptContext(), propertyNameString->GetString());
  2739. return false;
  2740. }
  2741. }
  2742. else if (BuiltInPropertyRecords::length.Equals(propertyName))
  2743. {
  2744. if (this->IsScriptFunction())
  2745. {
  2746. JavascriptError::ThrowCantDeleteIfStrictMode(flags, this->GetScriptContext(), propertyNameString->GetString());
  2747. return false;
  2748. }
  2749. }
  2750. BOOL result = DynamicObject::DeleteProperty(propertyNameString, flags);
  2751. if (result && (BuiltInPropertyRecords::prototype.Equals(propertyName) || BuiltInPropertyRecords::_symbolHasInstance.Equals(propertyName)))
  2752. {
  2753. InvalidateConstructorCacheOnPrototypeChange();
  2754. this->GetScriptContext()->GetThreadContext()->InvalidateIsInstInlineCachesForFunction(this);
  2755. }
  2756. return result;
  2757. }
  2758. void JavascriptFunction::InvalidateConstructorCacheOnPrototypeChange()
  2759. {
  2760. Assert(this->constructorCache != nullptr);
  2761. #if DBG_DUMP
  2762. if (PHASE_TRACE1(Js::ConstructorCachePhase))
  2763. {
  2764. // This is under DBG_DUMP so we can allow a check
  2765. ParseableFunctionInfo* body = this->GetFunctionProxy() != nullptr ? this->GetFunctionProxy()->EnsureDeserialized() : nullptr;
  2766. const char16* ctorName = body != nullptr ? body->GetDisplayName() : _u("<unknown>");
  2767. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2768. Output::Print(_u("CtorCache: before invalidating cache (0x%p) for ctor %s (%s): "), PointerValue(this->constructorCache), ctorName,
  2769. body ? body->GetDebugNumberSet(debugStringBuffer) : _u("(null)"));
  2770. this->constructorCache->Dump();
  2771. Output::Print(_u("\n"));
  2772. Output::Flush();
  2773. }
  2774. #endif
  2775. this->constructorCache->InvalidateOnPrototypeChange();
  2776. #if DBG_DUMP
  2777. if (PHASE_TRACE1(Js::ConstructorCachePhase))
  2778. {
  2779. // This is under DBG_DUMP so we can allow a check
  2780. ParseableFunctionInfo* body = this->GetFunctionProxy() != nullptr ? this->GetFunctionProxy()->EnsureDeserialized() : nullptr;
  2781. const char16* ctorName = body != nullptr ? body->GetDisplayName() : _u("<unknown>");
  2782. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  2783. Output::Print(_u("CtorCache: after invalidating cache (0x%p) for ctor %s (%s): "), PointerValue(this->constructorCache), ctorName,
  2784. body ? body->GetDebugNumberSet(debugStringBuffer) : _u("(null)"));
  2785. this->constructorCache->Dump();
  2786. Output::Print(_u("\n"));
  2787. Output::Flush();
  2788. }
  2789. #endif
  2790. }
  2791. BOOL JavascriptFunction::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  2792. {
  2793. JavascriptString * pString = NULL;
  2794. Var sourceString = this->GetSourceString();
  2795. if (sourceString == nullptr)
  2796. {
  2797. FunctionProxy* proxy = this->GetFunctionProxy();
  2798. if (proxy)
  2799. {
  2800. ParseableFunctionInfo * func = proxy->EnsureDeserialized();
  2801. Utf8SourceInfo* sourceInfo = func->GetUtf8SourceInfo();
  2802. if (sourceInfo->GetIsLibraryCode())
  2803. {
  2804. charcount_t displayNameLength = 0;
  2805. pString = JavascriptFunction::GetLibraryCodeDisplayString(this->GetScriptContext(), func->GetShortDisplayName(&displayNameLength));
  2806. }
  2807. else
  2808. {
  2809. charcount_t count = min(DIAG_MAX_FUNCTION_STRING, func->LengthInChars());
  2810. utf8::DecodeOptions options = sourceInfo->IsCesu8() ? utf8::doAllowThreeByteSurrogates : utf8::doDefault;
  2811. LPCUTF8 source = func->GetSource(_u("JavascriptFunction::GetDiagValueString"));
  2812. size_t cbLength = sourceInfo->GetCbLength(_u("JavascriptFunction::GetDiagValueString"));
  2813. size_t cbIndex = utf8::CharacterIndexToByteIndex(source, cbLength, count, options);
  2814. utf8::DecodeUnitsInto(stringBuilder->AllocBufferSpace(count), source, source + cbIndex, options);
  2815. stringBuilder->IncreaseCount(count);
  2816. return TRUE;
  2817. }
  2818. }
  2819. else
  2820. {
  2821. pString = GetLibrary()->GetFunctionDisplayString();
  2822. }
  2823. }
  2824. else
  2825. {
  2826. if (TaggedInt::Is(sourceString))
  2827. {
  2828. pString = GetNativeFunctionDisplayString(this->GetScriptContext(), this->GetScriptContext()->GetPropertyString(TaggedInt::ToInt32(sourceString)));
  2829. }
  2830. else
  2831. {
  2832. Assert(JavascriptString::Is(sourceString));
  2833. pString = JavascriptString::FromVar(sourceString);
  2834. }
  2835. }
  2836. Assert(pString);
  2837. stringBuilder->Append(pString->GetString(), pString->GetLength());
  2838. return TRUE;
  2839. }
  2840. BOOL JavascriptFunction::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  2841. {
  2842. stringBuilder->AppendCppLiteral(_u("Object, (Function)"));
  2843. return TRUE;
  2844. }
  2845. JavascriptString* JavascriptFunction::GetDisplayNameImpl() const
  2846. {
  2847. Assert(this->GetFunctionProxy() != nullptr); // The caller should guarantee a proxy exists
  2848. ParseableFunctionInfo * func = this->GetFunctionProxy()->EnsureDeserialized();
  2849. charcount_t length = 0;
  2850. const char16* name = func->GetShortDisplayName(&length);
  2851. return DisplayNameHelper(name, length);
  2852. }
  2853. JavascriptString* JavascriptFunction::DisplayNameHelper(const char16* name, charcount_t length) const
  2854. {
  2855. ScriptContext* scriptContext = this->GetScriptContext();
  2856. Assert(this->GetFunctionProxy() != nullptr); // The caller should guarantee a proxy exists
  2857. ParseableFunctionInfo * func = this->GetFunctionProxy()->EnsureDeserialized();
  2858. if (func->GetDisplayName() == Js::Constants::FunctionCode)
  2859. {
  2860. return LiteralString::NewCopyBuffer(Js::Constants::Anonymous, Js::Constants::AnonymousLength, scriptContext);
  2861. }
  2862. else if (func->GetIsAccessor())
  2863. {
  2864. const char16* accessorName = func->GetDisplayName();
  2865. if (accessorName[0] == _u('g'))
  2866. {
  2867. return LiteralString::Concat(LiteralString::NewCopySz(_u("get "), scriptContext), LiteralString::NewCopyBuffer(name, length, scriptContext));
  2868. }
  2869. AssertMsg(accessorName[0] == _u('s'), "should be a set");
  2870. return LiteralString::Concat(LiteralString::NewCopySz(_u("set "), scriptContext), LiteralString::NewCopyBuffer(name, length, scriptContext));
  2871. }
  2872. return LiteralString::NewCopyBuffer(name, length, scriptContext);
  2873. }
  2874. bool JavascriptFunction::GetFunctionName(JavascriptString** name) const
  2875. {
  2876. Assert(name != nullptr);
  2877. FunctionProxy* proxy = this->GetFunctionProxy();
  2878. JavascriptFunction* thisFunction = const_cast<JavascriptFunction*>(this);
  2879. if (proxy || thisFunction->IsBoundFunction() || JavascriptGeneratorFunction::Test(thisFunction) || JavascriptAsyncFunction::Test(thisFunction))
  2880. {
  2881. *name = GetDisplayNameImpl();
  2882. return true;
  2883. }
  2884. Assert(!ScriptFunction::Is(thisFunction));
  2885. return GetSourceStringName(name);
  2886. }
  2887. bool JavascriptFunction::GetSourceStringName(JavascriptString** name) const
  2888. {
  2889. Assert(name != nullptr);
  2890. ScriptContext* scriptContext = this->GetScriptContext();
  2891. Var sourceString = this->GetSourceString();
  2892. if (sourceString)
  2893. {
  2894. if (TaggedInt::Is(sourceString))
  2895. {
  2896. int32 propertyIdOfSourceString = TaggedInt::ToInt32(sourceString);
  2897. *name = scriptContext->GetPropertyString(propertyIdOfSourceString);
  2898. return true;
  2899. }
  2900. Assert(JavascriptString::Is(sourceString));
  2901. *name = JavascriptString::FromVar(sourceString);
  2902. return true;
  2903. }
  2904. return false;
  2905. }
  2906. JavascriptString* JavascriptFunction::GetDisplayName() const
  2907. {
  2908. ScriptContext* scriptContext = this->GetScriptContext();
  2909. FunctionProxy* proxy = this->GetFunctionProxy();
  2910. JavascriptLibrary* library = scriptContext->GetLibrary();
  2911. if (proxy)
  2912. {
  2913. ParseableFunctionInfo * func = proxy->EnsureDeserialized();
  2914. return LiteralString::NewCopySz(func->GetDisplayName(), scriptContext);
  2915. }
  2916. JavascriptString* sourceStringName = nullptr;
  2917. if (GetSourceStringName(&sourceStringName))
  2918. {
  2919. return sourceStringName;
  2920. }
  2921. return library->GetFunctionDisplayString();
  2922. }
  2923. Var JavascriptFunction::GetTypeOfString(ScriptContext * requestContext)
  2924. {
  2925. return requestContext->GetLibrary()->GetFunctionTypeDisplayString();
  2926. }
  2927. // Check if this function is native/script library code
  2928. bool JavascriptFunction::IsLibraryCode() const
  2929. {
  2930. return !this->IsScriptFunction() || this->GetFunctionProxy()->GetUtf8SourceInfo()->GetIsLibraryCode();
  2931. }
  2932. // Implementation of Function.prototype[@@hasInstance](V) as specified in 19.2.3.6 of ES6 spec
  2933. Var JavascriptFunction::EntrySymbolHasInstance(RecyclableObject* function, CallInfo callInfo, ...)
  2934. {
  2935. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  2936. ARGUMENTS(args, callInfo);
  2937. ScriptContext* scriptContext = function->GetScriptContext();
  2938. Assert(!(callInfo.Flags & CallFlags_New));
  2939. if (!JavascriptConversion::IsCallable(args[0]) || args.Info.Count < 2)
  2940. {
  2941. return JavascriptBoolean::ToVar(FALSE, scriptContext);
  2942. }
  2943. RecyclableObject * constructor = RecyclableObject::FromVar(args[0]);
  2944. Var instance = args[1];
  2945. Assert(JavascriptProxy::Is(constructor) || JavascriptFunction::Is(constructor));
  2946. return JavascriptBoolean::ToVar(constructor->HasInstance(instance, scriptContext, NULL), scriptContext);
  2947. }
  2948. BOOL JavascriptFunction::HasInstance(Var instance, ScriptContext* scriptContext, IsInstInlineCache* inlineCache)
  2949. {
  2950. Var funcPrototype;
  2951. if (this->GetTypeHandler()->GetHasKnownSlot0())
  2952. {
  2953. Assert(this->GetDynamicType()->GetTypeHandler()->GetPropertyId(scriptContext, (PropertyIndex)0) == PropertyIds::prototype);
  2954. funcPrototype = this->GetSlot(0);
  2955. }
  2956. else
  2957. {
  2958. funcPrototype = JavascriptOperators::GetProperty(this, PropertyIds::prototype, scriptContext, nullptr);
  2959. }
  2960. funcPrototype = CrossSite::MarshalVar(scriptContext, funcPrototype);
  2961. return JavascriptFunction::HasInstance(funcPrototype, instance, scriptContext, inlineCache, this);
  2962. }
  2963. BOOL JavascriptFunction::HasInstance(Var funcPrototype, Var instance, ScriptContext * scriptContext, IsInstInlineCache* inlineCache, JavascriptFunction *function)
  2964. {
  2965. BOOL result = FALSE;
  2966. JavascriptBoolean * javascriptResult;
  2967. //
  2968. // if "instance" is not a JavascriptObject, return false
  2969. //
  2970. if (!JavascriptOperators::IsObject(instance))
  2971. {
  2972. // Only update the cache for primitive cache if it is empty already for the JIT fast path
  2973. if (inlineCache && inlineCache->function == nullptr
  2974. && scriptContext == function->GetScriptContext())// only register when function has same scriptContext
  2975. {
  2976. inlineCache->Cache(RecyclableObject::Is(instance) ?
  2977. RecyclableObject::FromVar(instance)->GetType() : nullptr,
  2978. function, scriptContext->GetLibrary()->GetFalse(), scriptContext);
  2979. }
  2980. return result;
  2981. }
  2982. // If we have an instance of inline cache, let's try to use it to speed up the operation.
  2983. // We would like to catch all cases when we already know (by having checked previously)
  2984. // that an object on the left of instance of has been created by a function on the right,
  2985. // as well as when we already know the object on the left has not been created by a function on the right.
  2986. // In practice, we can do so only if the function matches the function in the cache, and the object's type matches the
  2987. // type in the cache. Notably, this typically means that if some of the objects evolved after construction,
  2988. // while others did not, we will miss the cache for one of the two (sets of objects).
  2989. // An important subtlety here arises when a function is called from different script contexts.
  2990. // Suppose we called function foo from script context A, and we pass it an object o created in the same script context.
  2991. // When function foo checks if object o is an instance of itself (function foo) for the first time (from context A) we will
  2992. // populate the cache with function foo and object o's type (which is permanently bound to the script context A,
  2993. // in which object o was created). If we later invoked function foo from script context B and perform the same instance-of check,
  2994. // the function will still match the function in the cache (because objects' identities do not change during cross-context marshalling).
  2995. // However, object o's type (even if it is of the same "shape" as before) will be different, because the object types are permanently
  2996. // bound and unique to the script context from which they were created. Hence, the cache may miss, even if the function matches.
  2997. if (inlineCache != nullptr)
  2998. {
  2999. Assert(function != nullptr);
  3000. if (inlineCache->TryGetResult(instance, function, &javascriptResult))
  3001. {
  3002. return javascriptResult == scriptContext->GetLibrary()->GetTrue();
  3003. }
  3004. }
  3005. // If we are here, then me must have missed the cache. This may be because:
  3006. // a) the cache has never been populated in the first place,
  3007. // b) the cache has been populated, but for an object of a different type (even if the object was created by the same constructor function),
  3008. // c) the cache has been populated, but for a different function,
  3009. // d) the cache has been populated, even for the same object type and function, but has since been invalidated, because the function's
  3010. // prototype property has been changed (see JavascriptFunction::SetProperty and ThreadContext::InvalidateIsInstInlineCachesForFunction).
  3011. // We may even miss the cache if we ask again about the very same object the very same function the cache was populated with.
  3012. // This subtlety arises when a function is called from two (or more) different script contexts.
  3013. // Suppose we called function foo from script context A, and passed it an object o created in the same script context.
  3014. // When function foo checks if object o is an instance of itself (function foo) for the first time (from context A) we will
  3015. // populate the cache with function foo and object o's type (which is permanently bound to the script context A,
  3016. // in which object o was created). If we later invoked function foo from script context B and perform the same instance of check,
  3017. // the function will still match the function in the cache (because objects' identities do not change during cross-context marshalling).
  3018. // However, object o's type (even if it is of the same "shape" as before, and even if o is the very same object) will be different,
  3019. // because the object types are permanently bound and unique to the script context from which they were created.
  3020. Var prototype = JavascriptOperators::GetPrototype(RecyclableObject::FromVar(instance));
  3021. if (!JavascriptOperators::IsObject(funcPrototype))
  3022. {
  3023. JavascriptError::ThrowTypeError(scriptContext, JSERR_InvalidPrototype);
  3024. }
  3025. // Since we missed the cache, we must now walk the prototype chain of the object to check if the given function's prototype is somewhere in
  3026. // that chain. If it is, we return true. Otherwise (i.e., we hit the end of the chain before finding the function's prototype) we return false.
  3027. while (JavascriptOperators::GetTypeId(prototype) != TypeIds_Null)
  3028. {
  3029. if (prototype == funcPrototype)
  3030. {
  3031. result = TRUE;
  3032. break;
  3033. }
  3034. prototype = JavascriptOperators::GetPrototype(RecyclableObject::FromVar(prototype));
  3035. }
  3036. // Now that we know the answer, let's cache it for next time if we have a cache.
  3037. if (inlineCache != NULL)
  3038. {
  3039. Assert(function != NULL);
  3040. JavascriptBoolean * boolResult = result ? scriptContext->GetLibrary()->GetTrue() :
  3041. scriptContext->GetLibrary()->GetFalse();
  3042. Type * instanceType = RecyclableObject::FromVar(instance)->GetType();
  3043. if (!instanceType->HasSpecialPrototype()
  3044. && scriptContext == function->GetScriptContext()) // only register when function has same scriptContext, otherwise when scriptContext close
  3045. // and the isInst inline cache chain will be broken by clearing the arenaAllocator
  3046. {
  3047. inlineCache->Cache(instanceType, function, boolResult, scriptContext);
  3048. }
  3049. }
  3050. return result;
  3051. }
  3052. }