GlobalObject.cpp 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344
  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. #ifndef USING_PAL_STDLIB
  7. #include <strsafe.h>
  8. #endif
  9. #include "ByteCode/ByteCodeApi.h"
  10. #include "Exceptions/EvalDisabledException.h"
  11. #include "Types/PropertyIndexRanges.h"
  12. #include "Types/SimpleDictionaryPropertyDescriptor.h"
  13. #include "Types/SimpleDictionaryTypeHandler.h"
  14. namespace Js
  15. {
  16. GlobalObject * GlobalObject::New(ScriptContext * scriptContext)
  17. {
  18. SimpleDictionaryTypeHandler* globalTypeHandler = SimpleDictionaryTypeHandler::New(
  19. scriptContext->GetRecycler(), InitialCapacity, InlineSlotCapacity, sizeof(Js::GlobalObject));
  20. DynamicType* globalType = DynamicType::New(
  21. scriptContext, TypeIds_GlobalObject, nullptr, nullptr, globalTypeHandler);
  22. GlobalObject* globalObject = RecyclerNewPlus(scriptContext->GetRecycler(),
  23. sizeof(Var) * InlineSlotCapacity, GlobalObject, globalType, scriptContext);
  24. #if ENABLE_FIXED_FIELDS
  25. globalTypeHandler->SetSingletonInstanceIfNeeded(scriptContext->GetRecycler()->CreateWeakReferenceHandle<DynamicObject>(globalObject));
  26. #endif
  27. return globalObject;
  28. }
  29. GlobalObject::GlobalObject(DynamicType * type, ScriptContext* scriptContext) :
  30. RootObjectBase(type, scriptContext),
  31. directHostObject(nullptr),
  32. secureDirectHostObject(nullptr),
  33. EvalHelper(&GlobalObject::DefaultEvalHelper),
  34. reservedProperties(nullptr)
  35. {
  36. }
  37. void GlobalObject::Initialize(ScriptContext * scriptContext)
  38. {
  39. Assert(type->javascriptLibrary == nullptr);
  40. JavascriptLibrary* localLibrary = RecyclerNewFinalized(scriptContext->GetRecycler(), JavascriptLibrary, this);
  41. scriptContext->SetLibrary(localLibrary);
  42. type->javascriptLibrary = localLibrary;
  43. scriptContext->InitializeCache();
  44. localLibrary->Initialize(scriptContext, this);
  45. library = localLibrary;
  46. }
  47. bool GlobalObject::Is(Var aValue)
  48. {
  49. return RecyclableObject::Is(aValue) && (RecyclableObject::UnsafeFromVar(aValue)->GetTypeId() == TypeIds_GlobalObject);
  50. }
  51. GlobalObject* GlobalObject::FromVar(Var aValue)
  52. {
  53. AssertOrFailFastMsg(Is(aValue), "Ensure var is actually a 'GlobalObject'");
  54. return static_cast<GlobalObject*>(aValue);
  55. }
  56. GlobalObject* GlobalObject::UnsafeFromVar(Var aValue)
  57. {
  58. AssertMsg(Is(aValue), "Ensure var is actually a 'GlobalObject'");
  59. return static_cast<GlobalObject*>(aValue);
  60. }
  61. HRESULT GlobalObject::SetDirectHostObject(RecyclableObject* hostObject, RecyclableObject* secureDirectHostObject)
  62. {
  63. HRESULT hr = S_OK;
  64. BEGIN_TRANSLATE_OOM_TO_HRESULT_NESTED
  65. {
  66. // In fastDOM scenario, we should use the host object to lookup the prototype.
  67. this->SetPrototype(library->GetNull());
  68. }
  69. END_TRANSLATE_OOM_TO_HRESULT(hr)
  70. this->directHostObject = hostObject;
  71. this->secureDirectHostObject = secureDirectHostObject;
  72. return hr;
  73. }
  74. RecyclableObject* GlobalObject::GetDirectHostObject()
  75. {
  76. return this->directHostObject;
  77. }
  78. RecyclableObject* GlobalObject::GetSecureDirectHostObject()
  79. {
  80. return this->secureDirectHostObject;
  81. }
  82. // Converts the global object into the object that should be used as the 'this' parameter.
  83. // In a non-hosted environment, the global object (this) is returned.
  84. // In a hosted environment, the host object is returned.
  85. Var GlobalObject::ToThis()
  86. {
  87. Var ret;
  88. // In fast DOM, we need to give user the secure version of host object
  89. if (secureDirectHostObject)
  90. {
  91. ret = secureDirectHostObject;
  92. }
  93. else if (hostObject)
  94. {
  95. // If the global object has the host object, use that as "this"
  96. ret = hostObject->GetHostDispatchVar();
  97. Assert(ret);
  98. }
  99. else
  100. {
  101. // Otherwise just use the global object
  102. ret = this;
  103. }
  104. return ret;
  105. }
  106. BOOL GlobalObject::ReserveGlobalProperty(PropertyId propertyId)
  107. {
  108. if (JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::HasPropertyQuery(propertyId)))
  109. {
  110. return false;
  111. }
  112. if (reservedProperties == nullptr)
  113. {
  114. Recycler* recycler = this->GetScriptContext()->GetRecycler();
  115. reservedProperties = RecyclerNew(recycler, ReservedPropertiesHashSet, recycler, 3);
  116. }
  117. reservedProperties->AddNew(propertyId);
  118. return true;
  119. }
  120. BOOL GlobalObject::IsReservedGlobalProperty(PropertyId propertyId)
  121. {
  122. return reservedProperties != nullptr && reservedProperties->Contains(propertyId);
  123. }
  124. #ifdef IR_VIEWER
  125. Var GlobalObject::EntryParseIR(RecyclableObject *function, CallInfo callInfo, ...)
  126. {
  127. //
  128. // retrieve arguments
  129. //
  130. RUNTIME_ARGUMENTS(args, callInfo);
  131. Js::Var codeVar = args[1]; // args[0] is (this)
  132. Js::JavascriptString *codeStringVar = nullptr;
  133. const char16 *source = nullptr;
  134. size_t sourceLength = 0;
  135. if (Js::JavascriptString::Is(codeVar))
  136. {
  137. codeStringVar = (Js::JavascriptString *)codeVar;
  138. source = codeStringVar->GetString();
  139. sourceLength = codeStringVar->GetLength();
  140. }
  141. else
  142. {
  143. AssertMsg(false, "The input to parseIR was not a string.");
  144. }
  145. //
  146. // collect arguments for eval
  147. //
  148. /* @see NativeCodeGenerator::CodeGen */
  149. ScriptContext *scriptContext = function->GetScriptContext();
  150. // used arbitrary defaults for these, but it seems to work
  151. ModuleID moduleID = 0;
  152. uint32 grfscr = 0;
  153. LPCOLESTR pszTitle = _u("");
  154. BOOL registerDocument = false;
  155. BOOL strictMode = true;
  156. return IRDumpEvalHelper(scriptContext, source, sourceLength, moduleID, grfscr,
  157. pszTitle, registerDocument, FALSE, strictMode);
  158. }
  159. // TODO remove when refactor
  160. Js::PropertyId GlobalObject::CreateProperty(Js::ScriptContext *scriptContext, const char16 *propertyName)
  161. {
  162. Js::PropertyRecord const *propertyRecord;
  163. scriptContext->GetOrAddPropertyRecord(propertyName, (int) wcslen(propertyName), &propertyRecord);
  164. Js::PropertyId propertyId = propertyRecord->GetPropertyId();
  165. return propertyId;
  166. }
  167. // TODO remove when refactor
  168. void GlobalObject::SetProperty(Js::DynamicObject *obj, const char16 *propertyName, Js::Var value)
  169. {
  170. const size_t len = wcslen(propertyName);
  171. if (!(len > 0))
  172. {
  173. return;
  174. }
  175. Js::PropertyId id = CreateProperty(obj->GetScriptContext(), propertyName);
  176. SetProperty(obj, id, value);
  177. }
  178. // TODO remove when refactor
  179. void GlobalObject::SetProperty(Js::DynamicObject *obj, Js::PropertyId id, Js::Var value)
  180. {
  181. if (value == NULL)
  182. {
  183. return;
  184. }
  185. Js::JavascriptOperators::SetProperty(obj, obj, id, value, obj->GetScriptContext());
  186. }
  187. Var GlobalObject::FunctionInfoObjectBuilder(ScriptContext *scriptContext, const char16 *file,
  188. const char16 *function, ULONG lineNum, ULONG colNum,
  189. uint functionId, Js::Utf8SourceInfo *utf8SrcInfo, Js::Var source)
  190. {
  191. Js::DynamicObject *fnInfoObj = scriptContext->GetLibrary()->CreateObject();
  192. // create javascript objects for properties
  193. Js::Var filenameString = Js::JavascriptString::NewCopyBuffer(file, wcslen(file), scriptContext);
  194. Js::Var funcnameString = Js::JavascriptString::NewCopyBuffer(function, wcslen(function), scriptContext);
  195. Js::Var lineNumber = Js::JavascriptNumber::ToVar((int64) lineNum, scriptContext);
  196. Js::Var colNumber = Js::JavascriptNumber::ToVar((int64) colNum, scriptContext);
  197. Js::Var functionIdNumberVar = Js::JavascriptNumber::ToVar(functionId, scriptContext);
  198. Js::Var utf8SourceInfoVar = Js::JavascriptNumber::ToVar((int32) utf8SrcInfo, scriptContext);
  199. // assign properties to function info object
  200. SetProperty(fnInfoObj, _u("filename"), filenameString);
  201. SetProperty(fnInfoObj, _u("function"), funcnameString);
  202. SetProperty(fnInfoObj, _u("line"), lineNumber);
  203. SetProperty(fnInfoObj, _u("col"), colNumber);
  204. SetProperty(fnInfoObj, _u("funcId"), functionIdNumberVar);
  205. SetProperty(fnInfoObj, _u("utf8SrcInfoPtr"), utf8SourceInfoVar);
  206. SetProperty(fnInfoObj, _u("source"), source);
  207. return fnInfoObj;
  208. }
  209. /**
  210. * Return a list of functions visible in the current ScriptContext.
  211. */
  212. Var GlobalObject::EntryFunctionList(RecyclableObject *function, CallInfo callInfo, ...)
  213. {
  214. // Note: the typedefs below help make the following code more readable
  215. // See: Js::ScriptContext::SourceList (declaration not visible from this file)
  216. typedef JsUtil::List<RecyclerWeakReference<Utf8SourceInfo>*, Recycler, false, Js::FreeListedRemovePolicy> SourceList;
  217. typedef RecyclerWeakReference<Js::Utf8SourceInfo> Utf8SourceInfoRef;
  218. ScriptContext *originalScriptContext = function->GetScriptContext();
  219. ThreadContext *threadContext = originalScriptContext->GetThreadContext();
  220. ScriptContext *scriptContext;
  221. int fnCount = 0;
  222. for (scriptContext = threadContext->GetScriptContextList();
  223. scriptContext;
  224. scriptContext = scriptContext->next)
  225. {
  226. if (scriptContext->IsClosed()) continue;
  227. //
  228. // get count of functions in all files in script context
  229. //
  230. SourceList *sourceList = scriptContext->GetSourceList();
  231. sourceList->Map([&fnCount](uint i, Utf8SourceInfoRef *sourceInfoWeakRef)
  232. {
  233. Js::Utf8SourceInfo *sourceInfo = sourceInfoWeakRef->Get();
  234. if (sourceInfo == nullptr || sourceInfo->GetIsLibraryCode()) // library code has no source, skip
  235. {
  236. return;
  237. }
  238. fnCount += sourceInfo->GetFunctionBodyCount();
  239. });
  240. }
  241. #ifdef ENABLE_IR_VIEWER_DBG_DUMP
  242. if (Js::Configuration::Global.flags.Verbose)
  243. {
  244. Output::Print(_u(">> There are %d total functions\n"), fnCount);
  245. Output::Flush();
  246. }
  247. #endif
  248. //
  249. // create a javascript array to hold info for all of the functions
  250. //
  251. Js::JavascriptArray *functionList = originalScriptContext->GetLibrary()->CreateArray(fnCount);
  252. int count = 0;
  253. for (scriptContext = threadContext->GetScriptContextList();
  254. scriptContext;
  255. scriptContext = scriptContext->next)
  256. {
  257. if (scriptContext->IsClosed()) continue;
  258. // if (scriptContext == originalScriptContext) continue; // uncomment to ignore the originalScriptContext
  259. SourceList *sourceList = scriptContext->GetSourceList();
  260. sourceList->Map([&fnCount, &count, functionList, scriptContext](uint i, Utf8SourceInfoRef *sourceInfoWeakRef)
  261. {
  262. Js::Utf8SourceInfo *sourceInfo = sourceInfoWeakRef->Get();
  263. if (sourceInfo == nullptr || sourceInfo->GetIsLibraryCode()) // library code has no source, skip
  264. {
  265. return;
  266. }
  267. const SRCINFO *srcInfo = sourceInfo->GetSrcInfo();
  268. SourceContextInfo *srcContextInfo = srcInfo->sourceContextInfo;
  269. //
  270. // get URL of source file
  271. //
  272. char16 filenameBuffer[128]; // hold dynamically built filename
  273. char16 const *srcFileUrl = NULL;
  274. if (!srcContextInfo->IsDynamic())
  275. {
  276. Assert(srcContextInfo->url != NULL);
  277. srcFileUrl = srcContextInfo->url;
  278. }
  279. else
  280. {
  281. StringCchPrintf(filenameBuffer, 128, _u("[dynamic(hash:%u)]"), srcContextInfo->hash);
  282. srcFileUrl = filenameBuffer;
  283. }
  284. sourceInfo->MapFunction([scriptContext, &count, functionList, srcFileUrl](Js::FunctionBody *functionBody)
  285. {
  286. char16 const *functionName = functionBody->GetExternalDisplayName();
  287. ULONG lineNum = functionBody->GetLineNumber();
  288. ULONG colNum = functionBody->GetColumnNumber();
  289. uint funcId = functionBody->GetLocalFunctionId();
  290. Js::Utf8SourceInfo *utf8SrcInfo = functionBody->GetUtf8SourceInfo();
  291. if (utf8SrcInfo == nullptr)
  292. {
  293. return;
  294. }
  295. Assert(utf8SrcInfo->FindFunction(funcId) == functionBody);
  296. BufferStringBuilder builder(functionBody->LengthInChars(), scriptContext);
  297. utf8::DecodeOptions options = utf8SrcInfo->IsCesu8() ? utf8::doAllowThreeByteSurrogates : utf8::doDefault;
  298. utf8::DecodeInto(builder.DangerousGetWritableBuffer(), functionBody->GetSource(), functionBody->LengthInChars(), options);
  299. Var cachedSourceString = builder.ToString();
  300. Js::Var obj = FunctionInfoObjectBuilder(scriptContext, srcFileUrl,
  301. functionName, lineNum, colNum, funcId, utf8SrcInfo, cachedSourceString);
  302. functionList->SetItem(count, obj, Js::PropertyOperationFlags::PropertyOperation_None);
  303. ++count;
  304. });
  305. });
  306. }
  307. #ifdef ENABLE_IR_VIEWER_DBG_DUMP
  308. if (Js::Configuration::Global.flags.Verbose)
  309. {
  310. Output::Print(_u(">> Returning from functionList()\n"));
  311. Output::Flush();
  312. }
  313. #endif
  314. return functionList;
  315. }
  316. /**
  317. * Return the parsed IR for the given function.
  318. */
  319. Var GlobalObject::EntryRejitFunction(RecyclableObject *function, CallInfo callInfo, ...)
  320. {
  321. #ifdef ENABLE_IR_VIEWER_DBG_DUMP
  322. if (Js::Configuration::Global.flags.Verbose)
  323. {
  324. Output::Print(_u(">> Entering rejitFunction()\n"));
  325. Output::Flush();
  326. }
  327. #endif
  328. //
  329. // retrieve and coerce arguments
  330. //
  331. RUNTIME_ARGUMENTS(args, callInfo); // args[0] is (callInfo)
  332. Js::Var jsVarUtf8SourceInfo = args[1];
  333. Js::Var jsVarFunctionId = args[2];
  334. #ifdef ENABLE_IR_VIEWER_DBG_DUMP
  335. if (Js::Configuration::Global.flags.Verbose)
  336. {
  337. Output::Print(_u("jsVarUtf8SourceInfo: %d (0x%08X)\n"), jsVarUtf8SourceInfo, jsVarUtf8SourceInfo);
  338. Output::Print(_u("jsVarFunctionId: %d (0x%08X)\n"), jsVarFunctionId, jsVarFunctionId);
  339. }
  340. #endif
  341. Js::JavascriptNumber *jsUtf8SourceInfoNumber = NULL;
  342. Js::JavascriptNumber *jsFunctionIdNumber = NULL;
  343. int32 utf8SourceInfoNumber = 0; // null
  344. int32 functionIdNumber = -1; // start with invalid function id
  345. // extract value of jsVarUtf8SourceInfo
  346. if (Js::TaggedInt::Is(jsVarUtf8SourceInfo))
  347. {
  348. utf8SourceInfoNumber = (int32)TaggedInt::ToInt64(jsVarUtf8SourceInfo); // REVIEW: just truncate?
  349. }
  350. else if (Js::JavascriptNumber::Is(jsVarUtf8SourceInfo))
  351. {
  352. jsUtf8SourceInfoNumber = (Js::JavascriptNumber *)jsVarUtf8SourceInfo;
  353. utf8SourceInfoNumber = (int32)JavascriptNumber::GetValue(jsUtf8SourceInfoNumber); // REVIEW: just truncate?
  354. }
  355. else
  356. {
  357. // should not reach here
  358. AssertMsg(false, "Failed to extract value for jsVarUtf8SourceInfo as either TaggedInt or JavascriptNumber.\n");
  359. }
  360. // extract value of jsVarFunctionId
  361. if (Js::TaggedInt::Is(jsVarFunctionId))
  362. {
  363. functionIdNumber = (int32)TaggedInt::ToInt64(jsVarFunctionId); // REVIEW: just truncate?
  364. }
  365. else if (Js::JavascriptNumber::Is(jsVarFunctionId))
  366. {
  367. jsFunctionIdNumber = (Js::JavascriptNumber *)jsVarFunctionId;
  368. functionIdNumber = (int32)JavascriptNumber::GetValue(jsFunctionIdNumber); // REVIEW: just truncate?
  369. }
  370. else
  371. {
  372. // should not reach here
  373. AssertMsg(false, "Failed to extract value for jsVarFunctionId as either TaggedInt or JavascriptNumber.\n");
  374. }
  375. #ifdef ENABLE_IR_VIEWER_DBG_DUMP
  376. if (Js::Configuration::Global.flags.Verbose)
  377. {
  378. Output::Print(_u("utf8SourceInfoNumber (value): %d (0x%08X)\n"), utf8SourceInfoNumber, utf8SourceInfoNumber);
  379. Output::Print(_u("jsVarFunctionId (value): %d (0x%08X)\n"), functionIdNumber, functionIdNumber);
  380. Output::Print(_u(">> Executing rejitFunction(%d, %d)\n"), utf8SourceInfoNumber, functionIdNumber);
  381. Output::Flush();
  382. }
  383. #endif
  384. //
  385. // recover functionBody
  386. //
  387. Js::Utf8SourceInfo *sourceInfo = (Js::Utf8SourceInfo *)(utf8SourceInfoNumber);
  388. if (sourceInfo == NULL)
  389. {
  390. return NULL;
  391. }
  392. Js::FunctionBody *functionBody = sourceInfo->FindFunction((Js::LocalFunctionId)functionIdNumber);
  393. //
  394. // rejit the function body
  395. //
  396. Js::ScriptContext *scriptContext = function->GetScriptContext();
  397. NativeCodeGenerator *nativeCodeGenerator = scriptContext->GetNativeCodeGenerator();
  398. if (!functionBody || !functionBody->GetByteCode())
  399. {
  400. return scriptContext->GetLibrary()->GetUndefined();
  401. }
  402. Js::Var retVal = RejitIRViewerFunction(nativeCodeGenerator, functionBody, scriptContext);
  403. //
  404. // return the parsed IR object
  405. //
  406. #ifdef ENABLE_IR_VIEWER_DBG_DUMP
  407. if (Js::Configuration::Global.flags.Verbose)
  408. {
  409. Output::Print(_u("rejitFunction - retVal: 0x%08X\n"), retVal);
  410. Output::Flush();
  411. }
  412. #endif
  413. return retVal;
  414. }
  415. #endif /* IR_VIEWER */
  416. Var GlobalObject::EntryEvalHelper(ScriptContext* scriptContext, RecyclableObject* function, Js::Arguments& args)
  417. {
  418. FrameDisplay* environment = (FrameDisplay*)&NullFrameDisplay;
  419. ModuleID moduleID = kmodGlobal;
  420. BOOL strictMode = FALSE;
  421. // TODO: Handle call from global scope, strict mode
  422. BOOL isIndirect = FALSE;
  423. if (args.IsDirectEvalCall())
  424. {
  425. // This was recognized as an eval call at compile time. The last one or two args are internal to us.
  426. // Argcount will be one of the following when called from global code
  427. // - eval("...") : argcount 3 : this, evalString, frameDisplay
  428. // - eval.call("..."): argcount 2 : this(which is string) , frameDisplay
  429. if (args.Info.Count >= 1)
  430. {
  431. environment = args.GetFrameDisplay();
  432. strictMode = environment->GetStrictMode();
  433. }
  434. }
  435. else
  436. {
  437. // This must be an indirect "eval" call that we didn't detect at compile time.
  438. // Pass null as the environment, which will force all lookups in the eval code
  439. // to use the root for the current module.
  440. // Also pass "null" for "this", which will force the callee to use the current module root.
  441. isIndirect = !PHASE_OFF1(Js::FastIndirectEvalPhase);
  442. }
  443. return GlobalObject::VEval(function->GetLibrary(), environment, moduleID, !!strictMode, !!isIndirect, args,
  444. /* isLibraryCode = */ false, /* registerDocument */ true, /*additionalGrfscr */ 0);
  445. }
  446. Var GlobalObject::EntryEvalRestrictedMode(RecyclableObject* function, CallInfo callInfo, ...)
  447. {
  448. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  449. RUNTIME_ARGUMENTS(args, callInfo);
  450. Assert(!(callInfo.Flags & CallFlags_New));
  451. JavascriptLibrary* library = function->GetLibrary();
  452. ScriptContext* scriptContext = library->GetScriptContext();
  453. scriptContext->CheckEvalRestriction();
  454. return EntryEvalHelper(scriptContext, function, args);
  455. }
  456. // This function is used to decipher eval function parameters and we don't want the stack arguments optimization by C++ compiler so turning off the optimization
  457. Var GlobalObject::EntryEval(RecyclableObject* function, CallInfo callInfo, ...)
  458. {
  459. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  460. RUNTIME_ARGUMENTS(args, callInfo);
  461. Assert(!(callInfo.Flags & CallFlags_New));
  462. JavascriptLibrary* library = function->GetLibrary();
  463. ScriptContext* scriptContext = library->GetScriptContext();
  464. return EntryEvalHelper(scriptContext, function, args);
  465. }
  466. Var GlobalObject::VEval(JavascriptLibrary* library, FrameDisplay* environment, ModuleID moduleID, bool strictMode, bool isIndirect,
  467. Arguments& args, bool isLibraryCode, bool registerDocument, uint32 additionalGrfscr, ScriptContext* debugEvalScriptContext)
  468. {
  469. Assert(library);
  470. ScriptContext* scriptContext = library->GetScriptContext();
  471. unsigned argCount = args.Info.Count;
  472. AssertMsg(argCount > 0, "Should always have implicit 'this'");
  473. bool doRegisterDocument = registerDocument & !isLibraryCode;
  474. Var varThis = library->GetUndefined();
  475. if (argCount < 2)
  476. {
  477. return library->GetUndefined();
  478. }
  479. Var evalArg = args[1];
  480. if (!JavascriptString::Is(evalArg))
  481. {
  482. // "If x is not a string value, return x."
  483. return evalArg;
  484. }
  485. #ifdef ENABLE_SCRIPT_DEBUGGING
  486. // It might happen that no script parsed on this context (scriptContext) till now,
  487. // so this Eval acts as the first source compile for scriptContext, transition to debugMode as needed
  488. scriptContext->TransitionToDebugModeIfFirstSource(/* utf8SourceInfo = */ nullptr);
  489. #endif
  490. ScriptFunction *pfuncScript = nullptr;
  491. JavascriptString *argString = JavascriptString::FromVar(evalArg);
  492. char16 const * sourceString = argString->GetSz();
  493. charcount_t sourceLen = argString->GetLength();
  494. FastEvalMapString key(sourceString, sourceLen, moduleID, strictMode, isLibraryCode);
  495. // PropertyString's buffer references to PropertyRecord's inline buffer, if both PropertyString and PropertyRecord are collected
  496. // we'll leave the PropertyRecord's interior buffer pointer in the EvalMap. So do not use evalmap if we are evaluating PropertyString
  497. bool useEvalMap = !VirtualTableInfo<PropertyString>::HasVirtualTable(argString) && debugEvalScriptContext == nullptr; // Don't use the cache in case of debugEval
  498. bool found = useEvalMap && scriptContext->IsInEvalMap(key, isIndirect, &pfuncScript);
  499. if (!found || (!isIndirect && pfuncScript->GetEnvironment() != &NullFrameDisplay))
  500. {
  501. uint32 grfscr = additionalGrfscr | fscrReturnExpression | fscrEval | fscrEvalCode | fscrGlobalCode;
  502. if (isLibraryCode)
  503. {
  504. grfscr |= fscrIsLibraryCode;
  505. }
  506. pfuncScript = library->GetGlobalObject()->EvalHelper(scriptContext, argString->GetSz(), argString->GetLength(), moduleID,
  507. grfscr, Constants::EvalCode, doRegisterDocument, isIndirect, strictMode);
  508. if (debugEvalScriptContext != nullptr && CrossSite::NeedMarshalVar(pfuncScript, debugEvalScriptContext))
  509. {
  510. // This is console scope scenario. DebugEval script context is on the top of the stack. But we are going
  511. // to execute the user script from target script context. In order to fix the script context stack we
  512. // need to marshall the function object.
  513. pfuncScript = ScriptFunction::FromVar(CrossSite::MarshalVar(debugEvalScriptContext, pfuncScript));
  514. }
  515. if (useEvalMap && !found)
  516. {
  517. scriptContext->AddToEvalMap(key, isIndirect, pfuncScript);
  518. }
  519. }
  520. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  521. else
  522. {
  523. Js::Utf8SourceInfo* utf8SourceInfo = pfuncScript->GetFunctionBody()->GetUtf8SourceInfo();
  524. if (scriptContext->IsScriptContextInDebugMode() && !utf8SourceInfo->GetIsLibraryCode() && !utf8SourceInfo->IsInDebugMode())
  525. {
  526. // Identifying if any non library function escaped for not being in debug mode.
  527. Throw::FatalInternalError();
  528. }
  529. }
  530. #endif
  531. #if ENABLE_TTD
  532. //
  533. //TODO: We may (probably?) want to use the debugger source rundown functionality here instead
  534. //
  535. if(!isLibraryCode && pfuncScript != nullptr && (scriptContext->IsTTDRecordModeEnabled() || scriptContext->ShouldPerformReplayAction()))
  536. {
  537. //Make sure we have the body and text information available
  538. FunctionBody* globalBody = TTD::JsSupport::ForceAndGetFunctionBody(pfuncScript->GetParseableFunctionInfo());
  539. if(!scriptContext->TTDContextInfo->IsBodyAlreadyLoadedAtTopLevel(globalBody))
  540. {
  541. uint32 bodyIdCtr = 0;
  542. if(scriptContext->IsTTDRecordModeEnabled())
  543. {
  544. const TTD::NSSnapValues::TopLevelEvalFunctionBodyResolveInfo* tbfi = scriptContext->GetThreadContext()->TTDLog->AddEvalFunction(globalBody, moduleID, sourceString, sourceLen, additionalGrfscr, registerDocument, isIndirect, strictMode);
  545. //We always want to register the top-level load but we don't always need to log the event
  546. if(scriptContext->ShouldPerformRecordAction())
  547. {
  548. scriptContext->GetThreadContext()->TTDLog->RecordTopLevelCodeAction(tbfi->TopLevelBase.TopLevelBodyCtr);
  549. }
  550. bodyIdCtr = tbfi->TopLevelBase.TopLevelBodyCtr;
  551. }
  552. if(scriptContext->ShouldPerformReplayAction())
  553. {
  554. bodyIdCtr = scriptContext->GetThreadContext()->TTDLog->ReplayTopLevelCodeAction();
  555. }
  556. //walk global body to (1) add functions to pin set (2) build parent map
  557. scriptContext->TTDContextInfo->ProcessFunctionBodyOnLoad(globalBody, nullptr);
  558. scriptContext->TTDContextInfo->RegisterEvalScript(globalBody, bodyIdCtr);
  559. if(scriptContext->ShouldPerformRecordOrReplayAction())
  560. {
  561. globalBody->GetUtf8SourceInfo()->SetSourceInfoForDebugReplay_TTD(bodyIdCtr);
  562. }
  563. if(scriptContext->ShouldPerformReplayDebuggerAction())
  564. {
  565. scriptContext->GetThreadContext()->TTDExecutionInfo->ProcessScriptLoad(scriptContext, bodyIdCtr, globalBody, globalBody->GetUtf8SourceInfo(), nullptr);
  566. }
  567. }
  568. }
  569. #endif
  570. //We shouldn't be serializing eval functions; unless with -ForceSerialized flag
  571. if (CONFIG_FLAG(ForceSerialized)) {
  572. pfuncScript->GetFunctionProxy()->EnsureDeserialized();
  573. }
  574. if (pfuncScript->GetFunctionBody()->GetHasThis())
  575. {
  576. // The eval expression refers to "this"
  577. if (args.Info.Flags & CallFlags_ExtraArg)
  578. {
  579. JavascriptFunction* pfuncCaller = nullptr;
  580. // If we are non-hidden call to eval then look for the "this" object in the frame display if the caller is a lambda else get "this" from the caller's frame.
  581. bool successful = false;
  582. if (JavascriptStackWalker::GetCaller(&pfuncCaller, scriptContext))
  583. {
  584. FunctionInfo* functionInfo = pfuncCaller->GetFunctionInfo();
  585. if (functionInfo != nullptr && (functionInfo->IsLambda() || functionInfo->IsClassConstructor()))
  586. {
  587. Var defaultInstance = (moduleID == kmodGlobal) ? JavascriptOperators::OP_LdRoot(scriptContext)->ToThis() : (Var)JavascriptOperators::GetModuleRoot(moduleID, scriptContext);
  588. varThis = JavascriptOperators::OP_GetThisScoped(environment, defaultInstance, scriptContext);
  589. UpdateThisForEval(varThis, moduleID, scriptContext, strictMode);
  590. successful = true;
  591. }
  592. }
  593. if (!successful)
  594. {
  595. JavascriptStackWalker::GetThis(&varThis, moduleID, scriptContext);
  596. UpdateThisForEval(varThis, moduleID, scriptContext, strictMode);
  597. }
  598. }
  599. else
  600. {
  601. // The expression, which refers to "this", is evaluated by an indirect eval.
  602. // Set "this" to the current module root.
  603. varThis = JavascriptOperators::OP_GetThis(scriptContext->GetLibrary()->GetUndefined(), moduleID, scriptContext);
  604. }
  605. }
  606. if (pfuncScript->HasSuperReference())
  607. {
  608. // Indirect evals cannot have a super reference.
  609. if (!(args.Info.Flags & CallFlags_ExtraArg))
  610. {
  611. JavascriptError::ThrowSyntaxError(scriptContext, ERRSuperInIndirectEval, _u("super"));
  612. }
  613. }
  614. return library->GetGlobalObject()->ExecuteEvalParsedFunction(pfuncScript, environment, varThis, scriptContext);
  615. }
  616. void GlobalObject::UpdateThisForEval(Var &varThis, ModuleID moduleID, ScriptContext *scriptContext, BOOL strictMode)
  617. {
  618. if (strictMode)
  619. {
  620. varThis = JavascriptOperators::OP_StrictGetThis(varThis, scriptContext);
  621. }
  622. else
  623. {
  624. varThis = JavascriptOperators::OP_GetThisNoFastPath(varThis, moduleID, scriptContext);
  625. }
  626. }
  627. Var GlobalObject::ExecuteEvalParsedFunction(ScriptFunction *pfuncScript, FrameDisplay* environment, Var &varThis, ScriptContext *scriptContext)
  628. {
  629. Assert(pfuncScript != nullptr);
  630. pfuncScript->SetEnvironment(environment);
  631. //This function is supposed to be deserialized
  632. Assert(pfuncScript->GetFunctionBody());
  633. if (pfuncScript->GetFunctionBody()->GetFuncEscapes())
  634. {
  635. // Executing the eval causes the scope chain to escape.
  636. pfuncScript->InvalidateCachedScopeChain();
  637. }
  638. Var varResult = CALL_FUNCTION(scriptContext->GetThreadContext(), pfuncScript, CallInfo(CallFlags_Eval, 1), varThis);
  639. pfuncScript->SetEnvironment((FrameDisplay*)&NullFrameDisplay);
  640. return varResult;
  641. }
  642. #ifdef ENABLE_SCRIPT_PROFILING
  643. ScriptFunction* GlobalObject::ProfileModeEvalHelper(ScriptContext* scriptContext, const char16 *source, int sourceLength, ModuleID moduleID, uint32 grfscr, LPCOLESTR pszTitle, BOOL registerDocument, BOOL isIndirect, BOOL strictMode)
  644. {
  645. #if ENABLE_DEBUG_CONFIG_OPTIONS
  646. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  647. #endif
  648. ScriptFunction *pEvalFunction = DefaultEvalHelper(scriptContext, source, sourceLength, moduleID, grfscr, pszTitle, registerDocument, isIndirect, strictMode);
  649. Assert(pEvalFunction);
  650. Js::FunctionProxy *proxy = pEvalFunction->GetFunctionProxy();
  651. Assert(proxy);
  652. OUTPUT_TRACE(Js::ScriptProfilerPhase, _u("GlobalObject::ProfileModeEvalHelper FunctionNumber : %s, Entrypoint : 0x%08X IsFunctionDefer : %d\n"),
  653. proxy->GetDebugNumberSet(debugStringBuffer), pEvalFunction->GetEntryPoint(), proxy->IsDeferred());
  654. if (proxy->IsDeferred())
  655. {
  656. // This could happen if the top level function is marked as deferred, we need to parse this to generate the script compile information (RegisterScript depends on that)
  657. Js::JavascriptFunction::DeferredParse(&pEvalFunction);
  658. proxy = pEvalFunction->GetFunctionProxy();
  659. }
  660. scriptContext->RegisterScript(proxy);
  661. return pEvalFunction;
  662. }
  663. #endif
  664. void GlobalObject::ValidateSyntax(ScriptContext* scriptContext, const char16 *source, int sourceLength, bool isGenerator, bool isAsync, void (Parser::*validateSyntax)())
  665. {
  666. Assert(sourceLength >= 0);
  667. HRESULT hr = S_OK;
  668. HRESULT hrParser = E_FAIL;
  669. CompileScriptException se;
  670. BEGIN_LEAVE_SCRIPT_INTERNAL(scriptContext);
  671. BEGIN_TRANSLATE_EXCEPTION_TO_HRESULT
  672. {
  673. ArenaAllocator tempAlloc(_u("ValidateSyntaxArena"), scriptContext->GetThreadContext()->GetPageAllocator(), Throw::OutOfMemory);
  674. size_t cchSource = sourceLength;
  675. size_t cbUtf8Buffer = UInt32Math::AddMul<1, 3>(sourceLength);
  676. LPUTF8 utf8Source = AnewArray(&tempAlloc, utf8char_t, cbUtf8Buffer);
  677. Assert(cchSource < MAXLONG);
  678. size_t cbSource = utf8::EncodeIntoAndNullTerminate(utf8Source, source, static_cast< charcount_t >(cchSource));
  679. utf8Source = reinterpret_cast< LPUTF8 >( tempAlloc.Realloc(utf8Source, cbUtf8Buffer, cbSource + 1) );
  680. Parser parser(scriptContext);
  681. hrParser = parser.ValidateSyntax(utf8Source, cbSource, isGenerator, isAsync, &se, validateSyntax);
  682. }
  683. END_TRANSLATE_EXCEPTION_TO_HRESULT(hr);
  684. END_LEAVE_SCRIPT_INTERNAL(scriptContext);
  685. if (FAILED(hr))
  686. {
  687. if (hr == E_OUTOFMEMORY)
  688. {
  689. JavascriptError::ThrowOutOfMemoryError(scriptContext);
  690. }
  691. if (hr == VBSERR_OutOfStack)
  692. {
  693. JavascriptError::ThrowStackOverflowError(scriptContext);
  694. }
  695. }
  696. if (!SUCCEEDED(hrParser))
  697. {
  698. hrParser = SCRIPT_E_RECORDED;
  699. EXCEPINFO ei;
  700. se.GetError(&hrParser, &ei);
  701. ErrorTypeEnum errorType;
  702. switch ((HRESULT)ei.scode)
  703. {
  704. #define RT_ERROR_MSG(name, errnum, str1, str2, jst, errorNumSource) \
  705. case name: \
  706. errorType = jst; \
  707. break;
  708. #define RT_PUBLICERROR_MSG(name, errnum, str1, str2, jst, errorNumSource) RT_ERROR_MSG(name, errnum, str1, str2, jst, errorNumSource)
  709. #include "rterrors.h"
  710. #undef RT_PUBLICERROR_MSG
  711. #undef RT_ERROR_MSG
  712. default:
  713. errorType = kjstSyntaxError;
  714. }
  715. JavascriptError::MapAndThrowError(scriptContext, ei.scode, errorType, &ei);
  716. }
  717. }
  718. ScriptFunction* GlobalObject::DefaultEvalHelper(ScriptContext* scriptContext, const char16 *source, int sourceLength, ModuleID moduleID, uint32 grfscr, LPCOLESTR pszTitle, BOOL registerDocument, BOOL isIndirect, BOOL strictMode)
  719. {
  720. Assert(sourceLength >= 0);
  721. AnalysisAssert(scriptContext);
  722. if (scriptContext->GetThreadContext()->EvalDisabled())
  723. {
  724. throw Js::EvalDisabledException();
  725. }
  726. #ifdef PROFILE_EXEC
  727. scriptContext->ProfileBegin(Js::EvalCompilePhase);
  728. #endif
  729. void * frameAddr = nullptr;
  730. GET_CURRENT_FRAME_ID(frameAddr);
  731. HRESULT hr = S_OK;
  732. HRESULT hrParser = S_OK;
  733. HRESULT hrCodeGen = S_OK;
  734. CompileScriptException se;
  735. Js::ParseableFunctionInfo * funcBody = NULL;
  736. BEGIN_LEAVE_SCRIPT_INTERNAL(scriptContext);
  737. BEGIN_TRANSLATE_EXCEPTION_TO_HRESULT
  738. {
  739. uint cchSource = sourceLength;
  740. size_t cbUtf8Buffer = UInt32Math::AddMul<1, 3>(cchSource);
  741. ArenaAllocator tempArena(_u("EvalHelperArena"), scriptContext->GetThreadContext()->GetPageAllocator(), Js::Throw::OutOfMemory);
  742. LPUTF8 utf8Source = AnewArray(&tempArena, utf8char_t, cbUtf8Buffer);
  743. Assert(cchSource < MAXLONG);
  744. size_t cbSource = utf8::EncodeIntoAndNullTerminate(utf8Source, source, static_cast< charcount_t >(cchSource));
  745. Assert(cbSource + 1 <= cbUtf8Buffer);
  746. SRCINFO const * pSrcInfo = scriptContext->GetModuleSrcInfo(moduleID);
  747. // Source Info objects are kept alive by the function bodies that are referencing it
  748. // The function body is created in GenerateByteCode but the source info isn't passed in, only the index
  749. // So we need to pin it here (TODO: Change GenerateByteCode to take in the sourceInfo itself)
  750. ENTER_PINNED_SCOPE(Utf8SourceInfo, sourceInfo);
  751. sourceInfo = Utf8SourceInfo::New(scriptContext, utf8Source, cchSource,
  752. cbSource, pSrcInfo, ((grfscr & fscrIsLibraryCode) != 0));
  753. Parser parser(scriptContext, strictMode);
  754. bool forceNoNative = false;
  755. ParseNodePtr parseTree = nullptr;
  756. SourceContextInfo * sourceContextInfo = pSrcInfo->sourceContextInfo;
  757. ULONG deferParseThreshold = Parser::GetDeferralThreshold(sourceContextInfo->IsSourceProfileLoaded());
  758. if ((ULONG)sourceLength > deferParseThreshold && !PHASE_OFF1(Phase::DeferParsePhase))
  759. {
  760. // Defer function bodies declared inside large dynamic blocks.
  761. grfscr |= fscrDeferFncParse;
  762. }
  763. grfscr = grfscr | fscrDynamicCode;
  764. // fscrEval signifies direct eval in parser
  765. hrParser = parser.ParseCesu8Source(&parseTree, utf8Source, cbSource, isIndirect ? grfscr & ~fscrEval : grfscr, &se, &sourceContextInfo->nextLocalFunctionId,
  766. sourceContextInfo);
  767. sourceInfo->SetParseFlags(grfscr);
  768. if (SUCCEEDED(hrParser) && parseTree)
  769. {
  770. // This keeps function bodies generated by the byte code alive till we return
  771. Js::AutoDynamicCodeReference dynamicFunctionReference(scriptContext);
  772. Assert(cchSource < MAXLONG);
  773. uint sourceIndex = scriptContext->SaveSourceNoCopy(sourceInfo, cchSource, true);
  774. // Tell byte code gen not to attempt to interact with the caller's context if this is indirect eval.
  775. // TODO: Handle strict mode.
  776. if (isIndirect &&
  777. !strictMode &&
  778. !parseTree->AsParseNodeFnc()->GetStrictMode())
  779. {
  780. grfscr &= ~fscrEval;
  781. }
  782. hrCodeGen = GenerateByteCode(parseTree, grfscr, scriptContext, &funcBody, sourceIndex, forceNoNative, &parser, &se);
  783. sourceInfo->SetByteCodeGenerationFlags(grfscr);
  784. }
  785. LEAVE_PINNED_SCOPE();
  786. }
  787. END_TRANSLATE_EXCEPTION_TO_HRESULT(hr);
  788. END_LEAVE_SCRIPT_INTERNAL(scriptContext);
  789. #ifdef PROFILE_EXEC
  790. scriptContext->ProfileEnd(Js::EvalCompilePhase);
  791. #endif
  792. THROW_KNOWN_HRESULT_EXCEPTIONS(hr, scriptContext);
  793. if (!SUCCEEDED(hrParser))
  794. {
  795. JavascriptError::ThrowParserError(scriptContext, hrParser, &se);
  796. }
  797. else if (!SUCCEEDED(hrCodeGen))
  798. {
  799. Assert(hrCodeGen == SCRIPT_E_RECORDED);
  800. hrCodeGen = se.ei.scode;
  801. /*
  802. * VBSERR_OutOfStack is of type kjstError but we throw a (more specific) StackOverflowError when a hard stack
  803. * overflow occurs. To keep the behavior consistent I'm special casing it here.
  804. */
  805. se.Free();
  806. if (hrCodeGen == VBSERR_OutOfStack)
  807. {
  808. JavascriptError::ThrowStackOverflowError(scriptContext);
  809. }
  810. else if (hrCodeGen == JSERR_AsmJsCompileError)
  811. {
  812. // if asm.js compilation succeeded, retry with asm.js disabled
  813. grfscr |= fscrNoAsmJs;
  814. return DefaultEvalHelper(scriptContext, source, sourceLength, moduleID, grfscr, pszTitle, registerDocument, isIndirect, strictMode);
  815. }
  816. JavascriptError::MapAndThrowError(scriptContext, hrCodeGen);
  817. }
  818. else
  819. {
  820. Assert(funcBody != nullptr);
  821. funcBody->SetDisplayName(pszTitle);
  822. // Set the functionbody information to dynamic content PROFILER_SCRIPT_TYPE_DYNAMIC
  823. funcBody->SetIsTopLevel(true);
  824. // If not library code then let's find the parent, we may need to register this source if any exception happens later
  825. if ((grfscr & fscrIsLibraryCode) == 0)
  826. {
  827. // For parented eval get the caller's utf8SourceInfo
  828. JavascriptFunction* pfuncCaller = nullptr;
  829. if (JavascriptStackWalker::GetCaller(&pfuncCaller, scriptContext) && pfuncCaller && pfuncCaller->IsScriptFunction())
  830. {
  831. FunctionBody* parentFuncBody = pfuncCaller->GetFunctionBody();
  832. Utf8SourceInfo* parentUtf8SourceInfo = parentFuncBody->GetUtf8SourceInfo();
  833. Utf8SourceInfo* utf8SourceInfo = funcBody->GetUtf8SourceInfo();
  834. utf8SourceInfo->SetCallerUtf8SourceInfo(parentUtf8SourceInfo);
  835. }
  836. }
  837. if (registerDocument)
  838. {
  839. funcBody->RegisterFuncToDiag(scriptContext, pszTitle);
  840. funcBody = funcBody->GetParseableFunctionInfo(); // RegisterFunction may parse and update function body
  841. }
  842. ScriptFunction* pfuncScript = funcBody->IsCoroutine() ?
  843. scriptContext->GetLibrary()->CreateGeneratorVirtualScriptFunction(funcBody) :
  844. scriptContext->GetLibrary()->CreateScriptFunction(funcBody);
  845. return pfuncScript;
  846. }
  847. }
  848. #ifdef IR_VIEWER
  849. Var GlobalObject::IRDumpEvalHelper(ScriptContext* scriptContext, const char16 *source,
  850. int sourceLength, ModuleID moduleID, uint32 grfscr, LPCOLESTR pszTitle,
  851. BOOL registerDocument, BOOL isIndirect, BOOL strictMode)
  852. {
  853. // TODO (t-doilij) clean up this function, specifically used for IR dump (don't execute bytecode; potentially dangerous)
  854. Assert(sourceLength >= 0);
  855. if (scriptContext->GetThreadContext()->EvalDisabled())
  856. {
  857. throw Js::EvalDisabledException();
  858. }
  859. #ifdef PROFILE_EXEC
  860. scriptContext->ProfileBegin(Js::EvalCompilePhase);
  861. #endif
  862. void * frameAddr = nullptr;
  863. GET_CURRENT_FRAME_ID(frameAddr);
  864. HRESULT hr = S_OK;
  865. HRESULT hrParser = S_OK;
  866. HRESULT hrCodeGen = S_OK;
  867. CompileScriptException se;
  868. Js::ParseableFunctionInfo * funcBody = NULL;
  869. BEGIN_LEAVE_SCRIPT_INTERNAL(scriptContext);
  870. BEGIN_TRANSLATE_EXCEPTION_TO_HRESULT
  871. {
  872. size_t cchSource = sourceLength;
  873. size_t cbUtf8Buffer = UInt32Math::AddMul<1, 3>(sourceLength);
  874. ArenaAllocator tempArena(_u("EvalHelperArena"), scriptContext->GetThreadContext()->GetPageAllocator(), Js::Throw::OutOfMemory);
  875. LPUTF8 utf8Source = AnewArray(&tempArena, utf8char_t, cbUtf8Buffer);
  876. Assert(cchSource < MAXLONG);
  877. size_t cbSource = utf8::EncodeIntoAndNullTerminate(utf8Source, source, static_cast< charcount_t >(cchSource));
  878. Assert(cbSource + 1 <= cbUtf8Buffer);
  879. SRCINFO const * pSrcInfo = scriptContext->GetModuleSrcInfo(moduleID);
  880. // Source Info objects are kept alive by the function bodies that are referencing it
  881. // The function body is created in GenerateByteCode but the source info isn't passed in, only the index
  882. // So we need to pin it here (TODO: Change GenerateByteCode to take in the sourceInfo itself)
  883. ENTER_PINNED_SCOPE(Utf8SourceInfo, sourceInfo);
  884. sourceInfo = Utf8SourceInfo::New(scriptContext, utf8Source, cchSource, cbSource, pSrcInfo, ((grfscr & fscrIsLibraryCode) != 0));
  885. Parser parser(scriptContext, strictMode);
  886. bool forceNoNative = false;
  887. ParseNodePtr parseTree = nullptr;
  888. SourceContextInfo * sourceContextInfo = pSrcInfo->sourceContextInfo;
  889. grfscr = grfscr | fscrDynamicCode;
  890. hrParser = parser.ParseCesu8Source(&parseTree, utf8Source, cbSource, grfscr, &se, &sourceContextInfo->nextLocalFunctionId,
  891. sourceContextInfo);
  892. sourceInfo->SetParseFlags(grfscr);
  893. if (SUCCEEDED(hrParser) && parseTree)
  894. {
  895. // This keeps function bodies generated by the byte code alive till we return
  896. Js::AutoDynamicCodeReference dynamicFunctionReference(scriptContext);
  897. Assert(cchSource < MAXLONG);
  898. uint sourceIndex = scriptContext->SaveSourceNoCopy(sourceInfo, cchSource, true);
  899. grfscr = grfscr | fscrIrDumpEnable;
  900. hrCodeGen = GenerateByteCode(parseTree, grfscr, scriptContext, &funcBody, sourceIndex, forceNoNative, &parser, &se);
  901. sourceInfo->SetByteCodeGenerationFlags(grfscr);
  902. }
  903. LEAVE_PINNED_SCOPE();
  904. }
  905. END_TRANSLATE_EXCEPTION_TO_HRESULT(hr);
  906. END_LEAVE_SCRIPT_INTERNAL(scriptContext);
  907. #ifdef PROFILE_EXEC
  908. scriptContext->ProfileEnd(Js::EvalCompilePhase);
  909. #endif
  910. THROW_KNOWN_HRESULT_EXCEPTIONS(hr);
  911. if (!SUCCEEDED(hrParser))
  912. {
  913. hrParser = SCRIPT_E_RECORDED;
  914. EXCEPINFO ei;
  915. se.GetError(&hrParser, &ei);
  916. ErrorTypeEnum errorType;
  917. switch ((HRESULT)ei.scode)
  918. {
  919. #define RT_ERROR_MSG(name, errnum, str1, str2, jst, errorNumSource) \
  920. case name: \
  921. errorType = jst; \
  922. break;
  923. #define RT_PUBLICERROR_MSG(name, errnum, str1, str2, jst, errorNumSource) RT_ERROR_MSG(name, errnum, str1, str2, jst, errorNumSource)
  924. #include "rterrors.h"
  925. #undef RT_PUBLICERROR_MSG
  926. #undef RT_ERROR_MSG
  927. default:
  928. errorType = kjstSyntaxError;
  929. }
  930. JavascriptError::MapAndThrowError(scriptContext, ei.scode, errorType, &ei);
  931. }
  932. else if (!SUCCEEDED(hrCodeGen))
  933. {
  934. Assert(hrCodeGen == SCRIPT_E_RECORDED);
  935. hrCodeGen = se.ei.scode;
  936. /*
  937. * VBSERR_OutOfStack is of type kjstError but we throw a (more specific) StackOverflowError when a hard stack
  938. * overflow occurs. To keep the behavior consistent I'm special casing it here.
  939. */
  940. se.Free();
  941. if (hrCodeGen == VBSERR_OutOfStack)
  942. {
  943. JavascriptError::ThrowStackOverflowError(scriptContext);
  944. }
  945. JavascriptError::MapAndThrowError(scriptContext, hrCodeGen);
  946. }
  947. else
  948. {
  949. Assert(funcBody != nullptr);
  950. funcBody->SetDisplayName(pszTitle);
  951. // Set the functionbody information to dynamic content PROFILER_SCRIPT_TYPE_DYNAMIC
  952. funcBody->SetIsTopLevel(true);
  953. if (registerDocument)
  954. {
  955. funcBody->RegisterFuncToDiag(scriptContext, pszTitle);
  956. funcBody = funcBody->GetParseableFunctionInfo(); // RegisterFunction may parse and update function body
  957. }
  958. NativeCodeGenerator *nativeCodeGenerator = scriptContext->GetNativeCodeGenerator();
  959. Js::FunctionBody *functionBody = funcBody->GetFunctionBody(); // funcBody is ParseableFunctionInfo
  960. if (!functionBody || !functionBody->GetByteCode())
  961. {
  962. return scriptContext->GetLibrary()->GetUndefined();
  963. }
  964. Js::Var retVal = RejitIRViewerFunction(nativeCodeGenerator, functionBody, scriptContext);
  965. return retVal;
  966. }
  967. }
  968. #endif /* IR_VIEWER */
  969. Var GlobalObject::EntryParseInt(RecyclableObject* function, CallInfo callInfo, ...)
  970. {
  971. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  972. ARGUMENTS(args, callInfo);
  973. ScriptContext* scriptContext = function->GetScriptContext();
  974. Assert(!(callInfo.Flags & CallFlags_New));
  975. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  976. JavascriptString *str;
  977. int radix = 0;
  978. if(args.Info.Count < 2)
  979. {
  980. // We're really converting "undefined" here, but "undefined" produces
  981. // NaN, so just return that directly.
  982. return JavascriptNumber::ToVarNoCheck(JavascriptNumber::NaN, scriptContext);
  983. }
  984. // Short cut for numbers and radix 10
  985. if (((args.Info.Count == 2) ||
  986. (TaggedInt::Is(args[2]) && TaggedInt::ToInt32(args[2]) == 10) ||
  987. (JavascriptNumber::Is(args[2]) && JavascriptNumber::GetValue(args[2]) == 10)))
  988. {
  989. if (TaggedInt::Is(args[1]))
  990. {
  991. return args[1];
  992. }
  993. if (JavascriptNumber::Is(args[1]))
  994. {
  995. double value = JavascriptNumber::GetValue(args[1]);
  996. // make sure we are in the ranges that don't have exponential notation.
  997. double absValue = Math::Abs(value);
  998. if (absValue < 1.0e21 && absValue >= 1e-5)
  999. {
  1000. double result;
  1001. #pragma prefast(suppress:6031, "We don't care about the fraction part")
  1002. ::modf(value, &result);
  1003. return JavascriptNumber::ToVarIntCheck(result, scriptContext);
  1004. }
  1005. }
  1006. }
  1007. // convert input to a string
  1008. if (JavascriptString::Is(args[1]))
  1009. {
  1010. str = JavascriptString::FromVar(args[1]);
  1011. }
  1012. else
  1013. {
  1014. str = JavascriptConversion::ToString(args[1], scriptContext);
  1015. }
  1016. if(args.Info.Count > 2)
  1017. {
  1018. // retrieve the radix
  1019. // TODO : verify for ES5 : radix is 10 when undefined or 0, except when it starts with 0x when it is 16.
  1020. radix = JavascriptConversion::ToInt32(args[2], scriptContext);
  1021. if(radix < 0 || radix == 1 || radix > 36)
  1022. {
  1023. //illegal, return NaN
  1024. return JavascriptNumber::ToVarNoCheck(JavascriptNumber::NaN, scriptContext);
  1025. }
  1026. }
  1027. Var result = str->ToInteger(radix);
  1028. return result;
  1029. }
  1030. Var GlobalObject::EntryParseFloat(RecyclableObject* function, CallInfo callInfo, ...)
  1031. {
  1032. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1033. ARGUMENTS(args, callInfo);
  1034. ScriptContext* scriptContext = function->GetScriptContext();
  1035. Assert(!(callInfo.Flags & CallFlags_New));
  1036. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  1037. double result = 0;
  1038. ENTER_PINNED_SCOPE(JavascriptString, str);
  1039. if(args.Info.Count < 2)
  1040. {
  1041. // We're really converting "undefined" here, but "undefined" produces
  1042. // NaN, so just return that directly.
  1043. return JavascriptNumber::ToVarNoCheck(JavascriptNumber::NaN, scriptContext);
  1044. }
  1045. // Short cut for numbers
  1046. if (TaggedInt::Is(args[1]))
  1047. {
  1048. return args[1];
  1049. }
  1050. if(JavascriptNumber::Is_NoTaggedIntCheck(args[1]))
  1051. {
  1052. // If the value is negative zero, return positive zero. Since the parameter type is string, -0 would first be
  1053. // converted to the string "0", then parsed to result in positive zero.
  1054. return
  1055. JavascriptNumber::IsNegZero(JavascriptNumber::GetValue(args[1])) ?
  1056. TaggedInt::ToVarUnchecked(0) :
  1057. args[1];
  1058. }
  1059. // convert input to a string
  1060. if (JavascriptString::Is(args[1]))
  1061. {
  1062. str = JavascriptString::FromVar(args[1]);
  1063. }
  1064. else
  1065. {
  1066. str = JavascriptConversion::ToString(args[1], scriptContext);
  1067. }
  1068. // skip preceding whitespace
  1069. const char16 *pch = scriptContext->GetCharClassifier()->SkipWhiteSpace(str->GetSz());
  1070. // perform the string -> float conversion
  1071. result = NumberUtilities::StrToDbl(pch, &pch, scriptContext);
  1072. LEAVE_PINNED_SCOPE(); // str
  1073. return JavascriptNumber::ToVarNoCheck(result, scriptContext);
  1074. }
  1075. Var GlobalObject::EntryIsNaN(RecyclableObject* function, CallInfo callInfo, ...)
  1076. {
  1077. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1078. ARGUMENTS(args, callInfo);
  1079. ScriptContext* scriptContext = function->GetScriptContext();
  1080. Assert(!(callInfo.Flags & CallFlags_New));
  1081. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  1082. if(args.Info.Count < 2)
  1083. {
  1084. return scriptContext->GetLibrary()->GetTrue();
  1085. }
  1086. return JavascriptBoolean::ToVar(
  1087. JavascriptNumber::IsNan(JavascriptConversion::ToNumber(args[1],scriptContext)),
  1088. scriptContext);
  1089. }
  1090. Var GlobalObject::EntryIsFinite(RecyclableObject* function, CallInfo callInfo, ...)
  1091. {
  1092. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1093. ARGUMENTS(args, callInfo);
  1094. ScriptContext* scriptContext = function->GetScriptContext();
  1095. Assert(!(callInfo.Flags & CallFlags_New));
  1096. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  1097. if(args.Info.Count < 2)
  1098. {
  1099. return scriptContext->GetLibrary()->GetFalse();
  1100. }
  1101. return JavascriptBoolean::ToVar(
  1102. NumberUtilities::IsFinite(JavascriptConversion::ToNumber(args[1],scriptContext)),
  1103. scriptContext);
  1104. }
  1105. Var GlobalObject::EntryDecodeURI(RecyclableObject* function, CallInfo callInfo, ...)
  1106. {
  1107. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1108. ARGUMENTS(args, callInfo);
  1109. ScriptContext* scriptContext = function->GetScriptContext();
  1110. Assert(!(callInfo.Flags & CallFlags_New));
  1111. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  1112. return UriHelper::DecodeCoreURI(scriptContext, args, UriHelper::URIReserved);
  1113. }
  1114. Var GlobalObject::EntryDecodeURIComponent(RecyclableObject* function, CallInfo callInfo, ...)
  1115. {
  1116. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1117. ARGUMENTS(args, callInfo);
  1118. ScriptContext* scriptContext = function->GetScriptContext();
  1119. Assert(!(callInfo.Flags & CallFlags_New));
  1120. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  1121. return UriHelper::DecodeCoreURI(scriptContext, args, UriHelper::URINone);
  1122. }
  1123. Var GlobalObject::EntryEncodeURI(RecyclableObject* function, CallInfo callInfo, ...)
  1124. {
  1125. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1126. ARGUMENTS(args, callInfo);
  1127. ScriptContext* scriptContext = function->GetScriptContext();
  1128. Assert(!(callInfo.Flags & CallFlags_New));
  1129. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  1130. return UriHelper::EncodeCoreURI(scriptContext, args, UriHelper::URIReserved | UriHelper::URIUnescaped);
  1131. }
  1132. Var GlobalObject::EntryEncodeURIComponent(RecyclableObject* function, CallInfo callInfo, ...)
  1133. {
  1134. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1135. ARGUMENTS(args, callInfo);
  1136. ScriptContext* scriptContext = function->GetScriptContext();
  1137. Assert(!(callInfo.Flags & CallFlags_New));
  1138. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  1139. return UriHelper::EncodeCoreURI(scriptContext, args, UriHelper::URIUnescaped);
  1140. }
  1141. //
  1142. // Part of Appendix B of ES5 spec
  1143. //
  1144. // This is a bit field for the hex values: 00-29, 2C, 3A-3F, 5B-5E, 60, 7B-FF
  1145. // These are the values escape encodes using the default mask (or mask >= 4)
  1146. static const BYTE _grfbitEscape[] =
  1147. {
  1148. 0xFF, 0xFF, // 00 - 0F
  1149. 0xFF, 0xFF, // 10 - 1F
  1150. 0xFF, 0x13, // 20 - 2F
  1151. 0x00, 0xFC, // 30 - 3F
  1152. 0x00, 0x00, // 40 - 4F
  1153. 0x00, 0x78, // 50 - 5F
  1154. 0x01, 0x00, // 60 - 6F
  1155. 0x00, 0xF8, // 70 - 7F
  1156. 0xFF, 0xFF, // 80 - 8F
  1157. 0xFF, 0xFF, // 90 - 9F
  1158. 0xFF, 0xFF, // A0 - AF
  1159. 0xFF, 0xFF, // B0 - BF
  1160. 0xFF, 0xFF, // C0 - CF
  1161. 0xFF, 0xFF, // D0 - DF
  1162. 0xFF, 0xFF, // E0 - EF
  1163. 0xFF, 0xFF, // F0 - FF
  1164. };
  1165. Var GlobalObject::EntryEscape(RecyclableObject* function, CallInfo callInfo, ...)
  1166. {
  1167. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1168. ARGUMENTS(args, callInfo);
  1169. ScriptContext* scriptContext = function->GetScriptContext();
  1170. Assert(!(callInfo.Flags & CallFlags_New));
  1171. if (args.Info.Count <= 1)
  1172. {
  1173. return scriptContext->GetLibrary()->GetUndefinedDisplayString();
  1174. }
  1175. CompoundString * bs = nullptr;
  1176. ENTER_PINNED_SCOPE(JavascriptString, src);
  1177. src = JavascriptConversion::ToString(args[1], scriptContext);
  1178. bs = CompoundString::NewWithCharCapacity(src->GetLength(), scriptContext->GetLibrary());
  1179. char16 chw;
  1180. char16 * pchSrc;
  1181. char16 * pchLim;
  1182. const char _rgchHex[] = "0123456789ABCDEF";
  1183. pchSrc = const_cast<char16 *>(src->GetString());
  1184. pchLim = pchSrc + src->GetLength();
  1185. while (pchSrc < pchLim)
  1186. {
  1187. chw = *pchSrc++;
  1188. if (0 != (chw & 0xFF00))
  1189. {
  1190. bs->AppendChars(_u("%u"));
  1191. bs->AppendChars(static_cast<char16>(_rgchHex[(chw >> 12) & 0x0F]));
  1192. bs->AppendChars(static_cast<char16>(_rgchHex[(chw >> 8) & 0x0F]));
  1193. bs->AppendChars(static_cast<char16>(_rgchHex[(chw >> 4) & 0x0F]));
  1194. bs->AppendChars(static_cast<char16>(_rgchHex[chw & 0x0F]));
  1195. }
  1196. else if (_grfbitEscape[chw >> 3] & (1 << (chw & 7)))
  1197. {
  1198. // Escape the byte.
  1199. bs->AppendChars(_u('%'));
  1200. bs->AppendChars(static_cast<char16>(_rgchHex[chw >> 4]));
  1201. bs->AppendChars(static_cast<char16>(_rgchHex[chw & 0x0F]));
  1202. }
  1203. else
  1204. {
  1205. bs->AppendChars(chw);
  1206. }
  1207. }
  1208. LEAVE_PINNED_SCOPE(); // src
  1209. return bs;
  1210. }
  1211. //
  1212. // Part of Appendix B of ES5 spec
  1213. //
  1214. Var GlobalObject::EntryUnEscape(RecyclableObject* function, CallInfo callInfo, ...)
  1215. {
  1216. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1217. ARGUMENTS(args, callInfo);
  1218. ScriptContext* scriptContext = function->GetScriptContext();
  1219. Assert(!(callInfo.Flags & CallFlags_New));
  1220. if (args.Info.Count <= 1)
  1221. {
  1222. return scriptContext->GetLibrary()->GetUndefinedDisplayString();
  1223. }
  1224. char16 chw;
  1225. char16 chT;
  1226. char16 * pchSrc;
  1227. char16 * pchLim;
  1228. char16 * pchMin;
  1229. CompoundString * bs = nullptr;
  1230. ENTER_PINNED_SCOPE(JavascriptString, src);
  1231. src = JavascriptConversion::ToString(args[1], scriptContext);
  1232. bs = CompoundString::NewWithCharCapacity(src->GetLength(), scriptContext->GetLibrary());
  1233. pchSrc = const_cast<char16 *>(src->GetString());
  1234. pchLim = pchSrc + src->GetLength();
  1235. while (pchSrc < pchLim)
  1236. {
  1237. if ('%' != (chT = *pchSrc++))
  1238. {
  1239. bs->AppendChars(chT);
  1240. continue;
  1241. }
  1242. pchMin = pchSrc;
  1243. chT = *pchSrc++;
  1244. if ('u' != chT)
  1245. {
  1246. chw = 0;
  1247. goto LTwoHexDigits;
  1248. }
  1249. // 4 hex digits.
  1250. if ((chT = *pchSrc++ - '0') <= 9)
  1251. chw = chT * 0x1000;
  1252. else if ((chT -= 'A' - '0') <= 5 || (chT -= 'a' - 'A') <= 5)
  1253. chw = (chT + 10) * 0x1000;
  1254. else
  1255. goto LHexError;
  1256. if ((chT = *pchSrc++ - '0') <= 9)
  1257. chw += chT * 0x0100;
  1258. else if ((chT -= 'A' - '0') <= 5 || (chT -= 'a' - 'A') <= 5)
  1259. chw += (chT + 10) * 0x0100;
  1260. else
  1261. goto LHexError;
  1262. chT = *pchSrc++;
  1263. LTwoHexDigits:
  1264. if ((chT -= '0') <= 9)
  1265. chw += chT * 0x0010;
  1266. else if ((chT -= 'A' - '0') <= 5 || (chT -= 'a' - 'A') <= 5)
  1267. chw += (chT + 10) * 0x0010;
  1268. else
  1269. goto LHexError;
  1270. if ((chT = *pchSrc++ - '0') <= 9)
  1271. chw += chT;
  1272. else if ((chT -= 'A' - '0') <= 5 || (chT -= 'a' - 'A') <= 5)
  1273. chw += chT + 10;
  1274. else
  1275. {
  1276. LHexError:
  1277. pchSrc = pchMin;
  1278. chw = '%';
  1279. }
  1280. bs->AppendChars(chw);
  1281. }
  1282. LEAVE_PINNED_SCOPE(); // src
  1283. return bs;
  1284. }
  1285. #if DBG
  1286. void DebugClearStack()
  1287. {
  1288. char buffer[1024];
  1289. memset(buffer, 0, sizeof(buffer));
  1290. }
  1291. #endif
  1292. Var GlobalObject::EntryCollectGarbage(RecyclableObject* function, CallInfo callInfo, ...)
  1293. {
  1294. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1295. #if DBG_DUMP
  1296. if (Js::Configuration::Global.flags.TraceWin8Allocations)
  1297. {
  1298. Output::Print(_u("MemoryTrace: GlobalObject::EntryCollectGarbage Invoke\n"));
  1299. Output::Flush();
  1300. }
  1301. #endif
  1302. #if DBG
  1303. // Clear 1K of stack to avoid false positive in debug build.
  1304. // Because we don't debug build don't stack pack
  1305. DebugClearStack();
  1306. #endif
  1307. Assert(!(callInfo.Flags & CallFlags_New));
  1308. ScriptContext* scriptContext = function->GetScriptContext();
  1309. if (!scriptContext->GetConfig()->IsCollectGarbageEnabled()
  1310. #ifdef ENABLE_PROJECTION
  1311. && scriptContext->GetConfig()->GetHostType() != HostType::HostTypeApplication
  1312. && scriptContext->GetConfig()->GetHostType() != HostType::HostTypeWebview
  1313. #endif
  1314. )
  1315. {
  1316. // We expose the CollectGarbage API with flag for compat reasons.
  1317. // If CollectGarbage key is not enabled, and if the HostType is neither
  1318. // HostType::HostTypeApplication nor HostType::HostTypeWebview,
  1319. // then we do not trigger collection.
  1320. return scriptContext->GetLibrary()->GetUndefined();
  1321. }
  1322. Recycler* recycler = scriptContext->GetRecycler();
  1323. if (recycler)
  1324. {
  1325. #if DBG && defined(RECYCLER_DUMP_OBJECT_GRAPH)
  1326. ARGUMENTS(args, callInfo);
  1327. if (args.Info.Count > 1)
  1328. {
  1329. double value = JavascriptConversion::ToNumber(args[1], function->GetScriptContext());
  1330. if (value == 1.0)
  1331. {
  1332. recycler->dumpObjectOnceOnCollect = true;
  1333. }
  1334. }
  1335. #endif
  1336. recycler->CollectNow<CollectNowDecommitNowExplicit>();
  1337. }
  1338. #if DBG_DUMP
  1339. #ifdef ENABLE_PROJECTION
  1340. scriptContext->GetThreadContext()->DumpProjectionContextMemoryStats(_u("Stats after GlobalObject::EntryCollectGarbage call"));
  1341. #endif
  1342. if (Js::Configuration::Global.flags.TraceWin8Allocations)
  1343. {
  1344. Output::Print(_u("MemoryTrace: GlobalObject::EntryCollectGarbage Exit\n"));
  1345. Output::Flush();
  1346. }
  1347. #endif
  1348. return scriptContext->GetLibrary()->GetUndefined();
  1349. }
  1350. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  1351. Var GlobalObject::EntryChWriteTraceEvent(RecyclableObject *function, CallInfo callInfo, ...)
  1352. {
  1353. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1354. ARGUMENTS(args, callInfo);
  1355. if (args.Info.Count < 2)
  1356. {
  1357. return function->GetScriptContext()->GetLibrary()->GetUndefined();
  1358. }
  1359. JS_ETW(EventWriteJSCRIPT_INTERNAL_GENERIC_EVENT(Js::JavascriptConversion::ToString(args[1], function->GetScriptContext())->GetSz()));
  1360. return function->GetScriptContext()->GetLibrary()->GetUndefined();
  1361. }
  1362. #endif
  1363. #if ENABLE_TTD
  1364. //Log a string in the telemetry system (and print to the console)
  1365. Var GlobalObject::EntryTelemetryLog(RecyclableObject* function, CallInfo callInfo, ...)
  1366. {
  1367. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1368. ARGUMENTS(args, callInfo);
  1369. TTDAssert(args.Info.Count >= 2 && Js::JavascriptString::Is(args[1]), "Bad arguments!!!");
  1370. Js::JavascriptString* jsString = Js::JavascriptString::FromVar(args[1]);
  1371. bool doPrint = (args.Info.Count == 3) && Js::JavascriptBoolean::Is(args[2]) && (Js::JavascriptBoolean::FromVar(args[2])->GetValue());
  1372. if(function->GetScriptContext()->ShouldPerformReplayAction())
  1373. {
  1374. function->GetScriptContext()->GetThreadContext()->TTDLog->ReplayTelemetryLogEvent(jsString);
  1375. }
  1376. if(function->GetScriptContext()->ShouldPerformRecordAction())
  1377. {
  1378. function->GetScriptContext()->GetThreadContext()->TTDLog->RecordTelemetryLogEvent(jsString, doPrint);
  1379. }
  1380. if(doPrint)
  1381. {
  1382. //
  1383. //TODO: the host should give us a print callback which we can use here
  1384. //
  1385. Output::Print(_u("%ls\n"), jsString->GetSz());
  1386. fflush(stdout);
  1387. }
  1388. return function->GetScriptContext()->GetLibrary()->GetUndefined();
  1389. }
  1390. //Check if diagnostic trace writing is enabled
  1391. Var GlobalObject::EntryEnabledDiagnosticsTrace(RecyclableObject* function, CallInfo callInfo, ...)
  1392. {
  1393. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1394. ARGUMENTS(args, callInfo);
  1395. if(function->GetScriptContext()->ShouldPerformRecordOrReplayAction())
  1396. {
  1397. return function->GetScriptContext()->GetLibrary()->GetTrue();
  1398. }
  1399. else
  1400. {
  1401. return function->GetScriptContext()->GetLibrary()->GetFalse();
  1402. }
  1403. }
  1404. //Write a copy of the current TTD log to a specified location
  1405. Var GlobalObject::EntryEmitTTDLog(RecyclableObject* function, CallInfo callInfo, ...)
  1406. {
  1407. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1408. ARGUMENTS(args, callInfo);
  1409. Js::JavascriptLibrary* jslib = function->GetScriptContext()->GetLibrary();
  1410. if(args.Info.Count != 2 || !Js::JavascriptString::Is(args[1]))
  1411. {
  1412. return jslib->GetFalse();
  1413. }
  1414. if(function->GetScriptContext()->ShouldPerformReplayAction())
  1415. {
  1416. function->GetScriptContext()->GetThreadContext()->TTDLog->ReplayEmitLogEvent();
  1417. return jslib->GetTrue();
  1418. }
  1419. if(function->GetScriptContext()->ShouldPerformRecordAction())
  1420. {
  1421. Js::JavascriptString* jsString = Js::JavascriptString::FromVar(args[1]);
  1422. function->GetScriptContext()->GetThreadContext()->TTDLog->RecordEmitLogEvent(jsString);
  1423. return jslib->GetTrue();
  1424. }
  1425. return jslib->GetFalse();
  1426. }
  1427. #endif
  1428. //Pattern match is unique to RuntimeObject. Only leading and trailing * are implemented
  1429. //Example: *pat*tern* actually matches all the strings having pat*tern as substring.
  1430. BOOL GlobalObject::MatchPatternHelper(JavascriptString *propertyName, JavascriptString *pattern, ScriptContext *scriptContext)
  1431. {
  1432. if (nullptr == propertyName || nullptr == pattern)
  1433. {
  1434. return FALSE;
  1435. }
  1436. charcount_t patternLength = pattern->GetLength();
  1437. charcount_t nameLength = propertyName->GetLength();
  1438. BOOL bStart;
  1439. BOOL bEnd;
  1440. if (0 == patternLength)
  1441. {
  1442. return TRUE; // empty pattern matches all
  1443. }
  1444. bStart = (_u('*') == pattern->GetItem(0));// Is there a start star?
  1445. bEnd = (_u('*') == pattern->GetItem(patternLength - 1));// Is there an end star?
  1446. //deal with the stars
  1447. if (bStart || bEnd)
  1448. {
  1449. JavascriptString *subPattern;
  1450. int idxStart = bStart? 1: 0;
  1451. int idxEnd = bEnd? (patternLength - 1): patternLength;
  1452. if (idxEnd <= idxStart)
  1453. {
  1454. return TRUE; //scenario double star **
  1455. }
  1456. //get a pattern which doesn't contain leading and trailing stars
  1457. subPattern = JavascriptString::FromVar(JavascriptString::SubstringCore(pattern, idxStart, idxEnd - idxStart, scriptContext));
  1458. uint index = JavascriptString::strstr(propertyName, subPattern, false);
  1459. if (index == (uint)-1)
  1460. {
  1461. return FALSE;
  1462. }
  1463. if (FALSE == bStart)
  1464. {
  1465. return index == 0; //begin at the same place;
  1466. }
  1467. else if (FALSE == bEnd)
  1468. {
  1469. return (index + patternLength - 1) == (nameLength);
  1470. }
  1471. return TRUE;
  1472. }
  1473. else
  1474. {
  1475. //full match
  1476. if (0 == JavascriptString::strcmp(propertyName, pattern))
  1477. {
  1478. return TRUE;
  1479. }
  1480. }
  1481. return FALSE;
  1482. }
  1483. PropertyQueryFlags GlobalObject::HasPropertyQuery(PropertyId propertyId)
  1484. {
  1485. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::HasPropertyQuery(propertyId)) ||
  1486. (this->directHostObject && JavascriptOperators::HasProperty(this->directHostObject, propertyId)) ||
  1487. (this->hostObject && JavascriptOperators::HasProperty(this->hostObject, propertyId)));
  1488. }
  1489. BOOL GlobalObject::HasRootProperty(PropertyId propertyId)
  1490. {
  1491. return __super::HasRootProperty(propertyId) ||
  1492. (this->directHostObject && JavascriptOperators::HasProperty(this->directHostObject, propertyId)) ||
  1493. (this->hostObject && JavascriptOperators::HasProperty(this->hostObject, propertyId));
  1494. }
  1495. BOOL GlobalObject::HasOwnProperty(PropertyId propertyId)
  1496. {
  1497. return JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::HasPropertyQuery(propertyId)) ||
  1498. (this->directHostObject && this->directHostObject->HasProperty(propertyId));
  1499. }
  1500. BOOL GlobalObject::HasOwnPropertyNoHostObject(PropertyId propertyId)
  1501. {
  1502. return JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::HasPropertyQuery(propertyId));
  1503. }
  1504. PropertyQueryFlags GlobalObject::GetPropertyQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  1505. {
  1506. if (JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext)))
  1507. {
  1508. return PropertyQueryFlags::Property_Found;
  1509. }
  1510. return JavascriptConversion::BooleanToPropertyQueryFlags((this->directHostObject && JavascriptOperators::GetProperty(this->directHostObject, propertyId, value, requestContext, info)) ||
  1511. (this->hostObject && JavascriptOperators::GetProperty(this->hostObject, propertyId, value, requestContext, info)));
  1512. }
  1513. PropertyQueryFlags GlobalObject::GetPropertyQuery(Var originalInstance, JavascriptString* propertyNameString, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  1514. {
  1515. PropertyRecord const* propertyRecord;
  1516. this->GetScriptContext()->GetOrAddPropertyRecord(propertyNameString, &propertyRecord);
  1517. return GlobalObject::GetPropertyQuery(originalInstance, propertyRecord->GetPropertyId(), value, info, requestContext);
  1518. }
  1519. BOOL GlobalObject::GetRootProperty(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  1520. {
  1521. if (__super::GetRootProperty(originalInstance, propertyId, value, info, requestContext))
  1522. {
  1523. return TRUE;
  1524. }
  1525. return (this->directHostObject && JavascriptOperators::GetProperty(this->directHostObject, propertyId, value, requestContext, info)) ||
  1526. (this->hostObject && JavascriptOperators::GetProperty(this->hostObject, propertyId, value, requestContext, info));
  1527. }
  1528. BOOL GlobalObject::GetAccessors(PropertyId propertyId, Var* getter, Var* setter, ScriptContext * requestContext)
  1529. {
  1530. if (DynamicObject::GetAccessors(propertyId, getter, setter, requestContext))
  1531. {
  1532. return TRUE;
  1533. }
  1534. if (this->directHostObject)
  1535. {
  1536. return this->directHostObject->GetAccessors(propertyId, getter, setter, requestContext);
  1537. }
  1538. else if (this->hostObject)
  1539. {
  1540. return this->hostObject->GetAccessors(propertyId, getter, setter, requestContext);
  1541. }
  1542. return FALSE;
  1543. }
  1544. PropertyQueryFlags GlobalObject::GetPropertyReferenceQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info,
  1545. ScriptContext* requestContext)
  1546. {
  1547. if (JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::GetPropertyReferenceQuery(originalInstance, propertyId, value, info, requestContext)))
  1548. {
  1549. return PropertyQueryFlags::Property_Found;
  1550. }
  1551. return JavascriptConversion::BooleanToPropertyQueryFlags((this->directHostObject && JavascriptOperators::GetPropertyReference(this->directHostObject, propertyId, value, requestContext, info)) ||
  1552. (this->hostObject && JavascriptOperators::GetPropertyReference(this->hostObject, propertyId, value, requestContext, info)));
  1553. }
  1554. BOOL GlobalObject::GetRootPropertyReference(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info,
  1555. ScriptContext* requestContext)
  1556. {
  1557. if (__super::GetRootPropertyReference(originalInstance, propertyId, value, info, requestContext))
  1558. {
  1559. return true;
  1560. }
  1561. return (this->directHostObject && JavascriptOperators::GetPropertyReference(this->directHostObject, propertyId, value, requestContext, info)) ||
  1562. (this->hostObject && JavascriptOperators::GetPropertyReference(this->hostObject, propertyId, value, requestContext, info));
  1563. }
  1564. BOOL GlobalObject::InitProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  1565. {
  1566. // var x = 10; variables declared with "var" at global scope
  1567. // These cannot be deleted
  1568. // In ES5 they are enumerable.
  1569. PropertyAttributes attributes = PropertyWritable | PropertyEnumerable | PropertyDeclaredGlobal;
  1570. flags = static_cast<PropertyOperationFlags>(flags | PropertyOperation_ThrowIfNotExtensible);
  1571. return DynamicObject::SetPropertyWithAttributes(propertyId, value, attributes, info, flags);
  1572. }
  1573. BOOL GlobalObject::InitPropertyInEval(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  1574. {
  1575. // This is var/function declared inside the 'eval'
  1576. PropertyAttributes attributes = PropertyDynamicTypeDefaults | PropertyDeclaredGlobal;
  1577. flags = static_cast<PropertyOperationFlags>(flags | PropertyOperation_ThrowIfNotExtensible);
  1578. return DynamicObject::SetPropertyWithAttributes(propertyId, value, attributes, info, flags);
  1579. }
  1580. BOOL GlobalObject::InitPropertyScoped(PropertyId propertyId, Var value)
  1581. {
  1582. // var x = 10; variables declared with "var" inside "eval"
  1583. // These CAN be deleted
  1584. // in ES5 they are enumerable.
  1585. //
  1586. PropertyAttributes attributes = PropertyDynamicTypeDefaults | PropertyDeclaredGlobal;
  1587. return DynamicObject::SetPropertyWithAttributes(propertyId, value, attributes, NULL, PropertyOperation_ThrowIfNotExtensible);
  1588. }
  1589. BOOL GlobalObject::InitFuncScoped(PropertyId propertyId, Var value)
  1590. {
  1591. // Var binding of functions declared in eval are elided when conflicting
  1592. // with global scope let/const variables, so do not actually set the
  1593. // property if it exists and is a let/const variable.
  1594. bool noRedecl = false;
  1595. if (!GetTypeHandler()->HasRootProperty(this, propertyId, &noRedecl) || !noRedecl)
  1596. {
  1597. //
  1598. // var x = 10; variables declared with "var" inside "eval"
  1599. // These CAN be deleted
  1600. // in ES5 they are enumerable.
  1601. PropertyAttributes attributes = PropertyDynamicTypeDefaults;
  1602. DynamicObject::SetPropertyWithAttributes(propertyId, value, attributes, NULL, PropertyOperation_ThrowIfNotExtensible);
  1603. }
  1604. return true;
  1605. }
  1606. BOOL GlobalObject::SetExistingProperty(PropertyId propertyId, Var value, PropertyValueInfo* info, BOOL *setAttempted)
  1607. {
  1608. BOOL hasOwnProperty = JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::HasPropertyQuery(propertyId));
  1609. BOOL hasProperty = JavascriptOperators::HasProperty(this->GetPrototype(), propertyId);
  1610. *setAttempted = TRUE;
  1611. if (this->directHostObject &&
  1612. !hasOwnProperty &&
  1613. !hasProperty &&
  1614. this->directHostObject->HasProperty(propertyId))
  1615. {
  1616. // directHostObject->HasProperty returns true for things in global collections, however, they are not able to be set.
  1617. // When we call SetProperty we'll return FALSE which means fall back to GlobalObject::SetProperty and shadow our collection
  1618. // object rather than failing the set altogether. See bug Windows Out Of Band Releases 1144780 and linked bugs for details.
  1619. if (this->directHostObject->SetProperty(propertyId, value, PropertyOperation_None, info))
  1620. {
  1621. return TRUE;
  1622. }
  1623. }
  1624. else
  1625. if (this->hostObject &&
  1626. // Consider to revert to the commented line and ignore the prototype chain when direct host is on by default in IE9 mode
  1627. !hasOwnProperty &&
  1628. !hasProperty &&
  1629. this->hostObject->HasProperty(propertyId))
  1630. {
  1631. return this->hostObject->SetProperty(propertyId, value, PropertyOperation_None, NULL);
  1632. }
  1633. if (hasOwnProperty || hasProperty)
  1634. {
  1635. return DynamicObject::SetProperty(propertyId, value, PropertyOperation_None, info);
  1636. }
  1637. *setAttempted = FALSE;
  1638. return FALSE;
  1639. }
  1640. BOOL GlobalObject::SetExistingRootProperty(PropertyId propertyId, Var value, PropertyValueInfo* info, BOOL *setAttempted)
  1641. {
  1642. BOOL hasOwnProperty = __super::HasRootProperty(propertyId);
  1643. BOOL hasProperty = JavascriptOperators::HasProperty(this->GetPrototype(), propertyId);
  1644. *setAttempted = TRUE;
  1645. if (this->directHostObject &&
  1646. !hasOwnProperty &&
  1647. !hasProperty &&
  1648. this->directHostObject->HasProperty(propertyId))
  1649. {
  1650. // directHostObject->HasProperty returns true for things in global collections, however, they are not able to be set.
  1651. // When we call SetProperty we'll return FALSE which means fall back to GlobalObject::SetProperty and shadow our collection
  1652. // object rather than failing the set altogether. See bug Windows Out Of Band Releases 1144780 and linked bugs for details.
  1653. if (this->directHostObject->SetProperty(propertyId, value, PropertyOperation_None, info))
  1654. {
  1655. return TRUE;
  1656. }
  1657. }
  1658. else
  1659. if (this->hostObject &&
  1660. // Consider to revert to the commented line and ignore the prototype chain when direct host is on by default in IE9 mode
  1661. !hasOwnProperty &&
  1662. !hasProperty &&
  1663. this->hostObject->HasProperty(propertyId))
  1664. {
  1665. return this->hostObject->SetProperty(propertyId, value, PropertyOperation_None, NULL);
  1666. }
  1667. if (hasOwnProperty || hasProperty)
  1668. {
  1669. return __super::SetRootProperty(propertyId, value, PropertyOperation_None, info);
  1670. }
  1671. *setAttempted = FALSE;
  1672. return FALSE;
  1673. }
  1674. BOOL GlobalObject::SetProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  1675. {
  1676. Assert(!(flags & PropertyOperation_Root));
  1677. BOOL setAttempted = TRUE;
  1678. if (this->SetExistingProperty(propertyId, value, info, &setAttempted))
  1679. {
  1680. return TRUE;
  1681. }
  1682. //
  1683. // Set was attempted. But the set operation returned false.
  1684. // This happens, when the property is read only.
  1685. // In those scenarios, we should be setting the property with default attributes
  1686. //
  1687. if (setAttempted)
  1688. {
  1689. return FALSE;
  1690. }
  1691. // Windows 8 430092: When we set a new property on globalObject there may be stale inline caches holding onto directHostObject->prototype
  1692. // properties of the same name. So we need to clear proto caches in this scenario. But check for same property in directHostObject->prototype
  1693. // chain is expensive (call to DOM) compared to just invalidating the cache.
  1694. // If this blind invalidation is expensive in any scenario then we need to revisit this.
  1695. // Another solution proposed was not to cache any of the properties of window->directHostObject->prototype.
  1696. // if ((this->directHostObject && JavascriptOperators::HasProperty(this->directHostObject->GetPrototype(), propertyId)) ||
  1697. // (this->hostObject && JavascriptOperators::HasProperty(this->hostObject->GetPrototype(), propertyId)))
  1698. this->GetScriptContext()->InvalidateProtoCaches(propertyId);
  1699. //
  1700. // x = 10; implicit/phantom variable at global scope
  1701. // These CAN be deleted
  1702. // In ES5 they are enumerable.
  1703. PropertyAttributes attributes = PropertyDynamicTypeDefaults;
  1704. return DynamicObject::SetPropertyWithAttributes(propertyId, value, attributes, info);
  1705. }
  1706. BOOL GlobalObject::SetProperty(JavascriptString* propertyNameString, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  1707. {
  1708. PropertyRecord const * propertyRecord;
  1709. this->GetScriptContext()->GetOrAddPropertyRecord(propertyNameString, &propertyRecord);
  1710. return GlobalObject::SetProperty(propertyRecord->GetPropertyId(), value, flags, info);
  1711. }
  1712. BOOL GlobalObject::SetRootProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  1713. {
  1714. Assert(flags & PropertyOperation_Root);
  1715. BOOL setAttempted = TRUE;
  1716. if (this->SetExistingRootProperty(propertyId, value, info, &setAttempted))
  1717. {
  1718. return TRUE;
  1719. }
  1720. //
  1721. // Set was attempted. But the set operation returned false.
  1722. // This happens, when the property is read only.
  1723. // In those scenarios, we should be setting the property with default attributes
  1724. //
  1725. if (setAttempted)
  1726. {
  1727. return FALSE;
  1728. }
  1729. if (flags & PropertyOperation_StrictMode)
  1730. {
  1731. if (!GetScriptContext()->GetThreadContext()->RecordImplicitException())
  1732. {
  1733. return FALSE;
  1734. }
  1735. JavascriptError::ThrowReferenceError(GetScriptContext(), JSERR_RefErrorUndefVariable);
  1736. }
  1737. // Windows 8 430092: When we set a new property on globalObject there may be stale inline caches holding onto directHostObject->prototype
  1738. // properties of the same name. So we need to clear proto caches in this scenario. But check for same property in directHostObject->prototype
  1739. // chain is expensive (call to DOM) compared to just invalidating the cache.
  1740. // If this blind invalidation is expensive in any scenario then we need to revisit this.
  1741. // Another solution proposed was not to cache any of the properties of window->directHostObject->prototype.
  1742. // if ((this->directHostObject && JavascriptOperators::HasProperty(this->directHostObject->GetPrototype(), propertyId)) ||
  1743. // (this->hostObject && JavascriptOperators::HasProperty(this->hostObject->GetPrototype(), propertyId)))
  1744. this->GetScriptContext()->InvalidateProtoCaches(propertyId);
  1745. return __super::SetRootProperty(propertyId, value, flags, info);
  1746. }
  1747. BOOL GlobalObject::SetAccessors(PropertyId propertyId, Var getter, Var setter, PropertyOperationFlags flags)
  1748. {
  1749. if (DynamicObject::SetAccessors(propertyId, getter, setter, flags))
  1750. {
  1751. return TRUE;
  1752. }
  1753. if (this->directHostObject)
  1754. {
  1755. return this->directHostObject->SetAccessors(propertyId, getter, setter, flags);
  1756. }
  1757. if (this->hostObject)
  1758. {
  1759. return this->hostObject->SetAccessors(propertyId, getter, setter, flags);
  1760. }
  1761. return TRUE;
  1762. }
  1763. DescriptorFlags GlobalObject::GetSetter(PropertyId propertyId, Var* setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  1764. {
  1765. DescriptorFlags flags = DynamicObject::GetSetter(propertyId, setterValue, info, requestContext);
  1766. if (flags == None)
  1767. {
  1768. if (this->directHostObject)
  1769. {
  1770. // We need to look up the prototype chain here.
  1771. JavascriptOperators::CheckPrototypesForAccessorOrNonWritableProperty(this->directHostObject, propertyId, setterValue, &flags, info, requestContext);
  1772. }
  1773. else if (this->hostObject)
  1774. {
  1775. JavascriptOperators::CheckPrototypesForAccessorOrNonWritableProperty(this->hostObject, propertyId, setterValue, &flags, info, requestContext);
  1776. }
  1777. }
  1778. return flags;
  1779. }
  1780. DescriptorFlags GlobalObject::GetSetter(JavascriptString* propertyNameString, Var* setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  1781. {
  1782. PropertyRecord const* propertyRecord;
  1783. this->GetScriptContext()->GetOrAddPropertyRecord(propertyNameString, &propertyRecord);
  1784. return GlobalObject::GetSetter(propertyRecord->GetPropertyId(), setterValue, info, requestContext);
  1785. }
  1786. DescriptorFlags GlobalObject::GetRootSetter(PropertyId propertyId, Var* setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  1787. {
  1788. DescriptorFlags flags = __super::GetRootSetter(propertyId, setterValue, info, requestContext);
  1789. if (flags == None)
  1790. {
  1791. if (this->directHostObject)
  1792. {
  1793. // We need to look up the prototype chain here.
  1794. JavascriptOperators::CheckPrototypesForAccessorOrNonWritableProperty(this->directHostObject, propertyId, setterValue, &flags, info, requestContext);
  1795. }
  1796. else if (this->hostObject)
  1797. {
  1798. JavascriptOperators::CheckPrototypesForAccessorOrNonWritableProperty(this->hostObject, propertyId, setterValue, &flags, info, requestContext);
  1799. }
  1800. }
  1801. return flags;
  1802. }
  1803. DescriptorFlags GlobalObject::GetItemSetter(uint32 index, Var* setterValue, ScriptContext* requestContext)
  1804. {
  1805. DescriptorFlags flags = DynamicObject::GetItemSetter(index, setterValue, requestContext);
  1806. if (flags == None)
  1807. {
  1808. if (this->directHostObject)
  1809. {
  1810. // We need to look up the prototype chain here.
  1811. JavascriptOperators::CheckPrototypesForAccessorOrNonWritableItem(this->directHostObject, index, setterValue, &flags, requestContext);
  1812. }
  1813. else if (this->hostObject)
  1814. {
  1815. JavascriptOperators::CheckPrototypesForAccessorOrNonWritableItem(this->hostObject, index, setterValue, &flags, requestContext);
  1816. }
  1817. }
  1818. return flags;
  1819. }
  1820. BOOL GlobalObject::DeleteProperty(PropertyId propertyId, PropertyOperationFlags flags)
  1821. {
  1822. if (JavascriptConversion::PropertyQueryFlagsToBoolean(__super::HasPropertyQuery(propertyId)))
  1823. {
  1824. return __super::DeleteProperty(propertyId, flags);
  1825. }
  1826. else if (this->directHostObject && this->directHostObject->HasProperty(propertyId))
  1827. {
  1828. return this->directHostObject->DeleteProperty(propertyId, flags);
  1829. }
  1830. else if (this->hostObject && this->hostObject->HasProperty(propertyId))
  1831. {
  1832. return this->hostObject->DeleteProperty(propertyId, flags);
  1833. }
  1834. // Non-existent property
  1835. return TRUE;
  1836. }
  1837. BOOL GlobalObject::DeleteProperty(JavascriptString *propertyNameString, PropertyOperationFlags flags)
  1838. {
  1839. PropertyRecord const *propertyRecord = nullptr;
  1840. if (JavascriptOperators::ShouldTryDeleteProperty(this, propertyNameString, &propertyRecord))
  1841. {
  1842. Assert(propertyRecord);
  1843. return DeleteProperty(propertyRecord->GetPropertyId(), flags);
  1844. }
  1845. return TRUE;
  1846. }
  1847. BOOL GlobalObject::DeleteRootProperty(PropertyId propertyId, PropertyOperationFlags flags)
  1848. {
  1849. if (__super::HasRootProperty(propertyId))
  1850. {
  1851. return __super::DeleteRootProperty(propertyId, flags);
  1852. }
  1853. else if (this->directHostObject && this->directHostObject->HasProperty(propertyId))
  1854. {
  1855. return this->directHostObject->DeleteProperty(propertyId, flags);
  1856. }
  1857. else if (this->hostObject && this->hostObject->HasProperty(propertyId))
  1858. {
  1859. return this->hostObject->DeleteProperty(propertyId, flags);
  1860. }
  1861. // Non-existent property
  1862. return TRUE;
  1863. }
  1864. PropertyQueryFlags GlobalObject::HasItemQuery(uint32 index)
  1865. {
  1866. return JavascriptConversion::BooleanToPropertyQueryFlags(JavascriptConversion::PropertyQueryFlagsToBoolean((DynamicObject::HasItemQuery(index)))
  1867. || (this->directHostObject && JavascriptOperators::HasItem(this->directHostObject, index))
  1868. || (this->hostObject && JavascriptOperators::HasItem(this->hostObject, index)));
  1869. }
  1870. BOOL GlobalObject::HasOwnItem(uint32 index)
  1871. {
  1872. return JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::HasItemQuery(index))
  1873. || (this->directHostObject && this->directHostObject->HasItem(index));
  1874. }
  1875. PropertyQueryFlags GlobalObject::GetItemReferenceQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  1876. {
  1877. if (JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::GetItemReferenceQuery(originalInstance, index, value, requestContext)))
  1878. {
  1879. return PropertyQueryFlags::Property_Found;
  1880. }
  1881. return JavascriptConversion::BooleanToPropertyQueryFlags(
  1882. (this->directHostObject && JavascriptConversion::PropertyQueryFlagsToBoolean(this->directHostObject->GetItemReferenceQuery(originalInstance, index, value, requestContext))) ||
  1883. (this->hostObject && JavascriptConversion::PropertyQueryFlagsToBoolean(this->hostObject->GetItemReferenceQuery(originalInstance, index, value, requestContext))));
  1884. }
  1885. BOOL GlobalObject::SetItem(uint32 index, Var value, PropertyOperationFlags flags)
  1886. {
  1887. BOOL result = DynamicObject::SetItem(index, value, flags);
  1888. return result;
  1889. }
  1890. PropertyQueryFlags GlobalObject::GetItemQuery(Var originalInstance, uint32 index, Var* value, ScriptContext* requestContext)
  1891. {
  1892. if (JavascriptConversion::PropertyQueryFlagsToBoolean(DynamicObject::GetItemQuery(originalInstance, index, value, requestContext)))
  1893. {
  1894. return PropertyQueryFlags::Property_Found;
  1895. }
  1896. return JavascriptConversion::BooleanToPropertyQueryFlags((this->directHostObject && this->directHostObject->GetItem(originalInstance, index, value, requestContext)) ||
  1897. (this->hostObject && this->hostObject->GetItem(originalInstance, index, value, requestContext)));
  1898. }
  1899. BOOL GlobalObject::DeleteItem(uint32 index, PropertyOperationFlags flags)
  1900. {
  1901. if (DynamicObject::DeleteItem(index, flags))
  1902. {
  1903. return TRUE;
  1904. }
  1905. if (this->directHostObject)
  1906. {
  1907. return this->directHostObject->DeleteItem(index, flags);
  1908. }
  1909. if (this->hostObject)
  1910. {
  1911. return this->hostObject->DeleteItem(index, flags);
  1912. }
  1913. return FALSE;
  1914. }
  1915. BOOL GlobalObject::GetDiagValueString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  1916. {
  1917. stringBuilder->AppendCppLiteral(_u("{...}"));
  1918. return TRUE;
  1919. }
  1920. BOOL GlobalObject::GetDiagTypeString(StringBuilder<ArenaAllocator>* stringBuilder, ScriptContext* requestContext)
  1921. {
  1922. stringBuilder->AppendCppLiteral(_u("Object, (Global)"));
  1923. return TRUE;
  1924. }
  1925. BOOL GlobalObject::StrictEquals(__in Js::Var other, __out BOOL* value, ScriptContext * requestContext)
  1926. {
  1927. if (this == other)
  1928. {
  1929. *value = TRUE;
  1930. return TRUE;
  1931. }
  1932. else if (this->directHostObject)
  1933. {
  1934. return this->directHostObject->StrictEquals(other, value, requestContext);
  1935. }
  1936. else if (this->hostObject)
  1937. {
  1938. return this->hostObject->StrictEquals(other, value, requestContext);
  1939. }
  1940. *value = FALSE;
  1941. return FALSE;
  1942. }
  1943. BOOL GlobalObject::Equals(__in Js::Var other, __out BOOL* value, ScriptContext * requestContext)
  1944. {
  1945. if (this == other)
  1946. {
  1947. *value = TRUE;
  1948. return TRUE;
  1949. }
  1950. else if (this->directHostObject)
  1951. {
  1952. return this->directHostObject->Equals(other, value, requestContext);
  1953. }
  1954. else if (this->hostObject)
  1955. {
  1956. return this->hostObject->Equals(other, value, requestContext);
  1957. }
  1958. *value = FALSE;
  1959. return TRUE;
  1960. }
  1961. #if ENABLE_TTD
  1962. TTD::NSSnapObjects::SnapObjectType GlobalObject::GetSnapTag_TTD() const
  1963. {
  1964. return TTD::NSSnapObjects::SnapObjectType::SnapWellKnownObject;
  1965. }
  1966. void GlobalObject::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  1967. {
  1968. //
  1969. //TODO: we assume that the global object is always set right (e.g., ignore the directHostObject and secureDirectHostObject values) we need to verify that this is ok and/or what to do about it
  1970. //
  1971. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<void*, TTD::NSSnapObjects::SnapObjectType::SnapWellKnownObject>(objData, nullptr);
  1972. }
  1973. #endif
  1974. }