JavascriptFunction.cpp 134 KB

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