aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • Computing
  • Practices
  • Programming
  • Tech

How To Write ‘Hello World’ in WebAssembly

  • root
  • April 16, 2021
  • 3 minute read

Get started writing WebAssembly in human-readable text with this step-by-step tutorial.

WebAssembly is a bytecode format that virtually every browser can compile to its host system’s machine code. Alongside JavaScript and WebGL, WebAssembly fulfills the demand for porting applications for platform-independent use in the web browser. As a compilation target for C++ and Rust, WebAssembly enables web browsers to execute code at near-native speed.


Partner with aster.cloud
for your next big idea.
Let us know here.



From our partners:

CITI.IO :: Business. Institutions. Society. Global Political Economy.
CYBERPOGO.COM :: For the Arts, Sciences, and Technology.
DADAHACKS.COM :: Parenting For The Rest Of Us.
ZEDISTA.COM :: Entertainment. Sports. Culture. Escape.
TAKUMAKU.COM :: For The Hearth And Home.
ASTER.CLOUD :: From The Cloud And Beyond.
LIWAIWAI.COM :: Intelligence, Inside and Outside.
GLOBALCLOUDPLATFORMS.COM :: For The World's Computing Needs.
FIREGULAMAN.COM :: For The Fire In The Belly Of The Coder.
ASTERCASTER.COM :: Supra Astra. Beyond The Stars.
BARTDAY.COM :: Prosperity For Everyone.

When you talk about a WebAssembly, application, you must distinguish between three states:

  1. Source code (e.g., C++ or Rust): You have an application written in a compatible language that you want to execute in the browser.
  2. WebAssembly bytecode: You choose WebAssembly bytecode as your compilation target. As a result, you get a .wasm file.
  3. Machine code (opcode): The browser loads the .wasm file and compiles it to the corresponding machine code of its host system.

WebAssembly also has a text format that represents the binary format in human-readable text. For the sake of simplicity, I will refer to this as WASM-text. WASM-text can be compared to high-level assembly language. Of course, you would not write a complete application based on WASM-text, but it’s good to know how it works under the hood (especially for debugging and performance optimization).

This article will guide you through creating the classic Hello World program in WASM-text.

 

Creating the .wat file

WASM-text files usually end with .wat. Start from scratch by creating an empty text file named helloworld.wat, open it with your favorite text editor, and paste in:

(module
;; Imports from JavaScript namespace
(import  “console”  “log” (func  $log (param  i32  i32))) ;; Import log function
(import  “js”  “mem” (memory  1)) ;; Import 1 page of memory (54kb);; Data section of our module
(data (i32.const 0) “Hello World from WebAssembly!”)

Read More  Microsoft To Acquire ZeniMax Media And Its Game Publisher Bethesda Softworks

;; Function declaration: Exported as helloWorld(), no arguments
(func (export  “helloWorld”)
i32.const 0  ;; pass offset 0 to log
i32.const 29  ;; pass length 29 to log (strlen of sample text)
call  $log
)
)

The WASM-text format is based upon S-expressions. To enable interaction, JavaScript functions are imported with the import statement, and WebAssembly functions are exported with the export statement. For this example, import the log function from the console module, which takes two parameters of type i32 as input and one page of memory (64KB) to store the string.

The string will be written into the data section at offset 0. The data section is an overlay of your memory, and the memory is allocated in the JavaScript part.

 

Functions are marked with the keyword func. The stack is empty when entering a function. Function parameters are pushed onto the stack (here offset and length) before another function is called (see call $log). When a function returns an f32 type (for example), an f32 variable must remain on the stack when leaving the function (but this is not the case in this example).

 

Creating the .wasm file

The WASM-text and the WebAssembly bytecode have 1:1 correspondence. This means you can convert WASM-text into bytecode (and vice versa). You already have the WASM-text, and now you want to create the bytecode.

The conversion can be performed with the WebAssembly Binary Toolkit (WABT). Make a clone of the repository at that link and follow the installation instructions.

After you build the toolchain, convert WASM-text to bytecode by opening a console and entering:

wat2wasm helloworld.wat -o helloworld.wasm

You can also convert bytecode to WASM-text with:

wasm2wat helloworld.wasm -o helloworld_reverse.wat

A .wat file created from a .wasm file does not include any function nor parameter names. By default, WebAssembly identifies functions and parameters with their index.

Read More  Reasons To Flatten Your Source Code

 

Compiling the .wasm file

Currently, WebAssembly only coexists with JavaScript, so you have to write a short script to load and compile the .wasm file and do the function calls. You also need to define the functions you will import in your WebAssembly module.

Create an empty text file and name it helloworld.html, then open your favorite text editor and paste in:

<!DOCTYPE  html>
<html>
<head>
<meta  charset=”utf-8″>
<title>Simple template</title>
</head>
<body>
<script>var memory = new  WebAssembly.Memory({initial:1});

function  consoleLogString(offset, length) {
var  bytes = new  Uint8Array(memory.buffer, offset, length);
var  string = new  TextDecoder(‘utf8’).decode(bytes);
console.log(string);
};

var  importObject = {
console: {
log:  consoleLogString
},
js : {
mem:  memory
}
};

WebAssembly.instantiateStreaming(fetch(‘helloworld.wasm’), importObject)
.then(obj  => {
obj.instance.exports.helloWorld();
});

</script>
</body>
</html>

The WebAssembly.Memory(...) method returns one page of memory that is 64KB in size. The function consoleLogString reads a string from that memory page based on the length and offset. Both objects are passed to your WebAssembly module as part of the importObject.

Before you can run this example, you may have to allow Firefox to access files from this directory by typing about:config in the address line and setting privacy.file_unique_origin to true:

 

Firefox setting

(Stephan Avenwedde, CC BY-SA 4.0)

Caution: This will make you vulnerable to the CVE-2019-11730 security issue.

Now, open helloworld.html in Firefox and enter Ctrl+K to open the developer console.

 

Debugger output

(Stephan Avenwedde, CC BY-SA 4.0)

Learn more

This Hello World example is just one of the detailed tutorials in MDN’s Understanding WebAssembly text format documentation. If you want to learn more about WebAssembly and how it works under the hood, take a look at these docs.

Read More  Google I/O 2019 | What's New in Android C++ Development

This article is republished from opensource.com


For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!

Our humans need coffee too! Your support is highly appreciated, thank you!

root

Related Topics
  • Compiling
  • Hello World example
  • Source code
  • Web Assembly
You May Also Like
Getting things done makes her feel amazing
View Post
  • Computing
  • Data
  • Featured
  • Learning
  • Tech
  • Technology

Nurturing Minds in the Digital Revolution

  • April 25, 2025
View Post
  • Computing
  • Public Cloud
  • Technology

United States Army Enterprise Cloud Management Agency Expands its Oracle Defense Cloud Services

  • April 15, 2025
Microsoft’s Majorana 1 chip carves new path for quantum computing
View Post
  • Computing
  • Technology

Microsoft’s Majorana 1 chip carves new path for quantum computing

  • February 19, 2025
View Post
  • Computing
  • Engineering

Why a decades old architecture decision is impeding the power of AI computing

  • February 19, 2025
View Post
  • Tech

Deep dive into AI with Google Cloud’s global generative AI roadshow

  • February 18, 2025
CES 2025: Intel Shows Off Its AI Tech
View Post
  • Computing
  • Technology

CES 2025: Intel Shows Off Its AI Tech

  • January 23, 2025
Volvo Group: Confidently ahead at CES
View Post
  • Tech

Volvo Group: Confidently ahead at CES

  • January 8, 2025
zedreviews-ces-2025-social-meta
View Post
  • Featured
  • Gears
  • Tech
  • Technology

What Not to Miss at CES 2025

  • January 6, 2025

Stay Connected!
LATEST
  • college-of-cardinals-2025 1
    The Definitive Who’s Who of the 2025 Papal Conclave
    • May 7, 2025
  • conclave-poster-black-smoke 2
    The World Is Revalidating Itself
    • May 6, 2025
  • oracle-ibm 3
    IBM and Oracle Expand Partnership to Advance Agentic AI and Hybrid Cloud
    • May 6, 2025
  • 4
    Conclave: How A New Pope Is Chosen
    • April 25, 2025
  • Getting things done makes her feel amazing 5
    Nurturing Minds in the Digital Revolution
    • April 25, 2025
  • 6
    AI is automating our jobs – but values need to change if we are to be liberated by it
    • April 17, 2025
  • 7
    Canonical Releases Ubuntu 25.04 Plucky Puffin
    • April 17, 2025
  • 8
    United States Army Enterprise Cloud Management Agency Expands its Oracle Defense Cloud Services
    • April 15, 2025
  • 9
    Tokyo Electron and IBM Renew Collaboration for Advanced Semiconductor Technology
    • April 2, 2025
  • 10
    IBM Accelerates Momentum in the as a Service Space with Growing Portfolio of Tools Simplifying Infrastructure Management
    • March 27, 2025
about
Hello World!

We are aster.cloud. We’re created by programmers for programmers.

Our site aims to provide guides, programming tips, reviews, and interesting materials for tech people and those who want to learn in general.

We would like to hear from you.

If you have any feedback, enquiries, or sponsorship request, kindly reach out to us at:

[email protected]
Most Popular
  • 1
    Tariffs, Trump, and Other Things That Start With T – They’re Not The Problem, It’s How We Use Them
    • March 25, 2025
  • 2
    IBM contributes key open-source projects to Linux Foundation to advance AI community participation
    • March 22, 2025
  • 3
    Co-op mode: New partners driving the future of gaming with AI
    • March 22, 2025
  • 4
    Mitsubishi Motors Canada Launches AI-Powered “Intelligent Companion” to Transform the 2025 Outlander Buying Experience
    • March 10, 2025
  • PiPiPi 5
    The Unexpected Pi-Fect Deals This March 14
    • March 13, 2025
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.