WScriptJsrt.cpp 81 KB

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