JavascriptObject.cpp 81 KB

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