JavascriptObject.cpp 87 KB

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