diff options
author | Alon Zakai <alonzakai@gmail.com> | 2015-11-12 12:45:34 -0800 |
---|---|---|
committer | Alon Zakai <alonzakai@gmail.com> | 2015-11-12 12:45:34 -0800 |
commit | 3a2768127856e7113317e5d907ead6cc41f60299 (patch) | |
tree | 6aa85f7676dc23c7086c729a9b1049c7a9187a9a /test/example/find_div0s.cpp | |
parent | 7725a4b87feead9416e419b3c95228c4515813da (diff) | |
parent | afce1de1495cc5782ec55b016d4e864b316d9920 (diff) | |
download | binaryen-3a2768127856e7113317e5d907ead6cc41f60299.tar.gz binaryen-3a2768127856e7113317e5d907ead6cc41f60299.tar.bz2 binaryen-3a2768127856e7113317e5d907ead6cc41f60299.zip |
Merge branch 'binaryen'
Diffstat (limited to 'test/example/find_div0s.cpp')
-rw-r--r-- | test/example/find_div0s.cpp | 56 |
1 files changed, 56 insertions, 0 deletions
diff --git a/test/example/find_div0s.cpp b/test/example/find_div0s.cpp new file mode 100644 index 000000000..60eed5f62 --- /dev/null +++ b/test/example/find_div0s.cpp @@ -0,0 +1,56 @@ + +// +// Tiny example, using Binaryen to walk a WebAssembly module in search +// for direct integer divisions by zero. To do so, we inherit from +// WasmWalker, and implement visitBinary, which is called on every +// Binary node in the module's functions. +// + +#include <ostream> +#include <wasm.h> +#include <wasm-s-parser.h> + +using namespace wasm; + +int main() { + // A simple WebAssembly module in S-Expression format. + char input[] = + "(module" + " (func $has_div_zero" + " (i32.div_s" + " (i32.const 5)" + " (i32.const 0)" + " )" + " )" + ")"; + + // Parse the S-Expression text, and prepare to build a WebAssembly module. + SExpressionParser parser(input); + Element& root = *parser.root; + Module module; + + // The parsed code has just one element, the module. Build the module + // from that (and abort on any errors, but there won't be one here). + SExpressionWasmBuilder builder(module, *root[0], [&]() { abort(); }); + + // Print it out + std::cout << module; + + // Search it for divisions by zero: Walk the module, looking for + // that operation. + struct DivZeroSeeker : public WasmWalker { + void visitBinary(Binary* curr) { + // In every Binary, look for integer divisions + if (curr->op == BinaryOp::DivS || curr->op == BinaryOp::DivU) { + // Check if the right operand is a constant, and if it is 0 + auto right = curr->right->dyn_cast<Const>(); + if (right && right->value.getInteger() == 0) { + std::cout << "We found that " << curr->left << " is divided by zero\n"; + } + } + } + }; + DivZeroSeeker seeker; + seeker.startWalk(&module); +} + |