DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

WebAssembly: Using Emscripten to Create a Bare-Bones Module

This article is the result of some research/experimentation to see if it’s possible to build a WebAssembly module using Emscripten but not have any of the plumbing code.

Gerard Gallant user avatar by
Gerard Gallant
·
Dec. 20, 17 · Tutorial
Like (2)
Save
Tweet
Share
8.87K Views

Join the DZone community and get the full member experience.

Join For Free

In my last article, An Introduction to WebAssembly, I showed you some of the basics of working with a WebAssembly module by using Emscripten.

This article is the result of some research and experiments to see if it’s possible to build a WebAssembly module using Emscripten but not have any of the plumbing code.

For example, if we were to build the following C file using the following command line, the result would be an HTML file that is 101 KB, a JS file that is 80.2 KB, and a wasm file that is 9.4 KB!

#include <stdio.h>
#include "../emscripten/emscripten.h"

int main() { return 0; }

int EMSCRIPTEN_KEEPALIVE add(int x, int y) { return x + y; }

emcc test.c -s WASM=1 -s NO_EXIT_RUNTIME=1 -O1 -o hello.html 

Having all of that plumbing is very convenient because it lets you start playing around with WebAssembly modules right away but what if we want just the bare minimum and will handle the HTML and JavaScript ourselves?

Fortunately, there is a way to tell Emscripten to output just the bare bones wasm file.

Let's first strip the C file down to just the bare minimum. In this case, we only want the add method:

int add(int x, int y) { return x + y; }

If we use the following command line, we will get just the wasm file and it’s only 202 bytes!

emcc test.c -s WASM=1 -s SIDE_MODULE=1 -O1 -o test.wasm 

The SIDE_MODULE flag tells Emscripten to compile only our methods and nothing else which means you will also not have access to things like printf or malloc.

If not specified, the default optimization flag used is -O0 (capital letter o and the number 0) but that results in the following error being thrown when you try to load the module:

LinkError: import object field 'DYNAMICTOP_PTR' is not a Number 

Adding any optimization flag other than-O0  will fix the issue so we went with -O1 (capital letter o and the number 1) for this example.

One thing to note, however, is that the O appears to be case sensitive. The various optimization flags that are available can be found here.

We also need to specify the name of the output file in the command line because, if we don't, Emscripten will output the file with the name a.out.wasm.

Because we've decided not to use Emscripten's plumbing code, we need to write our own HTML and JavaScript. The following is some example HTML and JavaScript to load in the module:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
  </head>
  <body>
    <input type="button" value="test" onclick="javascript:OnClickTest();" />

    <script type="text/javascript">
      var gModule = null;

      var importObject = {
        'env': {
          'memoryBase': 0,
          'tableBase': 0,
          'memory': new WebAssembly.Memory({initial: 256}),
          'table': new WebAssembly.Table({initial: 0, element: 'anyfunc'}) 
        } 
      }; 

      fetch('test.wasm').then(response => 
        response.arrayBuffer()
      ).then(bytes =>
        WebAssembly.instantiate(bytes, importObject)
      ).then(results => {
        gModule = results.instance; // Hold onto the module's instance so that we can reuse it 
      });

      function OnClickTest(){
        alert(gModule.exports._add(1, 2)); 
      }
    </script>
  </body>
</html>

One thing that you may have noticed that is different with our call to the C method, as compared to what we did in the previous blog post, is that we're not using Module.ccall or Module.cwrap. Those are Emscripten helper methods. Here, we're calling the C method directly.

Something else to be aware of here is that your JavaScript will need to include an underscore character before the method name. For example, in our case, our method is called add. When you call the add method in JavaScript you would use _add(1, 2); rather than add(1, 2);

Although this approach might not be a solution that will work in every situation, given that you don't have access to things like malloc, it might be a useful way of creating a helper library if you're doing things like number crunching and don't need all of the overhead that comes with Emscripten's plumbing.

Emscripten WebAssembly

Published at DZone with permission of Gerard Gallant, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Key Elements of Site Reliability Engineering (SRE)
  • Utilizing Database Hooks Like a Pro in Node.js
  • Reconciling Java and DevOps with JeKa
  • Benefits and Challenges of Multi-Cloud Integration

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: