BoundFunction.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. namespace Js
  7. {
  8. FunctionInfo BoundFunction::functionInfo(FORCE_NO_WRITE_BARRIER_TAG(BoundFunction::NewInstance), FunctionInfo::DoNotProfile);
  9. BoundFunction::BoundFunction(DynamicType * type)
  10. : JavascriptFunction(type, &functionInfo),
  11. targetFunction(nullptr),
  12. boundThis(nullptr),
  13. count(0),
  14. boundArgs(nullptr)
  15. {
  16. // Constructor used during copy on write.
  17. DebugOnly(VerifyEntryPoint());
  18. }
  19. BoundFunction::BoundFunction(Arguments args, DynamicType * type)
  20. : JavascriptFunction(type, &functionInfo),
  21. count(0),
  22. boundArgs(nullptr)
  23. {
  24. DebugOnly(VerifyEntryPoint());
  25. AssertMsg(args.Info.Count > 0, "wrong number of args in BoundFunction");
  26. ScriptContext *scriptContext = this->GetScriptContext();
  27. targetFunction = RecyclableObject::FromVar(args[0]);
  28. Assert(!CrossSite::NeedMarshalVar(targetFunction, scriptContext));
  29. // Let proto be targetFunction.[[GetPrototypeOf]]().
  30. RecyclableObject* proto = JavascriptOperators::GetPrototype(targetFunction);
  31. if (proto != type->GetPrototype())
  32. {
  33. if (type->GetIsShared())
  34. {
  35. this->ChangeType();
  36. type = this->GetDynamicType();
  37. }
  38. type->SetPrototype(proto);
  39. }
  40. int len = 0;
  41. // If targetFunction is proxy, need to make sure that traps are called in right order as per 19.2.3.2 in RC#4 dated April 3rd 2015.
  42. // additionally need to get the correct length value for the boundFunctions' length property
  43. if (JavascriptOperators::HasOwnProperty(targetFunction, PropertyIds::length, scriptContext, nullptr) == TRUE)
  44. {
  45. Var varLength;
  46. if (targetFunction->GetProperty(targetFunction, PropertyIds::length, &varLength, nullptr, scriptContext))
  47. {
  48. len = JavascriptConversion::ToInt32(varLength, scriptContext);
  49. }
  50. }
  51. GetTypeHandler()->EnsureObjectReady(this);
  52. if (args.Info.Count > 1)
  53. {
  54. boundThis = args[1];
  55. // function object and "this" arg
  56. const uint countAccountedFor = 2;
  57. count = args.Info.Count - countAccountedFor;
  58. // Store the args excluding function obj and "this" arg
  59. if (args.Info.Count > 2)
  60. {
  61. boundArgs = RecyclerNewArray(scriptContext->GetRecycler(), Field(Var), count);
  62. for (uint i=0; i<count; i++)
  63. {
  64. boundArgs[i] = args[i+countAccountedFor];
  65. }
  66. }
  67. }
  68. else
  69. {
  70. // If no "this" is passed, "undefined" is used
  71. boundThis = scriptContext->GetLibrary()->GetUndefined();
  72. }
  73. // Reduce length number of bound args
  74. len = len - this->count;
  75. len = max(len, 0);
  76. SetPropertyWithAttributes(PropertyIds::length, TaggedInt::ToVarUnchecked(len), PropertyConfigurable, nullptr, PropertyOperation_None, SideEffects_None);
  77. }
  78. BoundFunction* BoundFunction::New(ScriptContext* scriptContext, ArgumentReader args)
  79. {
  80. Recycler* recycler = scriptContext->GetRecycler();
  81. BoundFunction* boundFunc = RecyclerNew(recycler, BoundFunction, args,
  82. scriptContext->GetLibrary()->GetBoundFunctionType());
  83. return boundFunc;
  84. }
  85. Var BoundFunction::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  86. {
  87. RUNTIME_ARGUMENTS(args, callInfo);
  88. ScriptContext* scriptContext = function->GetScriptContext();
  89. if (args.Info.Count == 0)
  90. {
  91. JavascriptError::ThrowTypeError(scriptContext, JSERR_NeedFunction /* TODO-ERROR: get arg name - args[0] */);
  92. }
  93. BoundFunction *boundFunction = (BoundFunction *) function;
  94. RecyclableObject *targetFunction = boundFunction->targetFunction;
  95. //
  96. // var o = new boundFunction()
  97. // a new object should be created using the actual function object
  98. //
  99. Var newVarInstance = nullptr;
  100. if (callInfo.Flags & CallFlags_New)
  101. {
  102. if (args.HasNewTarget())
  103. {
  104. // target has an overriden new target make a new object from the newTarget
  105. Var newTargetVar = args.GetNewTarget();
  106. AssertOrFailFastMsg(JavascriptOperators::IsConstructor(newTargetVar), "newTarget must be a constructor");
  107. RecyclableObject* newTarget = RecyclableObject::UnsafeFromVar(newTargetVar);
  108. // Class constructors expect newTarget to be in args slot 0 (usually "this"),
  109. // because "this" is not constructed until we reach the most-super superclass.
  110. FunctionInfo* functionInfo = JavascriptOperators::GetConstructorFunctionInfo(targetFunction, scriptContext);
  111. if (functionInfo && functionInfo->IsClassConstructor())
  112. {
  113. args.Values[0] = newVarInstance = newTarget;
  114. }
  115. else
  116. {
  117. args.Values[0] = newVarInstance = JavascriptOperators::CreateFromConstructor(newTarget, scriptContext);
  118. }
  119. }
  120. else if (!JavascriptProxy::Is(targetFunction))
  121. {
  122. // No new target and target is not a proxy can make a new object in a "normal" way.
  123. // NewScObjectNoCtor will either construct an object or return targetFunction depending
  124. // on whether targetFunction is a class constructor.
  125. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  126. {
  127. args.Values[0] = newVarInstance = JavascriptOperators::NewScObjectNoCtor(targetFunction, scriptContext);
  128. }
  129. END_SAFE_REENTRANT_CALL
  130. }
  131. else
  132. {
  133. // target is a proxy without an overriden new target
  134. // give nullptr - FunctionCallTrap will make a new object
  135. args.Values[0] = newVarInstance;
  136. }
  137. }
  138. Js::Arguments actualArgs = args;
  139. if (boundFunction->count > 0)
  140. {
  141. // OACR thinks that this can change between here and the check in the for loop below
  142. const unsigned int argCount = args.Info.Count;
  143. uint32 newArgCount = UInt32Math::Add(boundFunction->count, args.GetLargeArgCountWithExtraArgs());
  144. if (newArgCount > CallInfo::kMaxCountArgs)
  145. {
  146. JavascriptError::ThrowRangeError(scriptContext, JSERR_ArgListTooLarge);
  147. }
  148. Field(Var) *newValues = RecyclerNewArray(scriptContext->GetRecycler(), Field(Var), newArgCount);
  149. uint index = 0;
  150. //
  151. // For [[Construct]] use the newly created var instance
  152. // For [[Call]] use the "this" to which bind bound it.
  153. //
  154. if (callInfo.Flags & CallFlags_New)
  155. {
  156. newValues[index++] = args[0];
  157. }
  158. else
  159. {
  160. newValues[index++] = boundFunction->boundThis;
  161. }
  162. for (uint i = 0; i < boundFunction->count; i++)
  163. {
  164. newValues[index++] = boundFunction->boundArgs[i];
  165. }
  166. // Copy the extra args
  167. for (uint i=1; i<argCount; i++)
  168. {
  169. newValues[index++] = args[i];
  170. }
  171. if (args.HasExtraArg())
  172. {
  173. newValues[index++] = args.Values[argCount];
  174. }
  175. actualArgs = Arguments(args.Info, unsafe_write_barrier_cast<Var*>(newValues));
  176. actualArgs.Info.Count = boundFunction->count + argCount;
  177. Assert(index == actualArgs.GetLargeArgCountWithExtraArgs());
  178. }
  179. else
  180. {
  181. if (!(callInfo.Flags & CallFlags_New))
  182. {
  183. actualArgs.Values[0] = boundFunction->boundThis;
  184. }
  185. }
  186. Var aReturnValue = nullptr;
  187. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  188. {
  189. // Number of arguments are allowed to be more than Constants::MaxAllowedArgs in runtime. Need to use the larger argcount logic for this call.
  190. aReturnValue = JavascriptFunction::CallFunction<true>(targetFunction, targetFunction->GetEntryPoint(), actualArgs, /* useLargeArgCount */ true);
  191. }
  192. END_SAFE_REENTRANT_CALL
  193. //
  194. // [[Construct]] and call returned a non-object
  195. // return the newly created var instance
  196. //
  197. if ((callInfo.Flags & CallFlags_New) && !JavascriptOperators::IsObject(aReturnValue))
  198. {
  199. aReturnValue = newVarInstance;
  200. }
  201. return aReturnValue;
  202. }
  203. JavascriptFunction * BoundFunction::GetTargetFunction() const
  204. {
  205. if (targetFunction != nullptr)
  206. {
  207. RecyclableObject* _targetFunction = targetFunction;
  208. while (JavascriptProxy::Is(_targetFunction))
  209. {
  210. _targetFunction = JavascriptProxy::FromVar(_targetFunction)->GetTarget();
  211. }
  212. if (JavascriptFunction::Is(_targetFunction))
  213. {
  214. return JavascriptFunction::FromVar(_targetFunction);
  215. }
  216. // targetFunction should always be a JavascriptFunction.
  217. Assert(FALSE);
  218. }
  219. return nullptr;
  220. }
  221. JavascriptString* BoundFunction::GetDisplayNameImpl() const
  222. {
  223. JavascriptString* displayName = GetLibrary()->GetEmptyString();
  224. if (targetFunction != nullptr)
  225. {
  226. Var value = JavascriptOperators::GetPropertyNoCache(targetFunction, PropertyIds::name, targetFunction->GetScriptContext());
  227. if (JavascriptString::Is(value))
  228. {
  229. displayName = JavascriptString::FromVar(value);
  230. }
  231. }
  232. return LiteralString::Concat(LiteralString::NewCopySz(_u("bound "), this->GetScriptContext()), displayName);
  233. }
  234. RecyclableObject* BoundFunction::GetBoundThis()
  235. {
  236. if (boundThis != nullptr && RecyclableObject::Is(boundThis))
  237. {
  238. return RecyclableObject::FromVar(boundThis);
  239. }
  240. return NULL;
  241. }
  242. inline BOOL BoundFunction::IsConstructor() const
  243. {
  244. if (this->targetFunction != nullptr)
  245. {
  246. return JavascriptOperators::IsConstructor(this->GetTargetFunction());
  247. }
  248. return false;
  249. }
  250. PropertyQueryFlags BoundFunction::GetPropertyReferenceQuery(Var originalInstance, PropertyId propertyId, Var* value, PropertyValueInfo* info, ScriptContext* requestContext)
  251. {
  252. return BoundFunction::GetPropertyQuery(originalInstance, propertyId, value, info, requestContext);
  253. }
  254. _Check_return_ _Success_(return) BOOL BoundFunction::GetAccessors(PropertyId propertyId, _Outptr_result_maybenull_ Var* getter, _Outptr_result_maybenull_ Var* setter, ScriptContext* requestContext)
  255. {
  256. return DynamicObject::GetAccessors(propertyId, getter, setter, requestContext);
  257. }
  258. DescriptorFlags BoundFunction::GetSetter(PropertyId propertyId, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  259. {
  260. return DynamicObject::GetSetter(propertyId, setterValue, info, requestContext);
  261. }
  262. DescriptorFlags BoundFunction::GetSetter(JavascriptString* propertyNameString, Var *setterValue, PropertyValueInfo* info, ScriptContext* requestContext)
  263. {
  264. return DynamicObject::GetSetter(propertyNameString, setterValue, info, requestContext);
  265. }
  266. BOOL BoundFunction::InitProperty(PropertyId propertyId, Var value, PropertyOperationFlags flags, PropertyValueInfo* info)
  267. {
  268. return SetProperty(propertyId, value, PropertyOperation_None, info);
  269. }
  270. BOOL BoundFunction::HasInstance(Var instance, ScriptContext* scriptContext, IsInstInlineCache* inlineCache)
  271. {
  272. return this->targetFunction->HasInstance(instance, scriptContext, inlineCache);
  273. }
  274. #if ENABLE_TTD
  275. void BoundFunction::MarkVisitKindSpecificPtrs(TTD::SnapshotExtractor* extractor)
  276. {
  277. extractor->MarkVisitVar(this->targetFunction);
  278. if(this->boundThis != nullptr)
  279. {
  280. extractor->MarkVisitVar(this->boundThis);
  281. }
  282. for(uint32 i = 0; i < this->count; ++i)
  283. {
  284. extractor->MarkVisitVar(this->boundArgs[i]);
  285. }
  286. }
  287. void BoundFunction::ProcessCorePaths()
  288. {
  289. this->GetScriptContext()->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, this->targetFunction, _u("!targetFunction"));
  290. this->GetScriptContext()->TTDWellKnownInfo->EnqueueNewPathVarAsNeeded(this, this->boundThis, _u("!boundThis"));
  291. TTDAssert(this->count == 0, "Should only have empty args in core image");
  292. }
  293. TTD::NSSnapObjects::SnapObjectType BoundFunction::GetSnapTag_TTD() const
  294. {
  295. return TTD::NSSnapObjects::SnapObjectType::SnapBoundFunctionObject;
  296. }
  297. void BoundFunction::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  298. {
  299. TTD::NSSnapObjects::SnapBoundFunctionInfo* bfi = alloc.SlabAllocateStruct<TTD::NSSnapObjects::SnapBoundFunctionInfo>();
  300. bfi->TargetFunction = TTD_CONVERT_VAR_TO_PTR_ID(static_cast<RecyclableObject*>(this->targetFunction));
  301. bfi->BoundThis = (this->boundThis != nullptr) ?
  302. TTD_CONVERT_VAR_TO_PTR_ID(static_cast<Var>(this->boundThis)) : TTD_INVALID_PTR_ID;
  303. bfi->ArgCount = this->count;
  304. bfi->ArgArray = nullptr;
  305. if(bfi->ArgCount > 0)
  306. {
  307. bfi->ArgArray = alloc.SlabAllocateArray<TTD::TTDVar>(bfi->ArgCount);
  308. }
  309. TTD_PTR_ID* depArray = alloc.SlabReserveArraySpace<TTD_PTR_ID>(bfi->ArgCount + 2 /*this and bound function*/);
  310. depArray[0] = bfi->TargetFunction;
  311. uint32 depCount = 1;
  312. if(this->boundThis != nullptr && TTD::JsSupport::IsVarComplexKind(this->boundThis))
  313. {
  314. depArray[depCount] = bfi->BoundThis;
  315. depCount++;
  316. }
  317. if(bfi->ArgCount > 0)
  318. {
  319. for(uint32 i = 0; i < bfi->ArgCount; ++i)
  320. {
  321. bfi->ArgArray[i] = this->boundArgs[i];
  322. //Primitive kinds always inflated first so we only need to deal with complex kinds as depends on
  323. if(TTD::JsSupport::IsVarComplexKind(this->boundArgs[i]))
  324. {
  325. depArray[depCount] = TTD_CONVERT_VAR_TO_PTR_ID(this->boundArgs[i]);
  326. depCount++;
  327. }
  328. }
  329. }
  330. alloc.SlabCommitArraySpace<TTD_PTR_ID>(depCount, depCount + bfi->ArgCount);
  331. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::NSSnapObjects::SnapBoundFunctionInfo*, TTD::NSSnapObjects::SnapObjectType::SnapBoundFunctionObject>(objData, bfi, alloc, depCount, depArray);
  332. }
  333. BoundFunction* BoundFunction::InflateBoundFunction(
  334. ScriptContext* ctx, RecyclableObject* function, Var bThis, uint32 ct, Field(Var)* args)
  335. {
  336. BoundFunction* res = RecyclerNew(ctx->GetRecycler(), BoundFunction, ctx->GetLibrary()->GetBoundFunctionType());
  337. res->boundThis = bThis;
  338. res->count = ct;
  339. res->boundArgs = args;
  340. res->targetFunction = function;
  341. return res;
  342. }
  343. #endif
  344. } // namespace Js