summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/binaryen-c.cpp161
-rw-r--r--src/binaryen-c.h38
-rw-r--r--src/ir/ReFinalize.cpp1
-rw-r--r--src/ir/import-utils.h24
-rw-r--r--src/ir/module-utils.h45
-rw-r--r--src/ir/utils.h2
-rw-r--r--src/js/binaryen.js-post.js37
-rw-r--r--src/passes/Metrics.cpp1
-rw-r--r--src/passes/MinifyImportsAndExports.cpp1
-rw-r--r--src/passes/Print.cpp26
-rw-r--r--src/passes/RemoveUnusedModuleElements.cpp33
-rw-r--r--src/shared-constants.h2
-rw-r--r--src/tools/fuzzing.h25
-rw-r--r--src/tools/wasm-metadce.cpp34
-rw-r--r--src/wasm-binary.h10
-rw-r--r--src/wasm-builder.h13
-rw-r--r--src/wasm-s-parser.h6
-rw-r--r--src/wasm-traversal.h13
-rw-r--r--src/wasm.h25
-rw-r--r--src/wasm/wasm-binary.cpp95
-rw-r--r--src/wasm/wasm-s-parser.cpp149
-rw-r--r--src/wasm/wasm-type.cpp3
-rw-r--r--src/wasm/wasm-validator.cpp35
-rw-r--r--src/wasm/wasm.cpp47
24 files changed, 810 insertions, 16 deletions
diff --git a/src/binaryen-c.cpp b/src/binaryen-c.cpp
index da3485843..2df1d478a 100644
--- a/src/binaryen-c.cpp
+++ b/src/binaryen-c.cpp
@@ -125,6 +125,7 @@ std::map<BinaryenFunctionTypeRef, size_t> functionTypes;
std::map<BinaryenExpressionRef, size_t> expressions;
std::map<BinaryenFunctionRef, size_t> functions;
std::map<BinaryenGlobalRef, size_t> globals;
+std::map<BinaryenEventRef, size_t> events;
std::map<BinaryenExportRef, size_t> exports;
std::map<RelooperBlockRef, size_t> relooperBlocks;
@@ -368,6 +369,9 @@ BinaryenExternalKind BinaryenExternalMemory(void) {
BinaryenExternalKind BinaryenExternalGlobal(void) {
return static_cast<BinaryenExternalKind>(ExternalKind::Global);
}
+BinaryenExternalKind BinaryenExternalEvent(void) {
+ return static_cast<BinaryenExternalKind>(ExternalKind::Event);
+}
// Features
@@ -417,12 +421,14 @@ void BinaryenModuleDispose(BinaryenModuleRef module) {
std::cout << " expressions.clear();\n";
std::cout << " functions.clear();\n";
std::cout << " globals.clear();\n";
+ std::cout << " events.clear();\n";
std::cout << " exports.clear();\n";
std::cout << " relooperBlocks.clear();\n";
functionTypes.clear();
expressions.clear();
functions.clear();
globals.clear();
+ events.clear();
exports.clear();
relooperBlocks.clear();
}
@@ -2775,6 +2781,45 @@ void BinaryenRemoveGlobal(BinaryenModuleRef module, const char* name) {
wasm->removeGlobal(name);
}
+// Events
+
+BinaryenEventRef BinaryenAddEvent(BinaryenModuleRef module,
+ const char* name,
+ uint32_t attribute,
+ BinaryenFunctionTypeRef type) {
+ if (tracing) {
+ std::cout << " BinaryenAddEvent(the_module, \"" << name << "\", "
+ << attribute << ", functionTypes[" << functionTypes[type]
+ << "]);\n";
+ }
+
+ auto* wasm = (Module*)module;
+ auto* ret = new Event();
+ ret->name = name;
+ ret->attribute = attribute;
+ ret->type = ((FunctionType*)type)->name;
+ ret->params = ((FunctionType*)type)->params;
+ wasm->addEvent(ret);
+ return ret;
+}
+
+BinaryenEventRef BinaryenGetEvent(BinaryenModuleRef module, const char* name) {
+ if (tracing) {
+ std::cout << " BinaryenGetEvent(the_module, \"" << name << "\");\n";
+ }
+
+ auto* wasm = (Module*)module;
+ return wasm->getEvent(name);
+}
+void BinaryenRemoveEvent(BinaryenModuleRef module, const char* name) {
+ if (tracing) {
+ std::cout << " BinaryenRemoveEvent(the_module, \"" << name << "\");\n";
+ }
+
+ auto* wasm = (Module*)module;
+ wasm->removeEvent(name);
+}
+
// Imports
void BinaryenAddFunctionImport(BinaryenModuleRef module,
@@ -2850,6 +2895,29 @@ void BinaryenAddGlobalImport(BinaryenModuleRef module,
ret->type = Type(globalType);
wasm->addGlobal(ret);
}
+void BinaryenAddEventImport(BinaryenModuleRef module,
+ const char* internalName,
+ const char* externalModuleName,
+ const char* externalBaseName,
+ uint32_t attribute,
+ BinaryenFunctionTypeRef eventType) {
+ auto* wasm = (Module*)module;
+ auto* ret = new Event();
+
+ if (tracing) {
+ std::cout << " BinaryenAddEventImport(the_module, \"" << internalName
+ << "\", \"" << externalModuleName << "\", \"" << externalBaseName
+ << "\", " << attribute << ", functionTypes["
+ << functionTypes[eventType] << "]);\n";
+ }
+
+ ret->name = internalName;
+ ret->module = externalModuleName;
+ ret->base = externalBaseName;
+ ret->type = ((FunctionType*)eventType)->name;
+ ret->params = ((FunctionType*)eventType)->params;
+ wasm->addEvent(ret);
+}
// Exports
@@ -2938,6 +3006,26 @@ BinaryenExportRef BinaryenAddGlobalExport(BinaryenModuleRef module,
wasm->addExport(ret);
return ret;
}
+BinaryenExportRef BinaryenAddEventExport(BinaryenModuleRef module,
+ const char* internalName,
+ const char* externalName) {
+ auto* wasm = (Module*)module;
+ auto* ret = new Export();
+
+ if (tracing) {
+ auto id = exports.size();
+ exports[ret] = id;
+ std::cout << " exports[" << id
+ << "] = BinaryenAddEventExport(the_module, \"" << internalName
+ << "\", \"" << externalName << "\");\n";
+ }
+
+ ret->value = internalName;
+ ret->name = externalName;
+ ret->kind = ExternalKind::Event;
+ wasm->addExport(ret);
+ return ret;
+}
void BinaryenRemoveExport(BinaryenModuleRef module, const char* externalName) {
if (tracing) {
std::cout << " BinaryenRemoveExport(the_module, \"" << externalName
@@ -3655,6 +3743,52 @@ BinaryenExpressionRef BinaryenGlobalGetInitExpr(BinaryenGlobalRef global) {
}
//
+// =========== Event operations ===========
+//
+
+const char* BinaryenEventGetName(BinaryenEventRef event) {
+ if (tracing) {
+ std::cout << " BinaryenEventGetName(events[" << events[event] << "]);\n";
+ }
+
+ return ((Event*)event)->name.c_str();
+}
+int BinaryenEventGetAttribute(BinaryenEventRef event) {
+ if (tracing) {
+ std::cout << " BinaryenEventGetAttribute(events[" << events[event]
+ << "]);\n";
+ }
+
+ return ((Event*)event)->attribute;
+}
+const char* BinaryenEventGetType(BinaryenEventRef event) {
+ if (tracing) {
+ std::cout << " BinaryenEventGetType(events[" << events[event] << "]);\n";
+ }
+
+ return ((Event*)event)->type.c_str();
+}
+BinaryenIndex BinaryenEventGetNumParams(BinaryenEventRef event) {
+ if (tracing) {
+ std::cout << " BinaryenEventGetNumParams(events[" << events[event]
+ << "]);\n";
+ }
+
+ return ((Event*)event)->params.size();
+}
+BinaryenType BinaryenEventGetParam(BinaryenEventRef event,
+ BinaryenIndex index) {
+ if (tracing) {
+ std::cout << " BinaryenEventGetParam(events[" << events[event] << "], "
+ << index << ");\n";
+ }
+
+ auto* fn = (Event*)event;
+ assert(index < fn->params.size());
+ return fn->params[index];
+}
+
+//
// =========== Import operations ===========
//
@@ -3684,6 +3818,19 @@ const char* BinaryenGlobalImportGetModule(BinaryenGlobalRef import) {
return "";
}
}
+const char* BinaryenEventImportGetModule(BinaryenEventRef import) {
+ if (tracing) {
+ std::cout << " BinaryenEventImportGetModule(events[" << events[import]
+ << "]);\n";
+ }
+
+ auto* event = (Event*)import;
+ if (event->imported()) {
+ return event->module.c_str();
+ } else {
+ return "";
+ }
+}
const char* BinaryenFunctionImportGetBase(BinaryenFunctionRef import) {
if (tracing) {
std::cout << " BinaryenFunctionImportGetBase(functions["
@@ -3710,6 +3857,19 @@ const char* BinaryenGlobalImportGetBase(BinaryenGlobalRef import) {
return "";
}
}
+const char* BinaryenEventImportGetBase(BinaryenEventRef import) {
+ if (tracing) {
+ std::cout << " BinaryenEventImportGetBase(events[" << events[import]
+ << "]);\n";
+ }
+
+ auto* event = (Event*)import;
+ if (event->imported()) {
+ return event->base.c_str();
+ } else {
+ return "";
+ }
+}
//
// =========== Export operations ===========
@@ -3875,6 +4035,7 @@ void BinaryenSetAPITracing(int on) {
" std::map<size_t, BinaryenExpressionRef> expressions;\n"
" std::map<size_t, BinaryenFunctionRef> functions;\n"
" std::map<size_t, BinaryenGlobalRef> globals;\n"
+ " std::map<size_t, BinaryenEventRef> events;\n"
" std::map<size_t, BinaryenExportRef> exports;\n"
" std::map<size_t, RelooperBlockRef> relooperBlocks;\n"
" BinaryenModuleRef the_module = NULL;\n"
diff --git a/src/binaryen-c.h b/src/binaryen-c.h
index 879d78498..7b9b0141a 100644
--- a/src/binaryen-c.h
+++ b/src/binaryen-c.h
@@ -136,6 +136,7 @@ BinaryenExternalKind BinaryenExternalFunction(void);
BinaryenExternalKind BinaryenExternalTable(void);
BinaryenExternalKind BinaryenExternalMemory(void);
BinaryenExternalKind BinaryenExternalGlobal(void);
+BinaryenExternalKind BinaryenExternalEvent(void);
// Features. Call to get the value of each; you can cache them. Use bitwise
// operators to combine and test particular features.
@@ -882,6 +883,12 @@ void BinaryenAddGlobalImport(BinaryenModuleRef module,
const char* externalModuleName,
const char* externalBaseName,
BinaryenType globalType);
+void BinaryenAddEventImport(BinaryenModuleRef module,
+ const char* internalName,
+ const char* externalModuleName,
+ const char* externalBaseName,
+ uint32_t attribute,
+ BinaryenFunctionTypeRef eventType);
// Exports
@@ -902,6 +909,9 @@ BinaryenExportRef BinaryenAddMemoryExport(BinaryenModuleRef module,
BinaryenExportRef BinaryenAddGlobalExport(BinaryenModuleRef module,
const char* internalName,
const char* externalName);
+BinaryenExportRef BinaryenAddEventExport(BinaryenModuleRef module,
+ const char* internalName,
+ const char* externalName);
void BinaryenRemoveExport(BinaryenModuleRef module, const char* externalName);
// Globals
@@ -917,6 +927,17 @@ BinaryenGlobalRef BinaryenAddGlobal(BinaryenModuleRef module,
BinaryenGlobalRef BinaryenGetGlobal(BinaryenModuleRef module, const char* name);
void BinaryenRemoveGlobal(BinaryenModuleRef module, const char* name);
+// Events
+
+typedef void* BinaryenEventRef;
+
+BinaryenEventRef BinaryenAddEvent(BinaryenModuleRef module,
+ const char* name,
+ uint32_t attribute,
+ BinaryenFunctionTypeRef type);
+BinaryenEventRef BinaryenGetEvent(BinaryenModuleRef module, const char* name);
+void BinaryenEventEvent(BinaryenModuleRef module, const char* name);
+
// Function table. One per module
void BinaryenSetFunctionTable(BinaryenModuleRef module,
@@ -1153,6 +1174,21 @@ int BinaryenGlobalIsMutable(BinaryenGlobalRef global);
BinaryenExpressionRef BinaryenGlobalGetInitExpr(BinaryenGlobalRef global);
//
+// ========== Event Operations ==========
+//
+
+// Gets the name of the specified `Event`.
+const char* BinaryenEventGetName(BinaryenEventRef event);
+// Gets the attribute of the specified `Event`.
+int BinaryenEventGetAttribute(BinaryenEventRef event);
+// Gets the name of the `FunctionType` associated with the specified `Event`.
+const char* BinaryenEventGetType(BinaryenEventRef event);
+// Gets the number of parameters of the specified `Event`.
+BinaryenIndex BinaryenEventGetNumParams(BinaryenEventRef event);
+// Gets the type of the parameter at the specified index of the specified
+// `Event`.
+BinaryenType BinaryenEventGetParam(BinaryenEventRef event, BinaryenIndex index);
+
//
// ========== Import Operations ==========
//
@@ -1160,9 +1196,11 @@ BinaryenExpressionRef BinaryenGlobalGetInitExpr(BinaryenGlobalRef global);
// Gets the external module name of the specified import.
const char* BinaryenFunctionImportGetModule(BinaryenFunctionRef import);
const char* BinaryenGlobalImportGetModule(BinaryenGlobalRef import);
+const char* BinaryenEventImportGetModule(BinaryenEventRef import);
// Gets the external base name of the specified import.
const char* BinaryenFunctionImportGetBase(BinaryenFunctionRef import);
const char* BinaryenGlobalImportGetBase(BinaryenGlobalRef import);
+const char* BinaryenEventImportGetBase(BinaryenEventRef import);
//
// ========== Export Operations ==========
diff --git a/src/ir/ReFinalize.cpp b/src/ir/ReFinalize.cpp
index 0bd8a7a0f..6723c5e4f 100644
--- a/src/ir/ReFinalize.cpp
+++ b/src/ir/ReFinalize.cpp
@@ -172,6 +172,7 @@ void ReFinalize::visitExport(Export* curr) { WASM_UNREACHABLE(); }
void ReFinalize::visitGlobal(Global* curr) { WASM_UNREACHABLE(); }
void ReFinalize::visitTable(Table* curr) { WASM_UNREACHABLE(); }
void ReFinalize::visitMemory(Memory* curr) { WASM_UNREACHABLE(); }
+void ReFinalize::visitEvent(Event* curr) { WASM_UNREACHABLE(); }
void ReFinalize::visitModule(Module* curr) { WASM_UNREACHABLE(); }
void ReFinalize::updateBreakValueType(Name name, Type type) {
diff --git a/src/ir/import-utils.h b/src/ir/import-utils.h
index 950b9bfcb..3f3d27f1b 100644
--- a/src/ir/import-utils.h
+++ b/src/ir/import-utils.h
@@ -29,6 +29,7 @@ struct ImportInfo {
std::vector<Global*> importedGlobals;
std::vector<Function*> importedFunctions;
+ std::vector<Event*> importedEvents;
ImportInfo(Module& wasm) : wasm(wasm) {
for (auto& import : wasm.globals) {
@@ -41,6 +42,11 @@ struct ImportInfo {
importedFunctions.push_back(import.get());
}
}
+ for (auto& import : wasm.events) {
+ if (import->imported()) {
+ importedEvents.push_back(import.get());
+ }
+ }
}
Global* getImportedGlobal(Name module, Name base) {
@@ -61,13 +67,25 @@ struct ImportInfo {
return nullptr;
}
+ Event* getImportedEvent(Name module, Name base) {
+ for (auto* import : importedEvents) {
+ if (import->module == module && import->base == base) {
+ return import;
+ }
+ }
+ return nullptr;
+ }
+
Index getNumImportedGlobals() { return importedGlobals.size(); }
Index getNumImportedFunctions() { return importedFunctions.size(); }
+ Index getNumImportedEvents() { return importedEvents.size(); }
+
Index getNumImports() {
return getNumImportedGlobals() + getNumImportedFunctions() +
- (wasm.memory.imported() ? 1 : 0) + (wasm.table.imported() ? 1 : 0);
+ getNumImportedEvents() + (wasm.memory.imported() ? 1 : 0) +
+ (wasm.table.imported() ? 1 : 0);
}
Index getNumDefinedGlobals() {
@@ -77,6 +95,10 @@ struct ImportInfo {
Index getNumDefinedFunctions() {
return wasm.functions.size() - getNumImportedFunctions();
}
+
+ Index getNumDefinedEvents() {
+ return wasm.events.size() - getNumImportedEvents();
+ }
};
} // namespace wasm
diff --git a/src/ir/module-utils.h b/src/ir/module-utils.h
index 5569843fd..067f59416 100644
--- a/src/ir/module-utils.h
+++ b/src/ir/module-utils.h
@@ -34,6 +34,7 @@ namespace ModuleUtils {
struct BinaryIndexes {
std::unordered_map<Name, Index> functionIndexes;
std::unordered_map<Name, Index> globalIndexes;
+ std::unordered_map<Name, Index> eventIndexes;
BinaryIndexes(Module& wasm) {
auto addGlobal = [&](Global* curr) {
@@ -66,6 +67,21 @@ struct BinaryIndexes {
}
}
assert(functionIndexes.size() == wasm.functions.size());
+ auto addEvent = [&](Event* curr) {
+ auto index = eventIndexes.size();
+ eventIndexes[curr->name] = index;
+ };
+ for (auto& curr : wasm.events) {
+ if (curr->imported()) {
+ addEvent(curr.get());
+ }
+ }
+ for (auto& curr : wasm.events) {
+ if (!curr->imported()) {
+ addEvent(curr.get());
+ }
+ }
+ assert(eventIndexes.size() == wasm.events.size());
}
};
@@ -105,6 +121,16 @@ inline Global* copyGlobal(Global* global, Module& out) {
return ret;
}
+inline Event* copyEvent(Event* event, Module& out) {
+ auto* ret = new Event();
+ ret->name = event->name;
+ ret->attribute = event->attribute;
+ ret->type = event->type;
+ ret->params = event->params;
+ out.addEvent(ret);
+ return ret;
+}
+
inline void copyModule(Module& in, Module& out) {
// we use names throughout, not raw points, so simple copying is fine
// for everything *but* expressions
@@ -120,6 +146,9 @@ inline void copyModule(Module& in, Module& out) {
for (auto& curr : in.globals) {
copyGlobal(curr.get(), out);
}
+ for (auto& curr : in.events) {
+ copyEvent(curr.get(), out);
+ }
out.table = in.table;
for (auto& segment : out.table.segments) {
segment.offset = ExpressionManipulator::copy(segment.offset, out);
@@ -243,6 +272,22 @@ template<typename T> inline void iterDefinedFunctions(Module& wasm, T visitor) {
}
}
+template<typename T> inline void iterImportedEvents(Module& wasm, T visitor) {
+ for (auto& import : wasm.events) {
+ if (import->imported()) {
+ visitor(import.get());
+ }
+ }
+}
+
+template<typename T> inline void iterDefinedEvents(Module& wasm, T visitor) {
+ for (auto& import : wasm.events) {
+ if (!import->imported()) {
+ visitor(import.get());
+ }
+ }
+}
+
} // namespace ModuleUtils
} // namespace wasm
diff --git a/src/ir/utils.h b/src/ir/utils.h
index a8af3ed18..b8e8fe815 100644
--- a/src/ir/utils.h
+++ b/src/ir/utils.h
@@ -154,6 +154,7 @@ struct ReFinalize
void visitGlobal(Global* curr);
void visitTable(Table* curr);
void visitMemory(Memory* curr);
+ void visitEvent(Event* curr);
void visitModule(Module* curr);
private:
@@ -208,6 +209,7 @@ struct ReFinalizeNode : public OverriddenVisitor<ReFinalizeNode> {
void visitGlobal(Global* curr) { WASM_UNREACHABLE(); }
void visitTable(Table* curr) { WASM_UNREACHABLE(); }
void visitMemory(Memory* curr) { WASM_UNREACHABLE(); }
+ void visitEvent(Event* curr) { WASM_UNREACHABLE(); }
void visitModule(Module* curr) { WASM_UNREACHABLE(); }
// given a stack of nested expressions, update them all from child to parent
diff --git a/src/js/binaryen.js-post.js b/src/js/binaryen.js-post.js
index 180d08bb5..d2703e425 100644
--- a/src/js/binaryen.js-post.js
+++ b/src/js/binaryen.js-post.js
@@ -84,6 +84,7 @@ Module['ExternalFunction'] = Module['_BinaryenExternalFunction']();
Module['ExternalTable'] = Module['_BinaryenExternalTable']();
Module['ExternalMemory'] = Module['_BinaryenExternalMemory']();
Module['ExternalGlobal'] = Module['_BinaryenExternalGlobal']();
+Module['ExternalEvent'] = Module['_BinaryenExternalEvent']();
// Features
Module['Features'] = {
@@ -1788,6 +1789,21 @@ function wrapModule(module, self) {
return Module['_BinaryenRemoveGlobal'](module, strToStack(name));
});
}
+ self['addEvent'] = function(name, attribute, eventType) {
+ return preserveStack(function() {
+ return Module['_BinaryenAddEvent'](module, strToStack(name), attribute, eventType);
+ });
+ };
+ self['getEvent'] = function(name) {
+ return preserveStack(function() {
+ return Module['_BinaryenGetEvent'](module, strToStack(name));
+ });
+ };
+ self['removeEvent'] = function(name) {
+ return preserveStack(function() {
+ return Module['_BinaryenRemoveEvent'](module, strToStack(name));
+ });
+ };
self['addFunctionImport'] = function(internalName, externalModuleName, externalBaseName, functionType) {
return preserveStack(function() {
return Module['_BinaryenAddFunctionImport'](module, strToStack(internalName), strToStack(externalModuleName), strToStack(externalBaseName), functionType);
@@ -1808,6 +1824,11 @@ function wrapModule(module, self) {
return Module['_BinaryenAddGlobalImport'](module, strToStack(internalName), strToStack(externalModuleName), strToStack(externalBaseName), globalType);
});
};
+ self['addEventImport'] = function(internalName, externalModuleName, externalBaseName, attribute, eventType) {
+ return preserveStack(function() {
+ return Module['_BinaryenAddEventImport'](module, strToStack(internalName), strToStack(externalModuleName), strToStack(externalBaseName), attribute, eventType);
+ });
+ };
self['addExport'] = // deprecated
self['addFunctionExport'] = function(internalName, externalName) {
return preserveStack(function() {
@@ -1829,6 +1850,11 @@ function wrapModule(module, self) {
return Module['_BinaryenAddGlobalExport'](module, strToStack(internalName), strToStack(externalName));
});
};
+ self['addEventExport'] = function(internalName, externalName) {
+ return preserveStack(function() {
+ return Module['_BinaryenAddEventExport'](module, strToStack(internalName), strToStack(externalName));
+ });
+ };
self['removeExport'] = function(externalName) {
return preserveStack(function() {
return Module['_BinaryenRemoveExport'](module, strToStack(externalName));
@@ -2354,6 +2380,17 @@ Module['getGlobalInfo'] = function(global) {
};
};
+// Obtains information about a 'Event'
+Module['getEventInfo'] = function(event_) {
+ return {
+ 'name': UTF8ToString(Module['_BinaryenEventGetName'](event_)),
+ 'module': UTF8ToString(Module['_BinaryenEventImportGetModule'](event_)),
+ 'base': UTF8ToString(Module['_BinaryenEventImportGetBase'](event_)),
+ 'attribute': Module['_BinaryenEventGetAttribute'](event_),
+ 'type': UTF8ToString(Module['_BinaryenEventGetType'](event_))
+ };
+};
+
// Obtains information about an 'Export'
Module['getExportInfo'] = function(export_) {
return {
diff --git a/src/passes/Metrics.cpp b/src/passes/Metrics.cpp
index af5a62697..a408ccf95 100644
--- a/src/passes/Metrics.cpp
+++ b/src/passes/Metrics.cpp
@@ -66,6 +66,7 @@ struct Metrics
counts["[imports]"] = imports.getNumImports();
counts["[funcs]"] = imports.getNumDefinedFunctions();
counts["[globals]"] = imports.getNumDefinedGlobals();
+ counts["[events]"] = imports.getNumDefinedEvents();
counts["[exports]"] = module->exports.size();
// add memory and table
if (module->memory.exists) {
diff --git a/src/passes/MinifyImportsAndExports.cpp b/src/passes/MinifyImportsAndExports.cpp
index 23dd2a21a..043cfb588 100644
--- a/src/passes/MinifyImportsAndExports.cpp
+++ b/src/passes/MinifyImportsAndExports.cpp
@@ -159,6 +159,7 @@ private:
};
ModuleUtils::iterImportedGlobals(*module, processImport);
ModuleUtils::iterImportedFunctions(*module, processImport);
+ ModuleUtils::iterImportedEvents(*module, processImport);
if (minifyExports) {
// Minify the exported names.
diff --git a/src/passes/Print.cpp b/src/passes/Print.cpp
index fb85023f0..9dbf3cc1f 100644
--- a/src/passes/Print.cpp
+++ b/src/passes/Print.cpp
@@ -1660,6 +1660,9 @@ struct PrintSExpression : public Visitor<PrintSExpression> {
case ExternalKind::Global:
o << "global";
break;
+ case ExternalKind::Event:
+ o << "event";
+ break;
case ExternalKind::Invalid:
WASM_UNREACHABLE();
}
@@ -1805,6 +1808,25 @@ struct PrintSExpression : public Visitor<PrintSExpression> {
}
o << maybeNewLine;
}
+ void visitEvent(Event* curr) {
+ doIndent(o, indent);
+ if (curr->imported()) {
+ o << '(';
+ emitImportHeader(curr);
+ }
+ o << "(event ";
+ printName(curr->name, o);
+ o << maybeSpace << "(attr " << curr->attribute << ')' << maybeSpace << '(';
+ printMinor(o, "param");
+ for (auto& param : curr->params) {
+ o << ' ' << printType(param);
+ }
+ o << "))";
+ if (curr->imported()) {
+ o << ')';
+ }
+ o << maybeNewLine;
+ }
void printTableHeader(Table* curr) {
o << '(';
printMedium(o, "table") << ' ';
@@ -1948,12 +1970,16 @@ struct PrintSExpression : public Visitor<PrintSExpression> {
*curr, [&](Global* global) { visitGlobal(global); });
ModuleUtils::iterImportedFunctions(
*curr, [&](Function* func) { visitFunction(func); });
+ ModuleUtils::iterImportedEvents(*curr,
+ [&](Event* event) { visitEvent(event); });
ModuleUtils::iterDefinedMemories(
*curr, [&](Memory* memory) { visitMemory(memory); });
ModuleUtils::iterDefinedTables(*curr,
[&](Table* table) { visitTable(table); });
ModuleUtils::iterDefinedGlobals(
*curr, [&](Global* global) { visitGlobal(global); });
+ ModuleUtils::iterDefinedEvents(*curr,
+ [&](Event* event) { visitEvent(event); });
for (auto& child : curr->exports) {
doIndent(o, indent);
visitExport(child.get());
diff --git a/src/passes/RemoveUnusedModuleElements.cpp b/src/passes/RemoveUnusedModuleElements.cpp
index c96ce1a8c..20c30d271 100644
--- a/src/passes/RemoveUnusedModuleElements.cpp
+++ b/src/passes/RemoveUnusedModuleElements.cpp
@@ -15,9 +15,9 @@
*/
//
-// Removes module elements that are are never used: functions and globals,
-// which may be imported or not, and function types (which we merge
-// and remove if unneeded)
+// Removes module elements that are are never used: functions, globals, and
+// events, which may be imported or not, and function types (which we merge and
+// remove if unneeded)
//
#include <memory>
@@ -30,7 +30,7 @@
namespace wasm {
-enum class ModuleElementKind { Function, Global };
+enum class ModuleElementKind { Function, Global, Event };
typedef std::pair<ModuleElementKind, Name> ModuleElement;
@@ -68,7 +68,7 @@ struct ReachabilityAnalyzer : public PostWalker<ReachabilityAnalyzer> {
if (!func->imported()) {
walk(func->body);
}
- } else {
+ } else if (curr.first == ModuleElementKind::Global) {
// if not imported, it has an init expression we need to walk
auto* global = module->getGlobal(curr.second);
if (!global->imported()) {
@@ -122,6 +122,7 @@ struct ReachabilityAnalyzer : public PostWalker<ReachabilityAnalyzer> {
struct FunctionTypeAnalyzer : public PostWalker<FunctionTypeAnalyzer> {
std::vector<Function*> functions;
std::vector<CallIndirect*> indirectCalls;
+ std::vector<Event*> events;
void visitFunction(Function* curr) {
if (curr->type.is()) {
@@ -129,6 +130,8 @@ struct FunctionTypeAnalyzer : public PostWalker<FunctionTypeAnalyzer> {
}
}
+ void visitEvent(Event* curr) { events.push_back(curr); }
+
void visitCallIndirect(CallIndirect* curr) { indirectCalls.push_back(curr); }
};
@@ -139,11 +142,11 @@ struct RemoveUnusedModuleElements : public Pass {
: rootAllFunctions(rootAllFunctions) {}
void run(PassRunner* runner, Module* module) override {
- optimizeGlobalsAndFunctions(module);
+ optimizeGlobalsAndFunctionsAndEvents(module);
optimizeFunctionTypes(module);
}
- void optimizeGlobalsAndFunctions(Module* module) {
+ void optimizeGlobalsAndFunctionsAndEvents(Module* module) {
std::vector<ModuleElement> roots;
// Module start is a root.
if (module->start.is()) {
@@ -169,6 +172,8 @@ struct RemoveUnusedModuleElements : public Pass {
roots.emplace_back(ModuleElementKind::Function, curr->value);
} else if (curr->kind == ExternalKind::Global) {
roots.emplace_back(ModuleElementKind::Global, curr->value);
+ } else if (curr->kind == ExternalKind::Event) {
+ roots.emplace_back(ModuleElementKind::Event, curr->value);
} else if (curr->kind == ExternalKind::Memory) {
exportsMemory = true;
} else if (curr->kind == ExternalKind::Table) {
@@ -215,6 +220,17 @@ struct RemoveUnusedModuleElements : public Pass {
}),
v.end());
}
+ {
+ auto& v = module->events;
+ v.erase(std::remove_if(v.begin(),
+ v.end(),
+ [&](const std::unique_ptr<Event>& curr) {
+ return analyzer.reachable.count(
+ ModuleElement(ModuleElementKind::Event,
+ curr->name)) == 0;
+ }),
+ v.end());
+ }
module->updateMaps();
// Handle the memory and table
if (!exportsMemory && !analyzer.usesMemory) {
@@ -272,6 +288,9 @@ struct RemoveUnusedModuleElements : public Pass {
for (auto* call : analyzer.indirectCalls) {
call->fullType = canonicalize(call->fullType);
}
+ for (auto* event : analyzer.events) {
+ event->type = canonicalize(event->type);
+ }
// remove no-longer used types
module->functionTypes.erase(
std::remove_if(module->functionTypes.begin(),
diff --git a/src/shared-constants.h b/src/shared-constants.h
index 9e119dc95..9fb84dbf8 100644
--- a/src/shared-constants.h
+++ b/src/shared-constants.h
@@ -62,6 +62,8 @@ extern Name SPECTEST;
extern Name PRINT;
extern Name EXIT;
extern Name SHARED;
+extern Name EVENT;
+extern Name ATTR;
} // namespace wasm
diff --git a/src/tools/fuzzing.h b/src/tools/fuzzing.h
index f7dd20e76..0a7128e3e 100644
--- a/src/tools/fuzzing.h
+++ b/src/tools/fuzzing.h
@@ -197,6 +197,9 @@ public:
}
setupTable();
setupGlobals();
+ if (wasm.features.hasExceptionHandling()) {
+ setupEvents();
+ }
addImportLoggingSupport();
// keep adding functions until we run out of input
while (!finishedInput) {
@@ -397,6 +400,28 @@ private:
}
}
+ void setupEvents() {
+ Index num = upTo(3);
+ for (size_t i = 0; i < num; i++) {
+ // Events should have void return type and at least one param type
+ Type type = pick(i32, i64, f32, f64);
+ std::string sig = std::string("v") + getSig(type);
+ std::vector<Type> params;
+ params.push_back(type);
+ Index numValues = upToSquared(MAX_PARAMS - 1);
+ for (Index i = 0; i < numValues; i++) {
+ type = pick(i32, i64, f32, f64);
+ sig += getSig(type);
+ params.push_back(type);
+ }
+ auto* event = builder.makeEvent(std::string("event$") + std::to_string(i),
+ WASM_EVENT_ATTRIBUTE_EXCEPTION,
+ ensureFunctionType(sig, &wasm)->name,
+ std::move(params));
+ wasm.addEvent(event);
+ }
+ }
+
void finalizeTable() {
wasm.table.initial = wasm.table.segments[0].data.size();
wasm.table.max =
diff --git a/src/tools/wasm-metadce.cpp b/src/tools/wasm-metadce.cpp
index c04286f59..96b368bc4 100644
--- a/src/tools/wasm-metadce.cpp
+++ b/src/tools/wasm-metadce.cpp
@@ -55,10 +55,12 @@ struct MetaDCEGraph {
std::unordered_map<Name, Name> exportToDCENode;
std::unordered_map<Name, Name> functionToDCENode; // function name => DCE name
std::unordered_map<Name, Name> globalToDCENode; // global name => DCE name
+ std::unordered_map<Name, Name> eventToDCENode; // event name => DCE name
std::unordered_map<Name, Name> DCENodeToExport; // reverse maps
std::unordered_map<Name, Name> DCENodeToFunction;
std::unordered_map<Name, Name> DCENodeToGlobal;
+ std::unordered_map<Name, Name> DCENodeToEvent;
// imports are not mapped 1:1 to DCE nodes in the wasm, since env.X might
// be imported twice, for example. So we don't map a DCE node to an Import,
@@ -80,6 +82,11 @@ struct MetaDCEGraph {
return getImportId(imp->module, imp->base);
}
+ ImportId getEventImportId(Name name) {
+ auto* imp = wasm.getEvent(name);
+ return getImportId(imp->module, imp->base);
+ }
+
// import module.base => DCE name
std::unordered_map<Name, Name> importIdToDCENode;
@@ -106,8 +113,14 @@ struct MetaDCEGraph {
globalToDCENode[global->name] = dceName;
nodes[dceName] = DCENode(dceName);
});
- // only process function and global imports - the table and memory are
- // always there
+ ModuleUtils::iterDefinedEvents(wasm, [&](Event* event) {
+ auto dceName = getName("event", event->name.str);
+ DCENodeToEvent[dceName] = event->name;
+ eventToDCENode[event->name] = dceName;
+ nodes[dceName] = DCENode(dceName);
+ });
+ // only process function, global, and event imports - the table and memory
+ // are always there
ModuleUtils::iterImportedFunctions(wasm, [&](Function* import) {
auto id = getImportId(import->module, import->base);
if (importIdToDCENode.find(id) == importIdToDCENode.end()) {
@@ -122,6 +135,13 @@ struct MetaDCEGraph {
importIdToDCENode[id] = dceName;
}
});
+ ModuleUtils::iterImportedEvents(wasm, [&](Event* import) {
+ auto id = getImportId(import->module, import->base);
+ if (importIdToDCENode.find(id) == importIdToDCENode.end()) {
+ auto dceName = getName("importId", import->name.str);
+ importIdToDCENode[id] = dceName;
+ }
+ });
for (auto& exp : wasm.exports) {
if (exportToDCENode.find(exp->name) == exportToDCENode.end()) {
auto dceName = getName("export", exp->name.str);
@@ -145,6 +165,13 @@ struct MetaDCEGraph {
node.reaches.push_back(
importIdToDCENode[getGlobalImportId(exp->value)]);
}
+ } else if (exp->kind == ExternalKind::Event) {
+ if (!wasm.getEvent(exp->value)->imported()) {
+ node.reaches.push_back(eventToDCENode[exp->value]);
+ } else {
+ node.reaches.push_back(
+ importIdToDCENode[getEventImportId(exp->value)]);
+ }
}
}
// Add initializer dependencies
@@ -355,6 +382,9 @@ public:
if (DCENodeToGlobal.find(name) != DCENodeToGlobal.end()) {
std::cout << " is global " << DCENodeToGlobal[name] << '\n';
}
+ if (DCENodeToEvent.find(name) != DCENodeToEvent.end()) {
+ std::cout << " is event " << DCENodeToEvent[name] << '\n';
+ }
for (auto target : node.reaches) {
std::cout << " reaches: " << target.str << '\n';
}
diff --git a/src/wasm-binary.h b/src/wasm-binary.h
index ce3144715..e2323967e 100644
--- a/src/wasm-binary.h
+++ b/src/wasm-binary.h
@@ -363,6 +363,7 @@ enum Section {
Code = 10,
Data = 11,
DataCount = 12,
+ Event = 13
};
enum SegmentFlag {
@@ -948,13 +949,18 @@ public:
void writeExports();
void writeDataCount();
void writeDataSegments();
+ void writeEvents();
// name of the Function => index. first imports, then internals
std::unordered_map<Name, Index> mappedFunctions;
// name of the Global => index. first imported globals, then internal globals
std::unordered_map<Name, uint32_t> mappedGlobals;
+ // name of the Event => index. first imported events, then internal events
+ std::unordered_map<Name, uint32_t> mappedEvents;
+
uint32_t getFunctionIndex(Name name);
uint32_t getGlobalIndex(Name name);
+ uint32_t getEventIndex(Name name);
void writeFunctionTableDeclaration();
void writeTableElements();
@@ -1071,6 +1077,7 @@ public:
// gets a name in the combined import+defined space
Name getFunctionName(Index index);
Name getGlobalName(Index index);
+ Name getEventName(Index index);
void getResizableLimits(Address& initial,
Address& max,
@@ -1165,6 +1172,9 @@ public:
void readFunctionTableDeclaration();
void readTableElements();
+
+ void readEvents();
+
void readNames(size_t);
void readFeatures(size_t);
diff --git a/src/wasm-builder.h b/src/wasm-builder.h
index 0b7326b6e..284608105 100644
--- a/src/wasm-builder.h
+++ b/src/wasm-builder.h
@@ -683,6 +683,19 @@ public:
glob->mutable_ = mutable_ == Mutable;
return glob;
}
+
+ // TODO Remove 'type' parameter once we remove FunctionType
+ static Event* makeEvent(Name name,
+ uint32_t attribute,
+ Name type,
+ std::vector<Type>&& params) {
+ auto* event = new Event;
+ event->name = name;
+ event->attribute = attribute;
+ event->type = type;
+ event->params = params;
+ return event;
+ }
};
} // namespace wasm
diff --git a/src/wasm-s-parser.h b/src/wasm-s-parser.h
index d501a349a..71249748e 100644
--- a/src/wasm-s-parser.h
+++ b/src/wasm-s-parser.h
@@ -113,8 +113,10 @@ class SExpressionWasmBuilder {
MixedArena& allocator;
std::vector<Name> functionNames;
std::vector<Name> globalNames;
- int functionCounter;
+ std::vector<Name> eventNames;
+ int functionCounter = 0;
int globalCounter = 0;
+ int eventCounter = 0;
// we need to know function return types before we parse their contents
std::map<Name, Type> functionTypes;
std::unordered_map<cashew::IString, Index> debugInfoFileIndices;
@@ -142,6 +144,7 @@ private:
Name getFunctionName(Element& s);
Name getFunctionTypeName(Element& s);
Name getGlobalName(Element& s);
+ Name getEventName(Element& s);
void parseStart(Element& s) { wasm.addStart(getFunctionName(*s[1])); }
// returns the next index in s
@@ -247,6 +250,7 @@ private:
void parseElem(Element& s);
void parseInnerElem(Element& s, Index i = 1, Expression* offset = nullptr);
void parseType(Element& s);
+ void parseEvent(Element& s, bool preParseImport = false);
Function::DebugLocation getDebugLocation(const SourceLocation& loc);
};
diff --git a/src/wasm-traversal.h b/src/wasm-traversal.h
index 73f57a538..f1306721e 100644
--- a/src/wasm-traversal.h
+++ b/src/wasm-traversal.h
@@ -79,6 +79,7 @@ template<typename SubType, typename ReturnType = void> struct Visitor {
ReturnType visitFunction(Function* curr) { return ReturnType(); }
ReturnType visitTable(Table* curr) { return ReturnType(); }
ReturnType visitMemory(Memory* curr) { return ReturnType(); }
+ ReturnType visitEvent(Event* curr) { return ReturnType(); }
ReturnType visitModule(Module* curr) { return ReturnType(); }
ReturnType visit(Expression* curr) {
@@ -223,6 +224,7 @@ struct OverriddenVisitor {
UNIMPLEMENTED(Function);
UNIMPLEMENTED(Table);
UNIMPLEMENTED(Memory);
+ UNIMPLEMENTED(Event);
UNIMPLEMENTED(Module);
#undef UNIMPLEMENTED
@@ -486,6 +488,10 @@ struct Walker : public VisitorType {
setFunction(nullptr);
}
+ void walkEvent(Event* event) {
+ static_cast<SubType*>(this)->visitEvent(event);
+ }
+
void walkFunctionInModule(Function* func, Module* module) {
setModule(module);
setFunction(func);
@@ -545,6 +551,13 @@ struct Walker : public VisitorType {
self->walkFunction(curr.get());
}
}
+ for (auto& curr : module->events) {
+ if (curr->imported()) {
+ self->visitEvent(curr.get());
+ } else {
+ self->walkEvent(curr.get());
+ }
+ }
self->walkTable(&module->table);
self->walkMemory(&module->memory);
}
diff --git a/src/wasm.h b/src/wasm.h
index d4ffe86f2..de3289289 100644
--- a/src/wasm.h
+++ b/src/wasm.h
@@ -1063,6 +1063,7 @@ enum class ExternalKind {
Table = 1,
Memory = 2,
Global = 3,
+ Event = 4,
Invalid = -1
};
@@ -1156,6 +1157,24 @@ public:
bool mutable_ = false;
};
+// Kinds of event attributes.
+enum WasmEventAttribute : unsigned { WASM_EVENT_ATTRIBUTE_EXCEPTION = 0x0 };
+
+class Event : public Importable {
+public:
+ Name name;
+ // Kind of event. Currently only WASM_EVENT_ATTRIBUTE_EXCEPTION is possible.
+ uint32_t attribute;
+ // Type string in the format of function type. Return type is considered as a
+ // void type. So if you have an event whose type is (i32, i32), the type
+ // string will be "vii".
+ Name type;
+ // This is duplicate info of 'Name type', but we store this anyway because
+ // we plan to remove FunctionType in future.
+ // TODO remove either this or FunctionType
+ std::vector<Type> params;
+};
+
// "Opaque" data, not part of the core wasm spec, that is held in binaries.
// May be parsed/handled by utility code elsewhere, but not in wasm.h
class UserSection {
@@ -1172,6 +1191,7 @@ public:
std::vector<std::unique_ptr<Export>> exports;
std::vector<std::unique_ptr<Function>> functions;
std::vector<std::unique_ptr<Global>> globals;
+ std::vector<std::unique_ptr<Event>> events;
Table table;
Memory memory;
@@ -1197,6 +1217,7 @@ private:
std::map<Name, Export*> exportsMap;
std::map<Name, Function*> functionsMap;
std::map<Name, Global*> globalsMap;
+ std::map<Name, Event*> eventsMap;
public:
Module() = default;
@@ -1205,17 +1226,20 @@ public:
Export* getExport(Name name);
Function* getFunction(Name name);
Global* getGlobal(Name name);
+ Event* getEvent(Name name);
FunctionType* getFunctionTypeOrNull(Name name);
Export* getExportOrNull(Name name);
Function* getFunctionOrNull(Name name);
Global* getGlobalOrNull(Name name);
+ Event* getEventOrNull(Name name);
FunctionType* addFunctionType(std::unique_ptr<FunctionType> curr);
Export* addExport(Export* curr);
Function* addFunction(Function* curr);
Function* addFunction(std::unique_ptr<Function> curr);
Global* addGlobal(Global* curr);
+ Event* addEvent(Event* curr);
void addStart(const Name& s);
@@ -1223,6 +1247,7 @@ public:
void removeExport(Name name);
void removeFunction(Name name);
void removeGlobal(Name name);
+ void removeEvent(Name name);
void updateMaps();
diff --git a/src/wasm/wasm-binary.cpp b/src/wasm/wasm-binary.cpp
index d8ce18de5..91a2184e9 100644
--- a/src/wasm/wasm-binary.cpp
+++ b/src/wasm/wasm-binary.cpp
@@ -37,6 +37,7 @@ void WasmBinaryWriter::prepare() {
ModuleUtils::BinaryIndexes indexes(*wasm);
mappedFunctions = std::move(indexes.functionIndexes);
mappedGlobals = std::move(indexes.globalIndexes);
+ mappedEvents = std::move(indexes.eventIndexes);
importInfo = wasm::make_unique<ImportInfo>(*wasm);
}
@@ -63,6 +64,7 @@ void WasmBinaryWriter::write() {
writeDataCount();
writeFunctions();
writeDataSegments();
+ writeEvents();
if (debugInfo) {
writeNames();
}
@@ -245,6 +247,15 @@ void WasmBinaryWriter::writeImports() {
o << binaryType(global->type);
o << U32LEB(global->mutable_);
});
+ ModuleUtils::iterImportedEvents(*wasm, [&](Event* event) {
+ if (debug) {
+ std::cerr << "write one event" << std::endl;
+ }
+ writeImportHeader(event);
+ o << U32LEB(int32_t(ExternalKind::Event));
+ o << U32LEB(event->attribute);
+ o << U32LEB(getFunctionTypeIndex(event->type));
+ });
if (wasm->memory.imported()) {
if (debug) {
std::cerr << "write one memory" << std::endl;
@@ -401,6 +412,9 @@ void WasmBinaryWriter::writeExports() {
case ExternalKind::Global:
o << U32LEB(getGlobalIndex(curr->value));
break;
+ case ExternalKind::Event:
+ o << U32LEB(getEventIndex(curr->value));
+ break;
default:
WASM_UNREACHABLE();
}
@@ -453,6 +467,11 @@ uint32_t WasmBinaryWriter::getGlobalIndex(Name name) {
return mappedGlobals[name];
}
+uint32_t WasmBinaryWriter::getEventIndex(Name name) {
+ assert(mappedEvents.count(name));
+ return mappedEvents[name];
+}
+
void WasmBinaryWriter::writeFunctionTableDeclaration() {
if (!wasm->table.exists || wasm->table.imported()) {
return;
@@ -493,6 +512,27 @@ void WasmBinaryWriter::writeTableElements() {
finishSection(start);
}
+void WasmBinaryWriter::writeEvents() {
+ if (importInfo->getNumDefinedEvents() == 0) {
+ return;
+ }
+ if (debug) {
+ std::cerr << "== writeEvents" << std::endl;
+ }
+ auto start = startSection(BinaryConsts::Section::Event);
+ auto num = importInfo->getNumDefinedEvents();
+ o << U32LEB(num);
+ ModuleUtils::iterDefinedEvents(*wasm, [&](Event* event) {
+ if (debug) {
+ std::cerr << "write one" << std::endl;
+ }
+ o << U32LEB(event->attribute);
+ o << U32LEB(getFunctionTypeIndex(event->type));
+ });
+
+ finishSection(start);
+}
+
void WasmBinaryWriter::writeNames() {
bool hasContents = false;
if (wasm->functions.size() > 0) {
@@ -828,6 +868,9 @@ void WasmBinaryBuilder::read() {
case BinaryConsts::Section::Table:
readFunctionTableDeclaration();
break;
+ case BinaryConsts::Section::Event:
+ readEvents();
+ break;
default: {
readUserSection(payloadLen);
if (pos > oldPos + payloadLen) {
@@ -1210,6 +1253,13 @@ Name WasmBinaryBuilder::getGlobalName(Index index) {
return wasm.globals[index]->name;
}
+Name WasmBinaryBuilder::getEventName(Index index) {
+ if (index >= wasm.events.size()) {
+ throwError("invalid event index");
+ }
+ return wasm.events[index]->name;
+}
+
void WasmBinaryBuilder::getResizableLimits(Address& initial,
Address& max,
bool& shared,
@@ -1310,6 +1360,23 @@ void WasmBinaryBuilder::readImports() {
wasm.addGlobal(curr);
break;
}
+ case ExternalKind::Event: {
+ auto name = Name(std::string("eimport$") + std::to_string(i));
+ auto attribute = getU32LEB();
+ auto index = getU32LEB();
+ if (index >= wasm.functionTypes.size()) {
+ throwError("invalid event index " + std::to_string(index) + " / " +
+ std::to_string(wasm.functionTypes.size()));
+ }
+ Name type = wasm.functionTypes[index]->name;
+ std::vector<Type> params = wasm.functionTypes[index]->params;
+ auto* curr =
+ builder.makeEvent(name, attribute, type, std::move(params));
+ curr->module = module;
+ curr->base = base;
+ wasm.addEvent(curr);
+ break;
+ }
default: { throwError("bad import kind"); }
}
}
@@ -1841,6 +1908,9 @@ void WasmBinaryBuilder::processFunctions() {
case ExternalKind::Global:
curr->value = getGlobalName(index);
break;
+ case ExternalKind::Event:
+ curr->value = getEventName(index);
+ break;
default:
throwError("bad export kind");
}
@@ -1954,6 +2024,31 @@ void WasmBinaryBuilder::readTableElements() {
}
}
+void WasmBinaryBuilder::readEvents() {
+ if (debug) {
+ std::cerr << "== readEvents" << std::endl;
+ }
+ size_t numEvents = getU32LEB();
+ if (debug) {
+ std::cerr << "num: " << numEvents << std::endl;
+ }
+ for (size_t i = 0; i < numEvents; i++) {
+ if (debug) {
+ std::cerr << "read one" << std::endl;
+ }
+ auto attribute = getU32LEB();
+ auto typeIndex = getU32LEB();
+ if (typeIndex >= wasm.functionTypes.size()) {
+ throwError("invalid event index " + std::to_string(typeIndex) + " / " +
+ std::to_string(wasm.functionTypes.size()));
+ }
+ Name type = wasm.functionTypes[typeIndex]->name;
+ std::vector<Type> params = wasm.functionTypes[typeIndex]->params;
+ wasm.addEvent(Builder::makeEvent(
+ "event$" + std::to_string(i), attribute, type, std::move(params)));
+ }
+}
+
static bool isIdChar(char ch) {
return (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') ||
(ch >= 'a' && ch <= 'z') || ch == '!' || ch == '#' || ch == '$' ||
diff --git a/src/wasm/wasm-s-parser.cpp b/src/wasm/wasm-s-parser.cpp
index 3a5dfbced..8ead42608 100644
--- a/src/wasm/wasm-s-parser.cpp
+++ b/src/wasm/wasm-s-parser.cpp
@@ -388,6 +388,8 @@ void SExpressionWasmBuilder::preParseImports(Element& curr) {
parseTable(curr, true /* preParseImport */);
} else if (id == MEMORY) {
parseMemory(curr, true /* preParseImport */);
+ } else if (id == EVENT) {
+ parseEvent(curr, true /* preParseImport */);
} else {
throw ParseException(
"fancy import we don't support yet", curr.line, curr.col);
@@ -430,6 +432,9 @@ void SExpressionWasmBuilder::parseModuleElement(Element& curr) {
if (id == TYPE) {
return; // already done
}
+ if (id == EVENT) {
+ return parseEvent(curr);
+ }
std::cerr << "bad module element " << id.str << '\n';
throw ParseException("unknown module element", curr.line, curr.col);
}
@@ -473,6 +478,19 @@ Name SExpressionWasmBuilder::getGlobalName(Element& s) {
}
}
+Name SExpressionWasmBuilder::getEventName(Element& s) {
+ if (s.dollared()) {
+ return s.str();
+ } else {
+ // index
+ size_t offset = atoi(s.str().c_str());
+ if (offset >= eventNames.size()) {
+ throw ParseException("unknown event in getEventName");
+ }
+ return eventNames[offset];
+ }
+}
+
// Parse various forms of (param ...) or (local ...) element. This ignores all
// parameter or local names when specified.
std::vector<Type> SExpressionWasmBuilder::parseParamOrLocal(Element& s) {
@@ -1877,6 +1895,8 @@ void SExpressionWasmBuilder::parseExport(Element& s) {
ex->kind = ExternalKind::Table;
} else if (elementStartsWith(inner, GLOBAL)) {
ex->kind = ExternalKind::Global;
+ } else if (inner[0]->str() == EVENT) {
+ ex->kind = ExternalKind::Event;
} else {
throw ParseException("invalid export");
}
@@ -1913,6 +1933,8 @@ void SExpressionWasmBuilder::parseImport(Element& s) {
wasm.table.exists = true;
} else if (elementStartsWith(*s[3], GLOBAL)) {
kind = ExternalKind::Global;
+ } else if ((*s[3])[0]->str() == EVENT) {
+ kind = ExternalKind::Event;
} else {
newStyle = false; // either (param..) or (result..)
}
@@ -1936,6 +1958,9 @@ void SExpressionWasmBuilder::parseImport(Element& s) {
name = Name("import$memory$" + std::to_string(0));
} else if (kind == ExternalKind::Table) {
name = Name("import$table$" + std::to_string(0));
+ } else if (kind == ExternalKind::Event) {
+ name = Name("import$event" + std::to_string(eventCounter++));
+ eventNames.push_back(name);
} else {
throw ParseException("invalid import");
}
@@ -1957,7 +1982,7 @@ void SExpressionWasmBuilder::parseImport(Element& s) {
if (kind == ExternalKind::Function) {
FunctionType* functionType = nullptr;
auto func = make_unique<Function>();
- parseTypeUse(inner, j, functionType, func->params, func->result);
+ j = parseTypeUse(inner, j, functionType, func->params, func->result);
func->name = name;
func->module = module;
func->base = base;
@@ -1968,9 +1993,9 @@ void SExpressionWasmBuilder::parseImport(Element& s) {
Type type;
bool mutable_ = false;
if (inner[j]->isStr()) {
- type = stringToType(inner[j]->str());
+ type = stringToType(inner[j++]->str());
} else {
- auto& inner2 = *inner[j];
+ auto& inner2 = *inner[j++];
if (inner2[0]->str() != MUT) {
throw ParseException("expected mut");
}
@@ -1997,6 +2022,7 @@ void SExpressionWasmBuilder::parseImport(Element& s) {
} else {
wasm.table.max = Table::kUnlimitedSize;
}
+ j++; // funcref
// ends with the table element type
} else if (kind == ExternalKind::Memory) {
wasm.memory.module = module;
@@ -2007,10 +2033,32 @@ void SExpressionWasmBuilder::parseImport(Element& s) {
throw ParseException("bad memory limit declaration");
}
wasm.memory.shared = true;
- parseMemoryLimits(limits, 1);
+ j = parseMemoryLimits(limits, 1);
} else {
- parseMemoryLimits(inner, j);
+ j = parseMemoryLimits(inner, j);
+ }
+ } else if (kind == ExternalKind::Event) {
+ FunctionType* functionType = nullptr;
+ auto event = make_unique<Event>();
+ if (j >= inner.size()) {
+ throw ParseException("event does not have an attribute", s.line, s.col);
+ }
+ auto& attrElem = *inner[j++];
+ if (!elementStartsWith(attrElem, ATTR) || attrElem.size() != 2) {
+ throw ParseException("invalid attribute", attrElem.line, attrElem.col);
}
+ event->attribute = atoi(attrElem[1]->c_str());
+ Type fakeResult; // just to call parseTypeUse
+ j = parseTypeUse(inner, j, functionType, event->params, fakeResult);
+ event->name = name;
+ event->module = module;
+ event->base = base;
+ event->type = functionType->name;
+ wasm.addEvent(event.release());
+ }
+ // If there are more elements, they are invalid
+ if (j < inner.size()) {
+ throw ParseException("invalid element", inner[j]->line, inner[j]->col);
}
}
@@ -2234,4 +2282,95 @@ void SExpressionWasmBuilder::parseType(Element& s) {
wasm.addFunctionType(std::move(type));
}
+void SExpressionWasmBuilder::parseEvent(Element& s, bool preParseImport) {
+ auto event = make_unique<Event>();
+ size_t i = 1;
+
+ // Parse name
+ if (s[i]->isStr() && s[i]->dollared()) {
+ auto& inner = *s[i++];
+ event->name = inner.str();
+ if (wasm.getEventOrNull(event->name)) {
+ throw ParseException("duplicate event", inner.line, inner.col);
+ }
+ } else {
+ event->name = Name::fromInt(eventCounter);
+ assert(!wasm.getEventOrNull(event->name));
+ }
+ eventCounter++;
+ eventNames.push_back(event->name);
+
+ // Parse import, if any
+ if (i < s.size() && elementStartsWith(*s[i], IMPORT)) {
+ assert(preParseImport && "import element in non-preParseImport mode");
+ auto& importElem = *s[i++];
+ if (importElem.size() != 3) {
+ throw ParseException("invalid import", importElem.line, importElem.col);
+ }
+ if (!importElem[1]->isStr() || importElem[1]->dollared()) {
+ throw ParseException(
+ "invalid import module name", importElem[1]->line, importElem[1]->col);
+ }
+ if (!importElem[2]->isStr() || importElem[2]->dollared()) {
+ throw ParseException(
+ "invalid import base name", importElem[2]->line, importElem[2]->col);
+ }
+ event->module = importElem[1]->str();
+ event->base = importElem[2]->str();
+ }
+
+ // Parse export, if any
+ if (i < s.size() && elementStartsWith(*s[i], EXPORT)) {
+ auto& exportElem = *s[i++];
+ if (event->module.is()) {
+ throw ParseException("import and export cannot be specified together",
+ exportElem.line,
+ exportElem.col);
+ }
+ if (exportElem.size() != 2) {
+ throw ParseException("invalid export", exportElem.line, exportElem.col);
+ }
+ if (!exportElem[1]->isStr() || exportElem[1]->dollared()) {
+ throw ParseException(
+ "invalid export name", exportElem[1]->line, exportElem[1]->col);
+ }
+ auto ex = make_unique<Export>();
+ ex->name = exportElem[1]->str();
+ if (wasm.getExportOrNull(ex->name)) {
+ throw ParseException(
+ "duplicate export", exportElem[1]->line, exportElem[1]->col);
+ }
+ ex->value = event->name;
+ ex->kind = ExternalKind::Event;
+ }
+
+ // Parse attribute
+ if (i >= s.size()) {
+ throw ParseException("event does not have an attribute", s.line, s.col);
+ }
+ auto& attrElem = *s[i++];
+ if (!elementStartsWith(attrElem, ATTR) || attrElem.size() != 2) {
+ throw ParseException("invalid attribute", attrElem.line, attrElem.col);
+ }
+ if (!attrElem[1]->isStr()) {
+ throw ParseException(
+ "invalid attribute", attrElem[1]->line, attrElem[1]->col);
+ }
+ event->attribute = atoi(attrElem[1]->c_str());
+
+ // Parse typeuse
+ FunctionType* functionType = nullptr;
+ Type fakeResult; // just co call parseTypeUse
+ i = parseTypeUse(s, i, functionType, event->params, fakeResult);
+ assert(functionType && "functionType should've been set by parseTypeUse");
+ event->type = functionType->name;
+
+ // If there are more elements, they are invalid
+ if (i < s.size()) {
+ throw ParseException("invalid element", s[i]->line, s[i]->col);
+ }
+
+ wasm.addEvent(event.release());
+}
+
} // namespace wasm
diff --git a/src/wasm/wasm-type.cpp b/src/wasm/wasm-type.cpp
index ebaba3f24..2c2723bf6 100644
--- a/src/wasm/wasm-type.cpp
+++ b/src/wasm/wasm-type.cpp
@@ -68,6 +68,9 @@ FeatureSet getFeatures(Type type) {
if (type == v128) {
return FeatureSet::SIMD;
}
+ if (type == except_ref) {
+ return FeatureSet::ExceptionHandling;
+ }
return FeatureSet();
}
diff --git a/src/wasm/wasm-validator.cpp b/src/wasm/wasm-validator.cpp
index 01fe7e976..1d12c2452 100644
--- a/src/wasm/wasm-validator.cpp
+++ b/src/wasm/wasm-validator.cpp
@@ -1745,6 +1745,10 @@ static void validateExports(Module& module, ValidationInfo& info) {
info.shouldBeTrue(name == Name("0") || name == module.memory.name,
name,
"module memory exports must be found");
+ } else if (exp->kind == ExternalKind::Event) {
+ info.shouldBeTrue(module.getEventOrNull(name),
+ name,
+ "module event exports must be found");
} else {
WASM_UNREACHABLE();
}
@@ -1855,6 +1859,36 @@ static void validateTable(Module& module, ValidationInfo& info) {
}
}
+static void validateEvents(Module& module, ValidationInfo& info) {
+ if (!module.events.empty()) {
+ info.shouldBeTrue(module.features.hasExceptionHandling(),
+ module.events[0]->name,
+ "Module has events (event-handling is disabled)");
+ }
+ for (auto& curr : module.events) {
+ info.shouldBeTrue(
+ curr->type.is(), curr->name, "Event should have a valid type");
+ FunctionType* ft = module.getFunctionType(curr->type);
+ info.shouldBeEqual(
+ ft->result, none, curr->name, "Event type's result type should be none");
+ info.shouldBeTrue(!curr->params.empty(),
+ curr->name,
+ "There should be 1 or more values in an event type");
+ info.shouldBeEqual(curr->attribute,
+ (unsigned)0,
+ curr->attribute,
+ "Currently only attribute 0 is supported");
+ for (auto type : curr->params) {
+ info.shouldBeTrue(isIntegerType(type) || isFloatType(type),
+ curr->name,
+ "Values in an event should have integer or float type");
+ }
+ info.shouldBeTrue(curr->params == ft->params,
+ curr->name,
+ "Event's function type and internal type should match");
+ }
+}
+
static void validateModule(Module& module, ValidationInfo& info) {
// start
if (module.start.is()) {
@@ -1889,6 +1923,7 @@ bool WasmValidator::validate(Module& module, Flags flags) {
validateGlobals(module, info);
validateMemory(module, info);
validateTable(module, info);
+ validateEvents(module, info);
validateModule(module, info);
}
// validate additional internal IR details when in pass-debug mode
diff --git a/src/wasm/wasm.cpp b/src/wasm/wasm.cpp
index c32ead836..c543686ed 100644
--- a/src/wasm/wasm.cpp
+++ b/src/wasm/wasm.cpp
@@ -82,6 +82,8 @@ Name SPECTEST("spectest");
Name PRINT("print");
Name EXIT("exit");
Name SHARED("shared");
+Name EVENT("event");
+Name ATTR("attr");
// Expressions
@@ -908,11 +910,20 @@ Function* Module::getFunction(Name name) {
Global* Module::getGlobal(Name name) {
auto iter = globalsMap.find(name);
if (iter == globalsMap.end()) {
+ assert(false);
Fatal() << "Module::getGlobal: " << name << " does not exist";
}
return iter->second;
}
+Event* Module::getEvent(Name name) {
+ auto iter = eventsMap.find(name);
+ if (iter == eventsMap.end()) {
+ Fatal() << "Module::getEvent: " << name << " does not exist";
+ }
+ return iter->second;
+}
+
FunctionType* Module::getFunctionTypeOrNull(Name name) {
auto iter = functionTypesMap.find(name);
if (iter == functionTypesMap.end()) {
@@ -945,6 +956,14 @@ Global* Module::getGlobalOrNull(Name name) {
return iter->second;
}
+Event* Module::getEventOrNull(Name name) {
+ auto iter = eventsMap.find(name);
+ if (iter == eventsMap.end()) {
+ return nullptr;
+ }
+ return iter->second;
+}
+
FunctionType* Module::addFunctionType(std::unique_ptr<FunctionType> curr) {
if (!curr->name.is()) {
Fatal() << "Module::addFunctionType: empty name";
@@ -1009,6 +1028,20 @@ Global* Module::addGlobal(Global* curr) {
return curr;
}
+Event* Module::addEvent(Event* curr) {
+ if (!curr->name.is()) {
+ Fatal() << "Module::addEvent: empty name";
+ }
+ if (getEventOrNull(curr->name)) {
+ Fatal() << "Module::addEvent: " << curr->name << " already exists";
+ }
+
+ events.emplace_back(curr);
+
+ eventsMap[curr->name] = curr;
+ return curr;
+}
+
void Module::addStart(const Name& s) { start = s; }
void Module::removeFunctionType(Name name) {
@@ -1051,6 +1084,16 @@ void Module::removeGlobal(Name name) {
globalsMap.erase(name);
}
+void Module::removeEvent(Name name) {
+ for (size_t i = 0; i < events.size(); i++) {
+ if (events[i]->name == name) {
+ events.erase(events.begin() + i);
+ break;
+ }
+ }
+ eventsMap.erase(name);
+}
+
// TODO: remove* for other elements
void Module::updateMaps() {
@@ -1070,6 +1113,10 @@ void Module::updateMaps() {
for (auto& curr : globals) {
globalsMap[curr->name] = curr.get();
}
+ eventsMap.clear();
+ for (auto& curr : events) {
+ eventsMap[curr->name] = curr.get();
+ }
}
void Module::clearDebugInfo() { debugInfoFileNames.clear(); }