WebAssemblyModule.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "RuntimeLibraryPch.h"
  6. #ifdef ENABLE_WASM
  7. #include "../WasmReader/WasmReaderPch.h"
  8. namespace Js
  9. {
  10. WebAssemblyModule::WebAssemblyModule(Js::ScriptContext* scriptContext, const byte* binaryBuffer, uint binaryBufferLength, DynamicType * type) :
  11. DynamicObject(type),
  12. m_hasMemory(false),
  13. m_hasTable(false),
  14. m_memImport(nullptr),
  15. m_tableImport(nullptr),
  16. m_importedFunctionCount(0),
  17. m_memoryInitSize(0),
  18. m_memoryMaxSize(0),
  19. m_tableInitSize(0),
  20. m_tableMaxSize(0),
  21. m_alloc(_u("WebAssemblyModule"), scriptContext->GetThreadContext()->GetPageAllocator(), Js::Throw::OutOfMemory),
  22. m_indirectfuncs(nullptr),
  23. m_exports(nullptr),
  24. m_exportCount(0),
  25. m_datasegCount(0),
  26. m_elementsegCount(0),
  27. m_elementsegs(nullptr),
  28. m_signatures(nullptr),
  29. m_signaturesCount(0),
  30. m_startFuncIndex(Js::Constants::UninitializedValue),
  31. m_binaryBuffer(binaryBuffer)
  32. {
  33. //the first elm is the number of Vars in front of I32; makes for a nicer offset computation
  34. memset(m_globalCounts, 0, sizeof(uint) * Wasm::WasmTypes::Limit);
  35. m_functionsInfo = RecyclerNew(scriptContext->GetRecycler(), WasmFunctionInfosList, scriptContext->GetRecycler());
  36. m_imports = Anew(&m_alloc, WasmImportsList, &m_alloc);
  37. m_globals = Anew(&m_alloc, WasmGlobalsList, &m_alloc);
  38. m_reader = Anew(&m_alloc, Wasm::WasmBinaryReader, &m_alloc, this, binaryBuffer, binaryBufferLength);
  39. }
  40. /* static */
  41. bool
  42. WebAssemblyModule::Is(Var value)
  43. {
  44. return JavascriptOperators::GetTypeId(value) == TypeIds_WebAssemblyModule;
  45. }
  46. /* static */
  47. WebAssemblyModule *
  48. WebAssemblyModule::FromVar(Var value)
  49. {
  50. Assert(WebAssemblyModule::Is(value));
  51. return static_cast<WebAssemblyModule*>(value);
  52. }
  53. /* static */
  54. Var
  55. WebAssemblyModule::NewInstance(RecyclableObject* function, CallInfo callInfo, ...)
  56. {
  57. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  58. ARGUMENTS(args, callInfo);
  59. ScriptContext* scriptContext = function->GetScriptContext();
  60. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  61. Var newTarget = callInfo.Flags & CallFlags_NewTarget ? args.Values[args.Info.Count] : args[0];
  62. bool isCtorSuperCall = (callInfo.Flags & CallFlags_New) && newTarget != nullptr && !JavascriptOperators::IsUndefined(newTarget);
  63. Assert(isCtorSuperCall || !(callInfo.Flags & CallFlags_New) || args[0] == nullptr);
  64. if (!(callInfo.Flags & CallFlags_New) || (newTarget && JavascriptOperators::IsUndefinedObject(newTarget)))
  65. {
  66. JavascriptError::ThrowTypeError(scriptContext, JSERR_ClassConstructorCannotBeCalledWithoutNew, _u("WebAssembly.Module"));
  67. }
  68. if (args.Info.Count < 2)
  69. {
  70. JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedBufferSource);
  71. }
  72. BYTE* buffer;
  73. uint byteLength;
  74. WebAssembly::ReadBufferSource(args[1], scriptContext, &buffer, &byteLength);
  75. return CreateModule(scriptContext, buffer, byteLength);
  76. }
  77. Var
  78. WebAssemblyModule::EntryExports(RecyclableObject* function, CallInfo callInfo, ...)
  79. {
  80. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  81. ARGUMENTS(args, callInfo);
  82. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  83. ScriptContext* scriptContext = function->GetScriptContext();
  84. Assert(!(callInfo.Flags & CallFlags_New));
  85. if (args.Info.Count < 2 || !WebAssemblyModule::Is(args[1]))
  86. {
  87. JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedModule);
  88. }
  89. WebAssemblyModule * module = WebAssemblyModule::FromVar(args[1]);
  90. Var exportArray = JavascriptOperators::NewJavascriptArrayNoArg(scriptContext);
  91. for (uint i = 0; i < module->GetExportCount(); ++i)
  92. {
  93. Wasm::WasmExport wasmExport = module->m_exports[i];
  94. Js::JavascriptString * kind = GetExternalKindString(scriptContext, wasmExport.kind);
  95. Js::JavascriptString * name = JavascriptString::NewCopySz(wasmExport.name, scriptContext);
  96. Var pair = JavascriptOperators::NewJavascriptObjectNoArg(scriptContext);
  97. JavascriptOperators::OP_SetProperty(pair, PropertyIds::kind, kind, scriptContext);
  98. JavascriptOperators::OP_SetProperty(pair, PropertyIds::name, name, scriptContext);
  99. JavascriptArray::Push(scriptContext, exportArray, pair);
  100. }
  101. return exportArray;
  102. }
  103. Var
  104. WebAssemblyModule::EntryImports(RecyclableObject* function, CallInfo callInfo, ...)
  105. {
  106. PROBE_STACK(function->GetScriptContext(), Js::Constants::MinStackDefault);
  107. ARGUMENTS(args, callInfo);
  108. AssertMsg(args.Info.Count > 0, "Should always have implicit 'this'");
  109. ScriptContext* scriptContext = function->GetScriptContext();
  110. Assert(!(callInfo.Flags & CallFlags_New));
  111. if (args.Info.Count < 2 || !WebAssemblyModule::Is(args[1]))
  112. {
  113. JavascriptError::ThrowTypeError(scriptContext, WASMERR_NeedModule);
  114. }
  115. WebAssemblyModule * module = WebAssemblyModule::FromVar(args[1]);
  116. Var importArray = JavascriptOperators::NewJavascriptArrayNoArg(scriptContext);
  117. for (uint32 i = 0; i < module->GetImportCount(); ++i)
  118. {
  119. Wasm::WasmImport * import = module->GetImport(i);
  120. Js::JavascriptString * kind = GetExternalKindString(scriptContext, import->kind);
  121. Js::JavascriptString * moduleName = JavascriptString::NewCopySz(import->modName, scriptContext);
  122. Js::JavascriptString * name = JavascriptString::NewCopySz(import->importName, scriptContext);
  123. Var pair = JavascriptOperators::NewJavascriptObjectNoArg(scriptContext);
  124. JavascriptOperators::OP_SetProperty(pair, PropertyIds::kind, kind, scriptContext);
  125. JavascriptOperators::OP_SetProperty(pair, PropertyIds::module, moduleName, scriptContext);
  126. JavascriptOperators::OP_SetProperty(pair, PropertyIds::name, name, scriptContext);
  127. JavascriptArray::Push(scriptContext, importArray, pair);
  128. }
  129. return importArray;
  130. }
  131. /* static */
  132. WebAssemblyModule *
  133. WebAssemblyModule::CreateModule(
  134. ScriptContext* scriptContext,
  135. const byte* buffer,
  136. const uint lengthBytes)
  137. {
  138. AutoProfilingPhase wasmPhase(scriptContext, Js::WasmBytecodePhase);
  139. Unused(wasmPhase);
  140. WebAssemblyModule * webAssemblyModule = nullptr;
  141. Wasm::WasmReaderInfo * readerInfo = nullptr;
  142. Js::FunctionBody * currentBody = nullptr;
  143. try
  144. {
  145. Js::AutoDynamicCodeReference dynamicFunctionReference(scriptContext);
  146. SRCINFO const * srcInfo = scriptContext->cache->noContextGlobalSourceInfo;
  147. Js::Utf8SourceInfo* utf8SourceInfo = Utf8SourceInfo::New(scriptContext, (LPCUTF8)buffer, lengthBytes / sizeof(char16), lengthBytes, srcInfo, false);
  148. // copy buffer so external changes to it don't cause issues when defer parsing
  149. byte* newBuffer = RecyclerNewArray(scriptContext->GetRecycler(), byte, lengthBytes);
  150. js_memcpy_s(newBuffer, lengthBytes, buffer, lengthBytes);
  151. Wasm::WasmModuleGenerator bytecodeGen(scriptContext, utf8SourceInfo, newBuffer, lengthBytes);
  152. webAssemblyModule = bytecodeGen.GenerateModule();
  153. for (uint i = 0; i < webAssemblyModule->GetWasmFunctionCount(); ++i)
  154. {
  155. currentBody = webAssemblyModule->GetWasmFunctionInfo(i)->GetBody();
  156. if (!PHASE_OFF(WasmDeferredPhase, currentBody))
  157. {
  158. continue;
  159. }
  160. readerInfo = currentBody->GetAsmJsFunctionInfo()->GetWasmReaderInfo();
  161. Wasm::WasmBytecodeGenerator::GenerateFunctionBytecode(scriptContext, readerInfo);
  162. }
  163. }
  164. catch (Wasm::WasmCompilationException& ex)
  165. {
  166. Wasm::WasmCompilationException newEx = ex;
  167. if (currentBody != nullptr)
  168. {
  169. char16* originalMessage = ex.ReleaseErrorMessage();
  170. intptr_t offset = readerInfo->m_module->GetReader()->GetCurrentOffset();
  171. intptr_t start = readerInfo->m_funcInfo->m_readerInfo.startOffset;
  172. uint32 size = readerInfo->m_funcInfo->m_readerInfo.size;
  173. newEx = Wasm::WasmCompilationException(
  174. _u("function %s at offset %d/%d: %s"),
  175. currentBody->GetDisplayName(),
  176. offset - start,
  177. size,
  178. originalMessage
  179. );
  180. currentBody->GetAsmJsFunctionInfo()->SetWasmReaderInfo(nullptr);
  181. SysFreeString(originalMessage);
  182. }
  183. JavascriptLibrary *library = scriptContext->GetLibrary();
  184. JavascriptError *pError = library->CreateWebAssemblyCompileError();
  185. JavascriptError::SetErrorMessage(pError, JSERR_WasmCompileError, newEx.ReleaseErrorMessage(), scriptContext);
  186. JavascriptExceptionOperators::Throw(pError, scriptContext);
  187. }
  188. return webAssemblyModule;
  189. }
  190. /* static */
  191. bool
  192. WebAssemblyModule::ValidateModule(
  193. ScriptContext* scriptContext,
  194. const byte* buffer,
  195. const uint lengthBytes)
  196. {
  197. AutoProfilingPhase wasmPhase(scriptContext, Js::WasmBytecodePhase);
  198. Unused(wasmPhase);
  199. try
  200. {
  201. Js::AutoDynamicCodeReference dynamicFunctionReference(scriptContext);
  202. SRCINFO const * srcInfo = scriptContext->cache->noContextGlobalSourceInfo;
  203. Js::Utf8SourceInfo* utf8SourceInfo = Utf8SourceInfo::New(scriptContext, (LPCUTF8)buffer, lengthBytes / sizeof(char16), lengthBytes, srcInfo, false);
  204. Wasm::WasmModuleGenerator bytecodeGen(scriptContext, utf8SourceInfo, (byte*)buffer, lengthBytes);
  205. WebAssemblyModule * webAssemblyModule = bytecodeGen.GenerateModule();
  206. for (uint i = 0; i < webAssemblyModule->GetWasmFunctionCount(); ++i)
  207. {
  208. Js::FunctionBody * body = webAssemblyModule->GetWasmFunctionInfo(i)->GetBody();
  209. Wasm::WasmReaderInfo * readerInfo = body->GetAsmJsFunctionInfo()->GetWasmReaderInfo();
  210. // TODO: avoid actually generating bytecode here
  211. Wasm::WasmBytecodeGenerator::GenerateFunctionBytecode(scriptContext, readerInfo);
  212. #if ENABLE_DEBUG_CONFIG_OPTIONS
  213. if (PHASE_ON(WasmValidatePrejitPhase, body))
  214. {
  215. CONFIG_FLAG(MaxAsmJsInterpreterRunCount) = 0;
  216. AsmJsScriptFunction * funcObj = scriptContext->GetLibrary()->CreateAsmJsScriptFunction(body);
  217. FunctionEntryPointInfo * entypointInfo = (FunctionEntryPointInfo*)funcObj->GetEntryPointInfo();
  218. entypointInfo->SetIsAsmJSFunction(true);
  219. entypointInfo->SetModuleAddress(1);
  220. GenerateFunction(scriptContext->GetNativeCodeGenerator(), body, funcObj);
  221. }
  222. #endif
  223. }
  224. }
  225. catch (Wasm::WasmCompilationException& ex)
  226. {
  227. char16* originalMessage = ex.ReleaseErrorMessage();
  228. SysFreeString(originalMessage);
  229. return false;
  230. }
  231. return true;
  232. }
  233. uint32
  234. WebAssemblyModule::GetMaxFunctionIndex() const
  235. {
  236. return GetWasmFunctionCount();
  237. }
  238. Wasm::WasmSignature*
  239. WebAssemblyModule::GetFunctionSignature(uint32 funcIndex) const
  240. {
  241. Wasm::FunctionIndexTypes::Type funcType = GetFunctionIndexType(funcIndex);
  242. if (funcType == Wasm::FunctionIndexTypes::Invalid)
  243. {
  244. throw Wasm::WasmCompilationException(_u("Function index out of range"));
  245. }
  246. switch (funcType)
  247. {
  248. case Wasm::FunctionIndexTypes::ImportThunk:
  249. case Wasm::FunctionIndexTypes::Function:
  250. return GetWasmFunctionInfo(funcIndex)->GetSignature();
  251. default:
  252. throw Wasm::WasmCompilationException(_u("Unknown function index type"));
  253. }
  254. }
  255. Wasm::FunctionIndexTypes::Type
  256. WebAssemblyModule::GetFunctionIndexType(uint32 funcIndex) const
  257. {
  258. if (funcIndex >= GetMaxFunctionIndex())
  259. {
  260. return Wasm::FunctionIndexTypes::Invalid;
  261. }
  262. if (funcIndex < GetImportedFunctionCount())
  263. {
  264. return Wasm::FunctionIndexTypes::ImportThunk;
  265. }
  266. return Wasm::FunctionIndexTypes::Function;
  267. }
  268. void
  269. WebAssemblyModule::InitializeMemory(uint32 minPage, uint32 maxPage)
  270. {
  271. if (m_hasMemory)
  272. {
  273. throw Wasm::WasmCompilationException(_u("Memory already allocated"));
  274. }
  275. if (maxPage < minPage)
  276. {
  277. throw Wasm::WasmCompilationException(_u("Memory: MaxPage (%d) must be greater than MinPage (%d)"), maxPage, minPage);
  278. }
  279. m_hasMemory = true;
  280. m_memoryInitSize = minPage;
  281. m_memoryMaxSize = maxPage;
  282. }
  283. WebAssemblyMemory *
  284. WebAssemblyModule::CreateMemory() const
  285. {
  286. return WebAssemblyMemory::CreateMemoryObject(m_memoryInitSize, m_memoryMaxSize, GetScriptContext());
  287. }
  288. bool
  289. WebAssemblyModule::IsValidMemoryImport(const WebAssemblyMemory * memory) const
  290. {
  291. return m_memImport && memory->GetInitialLength() >= m_memoryInitSize && memory->GetMaximumLength() <= m_memoryMaxSize;
  292. }
  293. Wasm::WasmSignature *
  294. WebAssemblyModule::GetSignatures() const
  295. {
  296. return m_signatures;
  297. }
  298. Wasm::WasmSignature *
  299. WebAssemblyModule::GetSignature(uint32 index) const
  300. {
  301. if (index >= GetSignatureCount())
  302. {
  303. throw Wasm::WasmCompilationException(_u("Invalid signature index %u"), index);
  304. }
  305. return &m_signatures[index];
  306. }
  307. uint32
  308. WebAssemblyModule::GetSignatureCount() const
  309. {
  310. return m_signaturesCount;
  311. }
  312. uint32
  313. WebAssemblyModule::GetEquivalentSignatureId(uint32 sigId) const
  314. {
  315. if (m_equivalentSignatureMap && sigId < GetSignatureCount())
  316. {
  317. return m_equivalentSignatureMap[sigId];
  318. }
  319. Assert(UNREACHED);
  320. return sigId;
  321. }
  322. void
  323. WebAssemblyModule::InitializeTable(uint32 minEntries, uint32 maxEntries)
  324. {
  325. if (m_hasTable)
  326. {
  327. throw Wasm::WasmCompilationException(_u("Table already allocated"));
  328. }
  329. if (maxEntries < minEntries)
  330. {
  331. throw Wasm::WasmCompilationException(_u("Table: max entries (%d) is less than min entries (%d)"), maxEntries, minEntries);
  332. }
  333. m_hasTable = true;
  334. m_tableInitSize = minEntries;
  335. m_tableMaxSize = maxEntries;
  336. }
  337. WebAssemblyTable *
  338. WebAssemblyModule::CreateTable() const
  339. {
  340. return WebAssemblyTable::Create(m_tableInitSize, m_tableMaxSize, GetScriptContext());
  341. }
  342. bool
  343. WebAssemblyModule::IsValidTableImport(const WebAssemblyTable * table) const
  344. {
  345. return m_tableImport && table->GetInitialLength() >= m_tableInitSize && table->GetMaximumLength() <= m_tableMaxSize;
  346. }
  347. uint32
  348. WebAssemblyModule::GetWasmFunctionCount() const
  349. {
  350. return (uint32)m_functionsInfo->Count();
  351. }
  352. Wasm::WasmFunctionInfo*
  353. WebAssemblyModule::AddWasmFunctionInfo(Wasm::WasmSignature* sig)
  354. {
  355. uint32 functionId = GetWasmFunctionCount();
  356. // must be recycler memory, since it holds reference to the function body
  357. Wasm::WasmFunctionInfo* funcInfo = RecyclerNew(GetRecycler(), Wasm::WasmFunctionInfo, &m_alloc, sig, functionId);
  358. m_functionsInfo->Add(funcInfo);
  359. return funcInfo;
  360. }
  361. Wasm::WasmFunctionInfo*
  362. WebAssemblyModule::GetWasmFunctionInfo(uint index) const
  363. {
  364. if (index >= GetWasmFunctionCount())
  365. {
  366. throw Wasm::WasmCompilationException(_u("Invalid function index %u"), index);
  367. }
  368. return m_functionsInfo->Item(index);
  369. }
  370. void
  371. WebAssemblyModule::AllocateFunctionExports(uint32 entries)
  372. {
  373. m_exports = AnewArrayZ(&m_alloc, Wasm::WasmExport, entries);
  374. m_exportCount = entries;
  375. }
  376. void
  377. WebAssemblyModule::SetExport(uint32 iExport, uint32 funcIndex, const char16* exportName, uint32 nameLength, Wasm::ExternalKinds::ExternalKind kind)
  378. {
  379. m_exports[iExport].index = funcIndex;
  380. m_exports[iExport].nameLength = nameLength;
  381. m_exports[iExport].name = exportName;
  382. m_exports[iExport].kind = kind;
  383. }
  384. Wasm::WasmExport*
  385. WebAssemblyModule::GetExport(uint32 iExport) const
  386. {
  387. if (iExport >= m_exportCount)
  388. {
  389. return nullptr;
  390. }
  391. return &m_exports[iExport];
  392. }
  393. uint32
  394. WebAssemblyModule::GetImportCount() const
  395. {
  396. return (uint32)m_imports->Count();
  397. }
  398. void
  399. WebAssemblyModule::AddFunctionImport(uint32 sigId, const char16* modName, uint32 modNameLen, const char16* fnName, uint32 fnNameLen)
  400. {
  401. if (sigId >= GetSignatureCount())
  402. {
  403. throw Wasm::WasmCompilationException(_u("Function signature %u is out of bound"), sigId);
  404. }
  405. // Store the information about the import
  406. Wasm::WasmImport* importInfo = Anew(&m_alloc, Wasm::WasmImport);
  407. importInfo->kind = Wasm::ExternalKinds::Function;
  408. importInfo->modNameLen = modNameLen;
  409. importInfo->modName = modName;
  410. importInfo->importNameLen = fnNameLen;
  411. importInfo->importName = fnName;
  412. m_imports->Add(importInfo);
  413. Wasm::WasmSignature* signature = GetSignature(sigId);
  414. Wasm::WasmFunctionInfo* funcInfo = AddWasmFunctionInfo(signature);
  415. // Create the custom reader to generate the import thunk
  416. Wasm::WasmCustomReader* customReader = Anew(&m_alloc, Wasm::WasmCustomReader, &m_alloc);
  417. for (uint32 iParam = 0; iParam < signature->GetParamCount(); iParam++)
  418. {
  419. Wasm::WasmNode node;
  420. node.op = Wasm::wbGetLocal;
  421. node.var.num = iParam;
  422. customReader->AddNode(node);
  423. }
  424. Wasm::WasmNode callNode;
  425. callNode.op = Wasm::wbCall;
  426. callNode.call.num = m_importedFunctionCount++;
  427. callNode.call.funcType = Wasm::FunctionIndexTypes::Import;
  428. customReader->AddNode(callNode);
  429. funcInfo->SetCustomReader(customReader);
  430. #if DBG_DUMP
  431. funcInfo->importedFunctionReference = importInfo;
  432. #endif
  433. // 32 to account for hardcoded part of the name + max uint in decimal representation
  434. uint32 bufferLength = 32;
  435. if (!UInt32Math::Add(modNameLen, bufferLength, &bufferLength) &&
  436. !UInt32Math::Add(fnNameLen, bufferLength, &bufferLength))
  437. {
  438. char16 * autoName = RecyclerNewArrayLeafZ(GetScriptContext()->GetRecycler(), char16, bufferLength);
  439. uint32 nameLength = swprintf_s(autoName, bufferLength, _u("%s.%s.Thunk[%u]"), modName, fnName, funcInfo->GetNumber());
  440. if (nameLength != (uint32)-1)
  441. {
  442. funcInfo->SetName(autoName, nameLength);
  443. }
  444. else
  445. {
  446. AssertMsg(UNREACHED, "Failed to generate import' thunk name");
  447. }
  448. }
  449. }
  450. Wasm::WasmImport*
  451. WebAssemblyModule::GetImport(uint32 i) const
  452. {
  453. if (i >= GetImportCount())
  454. {
  455. throw Wasm::WasmCompilationException(_u("Import index out of range"));
  456. }
  457. return m_imports->Item(i);
  458. }
  459. void
  460. WebAssemblyModule::AddGlobalImport(const char16* modName, uint32 modNameLen, const char16* importName, uint32 importNameLen)
  461. {
  462. Wasm::WasmImport* wi = Anew(&m_alloc, Wasm::WasmImport);
  463. wi->kind = Wasm::ExternalKinds::Global;
  464. wi->importName = importName;
  465. wi->importNameLen = importNameLen;
  466. wi->modName = modName;
  467. wi->modNameLen = modNameLen;
  468. m_imports->Add(wi);
  469. }
  470. void
  471. WebAssemblyModule::AddMemoryImport(const char16* modName, uint32 modNameLen, const char16* importName, uint32 importNameLen)
  472. {
  473. Wasm::WasmImport* wi = Anew(&m_alloc, Wasm::WasmImport);
  474. wi->kind = Wasm::ExternalKinds::Memory;
  475. wi->importName = importName;
  476. wi->importNameLen = importNameLen;
  477. wi->modName = modName;
  478. wi->modNameLen = modNameLen;
  479. m_imports->Add(wi);
  480. m_memImport = wi;
  481. }
  482. void
  483. WebAssemblyModule::AddTableImport(const char16* modName, uint32 modNameLen, const char16* importName, uint32 importNameLen)
  484. {
  485. Wasm::WasmImport* wi = Anew(&m_alloc, Wasm::WasmImport);
  486. wi->kind = Wasm::ExternalKinds::Table;
  487. wi->importName = importName;
  488. wi->importNameLen = importNameLen;
  489. wi->modName = modName;
  490. wi->modNameLen = modNameLen;
  491. m_imports->Add(wi);
  492. m_tableImport = wi;
  493. }
  494. uint
  495. WebAssemblyModule::GetOffsetFromInit(const Wasm::WasmNode& initExpr, const WebAssemblyEnvironment* env) const
  496. {
  497. if (initExpr.op != Wasm::wbI32Const && initExpr.op != Wasm::wbGetGlobal)
  498. {
  499. throw Wasm::WasmCompilationException(_u("Invalid init_expr for element offset"));
  500. }
  501. uint offset = 0;
  502. if (initExpr.op == Wasm::wbI32Const)
  503. {
  504. offset = initExpr.cnst.i32;
  505. }
  506. else if (initExpr.op == Wasm::wbGetGlobal)
  507. {
  508. if (initExpr.var.num >= (uint)m_globals->Count())
  509. {
  510. throw Wasm::WasmCompilationException(_u("global %d doesn't exist"), initExpr.var.num);
  511. }
  512. Wasm::WasmGlobal* global = m_globals->Item(initExpr.var.num);
  513. if (global->GetType() != Wasm::WasmTypes::I32)
  514. {
  515. throw Wasm::WasmCompilationException(_u("global %d must be i32"), initExpr.var.num);
  516. }
  517. offset = env->GetGlobalValue(global).i32;
  518. }
  519. return offset;
  520. }
  521. void
  522. WebAssemblyModule::AddGlobal(Wasm::GlobalReferenceTypes::Type refType, Wasm::WasmTypes::WasmType type, bool isMutable, Wasm::WasmNode init)
  523. {
  524. Wasm::WasmGlobal* global = Anew(&m_alloc, Wasm::WasmGlobal, refType, m_globalCounts[type]++, type, isMutable, init);
  525. m_globals->Add(global);
  526. }
  527. uint32
  528. WebAssemblyModule::GetGlobalCount() const
  529. {
  530. return (uint32)m_globals->Count();
  531. }
  532. Wasm::WasmGlobal*
  533. WebAssemblyModule::GetGlobal(uint32 index) const
  534. {
  535. if (index >= GetGlobalCount())
  536. {
  537. throw Wasm::WasmCompilationException(_u("Global index out of bounds %u"), index);
  538. }
  539. return m_globals->Item(index);
  540. }
  541. void
  542. WebAssemblyModule::AllocateDataSegs(uint32 count)
  543. {
  544. Assert(count != 0);
  545. m_datasegCount = count;
  546. m_datasegs = AnewArray(&m_alloc, Wasm::WasmDataSegment*, count);
  547. }
  548. void
  549. WebAssemblyModule::SetDataSeg(Wasm::WasmDataSegment* seg, uint32 index)
  550. {
  551. Assert(index < m_datasegCount);
  552. m_datasegs[index] = seg;
  553. }
  554. Wasm::WasmDataSegment*
  555. WebAssemblyModule::GetDataSeg(uint32 index) const
  556. {
  557. if (index >= m_datasegCount)
  558. {
  559. return nullptr;
  560. }
  561. return m_datasegs[index];
  562. }
  563. void
  564. WebAssemblyModule::AllocateElementSegs(uint32 count)
  565. {
  566. Assert(count != 0);
  567. m_elementsegCount = count;
  568. m_elementsegs = AnewArrayZ(&m_alloc, Wasm::WasmElementSegment*, count);
  569. }
  570. void
  571. WebAssemblyModule::SetElementSeg(Wasm::WasmElementSegment* seg, uint32 index)
  572. {
  573. Assert(index < m_elementsegCount);
  574. m_elementsegs[index] = seg;
  575. }
  576. Wasm::WasmElementSegment*
  577. WebAssemblyModule::GetElementSeg(uint32 index) const
  578. {
  579. if (index >= m_elementsegCount)
  580. {
  581. throw Wasm::WasmCompilationException(_u("Invalid index for Element segment"));
  582. }
  583. return m_elementsegs[index];
  584. }
  585. void
  586. WebAssemblyModule::SetStartFunction(uint32 i)
  587. {
  588. if (i >= GetWasmFunctionCount())
  589. {
  590. TRACE_WASM_DECODER(_u("Invalid start function index"));
  591. return;
  592. }
  593. m_startFuncIndex = i;
  594. }
  595. uint32
  596. WebAssemblyModule::GetStartFunction() const
  597. {
  598. return m_startFuncIndex;
  599. }
  600. void WebAssemblyModule::SetSignatureCount(uint32 count)
  601. {
  602. Assert(m_signaturesCount == 0 && m_signatures == nullptr);
  603. m_signaturesCount = count;
  604. m_signatures = RecyclerNewArrayZ(GetRecycler(), Wasm::WasmSignature, count);
  605. }
  606. uint32 WebAssemblyModule::GetModuleEnvironmentSize() const
  607. {
  608. static const uint DOUBLE_SIZE_IN_INTS = sizeof(double) / sizeof(int);
  609. // 1 each for memory, table, and signatures
  610. uint32 size = 3;
  611. size = UInt32Math::Add(size, GetWasmFunctionCount());
  612. size = UInt32Math::Add(size, GetImportedFunctionCount());
  613. size = UInt32Math::Add(size, WAsmJs::ConvertToJsVarOffset<byte>(GetGlobalsByteSize()));
  614. return size;
  615. }
  616. void WebAssemblyModule::Finalize(bool isShutdown)
  617. {
  618. m_alloc.Clear();
  619. }
  620. void WebAssemblyModule::Dispose(bool isShutdown)
  621. {
  622. Assert(m_alloc.Size() == 0);
  623. }
  624. void WebAssemblyModule::Mark(Recycler * recycler)
  625. {
  626. }
  627. uint WebAssemblyModule::GetOffsetForGlobal(Wasm::WasmGlobal* global) const
  628. {
  629. Wasm::WasmTypes::WasmType type = global->GetType();
  630. if (type >= Wasm::WasmTypes::Limit)
  631. {
  632. throw Wasm::WasmCompilationException(_u("Invalid Global type"));
  633. }
  634. uint32 offset = WAsmJs::ConvertFromJsVarOffset<byte>(GetGlobalOffset());
  635. for (uint i = 1; i < (uint)type; i++)
  636. {
  637. offset = AddGlobalByteSizeToOffset((Wasm::WasmTypes::WasmType)i, offset);
  638. }
  639. uint32 typeSize = Wasm::WasmTypes::GetTypeByteSize(type);
  640. uint32 sizeUsed = WAsmJs::ConvertOffset<byte>(global->GetOffset(), typeSize);
  641. offset = UInt32Math::Add(offset, sizeUsed);
  642. return WAsmJs::ConvertOffset(offset, sizeof(byte), typeSize);
  643. }
  644. uint WebAssemblyModule::AddGlobalByteSizeToOffset(Wasm::WasmTypes::WasmType type, uint32 offset) const
  645. {
  646. uint32 typeSize = Wasm::WasmTypes::GetTypeByteSize(type);
  647. offset = ::Math::AlignOverflowCheck(offset, typeSize);
  648. uint32 sizeUsed = WAsmJs::ConvertOffset<byte>(m_globalCounts[type], typeSize);
  649. return UInt32Math::Add(offset, sizeUsed);
  650. }
  651. JavascriptString *
  652. WebAssemblyModule::GetExternalKindString(ScriptContext * scriptContext, Wasm::ExternalKinds::ExternalKind kind)
  653. {
  654. switch (kind)
  655. {
  656. case Wasm::ExternalKinds::Function:
  657. return scriptContext->GetLibrary()->CreateStringFromCppLiteral(_u("function"));
  658. case Wasm::ExternalKinds::Table:
  659. return scriptContext->GetLibrary()->CreateStringFromCppLiteral(_u("table"));
  660. case Wasm::ExternalKinds::Memory:
  661. return scriptContext->GetLibrary()->CreateStringFromCppLiteral(_u("memory"));
  662. case Wasm::ExternalKinds::Global:
  663. return scriptContext->GetLibrary()->CreateStringFromCppLiteral(_u("global"));
  664. default:
  665. Assume(UNREACHED);
  666. }
  667. return nullptr;
  668. }
  669. uint WebAssemblyModule::GetGlobalsByteSize() const
  670. {
  671. uint32 size = 0;
  672. for (Wasm::WasmTypes::WasmType type = (Wasm::WasmTypes::WasmType)(Wasm::WasmTypes::Void + 1); type < Wasm::WasmTypes::Limit; type = (Wasm::WasmTypes::WasmType)(type + 1))
  673. {
  674. size = AddGlobalByteSizeToOffset(type, size);
  675. }
  676. return size;
  677. }
  678. } // namespace Js
  679. #endif