JavascriptFunction.cpp 128 KB

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