JavascriptFunction.cpp 117 KB

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