JavascriptObject.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212
  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. using namespace Js;
  7. Var JavascriptObject::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  8. {
  9. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  10. ARGUMENTS(args, callInfo);
  11. ScriptContext* scriptContext = function->GetScriptContext();
  12. JavascriptLibrary* library = scriptContext->GetLibrary();
  13. AssertMsg(args.HasArg(), "Should always have implicit 'this'");
  14. Var newTarget = args.GetNewTarget();
  15. if (JavascriptOperators::GetAndAssertIsConstructorSuperCall(args) &&
  16. newTarget != function)
  17. {
  18. return JavascriptOperators::OrdinaryCreateFromConstructor(
  19. VarTo<RecyclableObject>(newTarget),
  20. library->CreateObject(true),
  21. nullptr,
  22. scriptContext);
  23. }
  24. Var arg = args.Info.Count > 1 ? args[1] : library->GetUndefined();
  25. switch (JavascriptOperators::GetTypeId(arg))
  26. {
  27. case TypeIds_Undefined:
  28. case TypeIds_Null:
  29. // Null and undefined result in a new object
  30. return (callInfo.Flags & CallFlags_NotUsed)
  31. ? arg
  32. : library->CreateObject(true);
  33. case TypeIds_StringObject:
  34. case TypeIds_Function:
  35. case TypeIds_Array:
  36. case TypeIds_ES5Array:
  37. case TypeIds_RegEx:
  38. case TypeIds_NumberObject:
  39. case TypeIds_SIMDObject:
  40. case TypeIds_Date:
  41. case TypeIds_BooleanObject:
  42. case TypeIds_Error:
  43. case TypeIds_Object:
  44. case TypeIds_Arguments:
  45. case TypeIds_ActivationObject:
  46. case TypeIds_SymbolObject:
  47. // Since we know this is an object, we can skip ToObject
  48. return arg;
  49. }
  50. RecyclableObject* result = nullptr;
  51. JavascriptConversion::ToObject(arg, scriptContext, &result);
  52. Assert(result);
  53. return result;
  54. }
  55. Var JavascriptObject::EntryHasOwnProperty(RecyclableObject* function, CallInfo callInfo, ...)
  56. {
  57. JIT_HELPER_REENTRANT_HEADER(Object_HasOwnProperty);
  58. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  59. ARGUMENTS(args, callInfo);
  60. ScriptContext* scriptContext = function->GetScriptContext();
  61. Assert(!(callInfo.Flags & CallFlags_New));
  62. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  63. RecyclableObject* dynamicObject = nullptr;
  64. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  65. {
  66. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Object.prototype.hasOwnProperty"));
  67. }
  68. Var propertyName = args.Info.Count == 1 ? scriptContext->GetLibrary()->GetUndefined() : args[1];
  69. const PropertyRecord* propertyRecord;
  70. PropertyString* propertyString;
  71. JavascriptConversion::ToPropertyKey(propertyName, scriptContext, &propertyRecord, &propertyString);
  72. if (JavascriptOperators::HasOwnProperty(dynamicObject, propertyRecord->GetPropertyId(), scriptContext, propertyString))
  73. {
  74. return scriptContext->GetLibrary()->GetTrue();
  75. }
  76. return scriptContext->GetLibrary()->GetFalse();
  77. JIT_HELPER_END(Object_HasOwnProperty);
  78. }
  79. Var JavascriptObject::EntryPropertyIsEnumerable(RecyclableObject* function, CallInfo callInfo, ...)
  80. {
  81. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  82. ARGUMENTS(args, callInfo);
  83. ScriptContext* scriptContext = function->GetScriptContext();
  84. Assert(!(callInfo.Flags & CallFlags_New));
  85. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  86. RecyclableObject* dynamicObject = nullptr;
  87. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  88. {
  89. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Object.prototype.propertyIsEnumerable"));
  90. }
  91. if (args.Info.Count >= 2)
  92. {
  93. const PropertyRecord* propertyRecord;
  94. JavascriptConversion::ToPropertyKey(args[1], scriptContext, &propertyRecord, nullptr);
  95. PropertyId propertyId = propertyRecord->GetPropertyId();
  96. PropertyDescriptor currentDescriptor;
  97. BOOL isCurrentDescriptorDefined = JavascriptOperators::GetOwnPropertyDescriptor(dynamicObject, propertyId, scriptContext, &currentDescriptor);
  98. if (isCurrentDescriptorDefined == TRUE)
  99. {
  100. if (currentDescriptor.IsEnumerable())
  101. {
  102. return scriptContext->GetLibrary()->GetTrue();
  103. }
  104. }
  105. }
  106. return scriptContext->GetLibrary()->GetFalse();
  107. }
  108. BOOL JavascriptObject::ChangePrototype(RecyclableObject* object, RecyclableObject* newPrototype, bool shouldThrow, ScriptContext* scriptContext)
  109. {
  110. // 8.3.2 [[SetInheritance]] (V)
  111. // When the [[SetInheritance]] internal method of O is called with argument V the following steps are taken:
  112. // 1. Assert: Either Type(V) is Object or Type(V) is Null.
  113. Assert(JavascriptOperators::IsObject(object));
  114. Assert(JavascriptOperators::IsObjectOrNull(newPrototype));
  115. if (VarIs<JavascriptProxy>(object))
  116. {
  117. JavascriptProxy* proxy = VarTo<JavascriptProxy>(object);
  118. CrossSite::ForceCrossSiteThunkOnPrototypeChain(newPrototype);
  119. return proxy->SetPrototypeTrap(newPrototype, shouldThrow, scriptContext);
  120. }
  121. // 2. Let extensible be the value of the [[Extensible]] internal data property of O.
  122. // 3. Let current be the value of the [[Prototype]] internal data property of O.
  123. // 4. If SameValue(V, current), then return true.
  124. if (newPrototype == JavascriptObject::GetPrototypeOf(object, scriptContext))
  125. {
  126. return TRUE;
  127. }
  128. // 5. If extensible is false, then return false.
  129. if (!object->IsExtensible())
  130. {
  131. if (shouldThrow)
  132. {
  133. JavascriptError::ThrowTypeError(scriptContext, JSERR_NonExtensibleObject);
  134. }
  135. return FALSE;
  136. }
  137. if (object->IsProtoImmutable())
  138. {
  139. // ES2016 19.1.3:
  140. // The Object prototype object is the intrinsic object %ObjectPrototype%.
  141. // The Object prototype object is an immutable prototype exotic object.
  142. // ES2016 9.4.7:
  143. // An immutable prototype exotic object is an exotic object that has an immutable [[Prototype]] internal slot.
  144. JavascriptError::ThrowTypeError(scriptContext, JSERR_ImmutablePrototypeSlot);
  145. }
  146. // 6. If V is not null, then
  147. // a. Let p be V.
  148. // b. Repeat, while p is not null
  149. // i. If SameValue(p, O) is true, then return false.
  150. // ii. Let nextp be the result of calling the [[GetInheritance]] internal method of p with no arguments.
  151. // iii. ReturnIfAbrupt(nextp).
  152. // iv. Let p be nextp.
  153. if (IsPrototypeOfStopAtProxy(object, newPrototype, scriptContext)) // Reject cycle
  154. {
  155. if (shouldThrow)
  156. {
  157. JavascriptError::ThrowTypeError(scriptContext, JSERR_CyclicProtoValue);
  158. }
  159. return FALSE;
  160. }
  161. // 7. Set the value of the [[Prototype]] internal data property of O to V.
  162. // 8. Return true.
  163. bool isInvalidationOfInlineCacheNeeded = true;
  164. DynamicObject * obj = VarTo<DynamicObject>(object);
  165. // If this object was not prototype object, then no need to invalidate inline caches.
  166. // Simply assign it a new type so if this object used protoInlineCache in past, it will
  167. // be invalidated because of type mismatch and subsequently we will update its protoInlineCache
  168. if (!(obj->GetDynamicType()->GetTypeHandler()->GetFlags() & DynamicTypeHandler::IsPrototypeFlag))
  169. {
  170. // If object has locked type, skip changing its type here as it will be changed anyway below
  171. // when object gets newPrototype object.
  172. if (!obj->HasLockedType())
  173. {
  174. obj->ChangeType();
  175. }
  176. Assert(!obj->GetScriptContext()->GetThreadContext()->IsObjectRegisteredInProtoInlineCaches(obj));
  177. Assert(!obj->GetScriptContext()->GetThreadContext()->IsObjectRegisteredInStoreFieldInlineCaches(obj));
  178. isInvalidationOfInlineCacheNeeded = false;
  179. }
  180. if (isInvalidationOfInlineCacheNeeded)
  181. {
  182. bool allProtoCachesInvalidated = false;
  183. JavascriptOperators::MapObjectAndPrototypes<true>(newPrototype, [&](RecyclableObject* obj)
  184. {
  185. obj->ClearProtoCachesWereInvalidated();
  186. });
  187. // Notify old prototypes that they are being removed from a prototype chain. This triggers invalidating protocache, etc.
  188. JavascriptOperators::MapObjectAndPrototypesUntil<true>(object->GetPrototype(), [&](RecyclableObject* obj)->bool
  189. {
  190. obj->RemoveFromPrototype(scriptContext, &allProtoCachesInvalidated);
  191. return allProtoCachesInvalidated;
  192. });
  193. // Examine new prototype chain. If it brings in any special property, we need to invalidate related caches.
  194. bool objectAndPrototypeChainHasNoSpecialProperties =
  195. JavascriptOperators::CheckIfObjectAndProtoChainHasNoSpecialProperties(newPrototype);
  196. if (!objectAndPrototypeChainHasNoSpecialProperties
  197. || object->GetScriptContext() != newPrototype->GetScriptContext())
  198. {
  199. // The HaveNoSpecialProperties cache is cleared when a property is added or changed,
  200. // but only for types in the same script context. Therefore, if the prototype is in another
  201. // context, the object's cache won't be cleared when a property is added or changed on the prototype.
  202. // Moreover, an object is added to the cache only when its whole prototype chain is in the same
  203. // context.
  204. //
  205. // Since we don't have a way to find out which objects have a certain object as their prototype,
  206. // we clear the cache here instead.
  207. object->GetLibrary()->GetTypesWithNoSpecialPropertyProtoChainCache()->Clear();
  208. }
  209. // Examine new prototype chain. If it brings in any non-WritableData property, we need to invalidate related caches.
  210. bool objectAndPrototypeChainHasOnlyWritableDataProperties =
  211. JavascriptOperators::CheckIfObjectAndPrototypeChainHasOnlyWritableDataProperties(newPrototype);
  212. if (!objectAndPrototypeChainHasOnlyWritableDataProperties
  213. || object->GetScriptContext() != newPrototype->GetScriptContext())
  214. {
  215. // The HaveOnlyWritableDataProperties cache is cleared when a property is added or changed,
  216. // but only for types in the same script context. Therefore, if the prototype is in another
  217. // context, the object's cache won't be cleared when a property is added or changed on the prototype.
  218. // Moreover, an object is added to the cache only when its whole prototype chain is in the same
  219. // context.
  220. //
  221. // Since we don't have a way to find out which objects have a certain object as their prototype,
  222. // we clear the cache here instead.
  223. // Invalidate fast prototype chain writable data test flag
  224. object->GetLibrary()->GetTypesWithOnlyWritablePropertyProtoChainCache()->Clear();
  225. }
  226. if (!allProtoCachesInvalidated)
  227. {
  228. // Invalidate StoreField/PropertyGuards for any non-WritableData property in the new chain
  229. JavascriptOperators::MapObjectAndPrototypesUntil<true>(newPrototype, [&](RecyclableObject* obj)->bool
  230. {
  231. obj->AddToPrototype(scriptContext, &allProtoCachesInvalidated);
  232. return allProtoCachesInvalidated;
  233. });
  234. }
  235. JavascriptOperators::MapObjectAndPrototypesUntil<true>(object->GetPrototype(), [](RecyclableObject* obj)->bool
  236. {
  237. return obj->ClearProtoCachesWereInvalidated();
  238. });
  239. }
  240. // Set to new prototype
  241. if (object->IsExternal() || (DynamicType::Is(object->GetTypeId()) && (UnsafeVarTo<DynamicObject>(object))->IsCrossSiteObject()))
  242. {
  243. CrossSite::ForceCrossSiteThunkOnPrototypeChain(newPrototype);
  244. }
  245. object->SetPrototype(newPrototype);
  246. return TRUE;
  247. }
  248. Var JavascriptObject::EntryIsPrototypeOf(RecyclableObject* function, CallInfo callInfo, ...)
  249. {
  250. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  251. ARGUMENTS(args, callInfo);
  252. ScriptContext* scriptContext = function->GetScriptContext();
  253. Assert(!(callInfo.Flags & CallFlags_New));
  254. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  255. // no property specified
  256. if (args.Info.Count == 1 || !JavascriptOperators::IsObject(args[1]))
  257. {
  258. return scriptContext->GetLibrary()->GetFalse();
  259. }
  260. RecyclableObject* dynamicObject = nullptr;
  261. if (FALSE == JavascriptConversion::ToObject(args[0], scriptContext, &dynamicObject))
  262. {
  263. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Object.prototype.isPrototypeOf"));
  264. }
  265. RecyclableObject* value = VarTo<RecyclableObject>(args[1]);
  266. if (dynamicObject->GetTypeId() == TypeIds_GlobalObject)
  267. {
  268. dynamicObject = VarTo<RecyclableObject>(static_cast<Js::GlobalObject*>(dynamicObject)->ToThis());
  269. }
  270. while (!JavascriptOperators::IsNull(value))
  271. {
  272. value = JavascriptOperators::GetPrototype(value);
  273. if (dynamicObject == value)
  274. {
  275. return scriptContext->GetLibrary()->GetTrue();
  276. }
  277. }
  278. return scriptContext->GetLibrary()->GetFalse();
  279. }
  280. // 19.1.3.5 - Object.prototype.toLocaleString as of ES6 (6.0)
  281. Var JavascriptObject::EntryToLocaleString(RecyclableObject* function, CallInfo callInfo, ...)
  282. {
  283. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  284. ARGUMENTS(args, callInfo);
  285. ScriptContext* scriptContext = function->GetScriptContext();
  286. Assert(!(callInfo.Flags & CallFlags_New));
  287. AssertMsg(args.Info.Count, "Should always have implicit 'this'");
  288. Var thisValue = args[0];
  289. RecyclableObject* dynamicObject = nullptr;
  290. if (FALSE == JavascriptConversion::ToObject(thisValue, scriptContext, &dynamicObject))
  291. {
  292. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Object.prototype.toLocaleString"));
  293. }
  294. Var toStringVar = nullptr;
  295. if (!JavascriptOperators::GetProperty(thisValue, dynamicObject, Js::PropertyIds::toString, &toStringVar, scriptContext) || !JavascriptConversion::IsCallable(toStringVar))
  296. {
  297. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Object.prototype.toLocaleString"));
  298. }
  299. RecyclableObject* toStringFunc = VarTo<RecyclableObject>(toStringVar);
  300. if (toStringFunc == scriptContext->GetLibrary()->GetObjectToStringFunction())
  301. {
  302. return ToStringHelper(thisValue, scriptContext);
  303. }
  304. else
  305. {
  306. return scriptContext->GetThreadContext()->ExecuteImplicitCall(toStringFunc, Js::ImplicitCall_ToPrimitive, [=]()->Js::Var
  307. {
  308. return CALL_FUNCTION(scriptContext->GetThreadContext(), toStringFunc, CallInfo(CallFlags_Value, 1), thisValue);
  309. });
  310. }
  311. }
  312. Var JavascriptObject::EntryToString(RecyclableObject* function, CallInfo callInfo, ...)
  313. {
  314. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  315. ARGUMENTS(args, callInfo);
  316. ScriptContext* scriptContext = function->GetScriptContext();
  317. Assert(!(callInfo.Flags & CallFlags_New));
  318. AssertMsg(args.Info.Count, "Should always have implicit 'this'");
  319. return ToStringHelper(args[0], scriptContext);
  320. }
  321. Var JavascriptObject::GetToStringTagValue(RecyclableObject *thisArg, ScriptContext *scriptContext)
  322. {
  323. if (JavascriptOperators::CheckIfObjectAndProtoChainHasNoSpecialProperties(thisArg))
  324. {
  325. return nullptr;
  326. }
  327. const PropertyId toStringTagId(PropertyIds::_symbolToStringTag);
  328. PolymorphicInlineCache *cache = scriptContext->GetLibrary()->GetToStringTagCache();
  329. PropertyValueInfo info;
  330. // We don't allow cache resizing, at least for the moment: it's more work, and since there's only one
  331. // cache per script context, we can afford to create each cache with the maximum size.
  332. PropertyValueInfo::SetCacheInfo(&info, cache, false);
  333. Var value;
  334. if (CacheOperators::TryGetProperty<
  335. true, // CheckLocal
  336. true, // CheckProto
  337. true, // CheckAccessor
  338. true, // CheckMissing
  339. true, // CheckPolymorphicInlineCache
  340. true, // CheckTypePropertyCache
  341. !PolymorphicInlineCache::IsPolymorphic, // IsInlineCacheAvailable
  342. PolymorphicInlineCache::IsPolymorphic, // IsPolymorphicInlineCacheAvailable
  343. false, // ReturnOperationInfo
  344. false> // OutputExistence
  345. (thisArg, false, thisArg, toStringTagId, &value, scriptContext, nullptr, &info))
  346. {
  347. return value;
  348. }
  349. else
  350. {
  351. #if DBG_DUMP
  352. if (PHASE_VERBOSE_TRACE1(Js::InlineCachePhase))
  353. {
  354. CacheOperators::TraceCache(cache, _u("PatchGetValue"), toStringTagId, scriptContext, thisArg);
  355. }
  356. #endif
  357. return JavascriptOperators::GetProperty(thisArg, thisArg, toStringTagId, scriptContext, &info);
  358. }
  359. }
  360. // ES2017 19.1.3.6 Object.prototype.toString()
  361. JavascriptString* JavascriptObject::ToStringTagHelper(Var thisArg, ScriptContext *scriptContext, TypeId type)
  362. {
  363. JavascriptLibrary *library = scriptContext->GetLibrary();
  364. // 1. If the this value is undefined, return "[object Undefined]".
  365. if (type == TypeIds_Undefined)
  366. {
  367. return library->GetObjectUndefinedDisplayString();
  368. }
  369. // 2. If the this value is null, return "[object Null]".
  370. if (type == TypeIds_Null)
  371. {
  372. return library->GetObjectNullDisplayString();
  373. }
  374. // 3. Let O be ToObject(this value).
  375. RecyclableObject *thisArgAsObject = JavascriptOperators::ToObject(thisArg, scriptContext);
  376. // 15. Let tag be ? Get(O, @@toStringTag).
  377. Var tag = JavascriptObject::GetToStringTagValue(thisArgAsObject, scriptContext);
  378. // 17. Return the String that is the result of concatenating "[object ", tag, and "]".
  379. auto buildToString = [&scriptContext](Var tag) {
  380. JavascriptString *tagStr = VarTo<JavascriptString>(tag);
  381. const WCHAR objectStartString[9] = _u("[object ");
  382. const WCHAR objectEndString[1] = { _u(']') };
  383. CompoundString *const cs = CompoundString::NewWithCharCapacity(_countof(objectStartString)
  384. + _countof(objectEndString) + tagStr->GetLength(), scriptContext->GetLibrary());
  385. cs->AppendChars(objectStartString, _countof(objectStartString) - 1 /* ditch \0 */);
  386. cs->AppendChars(tagStr);
  387. cs->AppendChars(objectEndString, _countof(objectEndString));
  388. return cs;
  389. };
  390. if (tag != nullptr && VarIs<JavascriptString>(tag))
  391. {
  392. return buildToString(tag);
  393. }
  394. // 4. Let isArray be ? IsArray(O).
  395. // There is an implicit check for a null proxy handler in IsArray, so use the operator.
  396. BOOL isArray = JavascriptOperators::IsArray(thisArgAsObject);
  397. // If we don't have a tag or it's not a string, use the 'built in tag'.
  398. if (isArray)
  399. {
  400. // 5. If isArray is true, let builtinTag be "Array".
  401. return library->GetObjectArrayDisplayString();
  402. }
  403. // callable proxy is considered as having [[Call]] internal method and should match #8 below
  404. if (type == TypeIds_Proxy && JavascriptConversion::IsCallable(thisArgAsObject))
  405. {
  406. type = TypeIds_Function;
  407. }
  408. JavascriptString* builtInTag = nullptr;
  409. switch (type)
  410. {
  411. // 6. Else if O is an exotic String object, let builtinTag be "String".
  412. case TypeIds_String:
  413. case TypeIds_StringObject:
  414. builtInTag = library->GetObjectStringDisplayString();
  415. break;
  416. // 7. Else if O has an[[ParameterMap]] internal slot, let builtinTag be "Arguments".
  417. case TypeIds_Arguments:
  418. builtInTag = library->GetObjectArgumentsDisplayString();
  419. break;
  420. // 8. Else if O has a [[Call]] internal method, let builtinTag be "Function".
  421. case TypeIds_Function:
  422. builtInTag = library->GetObjectFunctionDisplayString();
  423. break;
  424. // 9. Else if O has an [[ErrorData]] internal slot, let builtinTag be "Error".
  425. case TypeIds_Error:
  426. builtInTag = library->GetObjectErrorDisplayString();
  427. break;
  428. // 10. Else if O has a [[BooleanData]] internal slot, let builtinTag be "Boolean".
  429. case TypeIds_Boolean:
  430. case TypeIds_BooleanObject:
  431. builtInTag = library->GetObjectBooleanDisplayString();
  432. break;
  433. // 11. Else if O has a [[NumberData]] internal slot, let builtinTag be "Number".
  434. case TypeIds_Number:
  435. case TypeIds_Int64Number:
  436. case TypeIds_UInt64Number:
  437. case TypeIds_Integer:
  438. case TypeIds_NumberObject:
  439. builtInTag = library->GetObjectNumberDisplayString();
  440. break;
  441. // 12. Else if O has a [[DateValue]] internal slot, let builtinTag be "Date".
  442. case TypeIds_Date:
  443. builtInTag = library->GetObjectDateDisplayString();
  444. break;
  445. // 13. Else if O has a [[RegExpMatcher]] internal slot, let builtinTag be "RegExp".
  446. case TypeIds_RegEx:
  447. builtInTag = library->GetObjectRegExpDisplayString();
  448. break;
  449. // 14. Else, let builtinTag be "Object".
  450. default:
  451. {
  452. if (thisArgAsObject->IsExternal())
  453. {
  454. builtInTag = buildToString(thisArgAsObject->GetClassName(scriptContext));
  455. }
  456. else
  457. {
  458. builtInTag = library->GetObjectDisplayString(); // [object Object]
  459. }
  460. break;
  461. }
  462. }
  463. Assert(builtInTag != nullptr);
  464. return builtInTag;
  465. }
  466. Var JavascriptObject::ToStringHelper(Var thisArg, ScriptContext* scriptContext)
  467. {
  468. TypeId type = JavascriptOperators::GetTypeId(thisArg);
  469. // We first need to make sure we are in the right context.
  470. if (type == TypeIds_HostDispatch)
  471. {
  472. RecyclableObject* hostDispatchObject = VarTo<RecyclableObject>(thisArg);
  473. const DynamicObject* remoteObject = hostDispatchObject->GetRemoteObject();
  474. if (!remoteObject)
  475. {
  476. Var result = nullptr;
  477. Js::Var values[1];
  478. Js::CallInfo info(Js::CallFlags_Value, 1);
  479. Js::Arguments args(info, values);
  480. values[0] = thisArg;
  481. if (hostDispatchObject->InvokeBuiltInOperationRemotely(EntryToString, args, &result))
  482. {
  483. return result;
  484. }
  485. }
  486. }
  487. // Dispatch to @@toStringTag implementation.
  488. if (type >= TypeIds_TypedArrayMin && type <= TypeIds_TypedArrayMax && !scriptContext->GetThreadContext()->IsScriptActive())
  489. {
  490. // Use external call for typedarray in the debugger.
  491. Var toStringValue = nullptr;
  492. BEGIN_JS_RUNTIME_CALL_EX(scriptContext, false);
  493. toStringValue = ToStringTagHelper(thisArg, scriptContext, type);
  494. END_JS_RUNTIME_CALL(scriptContext);
  495. return toStringValue;
  496. }
  497. // By this point, we should be in the correct context, but the thisArg may still need to be marshalled (for to the implicit ToObject conversion call.)
  498. return ToStringTagHelper(CrossSite::MarshalVar(scriptContext, thisArg), scriptContext, type);
  499. }
  500. // -----------------------------------------------------------
  501. // Object.prototype.valueOf
  502. // 1. Let O be the result of calling ToObject passing the this value as the argument.
  503. // 2. If O is the result of calling the Object constructor with a host object (15.2.2.1), then
  504. // a. Return either O or another value such as the host object originally passed to the constructor. The specific result that is returned is implementation-defined.
  505. // 3. Return O.
  506. // -----------------------------------------------------------
  507. Var JavascriptObject::EntryValueOf(RecyclableObject* function, CallInfo callInfo, ...)
  508. {
  509. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  510. ARGUMENTS(args, callInfo);
  511. ScriptContext* scriptContext = function->GetScriptContext();
  512. Assert(!(callInfo.Flags & CallFlags_New));
  513. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  514. // throw a TypeError if TypeId is null or undefined, and apply ToObject to the 'this' value otherwise.
  515. if (JavascriptOperators::IsUndefinedOrNull(args[0]))
  516. {
  517. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Object.prototype.valueOf"));
  518. }
  519. else
  520. {
  521. return JavascriptOperators::ToObject(args[0], scriptContext);
  522. }
  523. }
  524. Var JavascriptObject::EntryGetOwnPropertyDescriptor(RecyclableObject* function, CallInfo callInfo, ...)
  525. {
  526. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  527. ARGUMENTS(args, callInfo);
  528. ScriptContext* scriptContext = function->GetScriptContext();
  529. Assert(!(callInfo.Flags & CallFlags_New));
  530. RecyclableObject* obj = nullptr;
  531. if (args.Info.Count < 2)
  532. {
  533. obj = JavascriptOperators::ToObject(scriptContext->GetLibrary()->GetUndefined(), scriptContext);
  534. }
  535. else
  536. {
  537. // Convert the argument to object first
  538. obj = JavascriptOperators::ToObject(args[1], scriptContext);
  539. }
  540. // If the object is HostDispatch try to invoke the operation remotely
  541. if (obj->GetTypeId() == TypeIds_HostDispatch)
  542. {
  543. Var result;
  544. if (obj->InvokeBuiltInOperationRemotely(EntryGetOwnPropertyDescriptor, args, &result))
  545. {
  546. return result;
  547. }
  548. }
  549. Var propertyKey = args.Info.Count > 2 ? args[2] : obj->GetLibrary()->GetUndefined();
  550. return JavascriptObject::GetOwnPropertyDescriptorHelper(obj, propertyKey, scriptContext);
  551. }
  552. Var JavascriptObject::GetOwnPropertyDescriptorHelper(RecyclableObject* obj, Var propertyKey, ScriptContext* scriptContext)
  553. {
  554. const PropertyRecord* propertyRecord;
  555. JavascriptConversion::ToPropertyKey(propertyKey, scriptContext, &propertyRecord, nullptr);
  556. PropertyId propertyId = propertyRecord->GetPropertyId();
  557. PropertyDescriptor propertyDescriptor;
  558. BOOL isPropertyDescriptorDefined;
  559. isPropertyDescriptorDefined = JavascriptObject::GetOwnPropertyDescriptorHelper(obj, propertyId, scriptContext, propertyDescriptor);
  560. if (!isPropertyDescriptorDefined)
  561. {
  562. return scriptContext->GetLibrary()->GetUndefined();
  563. }
  564. return JavascriptOperators::FromPropertyDescriptor(propertyDescriptor, scriptContext);
  565. }
  566. BOOL JavascriptObject::GetOwnPropertyDescriptorHelper(RecyclableObject* obj, PropertyId propertyId, ScriptContext* scriptContext, PropertyDescriptor& propertyDescriptor)
  567. {
  568. BOOL isPropertyDescriptorDefined;
  569. if (obj->IsExternal())
  570. {
  571. isPropertyDescriptorDefined = obj->HasOwnProperty(propertyId) ?
  572. JavascriptOperators::GetOwnPropertyDescriptor(obj, propertyId, scriptContext, &propertyDescriptor) :
  573. FALSE;
  574. }
  575. else
  576. {
  577. isPropertyDescriptorDefined = JavascriptOperators::GetOwnPropertyDescriptor(obj, propertyId, scriptContext, &propertyDescriptor);
  578. }
  579. return isPropertyDescriptorDefined;
  580. }
  581. Var JavascriptObject::EntryGetOwnPropertyDescriptors(RecyclableObject* function, CallInfo callInfo, ...)
  582. {
  583. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  584. ARGUMENTS(args, callInfo);
  585. ScriptContext* scriptContext = function->GetScriptContext();
  586. Assert(!(callInfo.Flags & CallFlags_New));
  587. RecyclableObject* obj = nullptr;
  588. if (args.Info.Count < 2)
  589. {
  590. obj = JavascriptOperators::ToObject(scriptContext->GetLibrary()->GetUndefined(), scriptContext);
  591. }
  592. else
  593. {
  594. // Convert the argument to object first
  595. obj = JavascriptOperators::ToObject(args[1], scriptContext);
  596. }
  597. // If the object is HostDispatch try to invoke the operation remotely
  598. if (obj->GetTypeId() == TypeIds_HostDispatch)
  599. {
  600. Var result;
  601. if (obj->InvokeBuiltInOperationRemotely(EntryGetOwnPropertyDescriptors, args, &result))
  602. {
  603. return result;
  604. }
  605. }
  606. JavascriptArray* ownPropertyKeys = JavascriptOperators::GetOwnPropertyKeys(obj, scriptContext);
  607. RecyclableObject* resultObj = scriptContext->GetLibrary()->CreateObject(true, (Js::PropertyIndex) ownPropertyKeys->GetLength());
  608. PropertyDescriptor propDesc;
  609. Var propKey = nullptr;
  610. for (uint i = 0; i < ownPropertyKeys->GetLength(); i++)
  611. {
  612. BOOL getPropResult = ownPropertyKeys->DirectGetItemAt(i, &propKey);
  613. Assert(getPropResult);
  614. if (!getPropResult)
  615. {
  616. continue;
  617. }
  618. PropertyRecord const * propertyRecord;
  619. JavascriptConversion::ToPropertyKey(propKey, scriptContext, &propertyRecord, nullptr);
  620. Var newDescriptor = JavascriptObject::GetOwnPropertyDescriptorHelper(obj, propKey, scriptContext);
  621. if (!JavascriptOperators::IsUndefined(newDescriptor))
  622. {
  623. resultObj->SetProperty(propertyRecord->GetPropertyId(), newDescriptor, PropertyOperation_None, nullptr);
  624. }
  625. }
  626. return resultObj;
  627. }
  628. Var JavascriptObject::EntryGetPrototypeOf(RecyclableObject* function, CallInfo callInfo, ...)
  629. {
  630. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  631. ARGUMENTS(args, callInfo);
  632. ScriptContext* scriptContext = function->GetScriptContext();
  633. Assert(!(callInfo.Flags & CallFlags_New));
  634. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_getPrototypeOf);
  635. // 19.1.2.9
  636. // Object.getPrototypeOf ( O )
  637. // When the getPrototypeOf function is called with argument O, the following steps are taken:
  638. RecyclableObject *object = nullptr;
  639. // 1. Let obj be ToObject(O).
  640. // 2. ReturnIfAbrupt(obj).
  641. if (args.Info.Count < 2 || !JavascriptConversion::ToObject(args[1], scriptContext, &object))
  642. {
  643. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Object.getPrototypeOf"));
  644. }
  645. // 3. Return obj.[[GetPrototypeOf]]().
  646. return CrossSite::MarshalVar(scriptContext, GetPrototypeOf(object, scriptContext));
  647. }
  648. Var JavascriptObject::EntrySetPrototypeOf(RecyclableObject* function, CallInfo callInfo, ...)
  649. {
  650. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  651. ARGUMENTS(args, callInfo);
  652. Assert(!(callInfo.Flags & CallFlags_New));
  653. ScriptContext* scriptContext = function->GetScriptContext();
  654. // 19.1.2.18
  655. // Object.setPrototypeOf ( O, proto )
  656. // When the setPrototypeOf function is called with arguments O and proto, the following steps are taken:
  657. // 1. Let O be RequireObjectCoercible(O).
  658. // 2. ReturnIfAbrupt(O).
  659. // 3. If Type(proto) is neither Object or Null, then throw a TypeError exception.
  660. int32 errCode = NOERROR;
  661. if (args.Info.Count < 2 || !JavascriptConversion::CheckObjectCoercible(args[1], scriptContext))
  662. {
  663. errCode = JSERR_FunctionArgument_NeedObject;
  664. }
  665. else if (args.Info.Count < 3 || !JavascriptOperators::IsObjectOrNull(args[2]))
  666. {
  667. errCode = JSERR_FunctionArgument_NotObjectOrNull;
  668. }
  669. if (errCode != NOERROR)
  670. {
  671. JavascriptError::ThrowTypeError(scriptContext, errCode, _u("Object.setPrototypeOf"));
  672. }
  673. // 4. If Type(O) is not Object, return O.
  674. if (!JavascriptOperators::IsObject(args[1]))
  675. {
  676. return args[1];
  677. }
  678. #if ENABLE_COPYONACCESS_ARRAY
  679. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
  680. #endif
  681. RecyclableObject* object = VarTo<RecyclableObject>(args[1]);
  682. RecyclableObject* newPrototype = VarTo<RecyclableObject>(args[2]);
  683. // 5. Let status be O.[[SetPrototypeOf]](proto).
  684. // 6. ReturnIfAbrupt(status).
  685. // 7. If status is false, throw a TypeError exception.
  686. ChangePrototype(object, newPrototype, /*shouldThrow*/true, scriptContext);
  687. // 8. Return O.
  688. return object;
  689. }
  690. Var JavascriptObject::EntrySeal(RecyclableObject* function, CallInfo callInfo, ...)
  691. {
  692. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  693. ARGUMENTS(args, callInfo);
  694. ScriptContext* scriptContext = function->GetScriptContext();
  695. Assert(!(callInfo.Flags & CallFlags_New));
  696. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_seal);
  697. // Spec update in Rev29 under section 19.1.2.17
  698. if (args.Info.Count < 2)
  699. {
  700. return scriptContext->GetLibrary()->GetUndefined();
  701. }
  702. else if (!JavascriptOperators::IsObject(args[1]))
  703. {
  704. return args[1];
  705. }
  706. RecyclableObject *object = VarTo<RecyclableObject>(args[1]);
  707. GlobalObject* globalObject = object->GetLibrary()->GetGlobalObject();
  708. if (globalObject != object && globalObject && (globalObject->ToThis() == object))
  709. {
  710. globalObject->Seal();
  711. }
  712. object->Seal();
  713. return object;
  714. }
  715. Var JavascriptObject::EntryFreeze(RecyclableObject* function, CallInfo callInfo, ...)
  716. {
  717. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  718. ARGUMENTS(args, callInfo);
  719. ScriptContext* scriptContext = function->GetScriptContext();
  720. Assert(!(callInfo.Flags & CallFlags_New));
  721. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_freeze);
  722. // Spec update in Rev29 under section 19.1.2.5
  723. if (args.Info.Count < 2)
  724. {
  725. return scriptContext->GetLibrary()->GetUndefined();
  726. }
  727. else if (!JavascriptOperators::IsObject(args[1]))
  728. {
  729. return args[1];
  730. }
  731. RecyclableObject *object = VarTo<RecyclableObject>(args[1]);
  732. GlobalObject* globalObject = object->GetLibrary()->GetGlobalObject();
  733. if (globalObject != object && globalObject && (globalObject->ToThis() == object))
  734. {
  735. globalObject->Freeze();
  736. }
  737. object->Freeze();
  738. return object;
  739. }
  740. Var JavascriptObject::EntryPreventExtensions(RecyclableObject* function, CallInfo callInfo, ...)
  741. {
  742. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  743. ARGUMENTS(args, callInfo);
  744. ScriptContext* scriptContext = function->GetScriptContext();
  745. Assert(!(callInfo.Flags & CallFlags_New));
  746. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_preventExtensions);
  747. // Spec update in Rev29 under section 19.1.2.15
  748. if (args.Info.Count < 2)
  749. {
  750. return scriptContext->GetLibrary()->GetUndefined();
  751. }
  752. else if (!JavascriptOperators::IsObject(args[1]))
  753. {
  754. return args[1];
  755. }
  756. RecyclableObject *object = VarTo<RecyclableObject>(args[1]);
  757. GlobalObject* globalObject = object->GetLibrary()->GetGlobalObject();
  758. if (globalObject != object && globalObject && (globalObject->ToThis() == object))
  759. {
  760. globalObject->PreventExtensions();
  761. }
  762. object->PreventExtensions();
  763. return object;
  764. }
  765. Var JavascriptObject::EntryIsSealed(RecyclableObject* function, CallInfo callInfo, ...)
  766. {
  767. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  768. ARGUMENTS(args, callInfo);
  769. ScriptContext* scriptContext = function->GetScriptContext();
  770. Assert(!(callInfo.Flags & CallFlags_New));
  771. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_isSealed);
  772. if (args.Info.Count < 2 || !JavascriptOperators::IsObject(args[1]))
  773. {
  774. return scriptContext->GetLibrary()->GetTrue();
  775. }
  776. RecyclableObject *object = VarTo<RecyclableObject>(args[1]);
  777. BOOL isSealed = object->IsSealed();
  778. GlobalObject* globalObject = object->GetLibrary()->GetGlobalObject();
  779. if (isSealed && globalObject != object && globalObject && (globalObject->ToThis() == object))
  780. {
  781. isSealed = globalObject->IsSealed();
  782. }
  783. return scriptContext->GetLibrary()->GetTrueOrFalse(isSealed);
  784. }
  785. Var JavascriptObject::EntryIsFrozen(RecyclableObject* function, CallInfo callInfo, ...)
  786. {
  787. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  788. ARGUMENTS(args, callInfo);
  789. ScriptContext* scriptContext = function->GetScriptContext();
  790. Assert(!(callInfo.Flags & CallFlags_New));
  791. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_isFrozen);
  792. if (args.Info.Count < 2 || !JavascriptOperators::IsObject(args[1]))
  793. {
  794. return scriptContext->GetLibrary()->GetTrue();
  795. }
  796. RecyclableObject *object = VarTo<RecyclableObject>(args[1]);
  797. BOOL isFrozen = object->IsFrozen();
  798. GlobalObject* globalObject = object->GetLibrary()->GetGlobalObject();
  799. if (isFrozen && globalObject != object && globalObject && (globalObject->ToThis() == object))
  800. {
  801. isFrozen = globalObject->IsFrozen();
  802. }
  803. return scriptContext->GetLibrary()->GetTrueOrFalse(isFrozen);
  804. }
  805. Var JavascriptObject::EntryIsExtensible(RecyclableObject* function, CallInfo callInfo, ...)
  806. {
  807. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  808. ARGUMENTS(args, callInfo);
  809. ScriptContext* scriptContext = function->GetScriptContext();
  810. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_isExtensible);
  811. Assert(!(callInfo.Flags & CallFlags_New));
  812. if (args.Info.Count < 2 || !JavascriptOperators::IsObject(args[1]))
  813. {
  814. return scriptContext->GetLibrary()->GetFalse();
  815. }
  816. RecyclableObject *object = VarTo<RecyclableObject>(args[1]);
  817. BOOL isExtensible = object->IsExtensible();
  818. GlobalObject* globalObject = object->GetLibrary()->GetGlobalObject();
  819. if (isExtensible && globalObject != object && globalObject && (globalObject->ToThis() == object))
  820. {
  821. isExtensible = globalObject->IsExtensible();
  822. }
  823. return scriptContext->GetLibrary()->GetTrueOrFalse(isExtensible);
  824. }
  825. Var JavascriptObject::EntryGetOwnPropertyNames(RecyclableObject* function, CallInfo callInfo, ...)
  826. {
  827. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  828. ARGUMENTS(args, callInfo);
  829. ScriptContext* scriptContext = function->GetScriptContext();
  830. Assert(!(callInfo.Flags & CallFlags_New));
  831. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_getOwnPropertyNames);
  832. Var tempVar = args.Info.Count < 2 ? scriptContext->GetLibrary()->GetUndefined() : args[1];
  833. RecyclableObject *object = JavascriptOperators::ToObject(tempVar, scriptContext);
  834. if (object->GetTypeId() == TypeIds_HostDispatch)
  835. {
  836. Var result;
  837. if (object->InvokeBuiltInOperationRemotely(EntryGetOwnPropertyNames, args, &result))
  838. {
  839. return result;
  840. }
  841. }
  842. return JavascriptOperators::GetOwnPropertyNames(object, scriptContext);
  843. }
  844. Var JavascriptObject::EntryGetOwnPropertySymbols(RecyclableObject* function, CallInfo callInfo, ...)
  845. {
  846. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  847. ARGUMENTS(args, callInfo);
  848. ScriptContext* scriptContext = function->GetScriptContext();
  849. Assert(!(callInfo.Flags & CallFlags_New));
  850. Var tempVar = args.Info.Count < 2 ? scriptContext->GetLibrary()->GetUndefined() : args[1];
  851. RecyclableObject *object = JavascriptOperators::ToObject(tempVar, scriptContext);
  852. if (object->GetTypeId() == TypeIds_HostDispatch)
  853. {
  854. Var result;
  855. if (object->InvokeBuiltInOperationRemotely(EntryGetOwnPropertySymbols, args, &result))
  856. {
  857. return result;
  858. }
  859. }
  860. return JavascriptOperators::GetOwnPropertySymbols(object, scriptContext);
  861. }
  862. Var JavascriptObject::EntryKeys(RecyclableObject* function, CallInfo callInfo, ...)
  863. {
  864. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  865. ARGUMENTS(args, callInfo);
  866. ScriptContext* scriptContext = function->GetScriptContext();
  867. Assert(!(callInfo.Flags & CallFlags_New));
  868. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_keys);
  869. Var tempVar = args.Info.Count < 2 ? scriptContext->GetLibrary()->GetUndefined() : args[1];
  870. RecyclableObject *object = JavascriptOperators::ToObject(tempVar, scriptContext);
  871. if (object->GetTypeId() == TypeIds_HostDispatch)
  872. {
  873. Var result;
  874. if (object->InvokeBuiltInOperationRemotely(EntryKeys, args, &result))
  875. {
  876. return result;
  877. }
  878. }
  879. return JavascriptOperators::GetOwnEnumerablePropertyNames(object, scriptContext);
  880. }
  881. Var JavascriptObject::GetValuesOrEntries(RecyclableObject* object, bool valuesToReturn, ScriptContext* scriptContext)
  882. {
  883. Assert(object != nullptr);
  884. Assert(scriptContext != nullptr);
  885. JavascriptArray* valuesArray = scriptContext->GetLibrary()->CreateArray(0);
  886. JavascriptArray* ownKeysResult = JavascriptOperators::GetOwnPropertyNames(object, scriptContext);
  887. uint32 length = ownKeysResult->GetLength();
  888. Var nextKey;
  889. const PropertyRecord* propertyRecord = nullptr;
  890. PropertyId propertyId;
  891. for (uint32 i = 0, index = 0; i < length; i++)
  892. {
  893. nextKey = ownKeysResult->DirectGetItem(i);
  894. Assert(VarIs<JavascriptString>(nextKey));
  895. PropertyDescriptor propertyDescriptor;
  896. JavascriptConversion::ToPropertyKey(nextKey, scriptContext, &propertyRecord, nullptr);
  897. propertyId = propertyRecord->GetPropertyId();
  898. Assert(propertyId != Constants::NoProperty);
  899. if (JavascriptOperators::GetOwnPropertyDescriptor(object, propertyId, scriptContext, &propertyDescriptor))
  900. {
  901. if (propertyDescriptor.IsEnumerable())
  902. {
  903. Var value = JavascriptOperators::GetProperty(object, propertyId, scriptContext);
  904. if (!valuesToReturn)
  905. {
  906. // For Object.entries each entry is key, value pair
  907. JavascriptArray* entry = scriptContext->GetLibrary()->CreateArray(2);
  908. entry->DirectSetItemAt(0, CrossSite::MarshalVar(scriptContext, nextKey));
  909. entry->DirectSetItemAt(1, CrossSite::MarshalVar(scriptContext, value));
  910. value = entry;
  911. }
  912. valuesArray->DirectSetItemAt(index++, CrossSite::MarshalVar(scriptContext, value));
  913. }
  914. }
  915. }
  916. return valuesArray;
  917. }
  918. Var JavascriptObject::EntryValues(RecyclableObject* function, CallInfo callInfo, ...)
  919. {
  920. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  921. ARGUMENTS(args, callInfo);
  922. ScriptContext* scriptContext = function->GetScriptContext();
  923. Assert(!(callInfo.Flags & CallFlags_New));
  924. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_values);
  925. Var tempVar = args.Info.Count < 2 ? scriptContext->GetLibrary()->GetUndefined() : args[1];
  926. RecyclableObject *object = JavascriptOperators::ToObject(tempVar, scriptContext);
  927. return GetValuesOrEntries(object, true /*valuesToReturn*/, scriptContext);
  928. }
  929. Var JavascriptObject::EntryEntries(RecyclableObject* function, CallInfo callInfo, ...)
  930. {
  931. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  932. ARGUMENTS(args, callInfo);
  933. ScriptContext* scriptContext = function->GetScriptContext();
  934. Assert(!(callInfo.Flags & CallFlags_New));
  935. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_entries);
  936. Var tempVar = args.Info.Count < 2 ? scriptContext->GetLibrary()->GetUndefined() : args[1];
  937. RecyclableObject *object = JavascriptOperators::ToObject(tempVar, scriptContext);
  938. return GetValuesOrEntries(object, false /*valuesToReturn*/, scriptContext);
  939. }
  940. JavascriptArray* JavascriptObject::CreateOwnSymbolPropertiesHelper(RecyclableObject* object, ScriptContext* scriptContext)
  941. {
  942. return CreateKeysHelper(object, scriptContext, TRUE, true /*includeSymbolsOnly */, false, true /*includeSpecialProperties*/);
  943. }
  944. JavascriptArray* JavascriptObject::CreateOwnStringPropertiesHelper(RecyclableObject* object, ScriptContext* scriptContext)
  945. {
  946. return CreateKeysHelper(object, scriptContext, TRUE, false, true /*includeStringsOnly*/, true /*includeSpecialProperties*/);
  947. }
  948. JavascriptArray* JavascriptObject::CreateOwnStringSymbolPropertiesHelper(RecyclableObject* object, ScriptContext* scriptContext)
  949. {
  950. return CreateKeysHelper(object, scriptContext, TRUE, true/*includeSymbolsOnly*/, true /*includeStringsOnly*/, true /*includeSpecialProperties*/);
  951. }
  952. JavascriptArray* JavascriptObject::CreateOwnEnumerableStringPropertiesHelper(RecyclableObject* object, ScriptContext* scriptContext)
  953. {
  954. return CreateKeysHelper(object, scriptContext, FALSE, false, true/*includeStringsOnly*/, false);
  955. }
  956. JavascriptArray* JavascriptObject::CreateOwnEnumerableStringSymbolPropertiesHelper(RecyclableObject* object, ScriptContext* scriptContext)
  957. {
  958. return CreateKeysHelper(object, scriptContext, FALSE, true/*includeSymbolsOnly*/, true/*includeStringsOnly*/, false);
  959. }
  960. // 9.1.12 [[OwnPropertyKeys]] () in RC#4 dated April 3rd 2015.
  961. JavascriptArray* JavascriptObject::CreateKeysHelper(RecyclableObject* object, ScriptContext* scriptContext, BOOL includeNonEnumerable, bool includeSymbolProperties, bool includeStringProperties, bool includeSpecialProperties)
  962. {
  963. //1. Let keys be a new empty List.
  964. //2. For each own property key P of O that is an integer index, in ascending numeric index order
  965. // a. Add P as the last element of keys.
  966. //3. For each own property key P of O that is a String but is not an integer index, in property creation order
  967. // a. Add P as the last element of keys.
  968. //4. For each own property key P of O that is a Symbol, in property creation order
  969. // a. Add P as the last element of keys.
  970. //5. Return keys.
  971. AssertMsg(includeStringProperties || includeSymbolProperties, "Should either get string or symbol properties.");
  972. JavascriptStaticEnumerator enumerator;
  973. EnumeratorFlags flags = EnumeratorFlags::SnapShotSemantics | EnumeratorFlags::UseCache;
  974. JavascriptArray* newArr = scriptContext->GetLibrary()->CreateArray(0);
  975. if (includeNonEnumerable)
  976. {
  977. flags |= EnumeratorFlags::EnumNonEnumerable;
  978. }
  979. if (includeSymbolProperties)
  980. {
  981. flags |= EnumeratorFlags::EnumSymbols;
  982. }
  983. EnumeratorCache* cache = scriptContext->GetLibrary()->GetCreateKeysCache(object->GetType());
  984. if (!object->GetEnumerator(&enumerator, flags, scriptContext, cache))
  985. {
  986. return newArr; // Return an empty array if we don't have an enumerator
  987. }
  988. JavascriptString * propertyName = nullptr;
  989. PropertyId propertyId;
  990. uint32 propertyIndex = 0;
  991. uint32 symbolIndex = 0;
  992. const PropertyRecord* propertyRecord;
  993. JavascriptSymbol* symbol;
  994. JavascriptArray* newArrForSymbols = nullptr;
  995. while ((propertyName = enumerator.MoveAndGetNext(propertyId)) != NULL)
  996. {
  997. if (propertyName)
  998. {
  999. if (includeSymbolProperties)
  1000. {
  1001. propertyRecord = scriptContext->GetPropertyName(propertyId);
  1002. if (propertyRecord->IsSymbol())
  1003. {
  1004. symbol = scriptContext->GetSymbol(propertyRecord);
  1005. // no need to marshal symbol because it is created from scriptContext
  1006. if (!newArrForSymbols)
  1007. {
  1008. newArrForSymbols = scriptContext->GetLibrary()->CreateArray(0);
  1009. }
  1010. newArrForSymbols->DirectSetItemAt(symbolIndex++, symbol);
  1011. continue;
  1012. }
  1013. }
  1014. if (includeStringProperties)
  1015. {
  1016. newArr->DirectSetItemAt(propertyIndex++, CrossSite::MarshalVar(scriptContext, propertyName, propertyName->GetScriptContext()));
  1017. }
  1018. }
  1019. }
  1020. // Special properties
  1021. if (includeSpecialProperties && includeStringProperties)
  1022. {
  1023. uint32 index = 0;
  1024. while (object->GetSpecialPropertyName(index, &propertyName, scriptContext))
  1025. {
  1026. newArr->DirectSetItemAt(propertyIndex++, propertyName);
  1027. index++;
  1028. }
  1029. }
  1030. if (newArrForSymbols)
  1031. {
  1032. // Append all the symbols at the end of list
  1033. uint32 totalSymbols = newArrForSymbols->GetLength();
  1034. for (uint32 symIndex = 0; symIndex < totalSymbols; symIndex++)
  1035. {
  1036. newArr->DirectSetItemAt(propertyIndex++, newArrForSymbols->DirectGetItem(symIndex));
  1037. }
  1038. }
  1039. return newArr;
  1040. }
  1041. // args[1] this object to operate on.
  1042. // args[2] property name.
  1043. // args[3] object that attributes for the new descriptor.
  1044. Var JavascriptObject::EntryDefineProperty(RecyclableObject* function, CallInfo callInfo, ...)
  1045. {
  1046. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1047. ARGUMENTS(args, callInfo);
  1048. ScriptContext* scriptContext = function->GetScriptContext();
  1049. Assert(!(callInfo.Flags & CallFlags_New));
  1050. if (args.Info.Count < 2 || !JavascriptOperators::IsObject(args[1]))
  1051. {
  1052. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Object.defineProperty"));
  1053. }
  1054. #if ENABLE_COPYONACCESS_ARRAY
  1055. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
  1056. #endif
  1057. RecyclableObject* obj = VarTo<RecyclableObject>(args[1]);
  1058. // If the object is HostDispatch try to invoke the operation remotely
  1059. if (obj->GetTypeId() == TypeIds_HostDispatch)
  1060. {
  1061. if (obj->InvokeBuiltInOperationRemotely(EntryDefineProperty, args, NULL))
  1062. {
  1063. return obj;
  1064. }
  1065. }
  1066. Var propertyKey = args.Info.Count > 2 ? args[2] : obj->GetLibrary()->GetUndefined();
  1067. PropertyRecord const * propertyRecord;
  1068. JavascriptConversion::ToPropertyKey(propertyKey, scriptContext, &propertyRecord, nullptr);
  1069. Var descVar = args.Info.Count > 3 ? args[3] : obj->GetLibrary()->GetUndefined();
  1070. PropertyDescriptor propertyDescriptor;
  1071. if (!JavascriptOperators::ToPropertyDescriptor(descVar, &propertyDescriptor, scriptContext))
  1072. {
  1073. JavascriptError::ThrowTypeError(scriptContext, JSERR_PropertyDescriptor_Invalid, scriptContext->GetPropertyName(propertyRecord->GetPropertyId())->GetBuffer());
  1074. }
  1075. if (CONFIG_FLAG(UseFullName))
  1076. {
  1077. ModifyGetterSetterFuncName(propertyRecord, propertyDescriptor, scriptContext);
  1078. }
  1079. DefineOwnPropertyHelper(obj, propertyRecord->GetPropertyId(), propertyDescriptor, scriptContext);
  1080. return obj;
  1081. }
  1082. Var JavascriptObject::EntryDefineProperties(RecyclableObject* function, CallInfo callInfo, ...)
  1083. {
  1084. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1085. ARGUMENTS(args, callInfo);
  1086. ScriptContext* scriptContext = function->GetScriptContext();
  1087. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_defineProperties);
  1088. Assert(!(callInfo.Flags & CallFlags_New));
  1089. if (args.Info.Count < 2 || !JavascriptOperators::IsObject(args[1]))
  1090. {
  1091. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Object.defineProperties"));
  1092. }
  1093. #if ENABLE_COPYONACCESS_ARRAY
  1094. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[1]);
  1095. #endif
  1096. RecyclableObject *object = VarTo<RecyclableObject>(args[1]);
  1097. // If the object is HostDispatch try to invoke the operation remotely
  1098. if (object->GetTypeId() == TypeIds_HostDispatch)
  1099. {
  1100. if (object->InvokeBuiltInOperationRemotely(EntryDefineProperties, args, NULL))
  1101. {
  1102. return object;
  1103. }
  1104. }
  1105. Var propertiesVar = args.Info.Count > 2 ? args[2] : object->GetLibrary()->GetUndefined();
  1106. RecyclableObject* properties = nullptr;
  1107. if (FALSE == JavascriptConversion::ToObject(propertiesVar, scriptContext, &properties))
  1108. {
  1109. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NullOrUndefined, _u("Object.defineProperties"));
  1110. }
  1111. return DefinePropertiesHelper(object, properties, scriptContext);
  1112. }
  1113. // args[1] property name.
  1114. // args[2] function object to use as the getter function.
  1115. Var JavascriptObject::EntryDefineGetter(RecyclableObject* function, CallInfo callInfo, ...)
  1116. {
  1117. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1118. ARGUMENTS(args, callInfo);
  1119. ScriptContext* scriptContext = function->GetScriptContext();
  1120. Assert(!(callInfo.Flags & CallFlags_New));
  1121. // For browser interop, simulate LdThis by calling OP implementation directly.
  1122. // Do not have module id here so use the global id, 0.
  1123. //
  1124. #if ENABLE_COPYONACCESS_ARRAY
  1125. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(args[0]);
  1126. #endif
  1127. RecyclableObject* obj = nullptr;
  1128. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  1129. {
  1130. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Object.prototype.__defineGetter__"));
  1131. }
  1132. Var getterFunc = args.Info.Count > 2 ? args[2] : obj->GetLibrary()->GetUndefined();
  1133. if (!JavascriptConversion::IsCallable(getterFunc))
  1134. {
  1135. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Object.prototype.__defineGetter__"));
  1136. }
  1137. Var propertyKey = args.Info.Count > 1 ? args[1] : obj->GetLibrary()->GetUndefined();
  1138. const PropertyRecord* propertyRecord;
  1139. JavascriptConversion::ToPropertyKey(propertyKey, scriptContext, &propertyRecord, nullptr);
  1140. PropertyDescriptor propertyDescriptor;
  1141. propertyDescriptor.SetEnumerable(true);
  1142. propertyDescriptor.SetConfigurable(true);
  1143. propertyDescriptor.SetGetter(getterFunc);
  1144. DefineOwnPropertyHelper(obj, propertyRecord->GetPropertyId(), propertyDescriptor, scriptContext);
  1145. return obj->GetLibrary()->GetUndefined();
  1146. }
  1147. // args[1] property name.
  1148. // args[2] function object to use as the setter function.
  1149. Var JavascriptObject::EntryDefineSetter(RecyclableObject* function, CallInfo callInfo, ...)
  1150. {
  1151. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1152. ARGUMENTS(args, callInfo);
  1153. ScriptContext* scriptContext = function->GetScriptContext();
  1154. Assert(!(callInfo.Flags & CallFlags_New));
  1155. // For browser interop, simulate LdThis by calling OP implementation directly.
  1156. // Do not have module id here so use the global id, 0.
  1157. //
  1158. RecyclableObject* obj = nullptr;
  1159. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  1160. {
  1161. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Object.prototype.__defineSetter__"));
  1162. }
  1163. Var setterFunc = args.Info.Count > 2 ? args[2] : obj->GetLibrary()->GetUndefined();
  1164. if (!JavascriptConversion::IsCallable(setterFunc))
  1165. {
  1166. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedFunction, _u("Object.prototype.__defineSetter__"));
  1167. }
  1168. Var propertyKey = args.Info.Count > 1 ? args[1] : obj->GetLibrary()->GetUndefined();
  1169. const PropertyRecord* propertyRecord;
  1170. JavascriptConversion::ToPropertyKey(propertyKey, scriptContext, &propertyRecord, nullptr);
  1171. PropertyDescriptor propertyDescriptor;
  1172. propertyDescriptor.SetEnumerable(true);
  1173. propertyDescriptor.SetConfigurable(true);
  1174. propertyDescriptor.SetSetter(setterFunc);
  1175. DefineOwnPropertyHelper(obj, propertyRecord->GetPropertyId(), propertyDescriptor, scriptContext);
  1176. return obj->GetLibrary()->GetUndefined();
  1177. }
  1178. // args[1] property name.
  1179. Var JavascriptObject::EntryLookupGetter(RecyclableObject* function, CallInfo callInfo, ...)
  1180. {
  1181. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1182. ARGUMENTS(args, callInfo);
  1183. ScriptContext* scriptContext = function->GetScriptContext();
  1184. Assert(!(callInfo.Flags & CallFlags_New));
  1185. RecyclableObject* obj = nullptr;
  1186. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  1187. {
  1188. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Object.prototype.__lookupGetter__"));
  1189. }
  1190. Var propertyKey = args.Info.Count > 1 ? args[1] : obj->GetLibrary()->GetUndefined();
  1191. const PropertyRecord* propertyRecord;
  1192. JavascriptConversion::ToPropertyKey(propertyKey, scriptContext, &propertyRecord, nullptr);
  1193. Var getter = nullptr;
  1194. Var unused = nullptr;
  1195. if (JavascriptOperators::GetAccessors(obj, propertyRecord->GetPropertyId(), scriptContext, &getter, &unused))
  1196. {
  1197. if (getter != nullptr)
  1198. {
  1199. return getter;
  1200. }
  1201. }
  1202. return obj->GetLibrary()->GetUndefined();
  1203. }
  1204. // args[1] property name.
  1205. Var JavascriptObject::EntryLookupSetter(RecyclableObject* function, CallInfo callInfo, ...)
  1206. {
  1207. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1208. ARGUMENTS(args, callInfo);
  1209. ScriptContext* scriptContext = function->GetScriptContext();
  1210. Assert(!(callInfo.Flags & CallFlags_New));
  1211. RecyclableObject* obj = nullptr;
  1212. if (!JavascriptConversion::ToObject(args[0], scriptContext, &obj))
  1213. {
  1214. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined, _u("Object.prototype.__lookupSetter__"));
  1215. }
  1216. Var propertyKey = args.Info.Count > 1 ? args[1] : obj->GetLibrary()->GetUndefined();
  1217. const PropertyRecord* propertyRecord;
  1218. JavascriptConversion::ToPropertyKey(propertyKey, scriptContext, &propertyRecord, nullptr);
  1219. Var unused = nullptr;
  1220. Var setter = nullptr;
  1221. if (JavascriptOperators::GetAccessors(obj, propertyRecord->GetPropertyId(), scriptContext, &unused, &setter))
  1222. {
  1223. if (setter != nullptr)
  1224. {
  1225. return setter;
  1226. }
  1227. }
  1228. return obj->GetLibrary()->GetUndefined();
  1229. }
  1230. Var JavascriptObject::EntryIs(RecyclableObject* function, CallInfo callInfo, ...)
  1231. {
  1232. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1233. ARGUMENTS(args, callInfo);
  1234. ScriptContext* scriptContext = function->GetScriptContext();
  1235. Assert(!(callInfo.Flags & CallFlags_New));
  1236. Var x = args.Info.Count > 1 ? args[1] : scriptContext->GetLibrary()->GetUndefined();
  1237. Var y = args.Info.Count > 2 ? args[2] : scriptContext->GetLibrary()->GetUndefined();
  1238. return JavascriptBoolean::ToVar(JavascriptConversion::SameValue(x, y), scriptContext);
  1239. }
  1240. //ES6 19.1.2.1
  1241. Var JavascriptObject::EntryAssign(RecyclableObject* function, CallInfo callInfo, ...)
  1242. {
  1243. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1244. ARGUMENTS(args, callInfo);
  1245. ScriptContext* scriptContext = function->GetScriptContext();
  1246. Assert(!(callInfo.Flags & CallFlags_New));
  1247. // 1. Let to be ToObject(target).
  1248. // 2. ReturnIfAbrupt(to).
  1249. // 3 If only one argument was passed, return to.
  1250. RecyclableObject* to = nullptr;
  1251. if (args.Info.Count == 1 || !JavascriptConversion::ToObject(args[1], scriptContext, &to))
  1252. {
  1253. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, _u("Object.assign"));
  1254. }
  1255. if (args.Info.Count < 3)
  1256. {
  1257. return to;
  1258. }
  1259. // 4. Let sources be the List of argument values starting with the second argument.
  1260. // 5. For each element nextSource of sources, in ascending index order,
  1261. CopyDataPropertiesHelper<true, true>(args[2], to, scriptContext);
  1262. for (unsigned int i = 3; i < args.Info.Count; i++)
  1263. {
  1264. CopyDataPropertiesHelper<false, true>(args[i], to, scriptContext);
  1265. }
  1266. // 6. Return to.
  1267. return to;
  1268. }
  1269. template <bool assign>
  1270. PCWSTR GetCopyDataPropertiesEntryName() {
  1271. return assign ? _u("Object.assign") : _u("Object.Spread");
  1272. }
  1273. /*static*/
  1274. template <bool tryCopy, bool assign>
  1275. void JavascriptObject::CopyDataPropertiesHelper(Var source, RecyclableObject* to, ScriptContext* scriptContext, const BVSparse<Recycler>* excluded)
  1276. {
  1277. // If assign is false, this performs CopyDataProperties(https://tc39.github.io/ecma262/#sec-copydataproperties).
  1278. // Variable excluded is ignored.
  1279. // Otherwise, it performs the loop body of step 4 in Object.assign (https://tc39.github.io/ecma262/#sec-object.assign).
  1280. // Value of tryCopy is ignored.
  1281. // 1. Assert Type(to) is Object.
  1282. // 2. Assert Type(excluded) is List.
  1283. // 3. If source is undefined or null, let keys be a new empty List
  1284. // 4. Else,
  1285. // a. Let from be ToObject(source).
  1286. // b. Let keys be from.[[OwnpropertyKeys]]().
  1287. // 5. Repeat for each element nextKey of keys in List order,
  1288. // a. If we are not in assign mode, then
  1289. // i. Let found be false.
  1290. // ii. Repeat for each element e of excluded,
  1291. // 1. If e is not empty and SameValue(e, nextKey) is true, then
  1292. // a. Set found to true.
  1293. // b. If found is false or we are in assign mode, then
  1294. // i. Let desc be from.[[GetOwnProperty]](nextKey).
  1295. // ii. If desc is not undefined and desc.[[Enumerable]] is true, then
  1296. // 1. Let propValue be Get(from, nextKey).
  1297. // 2. If we are in assign mode, then
  1298. // a. Perform Set(to, nextKey, propValue, true).
  1299. // 3. Else,
  1300. // a. Perform CreateDataProperty(to, nextKey, propValue).
  1301. // 6. Return target (target is returned in pointer).
  1302. Assert(JavascriptOperators::IsObject(to));
  1303. RecyclableObject* from = nullptr;
  1304. if (!JavascriptConversion::ToObject(source, scriptContext, &from))
  1305. {
  1306. if (JavascriptOperators::IsUndefinedOrNull(source))
  1307. {
  1308. return;
  1309. }
  1310. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, GetCopyDataPropertiesEntryName<assign>());
  1311. }
  1312. #if ENABLE_COPYONACCESS_ARRAY
  1313. JavascriptLibrary::CheckAndConvertCopyOnAccessNativeIntArray<Var>(from);
  1314. #endif
  1315. // if proxy, take slow path by calling [[OwnPropertyKeys]] on source
  1316. if (VarIs<JavascriptProxy>(from))
  1317. {
  1318. CopyDataPropertiesForProxyObjects<assign>(from, to, excluded, scriptContext);
  1319. }
  1320. // else use enumerator to extract keys from source
  1321. else
  1322. {
  1323. if (assign)
  1324. {
  1325. bool copied = false;
  1326. if (tryCopy)
  1327. {
  1328. DynamicObject* fromObj = DynamicObject::TryVarToBaseDynamicObject(from);
  1329. DynamicObject* toObj = DynamicObject::TryVarToBaseDynamicObject(to);
  1330. if (toObj && fromObj && toObj->GetType() == scriptContext->GetLibrary()->GetObjectType())
  1331. {
  1332. copied = toObj->TryCopy(fromObj);
  1333. }
  1334. }
  1335. if (!copied)
  1336. {
  1337. CopyDataPropertiesForGenericObjects<assign>(from, to, /*excluded*/ nullptr, scriptContext);
  1338. }
  1339. }
  1340. else
  1341. {
  1342. CopyDataPropertiesForGenericObjects<assign>(from, to, excluded, scriptContext);
  1343. }
  1344. }
  1345. }
  1346. /*static*/
  1347. template <bool assign>
  1348. void JavascriptObject::CopyDataPropertiesForGenericObjects(RecyclableObject* from, RecyclableObject* to, const BVSparse<Recycler>* excluded, ScriptContext* scriptContext)
  1349. {
  1350. // Steps 4 and 5 of CopyDataPropertiesHelper
  1351. EnumeratorCache* cache = scriptContext->GetLibrary()->GetObjectAssignCache(from->GetType());
  1352. JavascriptStaticEnumerator enumerator;
  1353. if (!from->GetEnumerator(&enumerator, EnumeratorFlags::SnapShotSemantics | EnumeratorFlags::EnumSymbols | EnumeratorFlags::UseCache, scriptContext, cache))
  1354. {
  1355. // Nothing to enumerate, continue with the nextSource.
  1356. return;
  1357. }
  1358. PropertyId nextKey = Constants::NoProperty;
  1359. Var propValue = nullptr;
  1360. JavascriptString * propertyName = nullptr;
  1361. // Enumerate through each property of properties and fetch the property descriptor
  1362. while ((propertyName = enumerator.MoveAndGetNext(nextKey)) != NULL)
  1363. {
  1364. // Make sure nextKey is defined for the current propertyName
  1365. if (nextKey == Constants::NoProperty)
  1366. {
  1367. PropertyRecord const * propertyRecord = nullptr;
  1368. scriptContext->GetOrAddPropertyRecord(propertyName, &propertyRecord);
  1369. nextKey = propertyRecord->GetPropertyId();
  1370. }
  1371. bool found = false;
  1372. if (excluded)
  1373. {
  1374. found = excluded->Test(nextKey);
  1375. }
  1376. if (!found)
  1377. {
  1378. PropertyString * propertyString = JavascriptOperators::TryFromVar<PropertyString>(propertyName);
  1379. // If propertyName is a PropertyString* we can try getting the property from the inline cache to avoid having a full property lookup
  1380. //
  1381. // Whenever possible, our enumerator populates the cache, so we should generally get a cache hit here
  1382. PropertyValueInfo getPropertyInfo;
  1383. if (propertyString == nullptr || !propertyString->TryGetPropertyFromCache<true /* OwnPropertyOnly */, false /* OutputExistence */>(from, from, &propValue, scriptContext, &getPropertyInfo))
  1384. {
  1385. if (!JavascriptOperators::GetOwnProperty(from, nextKey, &propValue, scriptContext, &getPropertyInfo))
  1386. {
  1387. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, GetCopyDataPropertiesEntryName<assign>());
  1388. }
  1389. }
  1390. if (assign)
  1391. {
  1392. // Similarly, try to set the property using our cache to avoid having to do the full work of SetProperty
  1393. PropertyValueInfo setPropertyInfo;
  1394. if (propertyString == nullptr || !propertyString->TrySetPropertyFromCache(to, propValue, scriptContext, PropertyOperation_ThrowIfNonWritable, &setPropertyInfo))
  1395. {
  1396. if (!JavascriptOperators::SetProperty(to, to, nextKey, propValue, &setPropertyInfo, scriptContext, PropertyOperation_ThrowIfNonWritable))
  1397. {
  1398. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, GetCopyDataPropertiesEntryName<assign>());
  1399. }
  1400. }
  1401. }
  1402. else
  1403. {
  1404. //TODO[t-huyan]: potentially use caching to improve efficiency? (see AssignForGenericObjects implementation)
  1405. if (!CreateDataProperty(to, nextKey, propValue, scriptContext))
  1406. {
  1407. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, GetCopyDataPropertiesEntryName<assign>());
  1408. }
  1409. }
  1410. }
  1411. }
  1412. }
  1413. /*static*/
  1414. template <bool assign>
  1415. void JavascriptObject::CopyDataPropertiesForProxyObjects(RecyclableObject* from, RecyclableObject* to, const BVSparse<Recycler>* excluded, ScriptContext* scriptContext)
  1416. {
  1417. // Steps 4 and 5 of CopyDataPropertiesHelper
  1418. JavascriptArray *keys = JavascriptOperators::GetOwnEnumerablePropertyNamesSymbols(from, scriptContext);
  1419. uint32 length = keys->GetLength();
  1420. Var nextKey;
  1421. const PropertyRecord* propertyRecord = nullptr;
  1422. PropertyId propertyId;
  1423. Var propValue = nullptr;
  1424. for (uint32 j = 0; j < length; j++)
  1425. {
  1426. PropertyDescriptor propertyDescriptor;
  1427. nextKey = keys->DirectGetItem(j);
  1428. AssertMsg(VarIs<JavascriptSymbol>(nextKey) || VarIs<JavascriptString>(nextKey), "Invariant check during ownKeys proxy trap should make sure we only get property key here. (symbol or string primitives)");
  1429. // Spec doesn't strictly call for us to use ToPropertyKey but since we know nextKey is already a symbol or string primitive, ToPropertyKey will be a nop and return us the propertyRecord
  1430. JavascriptConversion::ToPropertyKey(nextKey, scriptContext, &propertyRecord, nullptr);
  1431. propertyId = propertyRecord->GetPropertyId();
  1432. AssertMsg(propertyId != Constants::NoProperty, "CopyDataPropertiesForProxyObjects - OwnPropertyKeys returned a propertyId with value NoProperty.");
  1433. bool found = false;
  1434. if (excluded)
  1435. {
  1436. found = excluded->Test(propertyId);
  1437. }
  1438. if (!found)
  1439. {
  1440. if (JavascriptOperators::GetOwnPropertyDescriptor(from, propertyRecord->GetPropertyId(), scriptContext, &propertyDescriptor))
  1441. {
  1442. if (propertyDescriptor.IsEnumerable())
  1443. {
  1444. if (!JavascriptOperators::GetOwnProperty(from, propertyId, &propValue, scriptContext, nullptr))
  1445. {
  1446. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, GetCopyDataPropertiesEntryName<assign>());
  1447. }
  1448. if (assign)
  1449. {
  1450. if (!JavascriptOperators::SetProperty(to, to, propertyId, propValue, scriptContext))
  1451. {
  1452. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, GetCopyDataPropertiesEntryName<assign>());
  1453. }
  1454. }
  1455. else
  1456. {
  1457. if (!CreateDataProperty(to, propertyId, propValue, scriptContext))
  1458. {
  1459. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NeedObject, GetCopyDataPropertiesEntryName<assign>());
  1460. }
  1461. }
  1462. }
  1463. }
  1464. }
  1465. }
  1466. }
  1467. BOOL JavascriptObject::CreateDataProperty(RecyclableObject* obj, PropertyId key, Var value, ScriptContext* scriptContext)
  1468. {
  1469. // Performs CreateDataProperty operation as outlined in https://tc39.github.io/ecma262/#sec-createdataproperty.
  1470. // 1. Assert: Type(obj) is Object
  1471. // 2. Assert: IsPropertyKey(key) is true
  1472. Assert(JavascriptOperators::IsObject(obj));
  1473. // 3. Let newDesc be the PropertyDescriptor{[[Value]]: V, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true}.
  1474. PropertyDescriptor newDesc;
  1475. newDesc.SetValue(value);
  1476. newDesc.SetWritable(true);
  1477. newDesc.SetEnumerable(true);
  1478. newDesc.SetConfigurable(true);
  1479. // 4. Return ? O.[[DefineOwnProperty]](P, newDesc).
  1480. return DefineOwnPropertyHelper(obj, key, newDesc, scriptContext);
  1481. }
  1482. //ES5 15.2.3.5
  1483. Var JavascriptObject::EntryCreate(RecyclableObject* function, CallInfo callInfo, ...)
  1484. {
  1485. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  1486. ARGUMENTS(args, callInfo);
  1487. ScriptContext* scriptContext = function->GetScriptContext();
  1488. CHAKRATEL_LANGSTATS_INC_BUILTINCOUNT(Object_Constructor_create)
  1489. Assert(!(callInfo.Flags & CallFlags_New));
  1490. if (args.Info.Count < 2)
  1491. {
  1492. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NotObjectOrNull, _u("Object.create"));
  1493. }
  1494. Var protoVar = args[1];
  1495. if (!JavascriptOperators::IsObjectOrNull(protoVar))
  1496. {
  1497. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NotObjectOrNull, _u("Object.create"));
  1498. }
  1499. RecyclableObject* protoObj = VarTo<RecyclableObject>(protoVar);
  1500. DynamicObject* object = function->GetLibrary()->CreateObject(protoObj);
  1501. JS_ETW(EventWriteJSCRIPT_RECYCLER_ALLOCATE_OBJECT(object));
  1502. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1503. if (Js::Configuration::Global.flags.IsEnabled(Js::autoProxyFlag))
  1504. {
  1505. object = VarTo<DynamicObject>(JavascriptProxy::AutoProxyWrapper(object));
  1506. }
  1507. #endif
  1508. if (args.Info.Count > 2 && JavascriptOperators::GetTypeId(args[2]) != TypeIds_Undefined)
  1509. {
  1510. RecyclableObject* properties = nullptr;
  1511. if (FALSE == JavascriptConversion::ToObject(args[2], scriptContext, &properties))
  1512. {
  1513. JavascriptError::ThrowTypeError(scriptContext, JSERR_FunctionArgument_NullOrUndefined, _u("Object.create"));
  1514. }
  1515. return DefinePropertiesHelper(object, properties, scriptContext);
  1516. }
  1517. return object;
  1518. }
  1519. Var JavascriptObject::DefinePropertiesHelper(RecyclableObject *object, RecyclableObject* props, ScriptContext *scriptContext)
  1520. {
  1521. if (VarIs<JavascriptProxy>(props))
  1522. {
  1523. return DefinePropertiesHelperForProxyObjects(object, props, scriptContext);
  1524. }
  1525. else
  1526. {
  1527. return DefinePropertiesHelperForGenericObjects(object, props, scriptContext);
  1528. }
  1529. }
  1530. Var JavascriptObject::DefinePropertiesHelperForGenericObjects(RecyclableObject *object, RecyclableObject* props, ScriptContext *scriptContext)
  1531. {
  1532. size_t descSize = 16;
  1533. size_t descCount = 0;
  1534. struct DescriptorMap
  1535. {
  1536. Field(PropertyRecord const *) propRecord;
  1537. Field(PropertyDescriptor) descriptor;
  1538. Field(Var) originalVar;
  1539. };
  1540. JavascriptStaticEnumerator enumerator;
  1541. if (!props->GetEnumerator(&enumerator, EnumeratorFlags::EnumSymbols, scriptContext))
  1542. {
  1543. return object;
  1544. }
  1545. ENTER_PINNED_SCOPE(DescriptorMap, descriptors);
  1546. descriptors = RecyclerNewArray(scriptContext->GetRecycler(), DescriptorMap, descSize);
  1547. PropertyId propId;
  1548. PropertyRecord const * propertyRecord;
  1549. JavascriptString* propertyName = nullptr;
  1550. //enumerate through each property of properties and fetch the property descriptor
  1551. while ((propertyName = enumerator.MoveAndGetNext(propId)) != NULL)
  1552. {
  1553. if (propId == Constants::NoProperty) //try current property id query first
  1554. {
  1555. scriptContext->GetOrAddPropertyRecord(propertyName, &propertyRecord);
  1556. propId = propertyRecord->GetPropertyId();
  1557. }
  1558. else
  1559. {
  1560. propertyName->GetPropertyRecord(&propertyRecord);
  1561. }
  1562. if (descCount == descSize)
  1563. {
  1564. //reallocate - consider linked list of DescriptorMap if the descSize is too high
  1565. descSize = AllocSizeMath::Mul(descCount, 2);
  1566. __analysis_assume(descSize == descCount * 2);
  1567. DescriptorMap *temp = RecyclerNewArray(scriptContext->GetRecycler(), DescriptorMap, descSize);
  1568. for (size_t i = 0; i < descCount; i++)
  1569. {
  1570. temp[i] = descriptors[i];
  1571. }
  1572. descriptors = temp;
  1573. }
  1574. Var tempVar = JavascriptOperators::GetPropertyNoCache(props, propId, scriptContext);
  1575. AnalysisAssert(descCount < descSize);
  1576. if (!JavascriptOperators::ToPropertyDescriptor(tempVar, &descriptors[descCount].descriptor, scriptContext))
  1577. {
  1578. JavascriptError::ThrowTypeError(scriptContext, JSERR_PropertyDescriptor_Invalid, scriptContext->GetPropertyName(propId)->GetBuffer());
  1579. }
  1580. // In proxy, we need to get back the original ToPropertDescriptor var in [[defineProperty]] trap.
  1581. descriptors[descCount].originalVar = tempVar;
  1582. if (CONFIG_FLAG(UseFullName))
  1583. {
  1584. ModifyGetterSetterFuncName(propertyRecord, descriptors[descCount].descriptor, scriptContext);
  1585. }
  1586. descriptors[descCount].propRecord = propertyRecord;
  1587. descCount++;
  1588. }
  1589. //Once all the property descriptors are in place set each property descriptor to the object
  1590. for (size_t i = 0; i < descCount; i++)
  1591. {
  1592. DefineOwnPropertyHelper(object, descriptors[i].propRecord->GetPropertyId(), descriptors[i].descriptor, scriptContext);
  1593. }
  1594. LEAVE_PINNED_SCOPE();
  1595. return object;
  1596. }
  1597. //ES5 15.2.3.7
  1598. Var JavascriptObject::DefinePropertiesHelperForProxyObjects(RecyclableObject *object, RecyclableObject* props, ScriptContext *scriptContext)
  1599. {
  1600. Assert(VarIs<JavascriptProxy>(props));
  1601. //1. If Type(O) is not Object throw a TypeError exception.
  1602. //2. Let props be ToObject(Properties).
  1603. size_t descCount = 0;
  1604. struct DescriptorMap
  1605. {
  1606. Field(PropertyRecord const *) propRecord;
  1607. Field(PropertyDescriptor) descriptor;
  1608. };
  1609. //3. Let keys be props.[[OwnPropertyKeys]]().
  1610. //4. ReturnIfAbrupt(keys).
  1611. //5. Let descriptors be an empty List.
  1612. JavascriptArray* keys = JavascriptOperators::GetOwnEnumerablePropertyNamesSymbols(props, scriptContext);
  1613. uint32 length = keys->GetLength();
  1614. ENTER_PINNED_SCOPE(DescriptorMap, descriptors);
  1615. descriptors = RecyclerNewArray(scriptContext->GetRecycler(), DescriptorMap, length);
  1616. //6. Repeat for each element nextKey of keys in List order,
  1617. // 1. Let propDesc be props.[[GetOwnProperty]](nextKey).
  1618. // 2. ReturnIfAbrupt(propDesc).
  1619. // 3. If propDesc is not undefined and propDesc.[[Enumerable]] is true, then
  1620. // 1. Let descObj be Get(props, nextKey).
  1621. // 2. ReturnIfAbrupt(descObj).
  1622. // 3. Let desc be ToPropertyDescriptor(descObj).
  1623. // 4. ReturnIfAbrupt(desc).
  1624. // 5. Append the pair(a two element List) consisting of nextKey and desc to the end of descriptors.
  1625. Var nextKey;
  1626. const PropertyRecord* propertyRecord = nullptr;
  1627. PropertyId propertyId;
  1628. Var descObj;
  1629. for (uint32 j = 0; j < length; j++)
  1630. {
  1631. PropertyDescriptor propertyDescriptor;
  1632. nextKey = keys->DirectGetItem(j);
  1633. AssertMsg(VarIs<JavascriptSymbol>(nextKey) || VarIs<JavascriptString>(nextKey), "Invariant check during ownKeys proxy trap should make sure we only get property key here. (symbol or string primitives)");
  1634. JavascriptConversion::ToPropertyKey(nextKey, scriptContext, &propertyRecord, nullptr);
  1635. propertyId = propertyRecord->GetPropertyId();
  1636. AssertMsg(propertyId != Constants::NoProperty, "DefinePropertiesHelper - OwnPropertyKeys returned a propertyId with value NoProperty.");
  1637. if (JavascriptOperators::GetOwnPropertyDescriptor(props, propertyRecord->GetPropertyId(), scriptContext, &propertyDescriptor))
  1638. {
  1639. if (propertyDescriptor.IsEnumerable())
  1640. {
  1641. descObj = JavascriptOperators::GetProperty(props, propertyId, scriptContext);
  1642. if (!JavascriptOperators::ToPropertyDescriptor(descObj, &descriptors[descCount].descriptor, scriptContext))
  1643. {
  1644. JavascriptError::ThrowTypeError(scriptContext, JSERR_PropertyDescriptor_Invalid, scriptContext->GetPropertyName(propertyId)->GetBuffer());
  1645. }
  1646. if (CONFIG_FLAG(UseFullName))
  1647. {
  1648. ModifyGetterSetterFuncName(propertyRecord, descriptors[descCount].descriptor, scriptContext);
  1649. }
  1650. descriptors[descCount].propRecord = propertyRecord;
  1651. descCount++;
  1652. }
  1653. }
  1654. }
  1655. //7. For each pair from descriptors in list order,
  1656. // 1. Let P be the first element of pair.
  1657. // 2. Let desc be the second element of pair.
  1658. // 3. Let status be DefinePropertyOrThrow(O, P, desc).
  1659. // 4. ReturnIfAbrupt(status).
  1660. for (size_t i = 0; i < descCount; i++)
  1661. {
  1662. DefineOwnPropertyHelper(object, descriptors[i].propRecord->GetPropertyId(), descriptors[i].descriptor, scriptContext);
  1663. }
  1664. LEAVE_PINNED_SCOPE();
  1665. //8. Return O.
  1666. return object;
  1667. }
  1668. Var JavascriptObject::GetPrototypeOf(RecyclableObject* obj, ScriptContext* scriptContext)
  1669. {
  1670. return obj->IsExternal() ? obj->GetConfigurablePrototype(scriptContext) : obj->GetPrototype();
  1671. }
  1672. //
  1673. // Check if "proto" is a prototype of "object" (on its prototype chain).
  1674. //
  1675. bool JavascriptObject::IsPrototypeOf(RecyclableObject* proto, RecyclableObject* object, ScriptContext* scriptContext)
  1676. {
  1677. return JavascriptOperators::MapObjectAndPrototypesUntil<false>(object, [=](RecyclableObject* obj)
  1678. {
  1679. return obj == proto;
  1680. });
  1681. }
  1682. bool JavascriptObject::IsPrototypeOfStopAtProxy(RecyclableObject* proto, RecyclableObject* object, ScriptContext* scriptContext)
  1683. {
  1684. return JavascriptOperators::MapObjectAndPrototypesUntil<true>(object, [=](RecyclableObject* obj)
  1685. {
  1686. return obj == proto;
  1687. });
  1688. }
  1689. static const size_t ConstructNameGetSetLength = 5; // 5 = 1 ( for .) + 3 (get or set) + 1 for null)
  1690. /*static*/
  1691. char16 * JavascriptObject::ConstructName(const PropertyRecord * propertyRecord, const char16 * getOrSetStr, ScriptContext* scriptContext)
  1692. {
  1693. Assert(propertyRecord);
  1694. Assert(scriptContext);
  1695. char16 * finalName = nullptr;
  1696. size_t propertyLength = (size_t)propertyRecord->GetLength();
  1697. if (propertyLength > 0)
  1698. {
  1699. size_t totalChars;
  1700. if (SizeTAdd(propertyLength, ConstructNameGetSetLength, &totalChars) == S_OK)
  1701. {
  1702. finalName = RecyclerNewArrayLeafZ(scriptContext->GetRecycler(), char16, totalChars);
  1703. Assert(finalName != nullptr);
  1704. const char16* propertyName = propertyRecord->GetBuffer();
  1705. Assert(propertyName != nullptr);
  1706. wcscpy_s(finalName, totalChars, propertyName);
  1707. Assert(getOrSetStr != nullptr);
  1708. Assert(wcslen(getOrSetStr) == 4);
  1709. wcscpy_s(finalName + propertyLength, ConstructNameGetSetLength, getOrSetStr);
  1710. }
  1711. }
  1712. return finalName;
  1713. }
  1714. /*static*/
  1715. void JavascriptObject::ModifyGetterSetterFuncName(const PropertyRecord * propertyRecord, const PropertyDescriptor& descriptor, ScriptContext* scriptContext)
  1716. {
  1717. Assert(scriptContext);
  1718. Assert(propertyRecord);
  1719. if (descriptor.GetterSpecified() || descriptor.SetterSpecified())
  1720. {
  1721. charcount_t propertyLength = propertyRecord->GetLength();
  1722. if (descriptor.GetterSpecified()
  1723. && Js::VarIs<Js::ScriptFunction>(descriptor.GetGetter())
  1724. && _wcsicmp(Js::VarTo<Js::ScriptFunction>(descriptor.GetGetter())->GetFunctionProxy()->GetDisplayName(), _u("get")) == 0)
  1725. {
  1726. // modify to name.get
  1727. const char16* finalName = ConstructName(propertyRecord, _u(".get"), scriptContext);
  1728. if (finalName != nullptr)
  1729. {
  1730. FunctionProxy::SetDisplayNameFlags flags = (FunctionProxy::SetDisplayNameFlags) (FunctionProxy::SetDisplayNameFlagsDontCopy | FunctionProxy::SetDisplayNameFlagsRecyclerAllocated);
  1731. Js::VarTo<Js::ScriptFunction>(descriptor.GetGetter())->GetFunctionProxy()->SetDisplayName(finalName,
  1732. propertyLength + 4 /*".get"*/, propertyLength + 1, flags);
  1733. }
  1734. }
  1735. if (descriptor.SetterSpecified()
  1736. && Js::VarIs<Js::ScriptFunction>(descriptor.GetSetter())
  1737. && _wcsicmp(Js::VarTo<Js::ScriptFunction>(descriptor.GetSetter())->GetFunctionProxy()->GetDisplayName(), _u("set")) == 0)
  1738. {
  1739. // modify to name.set
  1740. const char16* finalName = ConstructName(propertyRecord, _u(".set"), scriptContext);
  1741. if (finalName != nullptr)
  1742. {
  1743. FunctionProxy::SetDisplayNameFlags flags = (FunctionProxy::SetDisplayNameFlags) (FunctionProxy::SetDisplayNameFlagsDontCopy | FunctionProxy::SetDisplayNameFlagsRecyclerAllocated);
  1744. Js::VarTo<Js::ScriptFunction>(descriptor.GetSetter())->GetFunctionProxy()->SetDisplayName(finalName,
  1745. propertyLength + 4 /*".set"*/, propertyLength + 1, flags);
  1746. }
  1747. }
  1748. }
  1749. }
  1750. BOOL JavascriptObject::DefineOwnPropertyHelper(RecyclableObject* obj, PropertyId propId, const PropertyDescriptor& descriptor, ScriptContext* scriptContext, bool throwOnError /* = true*/)
  1751. {
  1752. BOOL returnValue;
  1753. obj->ThrowIfCannotDefineProperty(propId, descriptor);
  1754. const Type* oldType = obj->GetType();
  1755. obj->ClearWritableDataOnlyDetectionBit();
  1756. // HostDispatch: it doesn't support changing property attributes and default attributes are not per ES5,
  1757. // so there is no benefit in using ES5 DefineOwnPropertyDescriptor for it, use old implementation.
  1758. if (TypeIds_HostDispatch != obj->GetTypeId())
  1759. {
  1760. // for Array Exotic Objects
  1761. if (DynamicObject::IsAnyArray(obj))
  1762. {
  1763. returnValue = JavascriptOperators::DefineOwnPropertyForArray(
  1764. JavascriptArray::FromAnyArray(obj), propId, descriptor, throwOnError, scriptContext);
  1765. }
  1766. // for Integer Indexed Exotic Objects
  1767. else if (DynamicObject::IsAnyTypedArray(obj))
  1768. {
  1769. returnValue = JavascriptOperators::DefineOwnPropertyForTypedArray(
  1770. VarTo<TypedArrayBase>(obj), propId, descriptor, throwOnError, scriptContext);
  1771. }
  1772. // TODO: implement DefineOwnProperty for other object built-in exotic types.
  1773. else
  1774. {
  1775. returnValue = JavascriptOperators::DefineOwnPropertyDescriptor(obj, propId, descriptor, throwOnError, scriptContext);
  1776. if (propId == PropertyIds::__proto__)
  1777. {
  1778. scriptContext->GetLibrary()->GetObjectPrototypeObject()->PostDefineOwnProperty__proto__(obj);
  1779. }
  1780. }
  1781. }
  1782. else
  1783. {
  1784. returnValue = JavascriptOperators::SetPropertyDescriptor(obj, propId, descriptor);
  1785. }
  1786. if (propId == PropertyIds::_symbolSpecies && obj == scriptContext->GetLibrary()->GetArrayConstructor())
  1787. {
  1788. scriptContext->GetLibrary()->SetArrayObjectHasUserDefinedSpecies(true);
  1789. }
  1790. if (obj->IsWritableDataOnlyDetectionBitSet())
  1791. {
  1792. if (obj->GetType() == oldType)
  1793. {
  1794. // Also, if the object's type has not changed, we need to ensure that
  1795. // the cached property string for this property, if any, does not
  1796. // specify this object's type.
  1797. scriptContext->InvalidatePropertyStringAndSymbolCaches(propId, obj->GetType());
  1798. }
  1799. }
  1800. if (descriptor.IsAccessorDescriptor())
  1801. {
  1802. scriptContext->optimizationOverrides.SetSideEffects(Js::SideEffects_Accessor);
  1803. }
  1804. return returnValue;
  1805. }
  1806. void JavascriptObject::SpreadObjectLiteral(Var source, Var to, ScriptContext* scriptContext)
  1807. {
  1808. RecyclableObject* target = nullptr;
  1809. bool succeeded = JavascriptConversion::ToObject(to, scriptContext, &target);
  1810. AssertOrFailFast(succeeded);
  1811. CopyDataPropertiesHelper<false, false>(source, target, scriptContext);
  1812. }
  1813. void JavascriptObject::Restify(Var source, Var to, void* excludedStatic, void* excludedComputed, ScriptContext* scriptContext)
  1814. {
  1815. RecyclableObject* target = nullptr;
  1816. bool succeeded = JavascriptConversion::ToObject(to, scriptContext, &target);
  1817. AssertOrFailFast(succeeded);
  1818. const Js::PropertyIdArray* propIdsStatic = reinterpret_cast<const Js::PropertyIdArray*>(excludedStatic);
  1819. const Js::PropertyIdArray* propIdsComputed = reinterpret_cast<const Js::PropertyIdArray*>(excludedComputed);
  1820. // Create a set of the property ids for faster lookup
  1821. BVSparse<Recycler> excluded(scriptContext->GetRecycler());
  1822. for (uint32 i = 0; i < propIdsStatic->count; i++)
  1823. {
  1824. PropertyId id = propIdsStatic->elements[i];
  1825. excluded.Set(id);
  1826. }
  1827. // If these two are equal, this means there were no computed properties
  1828. // and the static array was passed in to indicate this
  1829. if (propIdsStatic != propIdsComputed)
  1830. {
  1831. for (uint32 i = 0; i < propIdsComputed->count; i++)
  1832. {
  1833. PropertyId id = propIdsComputed->elements[i];
  1834. excluded.Set(id);
  1835. }
  1836. }
  1837. CopyDataPropertiesHelper<false, false>(source, target, scriptContext, &excluded);
  1838. }