JavascriptExternalFunction.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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/DeferredTypeHandler.h"
  7. namespace Js
  8. {
  9. // This is a wrapper class for javascript functions that are added directly to the JS engine via BuildDirectFunction
  10. // or CreateConstructor. We add a thunk before calling into user's direct C++ methods, with additional checks:
  11. // . check the script site is still alive.
  12. // . convert globalObject to hostObject
  13. // . leavescriptstart/end
  14. // . wrap the result value with potential cross site access
  15. JavascriptExternalFunction::JavascriptExternalFunction(ExternalMethod entryPoint, DynamicType* type)
  16. : RuntimeFunction(type, &EntryInfo::ExternalFunctionThunk), nativeMethod(entryPoint), signature(nullptr), callbackState(nullptr), initMethod(nullptr),
  17. oneBit(1), typeSlots(0), hasAccessors(0), flags(0), deferredLength(0)
  18. {
  19. DebugOnly(VerifyEntryPoint());
  20. }
  21. JavascriptExternalFunction::JavascriptExternalFunction(ExternalMethod entryPoint, DynamicType* type, InitializeMethod method, unsigned short deferredSlotCount, bool accessors)
  22. : RuntimeFunction(type, &EntryInfo::ExternalFunctionThunk), nativeMethod(entryPoint), signature(nullptr), callbackState(nullptr), initMethod(method),
  23. oneBit(1), typeSlots(deferredSlotCount), hasAccessors(accessors), flags(0), deferredLength(0)
  24. {
  25. DebugOnly(VerifyEntryPoint());
  26. }
  27. JavascriptExternalFunction::JavascriptExternalFunction(DynamicType* type, InitializeMethod method, unsigned short deferredSlotCount, bool accessors)
  28. : RuntimeFunction(type, &EntryInfo::DefaultExternalFunctionThunk), nativeMethod(nullptr), signature(nullptr), callbackState(nullptr), initMethod(method),
  29. oneBit(1), typeSlots(deferredSlotCount), hasAccessors(accessors), flags(0), deferredLength(0)
  30. {
  31. DebugOnly(VerifyEntryPoint());
  32. }
  33. JavascriptExternalFunction::JavascriptExternalFunction(JavascriptExternalFunction* entryPoint, DynamicType* type)
  34. : RuntimeFunction(type, &EntryInfo::WrappedFunctionThunk), wrappedMethod(entryPoint), callbackState(nullptr), initMethod(nullptr),
  35. oneBit(1), typeSlots(0), hasAccessors(0), flags(0), deferredLength(0)
  36. {
  37. DebugOnly(VerifyEntryPoint());
  38. }
  39. JavascriptExternalFunction::JavascriptExternalFunction(StdCallJavascriptMethod entryPoint, DynamicType* type)
  40. : RuntimeFunction(type, &EntryInfo::StdCallExternalFunctionThunk), stdCallNativeMethod(entryPoint), signature(nullptr), callbackState(nullptr), initMethod(nullptr),
  41. oneBit(1), typeSlots(0), hasAccessors(0), flags(0), deferredLength(0)
  42. {
  43. DebugOnly(VerifyEntryPoint());
  44. }
  45. JavascriptExternalFunction::JavascriptExternalFunction(DynamicType *type)
  46. : RuntimeFunction(type, &EntryInfo::ExternalFunctionThunk), nativeMethod(nullptr), signature(nullptr), callbackState(nullptr), initMethod(nullptr),
  47. oneBit(1), typeSlots(0), hasAccessors(0), flags(0), deferredLength(0)
  48. {
  49. DebugOnly(VerifyEntryPoint());
  50. }
  51. bool __cdecl JavascriptExternalFunction::DeferredLengthInitializer(DynamicObject * instance, DeferredTypeHandlerBase * typeHandler, DeferredInitializeMode mode)
  52. {
  53. Js::JavascriptLibrary::InitializeFunction<true, true, true, true>(instance, typeHandler, mode);
  54. JavascriptExternalFunction* object = static_cast<JavascriptExternalFunction*>(instance);
  55. object->UndeferLength(instance->GetScriptContext());
  56. return true;
  57. }
  58. // Note: non-constructors will probably use JavascriptFunction::InitiailizeFunction for undeferral.
  59. bool __cdecl JavascriptExternalFunction::DeferredConstructorInitializer(DynamicObject* instance, DeferredTypeHandlerBase* typeHandler, DeferredInitializeMode mode)
  60. {
  61. JavascriptExternalFunction* object = static_cast<JavascriptExternalFunction*>(instance);
  62. HRESULT hr = E_FAIL;
  63. ScriptContext* scriptContext = object->GetScriptContext();
  64. AnalysisAssert(scriptContext);
  65. // Don't call the implicit call if disable implicit call
  66. if (scriptContext->GetThreadContext()->IsDisableImplicitCall())
  67. {
  68. scriptContext->GetThreadContext()->AddImplicitCallFlags(ImplicitCall_External);
  69. //we will return if we get call further into implicitcalls.
  70. return false;
  71. }
  72. if (scriptContext->IsClosed() || scriptContext->IsInvalidatedForHostObjects())
  73. {
  74. Js::JavascriptError::MapAndThrowError(scriptContext, E_ACCESSDENIED);
  75. }
  76. ThreadContext* threadContext = scriptContext->GetThreadContext();
  77. typeHandler->Convert(instance, mode, object->typeSlots, object->hasAccessors);
  78. BEGIN_LEAVE_SCRIPT_INTERNAL(scriptContext)
  79. {
  80. ASYNC_HOST_OPERATION_START(threadContext);
  81. hr = object->initMethod(instance);
  82. ASYNC_HOST_OPERATION_END(threadContext);
  83. }
  84. END_LEAVE_SCRIPT_INTERNAL(scriptContext);
  85. if (FAILED(hr))
  86. {
  87. Js::JavascriptError::MapAndThrowError(scriptContext, hr);
  88. }
  89. JavascriptString * functionName = nullptr;
  90. if (object->GetFunctionName(&functionName))
  91. {
  92. object->SetPropertyWithAttributes(PropertyIds::name, functionName, PropertyConfigurable, nullptr);
  93. }
  94. return true;
  95. }
  96. void JavascriptExternalFunction::PrepareExternalCall(Js::Arguments * args)
  97. {
  98. ScriptContext * scriptContext = this->type->GetScriptContext();
  99. Assert(!scriptContext->GetThreadContext()->IsDisableImplicitException());
  100. scriptContext->VerifyAlive();
  101. Assert(scriptContext->GetThreadContext()->IsScriptActive());
  102. if (args->Info.Count == 0)
  103. {
  104. JavascriptError::ThrowTypeError(scriptContext, JSERR_This_NullOrUndefined);
  105. }
  106. Var &thisVar = args->Values[0];
  107. Js::TypeId typeId = Js::JavascriptOperators::GetTypeId(thisVar);
  108. Js::RecyclableObject* directHostObject = nullptr;
  109. switch(typeId)
  110. {
  111. case TypeIds_Integer:
  112. #if FLOATVAR
  113. case TypeIds_Number:
  114. #endif // FLOATVAR
  115. Assert(!Js::VarIs<Js::RecyclableObject>(thisVar));
  116. break;
  117. default:
  118. {
  119. Assert(Js::VarIs<Js::RecyclableObject>(thisVar));
  120. ScriptContext* scriptContextThisVar = Js::VarTo<Js::RecyclableObject>(thisVar)->GetScriptContext();
  121. // We need to verify "this" pointer is active as well. The problem is that DOM prototype functions are
  122. // the same across multiple frames, and caller can do function.call(closedthis)
  123. Assert(!scriptContext->GetThreadContext()->IsDisableImplicitException());
  124. scriptContextThisVar->VerifyAlive();
  125. // translate direct host for fastDOM.
  126. switch(typeId)
  127. {
  128. case Js::TypeIds_GlobalObject:
  129. {
  130. Js::GlobalObject* srcGlobalObject = (Js::GlobalObject*)(void*)(thisVar);
  131. directHostObject = srcGlobalObject->GetDirectHostObject();
  132. // For jsrt, direct host object can be null. If thats the case don't change it.
  133. if (directHostObject != nullptr)
  134. {
  135. thisVar = directHostObject;
  136. }
  137. }
  138. break;
  139. case Js::TypeIds_Undefined:
  140. case Js::TypeIds_Null:
  141. {
  142. // Call to DOM function with this as "undefined" or "null"
  143. // This should be converted to Global object
  144. Js::GlobalObject* srcGlobalObject = scriptContextThisVar->GetGlobalObject() ;
  145. directHostObject = srcGlobalObject->GetDirectHostObject();
  146. // For jsrt, direct host object can be null. If thats the case don't change it.
  147. if (directHostObject != nullptr)
  148. {
  149. thisVar = directHostObject;
  150. }
  151. }
  152. break;
  153. }
  154. }
  155. break;
  156. }
  157. }
  158. Var JavascriptExternalFunction::ExternalFunctionThunk(RecyclableObject* function, CallInfo callInfo, ...)
  159. {
  160. ARGUMENTS(args, callInfo);
  161. JavascriptExternalFunction* externalFunction = static_cast<JavascriptExternalFunction*>(function);
  162. ScriptContext * scriptContext = externalFunction->type->GetScriptContext();
  163. #ifdef ENABLE_DIRECTCALL_TELEMETRY
  164. DirectCallTelemetry::AutoLogger logger(scriptContext, externalFunction, &args);
  165. #endif
  166. externalFunction->PrepareExternalCall(&args);
  167. #if ENABLE_TTD
  168. Var result = nullptr;
  169. if(scriptContext->ShouldPerformRecordOrReplayAction())
  170. {
  171. result = JavascriptExternalFunction::HandleRecordReplayExternalFunction_Thunk(externalFunction, callInfo, args, scriptContext);
  172. }
  173. else
  174. {
  175. BEGIN_LEAVE_SCRIPT_WITH_EXCEPTION(scriptContext)
  176. {
  177. // Don't do stack probe since BEGIN_LEAVE_SCRIPT_WITH_EXCEPTION does that for us already
  178. result = externalFunction->nativeMethod(function, callInfo, args.Values);
  179. }
  180. END_LEAVE_SCRIPT_WITH_EXCEPTION(scriptContext);
  181. }
  182. #else
  183. Var result = nullptr;
  184. BEGIN_LEAVE_SCRIPT_WITH_EXCEPTION(scriptContext)
  185. {
  186. // Don't do stack probe since BEGIN_LEAVE_SCRIPT_WITH_EXCEPTION does that for us already
  187. result = externalFunction->nativeMethod(function, callInfo, args.Values);
  188. }
  189. END_LEAVE_SCRIPT_WITH_EXCEPTION(scriptContext);
  190. #endif
  191. if (result == nullptr)
  192. {
  193. #pragma warning(push)
  194. #pragma warning(disable:6011) // scriptContext cannot be null here
  195. result = scriptContext->GetLibrary()->GetUndefined();
  196. #pragma warning(pop)
  197. }
  198. else
  199. {
  200. result = CrossSite::MarshalVar(scriptContext, result);
  201. }
  202. return result;
  203. }
  204. Var JavascriptExternalFunction::WrappedFunctionThunk(RecyclableObject* function, CallInfo callInfo, ...)
  205. {
  206. ARGUMENTS(args, callInfo);
  207. JavascriptExternalFunction* externalFunction = static_cast<JavascriptExternalFunction*>(function);
  208. ScriptContext* scriptContext = externalFunction->type->GetScriptContext();
  209. Assert(!scriptContext->GetThreadContext()->IsDisableImplicitException());
  210. scriptContext->VerifyAlive();
  211. Assert(scriptContext->GetThreadContext()->IsScriptActive());
  212. // Make sure the callee knows we are a wrapped function thunk
  213. args.Info.Flags = (Js::CallFlags) (((int32) args.Info.Flags) | CallFlags_Wrapped);
  214. // don't need to leave script here, ExternalFunctionThunk will
  215. Assert(externalFunction->wrappedMethod->GetFunctionInfo()->GetOriginalEntryPoint() == JavascriptExternalFunction::ExternalFunctionThunk);
  216. BEGIN_SAFE_REENTRANT_CALL(scriptContext->GetThreadContext())
  217. {
  218. return JavascriptFunction::CallFunction<true>(externalFunction->wrappedMethod, externalFunction->wrappedMethod->GetEntryPoint(), args);
  219. }
  220. END_SAFE_REENTRANT_CALL
  221. }
  222. Var JavascriptExternalFunction::DefaultExternalFunctionThunk(RecyclableObject* function, CallInfo callInfo, ...)
  223. {
  224. TypeId typeId = function->GetTypeId();
  225. rtErrors err = typeId <= TypeIds_UndefinedOrNull ? JSERR_NeedObject : JSERR_NeedFunction;
  226. JavascriptError::ThrowTypeError(function->GetScriptContext(), err);
  227. }
  228. Var JavascriptExternalFunction::StdCallExternalFunctionThunk(RecyclableObject* function, CallInfo callInfo, ...)
  229. {
  230. ARGUMENTS(args, callInfo);
  231. JavascriptExternalFunction* externalFunction = static_cast<JavascriptExternalFunction*>(function);
  232. externalFunction->PrepareExternalCall(&args);
  233. ScriptContext * scriptContext = externalFunction->type->GetScriptContext();
  234. AnalysisAssert(scriptContext);
  235. if (args.Info.Count > USHORT_MAX)
  236. {
  237. // Due to compat reasons, stdcall external functions expect a ushort count of args.
  238. // To support more than this we will need a new API.
  239. Js::JavascriptError::ThrowTypeError(scriptContext, JSERR_ArgListTooLarge);
  240. }
  241. Var result = nullptr;
  242. Assert(callInfo.Count > 0);
  243. StdCallJavascriptMethodInfo info = {
  244. args[0],
  245. args.HasNewTarget() ? args.GetNewTarget() : args.IsNewCall() ? function : scriptContext->GetLibrary()->GetUndefined(),
  246. args.IsNewCall()
  247. };
  248. #if ENABLE_TTD
  249. if(scriptContext->ShouldPerformRecordOrReplayAction())
  250. {
  251. result = JavascriptExternalFunction::HandleRecordReplayExternalFunction_StdThunk(function, callInfo, args, scriptContext);
  252. }
  253. else
  254. {
  255. BEGIN_LEAVE_SCRIPT(scriptContext)
  256. {
  257. result = externalFunction->stdCallNativeMethod(function, args.Values, static_cast<USHORT>(args.Info.Count), &info, externalFunction->callbackState);
  258. }
  259. END_LEAVE_SCRIPT(scriptContext);
  260. }
  261. #else
  262. BEGIN_LEAVE_SCRIPT(scriptContext)
  263. {
  264. result = externalFunction->stdCallNativeMethod(function, args.Values, static_cast<USHORT>(args.Info.Count), &info, externalFunction->callbackState);
  265. }
  266. END_LEAVE_SCRIPT(scriptContext);
  267. #endif
  268. if (scriptContext->HasRecordedException())
  269. {
  270. bool considerPassingToDebugger = false;
  271. JavascriptExceptionObject* recordedException = scriptContext->GetAndClearRecordedException(&considerPassingToDebugger);
  272. if (recordedException != nullptr)
  273. {
  274. // If this is script termination, then throw ScriptAbortExceptio, else throw normal Exception object.
  275. if (recordedException == scriptContext->GetThreadContext()->GetPendingTerminatedErrorObject())
  276. {
  277. throw Js::ScriptAbortException();
  278. }
  279. else
  280. {
  281. JavascriptExceptionOperators::RethrowExceptionObject(recordedException, scriptContext, considerPassingToDebugger);
  282. }
  283. }
  284. }
  285. if (result == nullptr)
  286. {
  287. result = scriptContext->GetLibrary()->GetUndefined();
  288. }
  289. else
  290. {
  291. result = CrossSite::MarshalVar(scriptContext, result);
  292. }
  293. return result;
  294. }
  295. BOOL JavascriptExternalFunction::SetLengthProperty(Var length)
  296. {
  297. return DynamicObject::SetPropertyWithAttributes(PropertyIds::length, length, PropertyConfigurable, NULL, PropertyOperation_None, SideEffects_None);
  298. }
  299. void JavascriptExternalFunction::UndeferLength(ScriptContext *scriptContext)
  300. {
  301. if (deferredLength > 0)
  302. {
  303. SetLengthProperty(Js::JavascriptNumber::ToVar(deferredLength, scriptContext));
  304. deferredLength = 0;
  305. }
  306. }
  307. #if ENABLE_TTD
  308. TTD::NSSnapObjects::SnapObjectType JavascriptExternalFunction::GetSnapTag_TTD() const
  309. {
  310. return TTD::NSSnapObjects::SnapObjectType::SnapExternalFunctionObject;
  311. }
  312. void JavascriptExternalFunction::ExtractSnapObjectDataInto(TTD::NSSnapObjects::SnapObject* objData, TTD::SlabAllocator& alloc)
  313. {
  314. TTD::TTDVar fnameId = TTD_CONVERT_JSVAR_TO_TTDVAR(this->functionNameId);
  315. TTD::NSSnapObjects::StdExtractSetKindSpecificInfo<TTD::TTDVar, TTD::NSSnapObjects::SnapObjectType::SnapExternalFunctionObject>(objData, fnameId);
  316. }
  317. Var JavascriptExternalFunction::HandleRecordReplayExternalFunction_Thunk(Js::JavascriptFunction* function, CallInfo& callInfo, Arguments& args, ScriptContext* scriptContext)
  318. {
  319. JavascriptExternalFunction* externalFunction = static_cast<JavascriptExternalFunction*>(function);
  320. Var result = nullptr;
  321. if(scriptContext->ShouldPerformReplayAction())
  322. {
  323. TTD::TTDNestingDepthAutoAdjuster logPopper(scriptContext->GetThreadContext());
  324. scriptContext->GetThreadContext()->TTDLog->ReplayExternalCallEvent(externalFunction, args, &result);
  325. }
  326. else
  327. {
  328. TTDAssert(scriptContext->ShouldPerformRecordAction(), "Check either record/replay before calling!!!");
  329. TTD::EventLog* elog = scriptContext->GetThreadContext()->TTDLog;
  330. TTD::TTDNestingDepthAutoAdjuster logPopper(scriptContext->GetThreadContext());
  331. TTD::NSLogEvents::EventLogEntry* callEvent = elog->RecordExternalCallEvent(externalFunction, scriptContext->GetThreadContext()->TTDRootNestingCount, args, false);
  332. BEGIN_LEAVE_SCRIPT_WITH_EXCEPTION(scriptContext)
  333. {
  334. // Don't do stack probe since BEGIN_LEAVE_SCRIPT_WITH_EXCEPTION does that for us already
  335. result = externalFunction->nativeMethod(function, callInfo, args.Values);
  336. }
  337. END_LEAVE_SCRIPT_WITH_EXCEPTION(scriptContext);
  338. //Exceptions should be prohibited so no need to do extra work
  339. elog->RecordExternalCallEvent_Complete(externalFunction, callEvent, result);
  340. }
  341. return result;
  342. }
  343. Var JavascriptExternalFunction::HandleRecordReplayExternalFunction_StdThunk(Js::RecyclableObject* function, CallInfo& callInfo, Arguments& args, ScriptContext* scriptContext)
  344. {
  345. JavascriptExternalFunction* externalFunction = static_cast<JavascriptExternalFunction*>(function);
  346. Var result = nullptr;
  347. if(scriptContext->ShouldPerformReplayAction())
  348. {
  349. TTD::TTDNestingDepthAutoAdjuster logPopper(scriptContext->GetThreadContext());
  350. scriptContext->GetThreadContext()->TTDLog->ReplayExternalCallEvent(externalFunction, args, &result);
  351. }
  352. else
  353. {
  354. if (args.Info.Count > USHORT_MAX)
  355. {
  356. // Due to compat reasons, stdcall external functions expect a ushort count of args.
  357. // To support more than this we will need a new API.
  358. Js::JavascriptError::ThrowTypeError(scriptContext, JSERR_ArgListTooLarge);
  359. }
  360. TTDAssert(scriptContext->ShouldPerformRecordAction(), "Check either record/replay before calling!!!");
  361. TTD::EventLog* elog = scriptContext->GetThreadContext()->TTDLog;
  362. TTD::TTDNestingDepthAutoAdjuster logPopper(scriptContext->GetThreadContext());
  363. TTD::NSLogEvents::EventLogEntry* callEvent = elog->RecordExternalCallEvent(externalFunction, scriptContext->GetThreadContext()->TTDRootNestingCount, args, true);
  364. StdCallJavascriptMethodInfo info = {
  365. args[0],
  366. args.HasNewTarget() ? args.GetNewTarget() : args.IsNewCall() ? function : scriptContext->GetLibrary()->GetUndefined(),
  367. args.IsNewCall()
  368. };
  369. BEGIN_LEAVE_SCRIPT(scriptContext)
  370. {
  371. result = externalFunction->stdCallNativeMethod(function, args.Values, static_cast<ushort>(args.Info.Count), &info, externalFunction->callbackState);
  372. }
  373. END_LEAVE_SCRIPT(scriptContext);
  374. elog->RecordExternalCallEvent_Complete(externalFunction, callEvent, result);
  375. }
  376. return result;
  377. }
  378. Var __stdcall JavascriptExternalFunction::TTDReplayDummyExternalMethod(Var callee, Var *args, USHORT cargs, StdCallJavascriptMethodInfo *info, void *callbackState)
  379. {
  380. JavascriptExternalFunction* externalFunction = static_cast<JavascriptExternalFunction*>(callee);
  381. ScriptContext* scriptContext = externalFunction->type->GetScriptContext();
  382. TTD::EventLog* elog = scriptContext->GetThreadContext()->TTDLog;
  383. TTDAssert(elog != nullptr, "How did this get created then???");
  384. //If this flag is set then this is ok (the debugger may be evaluating this so just return undef -- otherwise this is an error
  385. if(!elog->IsDebugModeFlagSet())
  386. {
  387. TTDAssert(false, "This should never be reached in pure replay mode!!!");
  388. return nullptr;
  389. }
  390. return scriptContext->GetLibrary()->GetUndefined();
  391. }
  392. #endif
  393. }