JavascriptFunction.cpp 132 KB

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