WScriptJsrt.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft Corporation and contributors. All rights reserved.
  3. // Copyright (c) 2021 ChakraCore Project Contributors. All rights reserved.
  4. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  5. //-------------------------------------------------------------------------------------------------------
  6. #include "stdafx.h"
  7. #include "PlatformAgnostic/ChakraICU.h"
  8. #include <vector>
  9. #if defined(_X86_) || defined(_M_IX86)
  10. #define CPU_ARCH_TEXT "x86"
  11. #elif defined(_AMD64_) || defined(_IA64_) || defined(_M_AMD64) || defined(_M_IA64)
  12. #define CPU_ARCH_TEXT "x86_64"
  13. #elif defined(_ARM_) || defined(_M_ARM)
  14. #define CPU_ARCH_TEXT "ARM"
  15. #elif defined(_ARM64_) || defined(_M_ARM64)
  16. #define CPU_ARCH_TEXT "ARM64"
  17. #endif
  18. // do not change the order below
  19. // otherwise, i.e. android system can be marked as posix? etc..
  20. #ifdef _WIN32
  21. #define DEST_PLATFORM_TEXT "win32"
  22. #else // ! _WIN32
  23. #if defined(__APPLE__)
  24. #ifdef __IOS__
  25. #define DEST_PLATFORM_TEXT "ios"
  26. #else // ! iOS
  27. #define DEST_PLATFORM_TEXT "darwin"
  28. #endif // iOS ?
  29. #elif defined(__ANDROID__)
  30. #define DEST_PLATFORM_TEXT "android"
  31. #elif defined(__linux__)
  32. #define DEST_PLATFORM_TEXT "posix"
  33. #elif defined(__FreeBSD__) || defined(__unix__)
  34. #define DEST_PLATFORM_TEXT "bsd"
  35. #endif // FreeBSD or unix ?
  36. #endif // _WIN32 ?
  37. #pragma prefast(disable:26444, "This warning unfortunately raises false positives when auto is used for declaring the type of an iterator in a loop.")
  38. #ifdef HAS_ICU
  39. #define INTL_LIBRARY_TEXT "icu"
  40. #elif defined(_WIN32)
  41. #define INTL_LIBRARY_TEXT "winglob"
  42. #else
  43. #define INTL_LIBRARY_TEXT ""
  44. #endif
  45. struct ArrayBufferTransferInfo {
  46. byte* buffer;
  47. uint length;
  48. ArrayBufferFreeFn freeFn;
  49. };
  50. struct SerializerBlob
  51. {
  52. void *data;
  53. size_t dataLength;
  54. std::vector<ArrayBufferTransferInfo> transferableArrays;
  55. };
  56. MessageQueue* WScriptJsrt::messageQueue = nullptr;
  57. std::map<std::string, JsModuleRecord> WScriptJsrt::moduleRecordMap;
  58. std::map<JsModuleRecord, std::string> WScriptJsrt::moduleDirMap;
  59. std::map<JsModuleRecord, ModuleState> WScriptJsrt::moduleErrMap;
  60. std::map<DWORD_PTR, std::string> WScriptJsrt::scriptDirMap;
  61. DWORD_PTR WScriptJsrt::sourceContext = 0;
  62. #define ERROR_MESSAGE_TO_STRING(errorCode, errorMessage, errorMessageString) \
  63. JsErrorCode errorCode = JsNoError; \
  64. do \
  65. { \
  66. const char *outOfMemoryString = \
  67. "Failed to convert wide string. Out of memory?";\
  68. \
  69. char *errorMessageNarrow; \
  70. if (FAILED(WideStringToNarrowDynamic(errorMessage, &errorMessageNarrow))) \
  71. { \
  72. errorCode = ChakraRTInterface::JsCreateString(outOfMemoryString, \
  73. strlen(outOfMemoryString), &errorMessageString); \
  74. } \
  75. else \
  76. { \
  77. errorCode = ChakraRTInterface::JsCreateString(errorMessageNarrow, \
  78. strlen(errorMessageNarrow), &errorMessageString); \
  79. free(errorMessageNarrow); \
  80. } \
  81. } \
  82. while(0)
  83. DWORD_PTR WScriptJsrt::GetNextSourceContext()
  84. {
  85. return sourceContext++;
  86. }
  87. void WScriptJsrt::RegisterScriptDir(DWORD_PTR sourceContext, LPCSTR fullDirNarrow)
  88. {
  89. GetDir(fullDirNarrow, &scriptDirMap[sourceContext]);
  90. }
  91. bool WScriptJsrt::CreateArgumentsObject(JsValueRef *argsObject)
  92. {
  93. LPWSTR *argv = HostConfigFlags::argsVal;
  94. JsValueRef retArr;
  95. Assert(argsObject);
  96. *argsObject = nullptr;
  97. IfJsrtErrorFail(ChakraRTInterface::JsCreateArray(HostConfigFlags::argsCount, &retArr), false);
  98. for (int i = 0; i < HostConfigFlags::argsCount; i++)
  99. {
  100. JsValueRef value;
  101. JsValueRef index;
  102. char *argNarrow;
  103. if (FAILED(WideStringToNarrowDynamic(argv[i], &argNarrow)))
  104. {
  105. return false;
  106. }
  107. JsErrorCode errCode = ChakraRTInterface::JsCreateString(
  108. argNarrow,
  109. strlen(argNarrow), &value);
  110. free(argNarrow);
  111. IfJsrtErrorFail(errCode, false);
  112. IfJsrtErrorFail(ChakraRTInterface::JsDoubleToNumber(i, &index), false);
  113. IfJsrtErrorFail(ChakraRTInterface::JsSetIndexedProperty(retArr, index, value), false);
  114. }
  115. *argsObject = retArr;
  116. return true;
  117. }
  118. JsValueRef __stdcall WScriptJsrt::EchoCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  119. {
  120. for (unsigned int i = 1; i < argumentCount; i++)
  121. {
  122. JsValueRef strValue;
  123. JsErrorCode error = ChakraRTInterface::JsConvertValueToString(arguments[i], &strValue);
  124. if (error == JsNoError)
  125. {
  126. AutoString str(strValue);
  127. if (str.GetError() == JsNoError)
  128. {
  129. if (i > 1)
  130. {
  131. wprintf(_u(" "));
  132. }
  133. charcount_t len;
  134. LPWSTR ws = str.GetWideString(&len);
  135. LPWSTR wsNoNull = new WCHAR[((size_t)len) + 1];
  136. charcount_t newIndex = 0;
  137. for (charcount_t j = 0; j < len; j++)
  138. {
  139. if (ws[j] != _u('\0'))
  140. {
  141. wsNoNull[newIndex++] = ws[j];
  142. }
  143. }
  144. wsNoNull[newIndex] = _u('\0');
  145. wprintf(_u("%s"), wsNoNull);
  146. delete[] wsNoNull;
  147. }
  148. }
  149. if (error == JsErrorScriptException)
  150. {
  151. return nullptr;
  152. }
  153. }
  154. wprintf(_u("\n"));
  155. fflush(stdout);
  156. JsValueRef undefinedValue;
  157. if (ChakraRTInterface::JsGetUndefinedValue(&undefinedValue) == JsNoError)
  158. {
  159. return undefinedValue;
  160. }
  161. else
  162. {
  163. return nullptr;
  164. }
  165. }
  166. JsValueRef __stdcall WScriptJsrt::QuitCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  167. {
  168. int exitCode = 0;
  169. if (argumentCount > 1)
  170. {
  171. double exitCodeDouble;
  172. IfJsrtErrorFail(ChakraRTInterface::JsNumberToDouble(arguments[1], &exitCodeDouble), JS_INVALID_REFERENCE);
  173. exitCode = (int)exitCodeDouble;
  174. }
  175. ExitProcess(exitCode);
  176. }
  177. JsValueRef __stdcall WScriptJsrt::LoadScriptFileCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  178. {
  179. return LoadScriptFileHelper(callee, arguments, argumentCount, false);
  180. }
  181. // needed because of calling convention differences between _stdcall and _cdecl
  182. void CHAKRA_CALLBACK WScriptJsrt::FinalizeFree(void* addr)
  183. {
  184. free(addr);
  185. }
  186. JsValueRef WScriptJsrt::LoadScriptFileHelper(JsValueRef callee, JsValueRef *arguments, unsigned short argumentCount, bool isSourceModule)
  187. {
  188. HRESULT hr = E_FAIL;
  189. JsValueRef returnValue = JS_INVALID_REFERENCE;
  190. JsErrorCode errorCode = JsNoError;
  191. LPCWSTR errorMessage = _u("");
  192. if (argumentCount < 2 || argumentCount > 4)
  193. {
  194. errorCode = JsErrorInvalidArgument;
  195. errorMessage = _u("Need more or fewer arguments for WScript.LoadScript");
  196. }
  197. else
  198. {
  199. LPCSTR fileContent;
  200. AutoString fileName(arguments[1]);
  201. IfJsrtErrorSetGo(fileName.GetError());
  202. AutoString scriptInjectType;
  203. if (argumentCount > 2)
  204. {
  205. IfJsrtErrorSetGo(scriptInjectType.Initialize(arguments[2]));
  206. }
  207. if (errorCode == JsNoError)
  208. {
  209. hr = Helpers::LoadScriptFromFile(*fileName, fileContent);
  210. if (FAILED(hr))
  211. {
  212. fprintf(stderr, "Couldn't load file '%s'\n", fileName.GetString());
  213. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  214. return returnValue;
  215. }
  216. returnValue = LoadScript(callee, *fileName, fileContent, *scriptInjectType ? *scriptInjectType : "self", isSourceModule, WScriptJsrt::FinalizeFree, true);
  217. }
  218. }
  219. Error:
  220. SetExceptionIf(errorCode, errorMessage);
  221. return returnValue;
  222. }
  223. void WScriptJsrt::SetExceptionIf(JsErrorCode errorCode, LPCWSTR errorMessage)
  224. {
  225. if (errorCode != JsNoError)
  226. {
  227. // If the exception is already is set - no need to create a new exception.
  228. bool hasException = false;
  229. if (!(ChakraRTInterface::JsHasException(&hasException) == JsNoError && hasException))
  230. {
  231. JsValueRef errorObject;
  232. JsValueRef errorMessageString;
  233. if (wcscmp(errorMessage, _u("")) == 0)
  234. {
  235. errorMessage = ConvertErrorCodeToMessage(errorCode);
  236. }
  237. ERROR_MESSAGE_TO_STRING(errCode, errorMessage, errorMessageString);
  238. ChakraRTInterface::JsCreateError(errorMessageString, &errorObject);
  239. ChakraRTInterface::JsSetException(errorObject);
  240. }
  241. }
  242. }
  243. byte * CHAKRA_CALLBACK ReallocateBufferMemory(void * state, byte *oldBuffer, size_t newSize, size_t *allocatedSize)
  244. {
  245. void* data = realloc((void*)oldBuffer, newSize);
  246. if (allocatedSize)
  247. {
  248. *allocatedSize = newSize;
  249. }
  250. return (byte*)data;
  251. }
  252. bool CHAKRA_CALLBACK WriteHostObject(void * state, JsValueRef data)
  253. {
  254. // Not implemented
  255. return true;
  256. }
  257. JsValueRef __stdcall WScriptJsrt::SerializeObject(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  258. {
  259. JsErrorCode errorCode = JsNoError;
  260. LPCWSTR errorMessage = _u("");
  261. JsValueRef returnValue = JS_INVALID_REFERENCE;
  262. HRESULT hr = S_OK;
  263. JsValueRef *transferVarsArray = nullptr;
  264. int transferVarsCount = 0;
  265. if (argumentCount < 2)
  266. {
  267. errorCode = JsErrorInvalidArgument;
  268. errorMessage = _u("Need an argument for WScript.Serialize");
  269. }
  270. else
  271. {
  272. JsValueRef rootObject = arguments[1];
  273. JsValueRef transferArray = nullptr;
  274. if (argumentCount > 2)
  275. {
  276. JsValueType argumentType = JsUndefined;
  277. transferArray = arguments[2];
  278. IfJsrtErrorSetGo(ChakraRTInterface::JsGetValueType(transferArray, &argumentType));
  279. if (argumentType != JsUndefined)
  280. {
  281. if (argumentType != JsArray)
  282. {
  283. errorCode = JsErrorInvalidArgument;
  284. goto Error;
  285. }
  286. JsPropertyIdRef lengthPropId;
  287. JsValueRef arrayLengthObj = JS_INVALID_REFERENCE;
  288. int arrayLength = 0;
  289. IfJsrtErrorSetGo(CreatePropertyIdFromString("length", &lengthPropId));
  290. IfJsrtErrorSetGo(ChakraRTInterface::JsGetProperty(transferArray, lengthPropId, &arrayLengthObj));
  291. IfJsrtErrorSetGo(ChakraRTInterface::JsNumberToInt(arrayLengthObj, &arrayLength));
  292. if (arrayLength > 0)
  293. {
  294. transferVarsArray = new JsValueRef[arrayLength];
  295. if (transferVarsArray == nullptr)
  296. {
  297. errorCode = JsErrorOutOfMemory;
  298. goto Error;
  299. }
  300. for (int i = 0; i < arrayLength; i++)
  301. {
  302. JsValueRef index;
  303. JsValueRef value = JS_INVALID_REFERENCE;
  304. JsValueType jsType = JsUndefined;
  305. IfJsrtErrorSetGo(ChakraRTInterface::JsIntToNumber(i, &index));
  306. IfJsrtErrorSetGo(ChakraRTInterface::JsGetIndexedProperty(transferArray, index, &value));
  307. IfJsrtErrorSetGo(ChakraRTInterface::JsGetValueType(value, &jsType));
  308. if (jsType == JsArrayBuffer)
  309. {
  310. *(transferVarsArray + transferVarsCount) = value;
  311. transferVarsCount++;
  312. }
  313. }
  314. }
  315. }
  316. }
  317. JsVarSerializerHandle serializerHandle = nullptr;
  318. // This memory will be claimed at WScriptJsrt::Deserialize.
  319. SerializerBlob *blob = new SerializerBlob();
  320. IfJsrtErrorSetGo(ChakraRTInterface::JsVarSerializer(ReallocateBufferMemory, WriteHostObject, nullptr, &serializerHandle));
  321. IfJsrtErrorSetGo(ChakraRTInterface::JsVarSerializerSetTransferableVars(serializerHandle, transferVarsArray, transferVarsCount));
  322. IfJsrtErrorSetGo(ChakraRTInterface::JsVarSerializerWriteValue(serializerHandle, rootObject));
  323. IfJsrtErrorSetGo(ChakraRTInterface::JsVarSerializerReleaseData(serializerHandle, (byte**)&blob->data, &blob->dataLength));
  324. for (int i = 0; i < transferVarsCount; i++)
  325. {
  326. JsValueRef arrayBuffer = transferVarsArray[i];
  327. ArrayBufferTransferInfo bufferInfo;
  328. IfJsrtErrorSetGo(ChakraRTInterface::JsGetArrayBufferStorage(arrayBuffer, &bufferInfo.buffer, &bufferInfo.length));
  329. IfJsrtErrorSetGo(ChakraRTInterface::JsExternalizeArrayBuffer(arrayBuffer));
  330. IfJsrtErrorSetGo(ChakraRTInterface::JsGetArrayBufferFreeFunction(arrayBuffer, &bufferInfo.freeFn));
  331. blob->transferableArrays.push_back(bufferInfo);
  332. IfJsrtErrorSetGo(ChakraRTInterface::JsDetachArrayBuffer(arrayBuffer));
  333. }
  334. errorCode = ChakraRTInterface::JsCreateExternalArrayBuffer((void*)blob, sizeof(SerializerBlob), nullptr, nullptr, &returnValue);
  335. IfJsrtErrorSetGo(ChakraRTInterface::JsVarSerializerFree(serializerHandle));
  336. }
  337. Error:
  338. SetExceptionIf(errorCode, errorMessage);
  339. if (transferVarsArray)
  340. {
  341. delete[] transferVarsArray;
  342. }
  343. return returnValue;
  344. }
  345. JsValueRef CHAKRA_CALLBACK ReadHostObject(void * state)
  346. {
  347. Assert(false); // TBD
  348. return nullptr;
  349. }
  350. JsValueRef CHAKRA_CALLBACK GetSharedArrayBufferFromId(void * state, uint32_t id)
  351. {
  352. Assert(false); // TBD
  353. return nullptr;
  354. }
  355. JsValueRef CHAKRA_CALLBACK GetWasmModuleFromId(void * state, uint32_t transfer_id)
  356. {
  357. Assert(false); // TBD
  358. return nullptr;
  359. }
  360. struct BufferFreeFunctionState {
  361. ArrayBufferFreeFn freeFn;
  362. void* buffer;
  363. };
  364. void CHAKRA_CALLBACK BufferFreeFunction(void * state)
  365. {
  366. BufferFreeFunctionState* bufferState = (BufferFreeFunctionState*)state;
  367. if (!bufferState)
  368. {
  369. return;
  370. }
  371. if (bufferState->freeFn)
  372. {
  373. bufferState->freeFn(bufferState->buffer);
  374. }
  375. delete bufferState;
  376. }
  377. JsValueRef __stdcall WScriptJsrt::Deserialize(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  378. {
  379. JsErrorCode errorCode = JsNoError;
  380. LPCWSTR errorMessage = _u("");
  381. JsValueRef returnValue = JS_INVALID_REFERENCE;
  382. JsValueRef * transferables = nullptr;
  383. HRESULT hr = S_OK;
  384. if (argumentCount < 2)
  385. {
  386. errorCode = JsErrorInvalidArgument;
  387. errorMessage = _u("Need an argument for WScript.Deserialize");
  388. }
  389. else
  390. {
  391. JsValueRef dataObject = arguments[1];
  392. uint32 dataLength = 0;
  393. BYTE *data = nullptr;
  394. IfJsrtErrorSetGo(ChakraRTInterface::JsGetArrayBufferStorage(dataObject, &data, &dataLength));
  395. SerializerBlob *blob = (SerializerBlob*)data;
  396. JsVarDeserializerHandle deserializerHandle = nullptr;
  397. IfJsrtErrorSetGo(ChakraRTInterface::JsVarDeserializer(blob->data, blob->dataLength, ReadHostObject, GetSharedArrayBufferFromId, nullptr, &deserializerHandle));
  398. size_t arraySize = blob->transferableArrays.size();
  399. if (arraySize > 0)
  400. {
  401. transferables = new JsValueRef[arraySize];
  402. for (size_t i = 0; i < arraySize; ++i)
  403. {
  404. JsValueRef result = nullptr;
  405. BufferFreeFunctionState* bufferFreeState = new BufferFreeFunctionState();
  406. bufferFreeState->buffer = blob->transferableArrays[i].buffer;
  407. bufferFreeState->freeFn = blob->transferableArrays[i].freeFn;
  408. IfJsrtErrorSetGo(ChakraRTInterface::JsCreateExternalArrayBuffer(blob->transferableArrays[i].buffer, blob->transferableArrays[i].length, BufferFreeFunction, bufferFreeState, &result));
  409. transferables[i] = result;
  410. }
  411. IfJsrtErrorSetGo(ChakraRTInterface::JsVarDeserializerSetTransferableVars(deserializerHandle, transferables, arraySize));
  412. }
  413. IfJsrtErrorSetGo(ChakraRTInterface::JsVarDeserializerReadValue(deserializerHandle, &returnValue));
  414. IfJsrtErrorSetGo(ChakraRTInterface::JsVarDeserializerFree(deserializerHandle));
  415. delete blob;
  416. }
  417. Error:
  418. SetExceptionIf(errorCode, errorMessage);
  419. if (transferables)
  420. {
  421. delete[] transferables;
  422. }
  423. return returnValue;
  424. }
  425. JsValueRef __stdcall WScriptJsrt::GetModuleNamespace(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  426. {
  427. JsErrorCode errorCode = JsNoError;
  428. JsValueRef returnValue = JS_INVALID_REFERENCE;
  429. LPCWSTR errorMessage = _u("");
  430. char fullPath[_MAX_PATH];
  431. if (argumentCount < 2)
  432. {
  433. errorCode = JsErrorInvalidArgument;
  434. errorMessage = _u("Need an argument for WScript.GetModuleNamespace");
  435. }
  436. else
  437. {
  438. AutoString specifierStr(arguments[1]);
  439. errorCode = specifierStr.GetError();
  440. if (errorCode == JsNoError)
  441. {
  442. if (_fullpath(fullPath, specifierStr.GetString(), _MAX_PATH) == nullptr)
  443. {
  444. errorCode = JsErrorInvalidArgument;
  445. }
  446. else
  447. {
  448. auto moduleEntry = moduleRecordMap.find(fullPath);
  449. if (moduleEntry == moduleRecordMap.end())
  450. {
  451. errorCode = JsErrorInvalidArgument;
  452. errorMessage = _u("Need to supply a path for an already loaded module for WScript.GetModuleNamespace");
  453. }
  454. else
  455. {
  456. errorCode = ChakraRTInterface::JsGetModuleNamespace(moduleEntry->second, &returnValue);
  457. if (errorCode == JsErrorModuleNotEvaluated)
  458. {
  459. errorMessage = _u("GetModuleNamespace called with un-evaluated module");
  460. }
  461. }
  462. }
  463. }
  464. }
  465. SetExceptionIf(errorCode, errorMessage);
  466. return returnValue;
  467. }
  468. JsValueRef __stdcall WScriptJsrt::LoadScriptCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  469. {
  470. return LoadScriptHelper(callee, isConstructCall, arguments, argumentCount, callbackState, false);
  471. }
  472. JsValueRef __stdcall WScriptJsrt::LoadModuleCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  473. {
  474. return LoadScriptHelper(callee, isConstructCall, arguments, argumentCount, callbackState, true);
  475. }
  476. JsValueRef WScriptJsrt::LoadScriptHelper(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState, bool isSourceModule)
  477. {
  478. HRESULT hr = E_FAIL;
  479. JsErrorCode errorCode = JsNoError;
  480. LPCWSTR errorMessage = _u("");
  481. JsValueRef returnValue = JS_INVALID_REFERENCE;
  482. if (argumentCount < 2 || argumentCount > 4)
  483. {
  484. errorCode = JsErrorInvalidArgument;
  485. errorMessage = _u("Need more or fewer arguments for WScript.LoadScript");
  486. }
  487. else
  488. {
  489. AutoString fileContent;
  490. char *fileNameNarrow = nullptr;
  491. AutoString fileName;
  492. AutoString scriptInjectType;
  493. char fileNameBuffer[MAX_PATH];
  494. bool isFile = true;
  495. IfJsrtErrorSetGo(fileContent.Initialize(arguments[1]));
  496. // ExternalArrayBuffer Finalize will clean this up
  497. // but only if we actually register a finalizecallback for this
  498. fileContent.MakePersistent();
  499. if (argumentCount > 2)
  500. {
  501. IfJsrtErrorSetGo(scriptInjectType.Initialize(arguments[2]));
  502. if (argumentCount > 3)
  503. {
  504. IfJsrtErrorSetGo(fileName.Initialize(arguments[3]));
  505. fileNameNarrow = *fileName;
  506. }
  507. }
  508. if (!fileNameNarrow)
  509. {
  510. isFile = false;
  511. if (isSourceModule)
  512. {
  513. sprintf_s(fileNameBuffer, MAX_PATH, "moduleScript%i.js", (int)sourceContext);
  514. fileNameNarrow = fileNameBuffer;
  515. }
  516. }
  517. if (*fileContent)
  518. {
  519. // TODO: This is CESU-8. How to tell the engine?
  520. // TODO: How to handle this source (script) life time?
  521. returnValue = LoadScript(callee, fileNameNarrow, *fileContent, *scriptInjectType ? *scriptInjectType : "self", isSourceModule, WScriptJsrt::FinalizeFree, isFile);
  522. }
  523. }
  524. Error:
  525. SetExceptionIf(errorCode, errorMessage);
  526. return returnValue;
  527. }
  528. void WScriptJsrt::GetDir(LPCSTR fullPathNarrow, std::string *fullDirNarrow)
  529. {
  530. char fileDrive[_MAX_DRIVE];
  531. char fileDir[_MAX_DIR];
  532. std::string result;
  533. if (_splitpath_s(fullPathNarrow, fileDrive, _countof(fileDrive), fileDir, _countof(fileDir), nullptr, 0, nullptr, 0) == 0)
  534. {
  535. result += fileDrive;
  536. result += fileDir;
  537. }
  538. *fullDirNarrow = result;
  539. }
  540. JsErrorCode WScriptJsrt::ModuleEntryPoint(LPCSTR fileName, LPCSTR fileContent, LPCSTR fullName)
  541. {
  542. return LoadModuleFromString(fileName, fileContent, fullName, true);
  543. }
  544. JsErrorCode WScriptJsrt::LoadModuleFromString(LPCSTR fileName, LPCSTR fileContent, LPCSTR fullName, bool isFile)
  545. {
  546. DWORD_PTR dwSourceCookie = WScriptJsrt::GetNextSourceContext();
  547. JsModuleRecord requestModule = JS_INVALID_REFERENCE;
  548. LPCSTR moduleRecordKey = fullName ? fullName : fileName;
  549. auto moduleRecordEntry = moduleRecordMap.find(std::string(moduleRecordKey));
  550. JsErrorCode errorCode = JsNoError;
  551. // we need to create a new moduleRecord if the specifier (fileName) is not found;
  552. // otherwise we'll use the old one.
  553. if (moduleRecordEntry == moduleRecordMap.end())
  554. {
  555. JsValueRef specifier = nullptr;
  556. if (isFile && fullName)
  557. {
  558. errorCode = ChakraRTInterface::JsCreateString(
  559. fullName, strlen(fullName), &specifier);
  560. }
  561. if (errorCode == JsNoError)
  562. {
  563. errorCode = ChakraRTInterface::JsInitializeModuleRecord(
  564. nullptr, specifier, &requestModule);
  565. }
  566. if (errorCode == JsNoError)
  567. {
  568. if (fullName)
  569. {
  570. GetDir(fullName, &moduleDirMap[requestModule]);
  571. }
  572. moduleRecordMap[std::string(moduleRecordKey)] = requestModule;
  573. moduleErrMap[requestModule] = RootModule;
  574. }
  575. }
  576. else
  577. {
  578. requestModule = moduleRecordEntry->second;
  579. }
  580. IfJsrtErrorFailLogAndRetErrorCode(errorCode);
  581. JsValueRef errorObject = JS_INVALID_REFERENCE;
  582. // ParseModuleSource is sync, while additional fetch & evaluation are async.
  583. unsigned int fileContentLength = (fileContent == nullptr) ? 0 : (unsigned int)strlen(fileContent);
  584. errorCode = ChakraRTInterface::JsParseModuleSource(requestModule, dwSourceCookie, (LPBYTE)fileContent,
  585. fileContentLength, JsParseModuleSourceFlags_DataIsUTF8, &errorObject);
  586. if ((errorCode != JsNoError) && errorObject != JS_INVALID_REFERENCE && fileContent != nullptr && !HostConfigFlags::flags.IgnoreScriptErrorCode && moduleErrMap[requestModule] == RootModule)
  587. {
  588. ChakraRTInterface::JsSetException(errorObject);
  589. moduleErrMap[requestModule] = ErroredModule;
  590. return errorCode;
  591. }
  592. return JsNoError;
  593. }
  594. JsValueRef WScriptJsrt::LoadScript(JsValueRef callee, LPCSTR fileName,
  595. LPCSTR fileContent, LPCSTR scriptInjectType, bool isSourceModule, JsFinalizeCallback finalizeCallback, bool isFile)
  596. {
  597. HRESULT hr = E_FAIL;
  598. JsErrorCode errorCode = JsNoError;
  599. LPCWSTR errorMessage = _u("Internal error.");
  600. JsValueRef returnValue = JS_INVALID_REFERENCE;
  601. JsContextRef currentContext = JS_INVALID_REFERENCE;
  602. JsRuntimeHandle runtime = JS_INVALID_RUNTIME_HANDLE;
  603. void *callbackArg = (finalizeCallback != nullptr ? (void*)fileContent : nullptr);
  604. char fullPath[_MAX_PATH];
  605. IfJsrtErrorSetGo(ChakraRTInterface::JsGetCurrentContext(&currentContext));
  606. IfJsrtErrorSetGo(ChakraRTInterface::JsGetRuntime(currentContext, &runtime));
  607. if (fileName == nullptr)
  608. {
  609. fileName = "script.js";
  610. }
  611. if (_fullpath(fullPath, fileName, _MAX_PATH) == nullptr)
  612. {
  613. goto Error;
  614. }
  615. // this is called with LoadModuleCallback method as well where caller pass in a string that should be
  616. // treated as a module source text instead of opening a new file.
  617. if (isSourceModule || (strcmp(scriptInjectType, "module") == 0))
  618. {
  619. errorCode = LoadModuleFromString(fileName, fileContent, fullPath, isFile);
  620. }
  621. else if (strcmp(scriptInjectType, "self") == 0)
  622. {
  623. JsContextRef calleeContext;
  624. IfJsrtErrorSetGo(ChakraRTInterface::JsGetContextOfObject(callee, &calleeContext));
  625. IfJsrtErrorSetGo(ChakraRTInterface::JsSetCurrentContext(calleeContext));
  626. JsValueRef scriptSource;
  627. IfJsrtErrorSetGo(ChakraRTInterface::JsCreateExternalArrayBuffer((void*)fileContent,
  628. (unsigned int)strlen(fileContent), finalizeCallback, callbackArg, &scriptSource));
  629. JsValueRef fname;
  630. IfJsrtErrorSetGo(ChakraRTInterface::JsCreateString(fullPath,
  631. strlen(fullPath), &fname));
  632. JsSourceContext sourceContext = GetNextSourceContext();
  633. RegisterScriptDir(sourceContext, fullPath);
  634. if (HostConfigFlags::flags.UseParserStateCacheIsEnabled)
  635. {
  636. JsValueRef parserState;
  637. IfJsrtErrorSetGo(ChakraRTInterface::JsSerializeParserState(scriptSource, &parserState, JsParseScriptAttributeNone));
  638. errorCode = ChakraRTInterface::JsRunScriptWithParserState(scriptSource, sourceContext, fname, JsParseScriptAttributeNone, parserState, &returnValue);
  639. }
  640. else
  641. {
  642. errorCode = ChakraRTInterface::JsRun(scriptSource, sourceContext, fname, JsParseScriptAttributeNone, &returnValue);
  643. }
  644. if(errorCode == JsNoError)
  645. {
  646. errorCode = ChakraRTInterface::JsGetGlobalObject(&returnValue);
  647. }
  648. IfJsrtErrorSetGo(ChakraRTInterface::JsSetCurrentContext(currentContext));
  649. }
  650. else if (strcmp(scriptInjectType, "samethread") == 0)
  651. {
  652. JsValueRef newContext = JS_INVALID_REFERENCE;
  653. // Create a new context and set it as the current context
  654. IfJsrtErrorSetGo(ChakraRTInterface::JsCreateContext(runtime, &newContext));
  655. #if ENABLE_TTD
  656. //We need this here since this context is created in record
  657. IfJsrtErrorSetGo(ChakraRTInterface::JsSetObjectBeforeCollectCallback(newContext, nullptr, WScriptJsrt::JsContextBeforeCollectCallback));
  658. #endif
  659. IfJsrtErrorSetGo(ChakraRTInterface::JsSetCurrentContext(newContext));
  660. IfJsErrorFailLog(ChakraRTInterface::JsSetPromiseContinuationCallback(PromiseContinuationCallback, (void*)messageQueue));
  661. // Initialize the host objects
  662. Initialize();
  663. JsValueRef scriptSource;
  664. IfJsrtErrorSetGo(ChakraRTInterface::JsCreateExternalArrayBuffer((void*)fileContent,
  665. (unsigned int)strlen(fileContent), finalizeCallback, callbackArg, &scriptSource));
  666. JsValueRef fname;
  667. IfJsrtErrorSetGo(ChakraRTInterface::JsCreateString(fullPath,
  668. strlen(fullPath), &fname));
  669. JsSourceContext sourceContext = GetNextSourceContext();
  670. RegisterScriptDir(sourceContext, fullPath);
  671. if (HostConfigFlags::flags.UseParserStateCacheIsEnabled)
  672. {
  673. JsValueRef parserState;
  674. IfJsrtErrorSetGo(ChakraRTInterface::JsSerializeParserState(scriptSource, &parserState, JsParseScriptAttributeNone));
  675. errorCode = ChakraRTInterface::JsRunScriptWithParserState(scriptSource, sourceContext, fname, JsParseScriptAttributeNone, parserState, &returnValue);
  676. }
  677. else
  678. {
  679. errorCode = ChakraRTInterface::JsRun(scriptSource, sourceContext, fname, JsParseScriptAttributeNone, &returnValue);
  680. }
  681. if (errorCode == JsNoError)
  682. {
  683. errorCode = ChakraRTInterface::JsGetGlobalObject(&returnValue);
  684. }
  685. // Set the context back to the old one
  686. ChakraRTInterface::JsSetCurrentContext(currentContext);
  687. }
  688. else if (strcmp(scriptInjectType, "crossthread") == 0)
  689. {
  690. auto& threadData = GetRuntimeThreadLocalData().threadData;
  691. if (threadData == nullptr)
  692. {
  693. threadData = new RuntimeThreadData();
  694. }
  695. RuntimeThreadData* child = new RuntimeThreadData();
  696. child->initialSource = fileContent;
  697. threadData->children.push_back(child);
  698. child->parent = threadData;
  699. // TODO: need to add a switch in case we don't need to wait for
  700. // child initial script completion
  701. ResetEvent(threadData->hevntInitialScriptCompleted);
  702. child->hThread = ::CreateThread(NULL, NULL, [](void* param) -> DWORD
  703. {
  704. return ((RuntimeThreadData*)param)->ThreadProc();
  705. }, (void*)child, NULL, NULL);
  706. WaitForSingleObject(threadData->hevntInitialScriptCompleted, INFINITE);
  707. }
  708. else
  709. {
  710. errorCode = JsErrorInvalidArgument;
  711. errorMessage = _u("Unsupported argument type inject type.");
  712. }
  713. Error:
  714. JsValueRef value = returnValue;
  715. if (errorCode != JsNoError)
  716. {
  717. SetExceptionIf(errorCode, errorMessage);
  718. ChakraRTInterface::JsDoubleToNumber(errorCode, &value);
  719. }
  720. _flushall();
  721. return value;
  722. }
  723. JsValueRef WScriptJsrt::SetTimeoutCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  724. {
  725. LPCWSTR errorMessage = _u("invalid call to WScript.SetTimeout");
  726. JsErrorCode errorCode = JsNoError;
  727. HRESULT hr = S_OK;
  728. JsValueRef function;
  729. JsValueRef timerId;
  730. unsigned int time;
  731. double tmp;
  732. CallbackMessage *msg = nullptr;
  733. if (argumentCount != 3)
  734. {
  735. errorCode = JsErrorInvalidArgument;
  736. goto Error;
  737. }
  738. function = arguments[1];
  739. IfJsrtErrorSetGo(ChakraRTInterface::JsNumberToDouble(arguments[2], &tmp));
  740. time = static_cast<int>(tmp);
  741. msg = new CallbackMessage(time, function);
  742. messageQueue->InsertSorted(msg);
  743. IfJsrtErrorSetGo(ChakraRTInterface::JsDoubleToNumber(static_cast<double>(msg->GetId()), &timerId));
  744. return timerId;
  745. Error:
  746. SetExceptionIf(errorCode, errorMessage);
  747. return JS_INVALID_REFERENCE;
  748. }
  749. JsValueRef WScriptJsrt::ClearTimeoutCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  750. {
  751. LPCWSTR errorMessage = _u("invalid call to WScript.ClearTimeout");
  752. JsErrorCode errorCode = JsNoError;
  753. HRESULT hr = S_OK;
  754. if (argumentCount != 2)
  755. {
  756. errorCode = JsErrorInvalidArgument;
  757. goto Error;
  758. }
  759. unsigned int timerId;
  760. double tmp;
  761. JsValueRef undef;
  762. if (ChakraRTInterface::JsNumberToDouble(arguments[1], &tmp) == JsNoError)
  763. {
  764. timerId = static_cast<int>(tmp);
  765. messageQueue->RemoveById(timerId);
  766. }
  767. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&undef));
  768. return undef;
  769. Error:
  770. SetExceptionIf(errorCode, errorMessage);
  771. return JS_INVALID_REFERENCE;
  772. }
  773. template <class DebugOperationFunc>
  774. void QueueDebugOperation(JsValueRef function, const DebugOperationFunc& operation)
  775. {
  776. WScriptJsrt::PushMessage(WScriptJsrt::CallbackMessage::Create(function, operation));
  777. }
  778. JsValueRef WScriptJsrt::AttachCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  779. {
  780. LPCWSTR errorMessage = _u("WScript.Attach requires a function, like WScript.Attach(foo);");
  781. JsErrorCode errorCode = JsNoError;
  782. HRESULT hr = S_OK;
  783. JsValueType argumentType = JsUndefined;
  784. if (argumentCount != 2)
  785. {
  786. errorCode = JsErrorInvalidArgument;
  787. goto Error;
  788. }
  789. IfJsrtErrorSetGo(ChakraRTInterface::JsGetValueType(arguments[1], &argumentType));
  790. if (argumentType != JsFunction)
  791. {
  792. errorCode = JsErrorInvalidArgument;
  793. goto Error;
  794. }
  795. QueueDebugOperation(arguments[1], [](WScriptJsrt::CallbackMessage& msg)
  796. {
  797. JsContextRef currentContext = JS_INVALID_REFERENCE;
  798. ChakraRTInterface::JsGetCurrentContext(&currentContext);
  799. JsRuntimeHandle currentRuntime = JS_INVALID_RUNTIME_HANDLE;
  800. ChakraRTInterface::JsGetRuntime(currentContext, &currentRuntime);
  801. Debugger* debugger = Debugger::GetDebugger(currentRuntime);
  802. debugger->StartDebugging(currentRuntime);
  803. debugger->SourceRunDown();
  804. return msg.CallFunction("");
  805. });
  806. Error:
  807. SetExceptionIf(errorCode, errorMessage);
  808. return JS_INVALID_REFERENCE;
  809. }
  810. JsValueRef WScriptJsrt::DetachCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  811. {
  812. LPCWSTR errorMessage = _u("WScript.Detach requires a function, like WScript.Detach(foo);");
  813. JsErrorCode errorCode = JsNoError;
  814. HRESULT hr = S_OK;
  815. JsValueType argumentType = JsUndefined;
  816. if (argumentCount != 2)
  817. {
  818. errorCode = JsErrorInvalidArgument;
  819. goto Error;
  820. }
  821. IfJsrtErrorSetGo(ChakraRTInterface::JsGetValueType(arguments[1], &argumentType));
  822. if (argumentType != JsFunction)
  823. {
  824. errorCode = JsErrorInvalidArgument;
  825. goto Error;
  826. }
  827. QueueDebugOperation(arguments[1], [](WScriptJsrt::CallbackMessage& msg)
  828. {
  829. JsContextRef currentContext = JS_INVALID_REFERENCE;
  830. ChakraRTInterface::JsGetCurrentContext(&currentContext);
  831. JsRuntimeHandle currentRuntime = JS_INVALID_RUNTIME_HANDLE;
  832. ChakraRTInterface::JsGetRuntime(currentContext, &currentRuntime);
  833. if (Debugger::debugger != nullptr)
  834. {
  835. Debugger* debugger = Debugger::GetDebugger(currentRuntime);
  836. debugger->StopDebugging(currentRuntime);
  837. }
  838. return msg.CallFunction("");
  839. });
  840. Error:
  841. SetExceptionIf(errorCode, errorMessage);
  842. return JS_INVALID_REFERENCE;
  843. }
  844. JsValueRef WScriptJsrt::DumpFunctionPositionCallback(JsValueRef callee, bool isConstructCall, JsValueRef * arguments, unsigned short argumentCount, void * callbackState)
  845. {
  846. JsValueRef functionPosition = JS_INVALID_REFERENCE;
  847. if (argumentCount > 1)
  848. {
  849. if (ChakraRTInterface::JsDiagGetFunctionPosition(arguments[1], &functionPosition) != JsNoError)
  850. {
  851. // If we can't get the functionPosition pass undefined
  852. IfJsErrorFailLogAndRet(ChakraRTInterface::JsGetUndefinedValue(&functionPosition));
  853. }
  854. if (Debugger::debugger != nullptr)
  855. {
  856. Debugger::debugger->DumpFunctionPosition(functionPosition);
  857. }
  858. }
  859. return JS_INVALID_REFERENCE;
  860. }
  861. JsValueRef WScriptJsrt::RequestAsyncBreakCallback(JsValueRef callee, bool isConstructCall,
  862. JsValueRef * arguments, unsigned short argumentCount, void * callbackState)
  863. {
  864. if (Debugger::debugger != nullptr && !Debugger::debugger->IsDetached())
  865. {
  866. IfJsErrorFailLogAndRet(ChakraRTInterface::JsDiagRequestAsyncBreak(Debugger::GetRuntime()));
  867. }
  868. else
  869. {
  870. Helpers::LogError(_u("RequestAsyncBreak can only be called when debugger is attached"));
  871. }
  872. return JS_INVALID_REFERENCE;
  873. }
  874. JsValueRef WScriptJsrt::EmptyCallback(JsValueRef callee, bool isConstructCall,
  875. JsValueRef * arguments, unsigned short argumentCount, void * callbackState)
  876. {
  877. return JS_INVALID_REFERENCE;
  878. }
  879. bool WScriptJsrt::CreateNamedFunction(const char* nameString, JsNativeFunction callback,
  880. JsValueRef* functionVar)
  881. {
  882. JsValueRef nameVar;
  883. IfJsrtErrorFail(ChakraRTInterface::JsCreateString(
  884. nameString, strlen(nameString), &nameVar), false);
  885. IfJsrtErrorFail(ChakraRTInterface::JsCreateNamedFunction(nameVar, callback,
  886. nullptr, functionVar), false);
  887. return true;
  888. }
  889. bool WScriptJsrt::InstallObjectsOnObject(JsValueRef object, const char* name,
  890. JsNativeFunction nativeFunction)
  891. {
  892. JsValueRef propertyValueRef;
  893. JsPropertyIdRef propertyId;
  894. IfJsrtErrorFail(CreatePropertyIdFromString(name, &propertyId), false);
  895. if (!CreateNamedFunction(name, nativeFunction, &propertyValueRef))
  896. {
  897. return false;
  898. }
  899. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(object, propertyId,
  900. propertyValueRef, true), false);
  901. return true;
  902. }
  903. bool WScriptJsrt::Initialize()
  904. {
  905. HRESULT hr = S_OK;
  906. char CH_BINARY_LOCATION[2048];
  907. #ifdef CHAKRA_STATIC_LIBRARY
  908. const char* LINK_TYPE = "static";
  909. #else
  910. const char* LINK_TYPE = "shared";
  911. #endif
  912. #ifdef HAS_ICU
  913. int icuVersion = PlatformAgnostic::ICUHelpers::GetICUMajorVersion();
  914. #else
  915. int icuVersion = -1;
  916. #endif
  917. JsValueRef wscript;
  918. IfJsrtErrorFail(ChakraRTInterface::JsCreateObject(&wscript), false);
  919. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Echo", EchoCallback));
  920. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Quit", QuitCallback));
  921. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "LoadScriptFile", LoadScriptFileCallback));
  922. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "LoadScript", LoadScriptCallback));
  923. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "LoadModule", LoadModuleCallback));
  924. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "SetTimeout", SetTimeoutCallback));
  925. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "ClearTimeout", ClearTimeoutCallback));
  926. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Attach", AttachCallback));
  927. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Detach", DetachCallback));
  928. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "DumpFunctionPosition", DumpFunctionPositionCallback));
  929. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "RequestAsyncBreak", RequestAsyncBreakCallback));
  930. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "LoadBinaryFile", LoadBinaryFileCallback));
  931. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "LoadTextFile", LoadTextFileCallback));
  932. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Flag", FlagCallback));
  933. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "RegisterModuleSource", RegisterModuleSourceCallback));
  934. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "GetModuleNamespace", GetModuleNamespace));
  935. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "GetProxyProperties", GetProxyPropertiesCallback));
  936. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "SerializeObject", SerializeObject));
  937. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Deserialize", Deserialize));
  938. // ToDo Remove
  939. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Edit", EmptyCallback));
  940. // Platform
  941. JsValueRef platformObject;
  942. IfJsrtErrorFail(ChakraRTInterface::JsCreateObject(&platformObject), false);
  943. JsPropertyIdRef platformProperty;
  944. IfJsrtErrorFail(CreatePropertyIdFromString("Platform", &platformProperty), false);
  945. // Set CPU arch
  946. JsPropertyIdRef archProperty;
  947. IfJsrtErrorFail(CreatePropertyIdFromString("ARCH", &archProperty), false);
  948. JsValueRef archValue;
  949. IfJsrtErrorFail(ChakraRTInterface::JsCreateString(
  950. CPU_ARCH_TEXT, strlen(CPU_ARCH_TEXT), &archValue), false);
  951. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(platformObject, archProperty,
  952. archValue, true), false);
  953. // Set Build Type
  954. JsPropertyIdRef buildProperty;
  955. IfJsrtErrorFail(CreatePropertyIdFromString("BUILD_TYPE", &buildProperty), false);
  956. JsValueRef buildValue;
  957. #ifdef _DEBUG
  958. #define BUILD_TYPE_STRING_CH "Debug" // (O0)
  959. #elif defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  960. #define BUILD_TYPE_STRING_CH "Test" // (O3 with debug config options)
  961. #else
  962. #define BUILD_TYPE_STRING_CH "Release" // (O3)
  963. #endif
  964. IfJsrtErrorFail(ChakraRTInterface::JsCreateString(
  965. BUILD_TYPE_STRING_CH, strlen(BUILD_TYPE_STRING_CH), &buildValue), false);
  966. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(platformObject, buildProperty,
  967. buildValue, true), false);
  968. #undef BUILD_TYPE_STRING_CH
  969. // Set Link Type [static / shared]
  970. JsPropertyIdRef linkProperty;
  971. IfJsrtErrorFail(CreatePropertyIdFromString("LINK_TYPE", &linkProperty), false);
  972. JsValueRef linkValue;
  973. IfJsrtErrorFail(ChakraRTInterface::JsCreateString(
  974. LINK_TYPE, strlen(LINK_TYPE), &linkValue), false);
  975. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(platformObject, linkProperty,
  976. linkValue, true), false);
  977. // Set Binary Location
  978. JsValueRef binaryPathValue;
  979. PlatformAgnostic::SystemInfo::GetBinaryLocation(CH_BINARY_LOCATION, sizeof(CH_BINARY_LOCATION));
  980. JsPropertyIdRef binaryPathProperty;
  981. IfJsrtErrorFail(CreatePropertyIdFromString("BINARY_PATH", &binaryPathProperty), false);
  982. IfJsrtErrorFail(ChakraRTInterface::JsCreateString(
  983. CH_BINARY_LOCATION,
  984. strlen(CH_BINARY_LOCATION), &binaryPathValue), false);
  985. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(
  986. platformObject, binaryPathProperty, binaryPathValue, true), false);
  987. // Set destination OS
  988. JsPropertyIdRef osProperty;
  989. IfJsrtErrorFail(CreatePropertyIdFromString("OS", &osProperty), false);
  990. JsValueRef osValue;
  991. IfJsrtErrorFail(ChakraRTInterface::JsCreateString(
  992. DEST_PLATFORM_TEXT, strlen(DEST_PLATFORM_TEXT), &osValue), false);
  993. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(platformObject, osProperty,
  994. osValue, true), false);
  995. // set Internationalization library
  996. JsPropertyIdRef intlLibraryProp;
  997. IfJsrtErrorFail(CreatePropertyIdFromString("INTL_LIBRARY", &intlLibraryProp), false);
  998. JsValueRef intlLibraryStr;
  999. IfJsrtErrorFail(ChakraRTInterface::JsCreateString(INTL_LIBRARY_TEXT, strlen(INTL_LIBRARY_TEXT), &intlLibraryStr), false);
  1000. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(platformObject, intlLibraryProp, intlLibraryStr, true), false);
  1001. JsPropertyIdRef icuVersionProp;
  1002. IfJsrtErrorFail(CreatePropertyIdFromString("ICU_VERSION", &icuVersionProp), false);
  1003. JsValueRef icuVersionNum;
  1004. IfJsrtErrorFail(ChakraRTInterface::JsIntToNumber(icuVersion, &icuVersionNum), false);
  1005. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(platformObject, icuVersionProp, icuVersionNum, true), false);
  1006. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(wscript, platformProperty,
  1007. platformObject, true), false);
  1008. JsValueRef argsObject;
  1009. if (!CreateArgumentsObject(&argsObject))
  1010. {
  1011. return false;
  1012. }
  1013. JsPropertyIdRef argsName;
  1014. IfJsrtErrorFail(CreatePropertyIdFromString("Arguments", &argsName), false);
  1015. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(wscript, argsName, argsObject, true), false);
  1016. JsPropertyIdRef wscriptName;
  1017. IfJsrtErrorFail(CreatePropertyIdFromString("WScript", &wscriptName), false);
  1018. JsValueRef global;
  1019. IfJsrtErrorFail(ChakraRTInterface::JsGetGlobalObject(&global), false);
  1020. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(global, wscriptName, wscript, true), false);
  1021. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(global, "print", EchoCallback));
  1022. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(global, "read", LoadTextFileCallback));
  1023. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(global, "readbuffer", LoadBinaryFileCallback));
  1024. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(global, "readline", ReadLineStdinCallback));
  1025. JsValueRef console;
  1026. IfJsrtErrorFail(ChakraRTInterface::JsCreateObject(&console), false);
  1027. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(console, "log", EchoCallback));
  1028. JsPropertyIdRef consoleName;
  1029. IfJsrtErrorFail(CreatePropertyIdFromString("console", &consoleName), false);
  1030. IfJsrtErrorFail(ChakraRTInterface::JsSetProperty(global, consoleName, console, true), false);
  1031. IfJsrtErrorFail(ChakraRTInterface::JsSetModuleHostInfo(nullptr, JsModuleHostInfo_FetchImportedModuleCallback, (void*)WScriptJsrt::FetchImportedModule), false);
  1032. IfJsrtErrorFail(ChakraRTInterface::JsSetModuleHostInfo(nullptr, JsModuleHostInfo_FetchImportedModuleFromScriptCallback, (void*)WScriptJsrt::FetchImportedModuleFromScript), false);
  1033. IfJsrtErrorFail(ChakraRTInterface::JsSetModuleHostInfo(nullptr, JsModuleHostInfo_NotifyModuleReadyCallback, (void*)WScriptJsrt::NotifyModuleReadyCallback), false);
  1034. IfJsrtErrorFail(ChakraRTInterface::JsSetModuleHostInfo(nullptr, JsModuleHostInfo_InitializeImportMetaCallback, (void*)WScriptJsrt::InitializeImportMetaCallback), false);
  1035. IfJsrtErrorFail(ChakraRTInterface::JsSetModuleHostInfo(nullptr, JsModuleHostInfo_ReportModuleCompletionCallback, (void*)WScriptJsrt::ReportModuleCompletionCallback), false);
  1036. // When the command-line argument `-Test262` is set,
  1037. // WScript will have the extra support API below and $262 will be
  1038. // added to global scope
  1039. if (HostConfigFlags::flags.Test262)
  1040. {
  1041. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Broadcast", BroadcastCallback));
  1042. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "ReceiveBroadcast", ReceiveBroadcastCallback));
  1043. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Report", ReportCallback));
  1044. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "GetReport", GetReportCallback));
  1045. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Leaving", LeavingCallback));
  1046. IfFalseGo(WScriptJsrt::InstallObjectsOnObject(wscript, "Sleep", SleepCallback));
  1047. // $262
  1048. const char Test262[] =
  1049. #include "262.js"
  1050. ;
  1051. JsValueRef Test262ScriptRef;
  1052. IfJsrtErrorFailLogAndRetFalse(ChakraRTInterface::JsCreateString(Test262, strlen(Test262), &Test262ScriptRef));
  1053. JsValueRef fname;
  1054. IfJsrtErrorFailLogAndRetFalse(ChakraRTInterface::JsCreateString("262", strlen("262"), &fname));
  1055. IfJsrtErrorFailLogAndRetFalse(ChakraRTInterface::JsRun(Test262ScriptRef, WScriptJsrt::GetNextSourceContext(), fname, JsParseScriptAttributeNone, nullptr));
  1056. }
  1057. Error:
  1058. return hr == S_OK;
  1059. }
  1060. bool WScriptJsrt::Uninitialize()
  1061. {
  1062. // moduleRecordMap is a global std::map, its destructor may access overridden
  1063. // "operator delete" / global HeapAllocator::Instance. Clear it manually here
  1064. // to avoid worrying about global destructor order.
  1065. moduleRecordMap.clear();
  1066. moduleDirMap.clear();
  1067. moduleErrMap.clear();
  1068. scriptDirMap.clear();
  1069. auto& threadData = GetRuntimeThreadLocalData().threadData;
  1070. if (threadData && !threadData->children.empty())
  1071. {
  1072. LONG count = (LONG)threadData->children.size();
  1073. std::vector<HANDLE> childrenHandles;
  1074. //Clang does not support "for each" yet
  1075. for(auto i = threadData->children.begin(); i!= threadData->children.end(); i++)
  1076. {
  1077. auto child = *i;
  1078. childrenHandles.push_back(child->hThread);
  1079. SetEvent(child->hevntShutdown);
  1080. }
  1081. DWORD waitRet = WaitForMultipleObjects(count, &childrenHandles[0], TRUE, INFINITE);
  1082. Assert(waitRet == WAIT_OBJECT_0);
  1083. for (auto i = threadData->children.begin(); i != threadData->children.end(); i++)
  1084. {
  1085. delete *i;
  1086. }
  1087. threadData->children.clear();
  1088. }
  1089. return true;
  1090. }
  1091. #if ENABLE_TTD
  1092. void CALLBACK WScriptJsrt::JsContextBeforeCollectCallback(JsRef contextRef, void *data)
  1093. {
  1094. ChakraRTInterface::JsTTDNotifyContextDestroy(contextRef);
  1095. }
  1096. #endif
  1097. FileNode * SourceMap::root = nullptr;
  1098. JsValueRef __stdcall WScriptJsrt::RegisterModuleSourceCallback(JsValueRef callee, bool isConstructCall,
  1099. JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1100. {
  1101. HRESULT hr = E_FAIL;
  1102. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1103. JsErrorCode errorCode = JsNoError;
  1104. if (argumentCount < 3)
  1105. {
  1106. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  1107. }
  1108. else
  1109. {
  1110. AutoString fileName;
  1111. AutoString data;
  1112. IfJsrtErrorSetGo(fileName.Initialize(arguments[1]));
  1113. IfJsrtErrorSetGo(data.Initialize(arguments[2]));
  1114. SourceMap::Add(fileName, data);
  1115. }
  1116. Error:
  1117. return returnValue;
  1118. }
  1119. JsValueRef __stdcall WScriptJsrt::LoadTextFileCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1120. {
  1121. HRESULT hr = E_FAIL;
  1122. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1123. JsErrorCode errorCode = JsNoError;
  1124. const char* fileContent = nullptr;
  1125. if (argumentCount < 2)
  1126. {
  1127. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  1128. }
  1129. else
  1130. {
  1131. AutoString fileName;
  1132. IfJsrtErrorSetGo(fileName.Initialize(arguments[1]));
  1133. if (errorCode == JsNoError)
  1134. {
  1135. UINT lengthBytes = 0;
  1136. hr = Helpers::LoadScriptFromFile(*fileName, fileContent, &lengthBytes);
  1137. if (FAILED(hr))
  1138. {
  1139. fprintf(stderr, "Couldn't load file '%s'\n", fileName.GetString());
  1140. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  1141. return returnValue;
  1142. }
  1143. IfJsrtErrorSetGo(ChakraRTInterface::JsCreateString(
  1144. fileContent, lengthBytes, &returnValue));
  1145. }
  1146. }
  1147. Error:
  1148. if (fileContent)
  1149. {
  1150. free((void*)fileContent);
  1151. }
  1152. return returnValue;
  1153. }
  1154. int JsFgets(char* buf, int size, FILE* file)
  1155. {
  1156. int n = size - 1;
  1157. if (n < 0)
  1158. return -1;
  1159. bool crflag = false;
  1160. int c, i = 0;
  1161. for (i = 0; i < n && (c = getc(file)) != EOF; i++) {
  1162. buf[i] = (char)c;
  1163. if (c == '\n') { // any \n ends a line
  1164. i++; // keep the \n; we know there is room for \0
  1165. break;
  1166. }
  1167. if (crflag) { // \r not followed by \n ends line at the \r
  1168. ungetc(c, file);
  1169. break; // and overwrite c in buf with \0
  1170. }
  1171. crflag = (c == '\r');
  1172. }
  1173. buf[i] = '\0';
  1174. return i;
  1175. }
  1176. JsValueRef __stdcall WScriptJsrt::ReadLineStdinCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1177. {
  1178. HRESULT hr = E_FAIL;
  1179. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1180. JsErrorCode errorCode = JsNoError;
  1181. const int BUFSIZE = 256;
  1182. FILE* from = stdin;
  1183. int buflength = 0;
  1184. int bufsize = BUFSIZE;
  1185. char* buf = static_cast<char*>(malloc(bufsize));
  1186. char* tmp;
  1187. int gotlength = 0;
  1188. if (!buf)
  1189. {
  1190. goto Error;
  1191. }
  1192. while ((gotlength = JsFgets(buf + buflength, bufsize - buflength, from)) > 0)
  1193. {
  1194. buflength += gotlength;
  1195. // are we done?
  1196. if (buf[buflength - 2] == '\r' && buf[buflength - 1] == '\n')
  1197. {
  1198. buf[buflength - 1] = '\0';
  1199. buf[buflength - 2] = '\0';
  1200. buflength -= 2;
  1201. break;
  1202. }
  1203. else if (buf[buflength - 1] == '\n')
  1204. {
  1205. buf[buflength - 1] = '\0';
  1206. buflength -= 1;
  1207. break;
  1208. }
  1209. else if (buflength < bufsize - 1)
  1210. {
  1211. break;
  1212. }
  1213. // Else, grow our buffer for another pass.
  1214. bufsize *= 2;
  1215. if (bufsize > buflength)
  1216. {
  1217. tmp = static_cast<char*>(realloc(buf, bufsize));
  1218. }
  1219. else
  1220. {
  1221. goto Error;
  1222. }
  1223. if (!tmp)
  1224. {
  1225. goto Error;
  1226. }
  1227. buf = tmp;
  1228. }
  1229. //Treat the empty string specially.
  1230. if (buflength == 0)
  1231. {
  1232. if (feof(from))
  1233. {
  1234. goto Error;
  1235. }
  1236. else
  1237. {
  1238. JsValueRef emptyStringObject;
  1239. IfJsrtErrorSetGo(ChakraRTInterface::JsCreateString(buf, buflength, &emptyStringObject));
  1240. free(buf);
  1241. return emptyStringObject;
  1242. }
  1243. }
  1244. // Turn buf into a JSString. Note that buflength includes the trailing null character.
  1245. JsValueRef stringObject;
  1246. IfJsrtErrorSetGo(ChakraRTInterface::JsCreateString(buf, buflength, &stringObject));
  1247. free(buf);
  1248. return stringObject;
  1249. Error:
  1250. if (buf)
  1251. {
  1252. free(buf);
  1253. }
  1254. return returnValue;
  1255. }
  1256. JsValueRef __stdcall WScriptJsrt::LoadBinaryFileCallback(JsValueRef callee,
  1257. bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1258. {
  1259. HRESULT hr = E_FAIL;
  1260. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1261. JsErrorCode errorCode = JsNoError;
  1262. bool isHeapAlloc = true;
  1263. if (argumentCount < 2)
  1264. {
  1265. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  1266. }
  1267. else
  1268. {
  1269. const char *fileContent;
  1270. AutoString fileName;
  1271. IfJsrtErrorSetGo(fileName.Initialize(arguments[1]));
  1272. if (errorCode == JsNoError)
  1273. {
  1274. UINT lengthBytes = 0;
  1275. hr = Helpers::LoadBinaryFile(*fileName, fileContent, lengthBytes);
  1276. if (FAILED(hr))
  1277. {
  1278. fprintf(stderr, "Couldn't load file '%s'\n", fileName.GetString());
  1279. IfJsrtErrorSetGoLabel(ChakraRTInterface::JsGetUndefinedValue(&returnValue), Error);
  1280. return returnValue;
  1281. }
  1282. JsValueRef arrayBuffer;
  1283. IfJsrtErrorSetGoLabel(ChakraRTInterface::JsCreateArrayBuffer(lengthBytes, &arrayBuffer), ErrorStillFree);
  1284. BYTE* buffer;
  1285. unsigned int bufferLength;
  1286. IfJsrtErrorSetGoLabel(ChakraRTInterface::JsGetArrayBufferStorage(arrayBuffer, &buffer, &bufferLength), ErrorStillFree);
  1287. if (bufferLength < lengthBytes)
  1288. {
  1289. fwprintf(stderr, _u("Array buffer size is insufficient to store the binary file.\n"));
  1290. }
  1291. else
  1292. {
  1293. if (memcpy_s(buffer, bufferLength, (BYTE*)fileContent, lengthBytes) == 0)
  1294. {
  1295. returnValue = arrayBuffer;
  1296. }
  1297. }
  1298. ErrorStillFree:
  1299. if (isHeapAlloc)
  1300. {
  1301. HeapFree(GetProcessHeap(), 0, (void*)fileContent);
  1302. }
  1303. }
  1304. }
  1305. Error:
  1306. return returnValue;
  1307. }
  1308. JsValueRef __stdcall WScriptJsrt::FlagCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1309. {
  1310. HRESULT hr = E_FAIL;
  1311. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1312. JsErrorCode errorCode = JsNoError;
  1313. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  1314. #if ENABLE_DEBUG_CONFIG_OPTIONS
  1315. if (argumentCount > 1)
  1316. {
  1317. AutoString cmd;
  1318. IfJsrtErrorSetGo(cmd.Initialize(arguments[1]));
  1319. char16* argv[] = { nullptr, cmd.GetWideString() };
  1320. ChakraRTInterface::SetConfigFlags(2, argv, nullptr);
  1321. }
  1322. #endif
  1323. Error:
  1324. return returnValue;
  1325. }
  1326. JsValueRef __stdcall WScriptJsrt::BroadcastCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1327. {
  1328. HRESULT hr = E_FAIL;
  1329. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1330. JsErrorCode errorCode = JsNoError;
  1331. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  1332. if (argumentCount > 1)
  1333. {
  1334. auto& threadData = GetRuntimeThreadLocalData().threadData;
  1335. if (threadData)
  1336. {
  1337. ChakraRTInterface::JsGetSharedArrayBufferContent(arguments[1], &threadData->sharedContent);
  1338. LONG count = (LONG)threadData->children.size();
  1339. threadData->hSemaphore = CreateSemaphore(NULL, 0, count, NULL);
  1340. if (threadData->hSemaphore)
  1341. {
  1342. //Clang does not support "for each" yet
  1343. for (auto i = threadData->children.begin(); i != threadData->children.end(); i++)
  1344. {
  1345. auto child = *i;
  1346. SetEvent(child->hevntReceivedBroadcast);
  1347. }
  1348. WaitForSingleObject(threadData->hSemaphore, INFINITE);
  1349. CloseHandle(threadData->hSemaphore);
  1350. threadData->hSemaphore = INVALID_HANDLE_VALUE;
  1351. }
  1352. else
  1353. {
  1354. fwprintf(stderr, _u("Couldn't create semaphore.\n"));
  1355. fflush(stderr);
  1356. }
  1357. ChakraRTInterface::JsReleaseSharedArrayBufferContentHandle(threadData->sharedContent);
  1358. }
  1359. }
  1360. Error:
  1361. return returnValue;
  1362. }
  1363. JsValueRef __stdcall WScriptJsrt::ReceiveBroadcastCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1364. {
  1365. HRESULT hr = E_FAIL;
  1366. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1367. JsErrorCode errorCode = JsNoError;
  1368. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  1369. if (argumentCount > 1)
  1370. {
  1371. auto& threadData = GetRuntimeThreadLocalData().threadData;
  1372. if (threadData)
  1373. {
  1374. if (threadData->receiveBroadcastCallbackFunc)
  1375. {
  1376. ChakraRTInterface::JsRelease(threadData->receiveBroadcastCallbackFunc, nullptr);
  1377. }
  1378. threadData->receiveBroadcastCallbackFunc = arguments[1];
  1379. ChakraRTInterface::JsAddRef(threadData->receiveBroadcastCallbackFunc, nullptr);
  1380. }
  1381. }
  1382. Error:
  1383. return returnValue;
  1384. }
  1385. JsValueRef __stdcall WScriptJsrt::ReportCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1386. {
  1387. HRESULT hr = E_FAIL;
  1388. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1389. JsErrorCode errorCode = JsNoError;
  1390. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  1391. if (argumentCount > 1)
  1392. {
  1393. JsValueRef stringRef;
  1394. ChakraRTInterface::JsConvertValueToString(arguments[1], &stringRef);
  1395. AutoString autoStr(stringRef);
  1396. if (autoStr.GetError() == JsNoError)
  1397. {
  1398. std::string str(autoStr.GetString());
  1399. auto& threadData = GetRuntimeThreadLocalData().threadData;
  1400. if (threadData && threadData->parent)
  1401. {
  1402. EnterCriticalSection(&threadData->parent->csReportQ);
  1403. threadData->parent->reportQ.push_back(str);
  1404. LeaveCriticalSection(&threadData->parent->csReportQ);
  1405. }
  1406. }
  1407. }
  1408. Error:
  1409. return returnValue;
  1410. }
  1411. JsValueRef __stdcall WScriptJsrt::GetReportCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1412. {
  1413. HRESULT hr = E_FAIL;
  1414. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1415. JsErrorCode errorCode = JsNoError;
  1416. IfJsrtErrorSetGo(ChakraRTInterface::JsGetNullValue(&returnValue));
  1417. if (argumentCount > 0)
  1418. {
  1419. auto& threadData = GetRuntimeThreadLocalData().threadData;
  1420. if (threadData)
  1421. {
  1422. EnterCriticalSection(&threadData->csReportQ);
  1423. if (threadData->reportQ.size() > 0)
  1424. {
  1425. auto str = threadData->reportQ.front();
  1426. threadData->reportQ.pop_front();
  1427. ChakraRTInterface::JsCreateString(str.c_str(), str.size(), &returnValue);
  1428. }
  1429. LeaveCriticalSection(&threadData->csReportQ);
  1430. }
  1431. }
  1432. Error:
  1433. return returnValue;
  1434. }
  1435. JsValueRef __stdcall WScriptJsrt::LeavingCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1436. {
  1437. HRESULT hr = E_FAIL;
  1438. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1439. JsErrorCode errorCode = JsNoError;
  1440. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  1441. if (argumentCount > 0)
  1442. {
  1443. auto& threadData = GetRuntimeThreadLocalData().threadData;
  1444. if (threadData)
  1445. {
  1446. threadData->leaving = true;
  1447. }
  1448. }
  1449. Error:
  1450. return returnValue;
  1451. }
  1452. JsValueRef __stdcall WScriptJsrt::SleepCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1453. {
  1454. HRESULT hr = E_FAIL;
  1455. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1456. JsErrorCode errorCode = JsNoError;
  1457. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&returnValue));
  1458. if (argumentCount > 1)
  1459. {
  1460. double timeout = 0.0;
  1461. ChakraRTInterface::JsNumberToDouble(arguments[1], &timeout);
  1462. Sleep((DWORD)timeout);
  1463. }
  1464. Error:
  1465. return returnValue;
  1466. }
  1467. JsValueRef __stdcall WScriptJsrt::GetProxyPropertiesCallback(JsValueRef callee, bool isConstructCall, JsValueRef *arguments, unsigned short argumentCount, void *callbackState)
  1468. {
  1469. HRESULT hr = E_FAIL;
  1470. JsValueRef returnValue = JS_INVALID_REFERENCE;
  1471. JsValueRef undefined = JS_INVALID_REFERENCE;
  1472. JsErrorCode errorCode = JsNoError;
  1473. IfJsrtErrorSetGo(ChakraRTInterface::JsGetUndefinedValue(&undefined));
  1474. returnValue = undefined;
  1475. if (argumentCount > 1)
  1476. {
  1477. bool isProxy = false;
  1478. JsValueRef target;
  1479. JsValueRef handler;
  1480. IfJsrtErrorSetGo(ChakraRTInterface::JsGetProxyProperties(arguments[1], &isProxy, &target, &handler));
  1481. if (isProxy)
  1482. {
  1483. JsPropertyIdRef targetProperty;
  1484. JsPropertyIdRef handlerProperty;
  1485. JsPropertyIdRef revokedProperty;
  1486. IfJsrtErrorSetGo(CreatePropertyIdFromString("target", &targetProperty));
  1487. IfJsrtErrorSetGo(CreatePropertyIdFromString("handler", &handlerProperty));
  1488. IfJsrtErrorSetGo(CreatePropertyIdFromString("revoked", &revokedProperty));
  1489. IfJsrtErrorSetGo(ChakraRTInterface::JsCreateObject(&returnValue));
  1490. JsValueRef revoked = JS_INVALID_REFERENCE;
  1491. if (target == JS_INVALID_REFERENCE)
  1492. {
  1493. IfJsrtErrorSetGo(ChakraRTInterface::JsGetTrueValue(&revoked));
  1494. target = undefined;
  1495. handler = undefined;
  1496. }
  1497. else
  1498. {
  1499. IfJsrtErrorSetGo(ChakraRTInterface::JsGetFalseValue(&revoked));
  1500. }
  1501. IfJsrtErrorSetGo(ChakraRTInterface::JsSetProperty(returnValue, handlerProperty, handler, true));
  1502. IfJsrtErrorSetGo(ChakraRTInterface::JsSetProperty(returnValue, targetProperty, target, true));
  1503. IfJsrtErrorSetGo(ChakraRTInterface::JsSetProperty(returnValue, revokedProperty, revoked, true));
  1504. }
  1505. }
  1506. Error:
  1507. return returnValue;
  1508. }
  1509. bool WScriptJsrt::PrintException(LPCSTR fileName, JsErrorCode jsErrorCode, JsValueRef exception)
  1510. {
  1511. LPCWSTR errorTypeString = ConvertErrorCodeToMessage(jsErrorCode);
  1512. JsValueRef metaData = JS_INVALID_REFERENCE;
  1513. if (exception == nullptr)
  1514. {
  1515. if (ChakraRTInterface::JsGetAndClearExceptionWithMetadata(&metaData) == JsNoError)
  1516. {
  1517. JsPropertyIdRef exceptionId = JS_INVALID_REFERENCE;
  1518. IfJsrtErrorFail(CreatePropertyIdFromString("exception", &exceptionId), false);
  1519. IfJsrtErrorFail(ChakraRTInterface::JsGetProperty(metaData, exceptionId, &exception), false);
  1520. }
  1521. else
  1522. {
  1523. IfJsrtErrorFail(ChakraRTInterface::JsGetAndClearException(&exception), false);
  1524. }
  1525. }
  1526. if (HostConfigFlags::flags.MuteHostErrorMsgIsEnabled)
  1527. {
  1528. return false;
  1529. }
  1530. if (exception != nullptr)
  1531. {
  1532. if (jsErrorCode == JsErrorCode::JsErrorScriptCompile || jsErrorCode == JsErrorCode::JsErrorScriptException)
  1533. {
  1534. AutoString errorMessage;
  1535. if (errorMessage.Initialize(exception) != JsNoError)
  1536. {
  1537. fwprintf(stderr, _u("ERROR attempting to coerce error to string, using alternate handler\n"));
  1538. bool hasException = false;
  1539. ChakraRTInterface::JsHasException(&hasException);
  1540. if (hasException)
  1541. {
  1542. JsValueRef throwAway = JS_INVALID_REFERENCE;
  1543. ChakraRTInterface::JsGetAndClearException(&throwAway);
  1544. }
  1545. JsPropertyIdRef messagePropertyId = JS_INVALID_REFERENCE;
  1546. IfJsrtErrorFail(CreatePropertyIdFromString("message", &messagePropertyId), false);
  1547. JsValueRef message = JS_INVALID_REFERENCE;
  1548. IfJsrtErrorFail(ChakraRTInterface::JsGetProperty(exception, messagePropertyId, &message), false);
  1549. IfJsrtErrorFail(errorMessage.Initialize(message), false);
  1550. if (jsErrorCode != JsErrorCode::JsErrorScriptCompile)
  1551. {
  1552. CHAR shortFileName[_MAX_PATH];
  1553. CHAR ext[_MAX_EXT];
  1554. _splitpath_s(fileName, nullptr, 0, nullptr, 0, shortFileName, _countof(shortFileName), ext, _countof(ext));
  1555. if (metaData != JS_INVALID_REFERENCE)
  1556. {
  1557. JsPropertyIdRef linePropertyId = JS_INVALID_REFERENCE;
  1558. JsValueRef lineProperty = JS_INVALID_REFERENCE;
  1559. JsPropertyIdRef columnPropertyId = JS_INVALID_REFERENCE;
  1560. JsValueRef columnProperty = JS_INVALID_REFERENCE;
  1561. int line;
  1562. int column;
  1563. IfJsrtErrorFail(CreatePropertyIdFromString("line", &linePropertyId), false);
  1564. IfJsrtErrorFail(ChakraRTInterface::JsGetProperty(metaData, linePropertyId, &lineProperty), false);
  1565. IfJsrtErrorFail(ChakraRTInterface::JsNumberToInt(lineProperty, &line), false);
  1566. IfJsrtErrorFail(CreatePropertyIdFromString("column", &columnPropertyId), false);
  1567. IfJsrtErrorFail(ChakraRTInterface::JsGetProperty(metaData, columnPropertyId, &columnProperty), false);
  1568. IfJsrtErrorFail(ChakraRTInterface::JsNumberToInt(columnProperty, &column), false);
  1569. fwprintf(stderr, _u("%ls\n at code (%S%S:%d:%d)\n"),
  1570. errorMessage.GetWideString(), shortFileName, ext, line + 1, column + 1);
  1571. }
  1572. else
  1573. {
  1574. fwprintf(stderr, _u("%ls\n\tat code (%S%S:\?\?:\?\?)\n"), errorMessage.GetWideString(), shortFileName, ext);
  1575. }
  1576. return true;
  1577. }
  1578. }
  1579. if (jsErrorCode == JsErrorCode::JsErrorScriptCompile)
  1580. {
  1581. JsPropertyIdRef linePropertyId = JS_INVALID_REFERENCE;
  1582. JsValueRef lineProperty = JS_INVALID_REFERENCE;
  1583. JsPropertyIdRef columnPropertyId = JS_INVALID_REFERENCE;
  1584. JsValueRef columnProperty = JS_INVALID_REFERENCE;
  1585. int line;
  1586. int column;
  1587. IfJsrtErrorFail(CreatePropertyIdFromString("line", &linePropertyId), false);
  1588. IfJsrtErrorFail(ChakraRTInterface::JsGetProperty(exception, linePropertyId, &lineProperty), false);
  1589. IfJsrtErrorFail(ChakraRTInterface::JsNumberToInt(lineProperty, &line), false);
  1590. IfJsrtErrorFail(CreatePropertyIdFromString("column", &columnPropertyId), false);
  1591. IfJsrtErrorFail(ChakraRTInterface::JsGetProperty(exception, columnPropertyId, &columnProperty), false);
  1592. IfJsrtErrorFail(ChakraRTInterface::JsNumberToInt(columnProperty, &column), false);
  1593. CHAR shortFileName[_MAX_PATH];
  1594. CHAR ext[_MAX_EXT];
  1595. _splitpath_s(fileName, nullptr, 0, nullptr, 0, shortFileName, _countof(shortFileName), ext, _countof(ext));
  1596. fwprintf(stderr, _u("%ls\n\tat code (%S%S:%d:%d)\n"),
  1597. errorMessage.GetWideString(), shortFileName, ext, (int)line + 1,
  1598. (int)column + 1);
  1599. }
  1600. else
  1601. {
  1602. JsValueType propertyType = JsUndefined;
  1603. JsPropertyIdRef stackPropertyId = JS_INVALID_REFERENCE;
  1604. JsValueRef stackProperty = JS_INVALID_REFERENCE;
  1605. AutoString errorStack;
  1606. JsErrorCode errorCode = CreatePropertyIdFromString("stack", &stackPropertyId);
  1607. if (errorCode == JsErrorCode::JsNoError)
  1608. {
  1609. errorCode = ChakraRTInterface::JsGetProperty(exception, stackPropertyId, &stackProperty);
  1610. if (errorCode == JsErrorCode::JsNoError)
  1611. {
  1612. errorCode = ChakraRTInterface::JsGetValueType(stackProperty, &propertyType);
  1613. }
  1614. }
  1615. if (errorCode != JsErrorCode::JsNoError || propertyType == JsUndefined)
  1616. {
  1617. const char *fName = fileName != nullptr ? fileName : "(unknown)";
  1618. CHAR shortFileName[_MAX_PATH];
  1619. CHAR ext[_MAX_EXT];
  1620. _splitpath_s(fName, nullptr, 0, nullptr, 0, shortFileName, _countof(shortFileName), ext, _countof(ext));
  1621. // do not mix char/wchar. print them separately
  1622. fprintf(stderr, "thrown at %s%s:\n^\n", shortFileName, ext);
  1623. fwprintf(stderr, _u("%ls\n"), errorMessage.GetWideString());
  1624. }
  1625. else
  1626. {
  1627. IfJsrtErrorFail(errorStack.Initialize(stackProperty), false);
  1628. fwprintf(stderr, _u("%ls\n"), errorStack.GetWideString());
  1629. }
  1630. }
  1631. }
  1632. else
  1633. {
  1634. fwprintf(stderr, _u("Error : %ls\n"), errorTypeString);
  1635. }
  1636. return true;
  1637. }
  1638. else
  1639. {
  1640. fwprintf(stderr, _u("Error : %ls\n"), errorTypeString);
  1641. }
  1642. return false;
  1643. }
  1644. void WScriptJsrt::AddMessageQueue(MessageQueue *_messageQueue)
  1645. {
  1646. Assert(messageQueue == nullptr);
  1647. messageQueue = _messageQueue;
  1648. }
  1649. WScriptJsrt::CallbackMessage::CallbackMessage(unsigned int time, JsValueRef function) : MessageBase(time), m_function(function)
  1650. {
  1651. JsErrorCode error = ChakraRTInterface::JsAddRef(m_function, nullptr);
  1652. if (error != JsNoError)
  1653. {
  1654. // Simply report a fatal error and exit because continuing from this point would result in inconsistent state
  1655. // and FailFast telemetry would not be useful.
  1656. wprintf(_u("FATAL ERROR: ChakraRTInterface::JsAddRef failed in WScriptJsrt::CallbackMessage::`ctor`. error=0x%x\n"), error);
  1657. exit(1);
  1658. }
  1659. }
  1660. WScriptJsrt::CallbackMessage::~CallbackMessage()
  1661. {
  1662. bool hasException = false;
  1663. ChakraRTInterface::JsHasException(&hasException);
  1664. if (hasException)
  1665. {
  1666. WScriptJsrt::PrintException("", JsErrorScriptException);
  1667. }
  1668. JsErrorCode errorCode = ChakraRTInterface::JsRelease(m_function, nullptr);
  1669. Assert(errorCode == JsNoError);
  1670. m_function = JS_INVALID_REFERENCE;
  1671. }
  1672. HRESULT WScriptJsrt::CallbackMessage::Call(LPCSTR fileName)
  1673. {
  1674. return CallFunction(fileName);
  1675. }
  1676. HRESULT WScriptJsrt::CallbackMessage::CallFunction(LPCSTR fileName)
  1677. {
  1678. HRESULT hr = S_OK;
  1679. JsValueRef global;
  1680. JsValueRef result;
  1681. JsValueRef stringValue;
  1682. JsValueType type;
  1683. JsErrorCode errorCode = JsNoError;
  1684. IfJsrtErrorHR(ChakraRTInterface::JsGetGlobalObject(&global));
  1685. IfJsrtErrorHR(ChakraRTInterface::JsGetValueType(m_function, &type));
  1686. if (type == JsString)
  1687. {
  1688. IfJsrtErrorHR(ChakraRTInterface::JsConvertValueToString(m_function, &stringValue));
  1689. JsValueRef fname;
  1690. ChakraRTInterface::JsCreateString("", strlen(""), &fname);
  1691. // Run the code
  1692. errorCode = ChakraRTInterface::JsRun(stringValue, JS_SOURCE_CONTEXT_NONE,
  1693. fname, JsParseScriptAttributeArrayBufferIsUtf16Encoded,
  1694. nullptr /*no result needed*/);
  1695. }
  1696. else
  1697. {
  1698. errorCode = ChakraRTInterface::JsCallFunction(m_function, &global, 1, &result);
  1699. }
  1700. if (errorCode != JsNoError)
  1701. {
  1702. hr = E_FAIL;
  1703. PrintException(fileName, errorCode);
  1704. }
  1705. Error:
  1706. return hr;
  1707. }
  1708. WScriptJsrt::ModuleMessage::ModuleMessage(JsModuleRecord module, JsValueRef specifier, std::string* fullPathPtr)
  1709. : MessageBase(0), moduleRecord(module), specifier(specifier)
  1710. {
  1711. fullPath = nullptr;
  1712. ChakraRTInterface::JsAddRef(module, nullptr);
  1713. if (specifier != nullptr)
  1714. {
  1715. fullPath = new std::string (*fullPathPtr);
  1716. // nullptr specifier means a Promise to execute; non-nullptr means a "fetch" operation.
  1717. ChakraRTInterface::JsAddRef(specifier, nullptr);
  1718. }
  1719. }
  1720. WScriptJsrt::ModuleMessage::~ModuleMessage()
  1721. {
  1722. ChakraRTInterface::JsRelease(moduleRecord, nullptr);
  1723. if (specifier != nullptr)
  1724. {
  1725. delete fullPath;
  1726. ChakraRTInterface::JsRelease(specifier, nullptr);
  1727. }
  1728. }
  1729. HRESULT WScriptJsrt::ModuleMessage::Call(LPCSTR fileName)
  1730. {
  1731. JsErrorCode errorCode = JsNoError;
  1732. JsValueRef result = JS_INVALID_REFERENCE;
  1733. HRESULT hr;
  1734. if (specifier == nullptr)
  1735. {
  1736. if (moduleErrMap[moduleRecord] != ErroredModule)
  1737. {
  1738. errorCode = ChakraRTInterface::JsModuleEvaluation(moduleRecord, &result);
  1739. if (errorCode != JsNoError)
  1740. {
  1741. PrintException(fileName, errorCode); // this should not be called
  1742. }
  1743. }
  1744. }
  1745. else
  1746. {
  1747. LPCSTR fileContent = nullptr;
  1748. AutoString specifierStr(specifier);
  1749. errorCode = specifierStr.GetError();
  1750. if (errorCode == JsNoError)
  1751. {
  1752. hr = Helpers::LoadScriptFromFile(*specifierStr, fileContent, nullptr, fullPath, true);
  1753. if (FAILED(hr))
  1754. {
  1755. if (!HostConfigFlags::flags.MuteHostErrorMsgIsEnabled)
  1756. {
  1757. auto actualModuleRecord = moduleRecordMap.find(*fullPath);
  1758. if (actualModuleRecord == moduleRecordMap.end() || moduleErrMap[actualModuleRecord->second] == RootModule)
  1759. {
  1760. fprintf(stderr, "Couldn't load file '%s'\n", specifierStr.GetString());
  1761. }
  1762. }
  1763. LoadScript(nullptr, fullPath == nullptr ? *specifierStr : fullPath->c_str(), nullptr, "module", true, WScriptJsrt::FinalizeFree, false);
  1764. goto Error;
  1765. }
  1766. LoadScript(nullptr, fullPath == nullptr ? *specifierStr : fullPath->c_str(), fileContent, "module", true, WScriptJsrt::FinalizeFree, true);
  1767. }
  1768. }
  1769. Error:
  1770. return errorCode;
  1771. }
  1772. JsErrorCode WScriptJsrt::ReportModuleCompletionCallback(JsModuleRecord module, JsValueRef exception)
  1773. {
  1774. if (exception != nullptr)
  1775. {
  1776. JsValueRef specifier = JS_INVALID_REFERENCE;
  1777. ChakraRTInterface::JsGetModuleHostInfo(module, JsModuleHostInfo_Url, &specifier);
  1778. PrintException(AutoString(specifier).GetString(), JsErrorCode::JsErrorScriptException, exception);
  1779. }
  1780. return JsNoError;
  1781. }
  1782. JsErrorCode WScriptJsrt::FetchImportedModuleHelper(JsModuleRecord referencingModule,
  1783. JsValueRef specifier, __out JsModuleRecord* dependentModuleRecord, LPCSTR refdir)
  1784. {
  1785. JsModuleRecord moduleRecord = JS_INVALID_REFERENCE;
  1786. AutoString specifierStr;
  1787. *dependentModuleRecord = nullptr;
  1788. if (specifierStr.Initialize(specifier) != JsNoError)
  1789. {
  1790. return specifierStr.GetError();
  1791. }
  1792. char fullPath[_MAX_PATH];
  1793. std::string specifierFullPath = refdir ? refdir : "";
  1794. specifierFullPath += *specifierStr;
  1795. if (_fullpath(fullPath, specifierFullPath.c_str(), _MAX_PATH) == nullptr)
  1796. {
  1797. return JsErrorInvalidArgument;
  1798. }
  1799. auto moduleEntry = moduleRecordMap.find(std::string(fullPath));
  1800. if (moduleEntry != moduleRecordMap.end())
  1801. {
  1802. *dependentModuleRecord = moduleEntry->second;
  1803. return JsNoError;
  1804. }
  1805. JsErrorCode errorCode = ChakraRTInterface::JsInitializeModuleRecord(referencingModule, specifier, &moduleRecord);
  1806. if (errorCode == JsNoError)
  1807. {
  1808. GetDir(fullPath, &moduleDirMap[moduleRecord]);
  1809. std::string pathKey = std::string(fullPath);
  1810. moduleRecordMap[pathKey] = moduleRecord;
  1811. moduleErrMap[moduleRecord] = ImportedModule;
  1812. ModuleMessage* moduleMessage = WScriptJsrt::ModuleMessage::Create(referencingModule, specifier, &pathKey);
  1813. if (moduleMessage == nullptr)
  1814. {
  1815. return JsErrorOutOfMemory;
  1816. }
  1817. WScriptJsrt::PushMessage(moduleMessage);
  1818. *dependentModuleRecord = moduleRecord;
  1819. }
  1820. return errorCode;
  1821. }
  1822. // Callback from chakracore to fetch dependent module. In the test harness,
  1823. // we are not doing any translation, just treat the specifier as fileName.
  1824. // While this call will come back directly from ParseModuleSource, the additional
  1825. // task are treated as Promise that will be executed later.
  1826. JsErrorCode WScriptJsrt::FetchImportedModule(_In_ JsModuleRecord referencingModule,
  1827. _In_ JsValueRef specifier, _Outptr_result_maybenull_ JsModuleRecord* dependentModuleRecord)
  1828. {
  1829. auto moduleDirEntry = moduleDirMap.find(referencingModule);
  1830. if (moduleDirEntry != moduleDirMap.end())
  1831. {
  1832. std::string dir = moduleDirEntry->second;
  1833. return FetchImportedModuleHelper(referencingModule, specifier, dependentModuleRecord, dir.c_str());
  1834. }
  1835. return FetchImportedModuleHelper(referencingModule, specifier, dependentModuleRecord);
  1836. }
  1837. // Callback from chakracore to fetch module dynamically during runtime. In the test harness,
  1838. // we are not doing any translation, just treat the specifier as fileName.
  1839. // While this call will come back directly from runtime script or module code, the additional
  1840. // task can be scheduled asynchronously that executed later.
  1841. JsErrorCode WScriptJsrt::FetchImportedModuleFromScript(_In_ JsSourceContext dwReferencingSourceContext,
  1842. _In_ JsValueRef specifier, _Outptr_result_maybenull_ JsModuleRecord* dependentModuleRecord)
  1843. {
  1844. return FetchImportedModuleHelper(nullptr, specifier, dependentModuleRecord);
  1845. }
  1846. // Callback from chakraCore when the module resolution is finished, either successfully or unsuccessfully.
  1847. JsErrorCode WScriptJsrt::NotifyModuleReadyCallback(_In_opt_ JsModuleRecord referencingModule, _In_opt_ JsValueRef exceptionVar)
  1848. {
  1849. if (exceptionVar != nullptr && HostConfigFlags::flags.TraceHostCallbackIsEnabled)
  1850. {
  1851. JsValueRef specifier = JS_INVALID_REFERENCE;
  1852. ChakraRTInterface::JsGetModuleHostInfo(referencingModule, JsModuleHostInfo_Url, &specifier);
  1853. AutoString fileName;
  1854. if (specifier != JS_INVALID_REFERENCE)
  1855. {
  1856. fileName.Initialize(specifier);
  1857. }
  1858. wprintf(_u("NotifyModuleReadyCallback(exception) %S\n"), fileName.GetString());
  1859. }
  1860. if (moduleErrMap[referencingModule] != ErroredModule)
  1861. {
  1862. WScriptJsrt::ModuleMessage* moduleMessage =
  1863. WScriptJsrt::ModuleMessage::Create(referencingModule, nullptr);
  1864. if (moduleMessage == nullptr)
  1865. {
  1866. return JsErrorOutOfMemory;
  1867. }
  1868. WScriptJsrt::PushMessage(moduleMessage);
  1869. }
  1870. return JsNoError;
  1871. }
  1872. JsErrorCode __stdcall WScriptJsrt::InitializeImportMetaCallback(_In_opt_ JsModuleRecord referencingModule, _In_opt_ JsValueRef importMetaVar)
  1873. {
  1874. if (importMetaVar != nullptr)
  1875. {
  1876. JsValueRef specifier = JS_INVALID_REFERENCE;
  1877. ChakraRTInterface::JsGetModuleHostInfo(referencingModule, JsModuleHostInfo_Url, &specifier);
  1878. JsPropertyIdRef urlPropId;
  1879. if (JsNoError == CreatePropertyIdFromString("url", &urlPropId))
  1880. {
  1881. ChakraRTInterface::JsSetProperty(importMetaVar, urlPropId, specifier, false);
  1882. }
  1883. }
  1884. return JsNoError;
  1885. }
  1886. void WScriptJsrt::PromiseContinuationCallback(JsValueRef task, void *callbackState)
  1887. {
  1888. Assert(task != JS_INVALID_REFERENCE);
  1889. Assert(callbackState != JS_INVALID_REFERENCE);
  1890. MessageQueue * messageQueue = (MessageQueue *)callbackState;
  1891. WScriptJsrt::CallbackMessage *msg = new WScriptJsrt::CallbackMessage(0, task);
  1892. messageQueue->InsertSorted(msg);
  1893. }
  1894. void WScriptJsrt::PromiseRejectionTrackerCallback(JsValueRef promise, JsValueRef reason, bool handled, void *callbackState)
  1895. {
  1896. Assert(promise != JS_INVALID_REFERENCE);
  1897. Assert(reason != JS_INVALID_REFERENCE);
  1898. if (!handled)
  1899. {
  1900. wprintf(_u("Uncaught promise rejection\n"));
  1901. }
  1902. else
  1903. {
  1904. wprintf(_u("Promise rejection handled\n"));
  1905. }
  1906. JsPropertyIdRef stackPropertyID;
  1907. JsErrorCode error = ChakraRTInterface::JsCreatePropertyId("stack", strlen("stack"), &stackPropertyID);
  1908. if (error == JsNoError)
  1909. {
  1910. JsValueRef stack;
  1911. error = ChakraRTInterface::JsGetProperty(reason, stackPropertyID, &stack);
  1912. if (error == JsNoError)
  1913. {
  1914. JsValueRef stackStrValue;
  1915. error = ChakraRTInterface::JsConvertValueToString(stack, &stackStrValue);
  1916. if (error == JsNoError)
  1917. {
  1918. AutoString str(stackStrValue);
  1919. wprintf(_u("%ls\n"), str.GetWideString());
  1920. }
  1921. }
  1922. }
  1923. if (error != JsNoError)
  1924. {
  1925. // weren't able to print stack, so just convert reason to a string
  1926. JsValueRef strValue;
  1927. error = ChakraRTInterface::JsConvertValueToString(reason, &strValue);
  1928. if (error == JsNoError)
  1929. {
  1930. AutoString str(strValue);
  1931. wprintf(_u("%ls\n"), str.GetWideString());
  1932. }
  1933. }
  1934. fflush(stdout);
  1935. }