WebAssemblyModule.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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, WASMERR_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. GenerateFunction(scriptContext->GetNativeCodeGenerator(), body, funcObj);
  220. }
  221. #endif
  222. }
  223. }
  224. catch (Wasm::WasmCompilationException& ex)
  225. {
  226. char16* originalMessage = ex.ReleaseErrorMessage();
  227. SysFreeString(originalMessage);
  228. return false;
  229. }
  230. return true;
  231. }
  232. uint32
  233. WebAssemblyModule::GetMaxFunctionIndex() const
  234. {
  235. return GetWasmFunctionCount();
  236. }
  237. Wasm::FunctionIndexTypes::Type
  238. WebAssemblyModule::GetFunctionIndexType(uint32 funcIndex) const
  239. {
  240. if (funcIndex >= GetMaxFunctionIndex())
  241. {
  242. return Wasm::FunctionIndexTypes::Invalid;
  243. }
  244. if (funcIndex < GetImportedFunctionCount())
  245. {
  246. return Wasm::FunctionIndexTypes::ImportThunk;
  247. }
  248. return Wasm::FunctionIndexTypes::Function;
  249. }
  250. void
  251. WebAssemblyModule::InitializeMemory(uint32 minPage, uint32 maxPage)
  252. {
  253. if (m_hasMemory)
  254. {
  255. throw Wasm::WasmCompilationException(_u("Memory already allocated"));
  256. }
  257. if (maxPage < minPage)
  258. {
  259. throw Wasm::WasmCompilationException(_u("Memory: MaxPage (%d) must be greater than MinPage (%d)"), maxPage, minPage);
  260. }
  261. m_hasMemory = true;
  262. m_memoryInitSize = minPage;
  263. m_memoryMaxSize = maxPage;
  264. }
  265. WebAssemblyMemory *
  266. WebAssemblyModule::CreateMemory() const
  267. {
  268. return WebAssemblyMemory::CreateMemoryObject(m_memoryInitSize, m_memoryMaxSize, GetScriptContext());
  269. }
  270. bool
  271. WebAssemblyModule::IsValidMemoryImport(const WebAssemblyMemory * memory) const
  272. {
  273. return m_memImport && memory->GetInitialLength() >= m_memoryInitSize && memory->GetMaximumLength() <= m_memoryMaxSize;
  274. }
  275. Wasm::WasmSignature *
  276. WebAssemblyModule::GetSignatures() const
  277. {
  278. return m_signatures;
  279. }
  280. Wasm::WasmSignature *
  281. WebAssemblyModule::GetSignature(uint32 index) const
  282. {
  283. if (index >= GetSignatureCount())
  284. {
  285. throw Wasm::WasmCompilationException(_u("Invalid signature index %u"), index);
  286. }
  287. return &m_signatures[index];
  288. }
  289. uint32
  290. WebAssemblyModule::GetSignatureCount() const
  291. {
  292. return m_signaturesCount;
  293. }
  294. uint32
  295. WebAssemblyModule::GetEquivalentSignatureId(uint32 sigId) const
  296. {
  297. if (m_equivalentSignatureMap && sigId < GetSignatureCount())
  298. {
  299. return m_equivalentSignatureMap[sigId];
  300. }
  301. Assert(UNREACHED);
  302. return sigId;
  303. }
  304. void
  305. WebAssemblyModule::InitializeTable(uint32 minEntries, uint32 maxEntries)
  306. {
  307. if (m_hasTable)
  308. {
  309. throw Wasm::WasmCompilationException(_u("Table already allocated"));
  310. }
  311. if (maxEntries < minEntries)
  312. {
  313. throw Wasm::WasmCompilationException(_u("Table: max entries (%d) is less than min entries (%d)"), maxEntries, minEntries);
  314. }
  315. m_hasTable = true;
  316. m_tableInitSize = minEntries;
  317. m_tableMaxSize = maxEntries;
  318. }
  319. WebAssemblyTable *
  320. WebAssemblyModule::CreateTable() const
  321. {
  322. return WebAssemblyTable::Create(m_tableInitSize, m_tableMaxSize, GetScriptContext());
  323. }
  324. bool
  325. WebAssemblyModule::IsValidTableImport(const WebAssemblyTable * table) const
  326. {
  327. return m_tableImport && table->GetInitialLength() >= m_tableInitSize && table->GetMaximumLength() <= m_tableMaxSize;
  328. }
  329. uint32
  330. WebAssemblyModule::GetWasmFunctionCount() const
  331. {
  332. return (uint32)m_functionsInfo->Count();
  333. }
  334. Wasm::WasmFunctionInfo*
  335. WebAssemblyModule::AddWasmFunctionInfo(Wasm::WasmSignature* sig)
  336. {
  337. uint32 functionId = GetWasmFunctionCount();
  338. // must be recycler memory, since it holds reference to the function body
  339. Wasm::WasmFunctionInfo* funcInfo = RecyclerNew(GetRecycler(), Wasm::WasmFunctionInfo, &m_alloc, sig, functionId);
  340. m_functionsInfo->Add(funcInfo);
  341. return funcInfo;
  342. }
  343. Wasm::WasmFunctionInfo*
  344. WebAssemblyModule::GetWasmFunctionInfo(uint index) const
  345. {
  346. if (index >= GetWasmFunctionCount())
  347. {
  348. throw Wasm::WasmCompilationException(_u("Invalid function index %u"), index);
  349. }
  350. return m_functionsInfo->Item(index);
  351. }
  352. void
  353. WebAssemblyModule::AllocateFunctionExports(uint32 entries)
  354. {
  355. m_exports = AnewArrayZ(&m_alloc, Wasm::WasmExport, entries);
  356. m_exportCount = entries;
  357. }
  358. void
  359. WebAssemblyModule::SetExport(uint32 iExport, uint32 funcIndex, const char16* exportName, uint32 nameLength, Wasm::ExternalKinds::ExternalKind kind)
  360. {
  361. m_exports[iExport].index = funcIndex;
  362. m_exports[iExport].nameLength = nameLength;
  363. m_exports[iExport].name = exportName;
  364. m_exports[iExport].kind = kind;
  365. }
  366. Wasm::WasmExport*
  367. WebAssemblyModule::GetExport(uint32 iExport) const
  368. {
  369. if (iExport >= m_exportCount)
  370. {
  371. return nullptr;
  372. }
  373. return &m_exports[iExport];
  374. }
  375. uint32
  376. WebAssemblyModule::GetImportCount() const
  377. {
  378. return (uint32)m_imports->Count();
  379. }
  380. void
  381. WebAssemblyModule::AddFunctionImport(uint32 sigId, const char16* modName, uint32 modNameLen, const char16* fnName, uint32 fnNameLen)
  382. {
  383. if (sigId >= GetSignatureCount())
  384. {
  385. throw Wasm::WasmCompilationException(_u("Function signature %u is out of bound"), sigId);
  386. }
  387. // Store the information about the import
  388. Wasm::WasmImport* importInfo = Anew(&m_alloc, Wasm::WasmImport);
  389. importInfo->kind = Wasm::ExternalKinds::Function;
  390. importInfo->modNameLen = modNameLen;
  391. importInfo->modName = modName;
  392. importInfo->importNameLen = fnNameLen;
  393. importInfo->importName = fnName;
  394. m_imports->Add(importInfo);
  395. Wasm::WasmSignature* signature = GetSignature(sigId);
  396. Wasm::WasmFunctionInfo* funcInfo = AddWasmFunctionInfo(signature);
  397. // Create the custom reader to generate the import thunk
  398. Wasm::WasmCustomReader* customReader = Anew(&m_alloc, Wasm::WasmCustomReader, &m_alloc);
  399. for (uint32 iParam = 0; iParam < signature->GetParamCount(); iParam++)
  400. {
  401. Wasm::WasmNode node;
  402. node.op = Wasm::wbGetLocal;
  403. node.var.num = iParam;
  404. customReader->AddNode(node);
  405. }
  406. Wasm::WasmNode callNode;
  407. callNode.op = Wasm::wbCall;
  408. callNode.call.num = m_importedFunctionCount++;
  409. callNode.call.funcType = Wasm::FunctionIndexTypes::Import;
  410. customReader->AddNode(callNode);
  411. funcInfo->SetCustomReader(customReader);
  412. #if DBG_DUMP
  413. funcInfo->importedFunctionReference = importInfo;
  414. #endif
  415. // 32 to account for hardcoded part of the name + max uint in decimal representation
  416. uint32 bufferLength = 32;
  417. if (!UInt32Math::Add(modNameLen, bufferLength, &bufferLength) &&
  418. !UInt32Math::Add(fnNameLen, bufferLength, &bufferLength))
  419. {
  420. char16 * autoName = RecyclerNewArrayLeafZ(GetScriptContext()->GetRecycler(), char16, bufferLength);
  421. uint32 nameLength = swprintf_s(autoName, bufferLength, _u("%s.%s.Thunk[%u]"), modName, fnName, funcInfo->GetNumber());
  422. if (nameLength != (uint32)-1)
  423. {
  424. funcInfo->SetName(autoName, nameLength);
  425. }
  426. else
  427. {
  428. AssertMsg(UNREACHED, "Failed to generate import' thunk name");
  429. }
  430. }
  431. }
  432. Wasm::WasmImport*
  433. WebAssemblyModule::GetImport(uint32 i) const
  434. {
  435. if (i >= GetImportCount())
  436. {
  437. throw Wasm::WasmCompilationException(_u("Import index out of range"));
  438. }
  439. return m_imports->Item(i);
  440. }
  441. void
  442. WebAssemblyModule::AddGlobalImport(const char16* modName, uint32 modNameLen, const char16* importName, uint32 importNameLen)
  443. {
  444. Wasm::WasmImport* wi = Anew(&m_alloc, Wasm::WasmImport);
  445. wi->kind = Wasm::ExternalKinds::Global;
  446. wi->importName = importName;
  447. wi->importNameLen = importNameLen;
  448. wi->modName = modName;
  449. wi->modNameLen = modNameLen;
  450. m_imports->Add(wi);
  451. }
  452. void
  453. WebAssemblyModule::AddMemoryImport(const char16* modName, uint32 modNameLen, const char16* importName, uint32 importNameLen)
  454. {
  455. Wasm::WasmImport* wi = Anew(&m_alloc, Wasm::WasmImport);
  456. wi->kind = Wasm::ExternalKinds::Memory;
  457. wi->importName = importName;
  458. wi->importNameLen = importNameLen;
  459. wi->modName = modName;
  460. wi->modNameLen = modNameLen;
  461. m_imports->Add(wi);
  462. m_memImport = wi;
  463. }
  464. void
  465. WebAssemblyModule::AddTableImport(const char16* modName, uint32 modNameLen, const char16* importName, uint32 importNameLen)
  466. {
  467. Wasm::WasmImport* wi = Anew(&m_alloc, Wasm::WasmImport);
  468. wi->kind = Wasm::ExternalKinds::Table;
  469. wi->importName = importName;
  470. wi->importNameLen = importNameLen;
  471. wi->modName = modName;
  472. wi->modNameLen = modNameLen;
  473. m_imports->Add(wi);
  474. m_tableImport = wi;
  475. }
  476. uint
  477. WebAssemblyModule::GetOffsetFromInit(const Wasm::WasmNode& initExpr, const WebAssemblyEnvironment* env) const
  478. {
  479. if (initExpr.op != Wasm::wbI32Const && initExpr.op != Wasm::wbGetGlobal)
  480. {
  481. throw Wasm::WasmCompilationException(_u("Invalid init_expr for element offset"));
  482. }
  483. uint offset = 0;
  484. if (initExpr.op == Wasm::wbI32Const)
  485. {
  486. offset = initExpr.cnst.i32;
  487. }
  488. else if (initExpr.op == Wasm::wbGetGlobal)
  489. {
  490. if (initExpr.var.num >= (uint)m_globals->Count())
  491. {
  492. throw Wasm::WasmCompilationException(_u("global %d doesn't exist"), initExpr.var.num);
  493. }
  494. Wasm::WasmGlobal* global = m_globals->Item(initExpr.var.num);
  495. if (global->GetType() != Wasm::WasmTypes::I32)
  496. {
  497. throw Wasm::WasmCompilationException(_u("global %d must be i32"), initExpr.var.num);
  498. }
  499. offset = env->GetGlobalValue(global).i32;
  500. }
  501. return offset;
  502. }
  503. void
  504. WebAssemblyModule::AddGlobal(Wasm::GlobalReferenceTypes::Type refType, Wasm::WasmTypes::WasmType type, bool isMutable, Wasm::WasmNode init)
  505. {
  506. Wasm::WasmGlobal* global = Anew(&m_alloc, Wasm::WasmGlobal, refType, m_globalCounts[type]++, type, isMutable, init);
  507. m_globals->Add(global);
  508. }
  509. uint32
  510. WebAssemblyModule::GetGlobalCount() const
  511. {
  512. return (uint32)m_globals->Count();
  513. }
  514. Wasm::WasmGlobal*
  515. WebAssemblyModule::GetGlobal(uint32 index) const
  516. {
  517. if (index >= GetGlobalCount())
  518. {
  519. throw Wasm::WasmCompilationException(_u("Global index out of bounds %u"), index);
  520. }
  521. return m_globals->Item(index);
  522. }
  523. void
  524. WebAssemblyModule::AllocateDataSegs(uint32 count)
  525. {
  526. Assert(count != 0);
  527. m_datasegCount = count;
  528. m_datasegs = AnewArray(&m_alloc, Wasm::WasmDataSegment*, count);
  529. }
  530. void
  531. WebAssemblyModule::SetDataSeg(Wasm::WasmDataSegment* seg, uint32 index)
  532. {
  533. Assert(index < m_datasegCount);
  534. m_datasegs[index] = seg;
  535. }
  536. Wasm::WasmDataSegment*
  537. WebAssemblyModule::GetDataSeg(uint32 index) const
  538. {
  539. if (index >= m_datasegCount)
  540. {
  541. return nullptr;
  542. }
  543. return m_datasegs[index];
  544. }
  545. void
  546. WebAssemblyModule::AllocateElementSegs(uint32 count)
  547. {
  548. Assert(count != 0);
  549. m_elementsegCount = count;
  550. m_elementsegs = AnewArrayZ(&m_alloc, Wasm::WasmElementSegment*, count);
  551. }
  552. void
  553. WebAssemblyModule::SetElementSeg(Wasm::WasmElementSegment* seg, uint32 index)
  554. {
  555. Assert(index < m_elementsegCount);
  556. m_elementsegs[index] = seg;
  557. }
  558. Wasm::WasmElementSegment*
  559. WebAssemblyModule::GetElementSeg(uint32 index) const
  560. {
  561. if (index >= m_elementsegCount)
  562. {
  563. throw Wasm::WasmCompilationException(_u("Invalid index for Element segment"));
  564. }
  565. return m_elementsegs[index];
  566. }
  567. void
  568. WebAssemblyModule::SetStartFunction(uint32 i)
  569. {
  570. if (i >= GetWasmFunctionCount())
  571. {
  572. TRACE_WASM_DECODER(_u("Invalid start function index"));
  573. return;
  574. }
  575. m_startFuncIndex = i;
  576. }
  577. uint32
  578. WebAssemblyModule::GetStartFunction() const
  579. {
  580. return m_startFuncIndex;
  581. }
  582. void WebAssemblyModule::SetSignatureCount(uint32 count)
  583. {
  584. Assert(m_signaturesCount == 0 && m_signatures == nullptr);
  585. m_signaturesCount = count;
  586. m_signatures = RecyclerNewArrayZ(GetRecycler(), Wasm::WasmSignature, count);
  587. }
  588. uint32 WebAssemblyModule::GetModuleEnvironmentSize() const
  589. {
  590. static const uint DOUBLE_SIZE_IN_INTS = sizeof(double) / sizeof(int);
  591. // 1 each for memory, table, and signatures
  592. uint32 size = 3;
  593. size = UInt32Math::Add(size, GetWasmFunctionCount());
  594. size = UInt32Math::Add(size, GetImportedFunctionCount());
  595. size = UInt32Math::Add(size, WAsmJs::ConvertToJsVarOffset<byte>(GetGlobalsByteSize()));
  596. return size;
  597. }
  598. void WebAssemblyModule::Finalize(bool isShutdown)
  599. {
  600. m_alloc.Clear();
  601. }
  602. void WebAssemblyModule::Dispose(bool isShutdown)
  603. {
  604. Assert(m_alloc.Size() == 0);
  605. }
  606. void WebAssemblyModule::Mark(Recycler * recycler)
  607. {
  608. }
  609. uint WebAssemblyModule::GetOffsetForGlobal(Wasm::WasmGlobal* global) const
  610. {
  611. Wasm::WasmTypes::WasmType type = global->GetType();
  612. if (type >= Wasm::WasmTypes::Limit)
  613. {
  614. throw Wasm::WasmCompilationException(_u("Invalid Global type"));
  615. }
  616. uint32 offset = WAsmJs::ConvertFromJsVarOffset<byte>(GetGlobalOffset());
  617. for (uint i = 1; i < (uint)type; i++)
  618. {
  619. offset = AddGlobalByteSizeToOffset((Wasm::WasmTypes::WasmType)i, offset);
  620. }
  621. uint32 typeSize = Wasm::WasmTypes::GetTypeByteSize(type);
  622. uint32 sizeUsed = WAsmJs::ConvertOffset<byte>(global->GetOffset(), typeSize);
  623. offset = UInt32Math::Add(offset, sizeUsed);
  624. return WAsmJs::ConvertOffset(offset, sizeof(byte), typeSize);
  625. }
  626. uint WebAssemblyModule::AddGlobalByteSizeToOffset(Wasm::WasmTypes::WasmType type, uint32 offset) const
  627. {
  628. uint32 typeSize = Wasm::WasmTypes::GetTypeByteSize(type);
  629. offset = ::Math::AlignOverflowCheck(offset, typeSize);
  630. uint32 sizeUsed = WAsmJs::ConvertOffset<byte>(m_globalCounts[type], typeSize);
  631. return UInt32Math::Add(offset, sizeUsed);
  632. }
  633. JavascriptString *
  634. WebAssemblyModule::GetExternalKindString(ScriptContext * scriptContext, Wasm::ExternalKinds::ExternalKind kind)
  635. {
  636. switch (kind)
  637. {
  638. case Wasm::ExternalKinds::Function:
  639. return scriptContext->GetLibrary()->CreateStringFromCppLiteral(_u("function"));
  640. case Wasm::ExternalKinds::Table:
  641. return scriptContext->GetLibrary()->CreateStringFromCppLiteral(_u("table"));
  642. case Wasm::ExternalKinds::Memory:
  643. return scriptContext->GetLibrary()->CreateStringFromCppLiteral(_u("memory"));
  644. case Wasm::ExternalKinds::Global:
  645. return scriptContext->GetLibrary()->CreateStringFromCppLiteral(_u("global"));
  646. default:
  647. Assume(UNREACHED);
  648. }
  649. return nullptr;
  650. }
  651. uint WebAssemblyModule::GetGlobalsByteSize() const
  652. {
  653. uint32 size = 0;
  654. for (Wasm::WasmTypes::WasmType type = (Wasm::WasmTypes::WasmType)(Wasm::WasmTypes::Void + 1); type < Wasm::WasmTypes::Limit; type = (Wasm::WasmTypes::WasmType)(type + 1))
  655. {
  656. size = AddGlobalByteSizeToOffset(type, size);
  657. }
  658. return size;
  659. }
  660. } // namespace Js
  661. #endif