Slide 1

Slide 1 text

WebАssembly from Java Perspective

Slide 2

Slide 2 text

Dmitry Aleksandrov Chief Architect | JUG co-lead | Java Champion

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

Back to Java-Applets?

Slide 6

Slide 6 text

Disclaimer: We have to first understand what WebAssembly is than see how to use it with Java

Slide 7

Slide 7 text

Disclaimer: (Keep It Simple and Stupid)

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

Modern Web

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

HTML:

Slide 14

Slide 14 text

CSS: Sorry, no funny image found...

Slide 15

Slide 15 text

JavaScript: JavaScript (/ˈdʒɑːvəˌskrɪpt/), often abbreviated as JS, is a high-level, interpreted programming language that conforms to the ECMAScript specification. It is a language that is also characterized as dynamic, weakly typed, prototype-based and multi-paradigm. Created 04 December 1995 by Brendan Eich. © Wikipedia

Slide 16

Slide 16 text

Once this was just enough

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

No content

Slide 19

Slide 19 text

And all those frameworks...

Slide 20

Slide 20 text

But now:

Slide 21

Slide 21 text

No content

Slide 22

Slide 22 text

What is this? Compiling for the Web with WebAssembly (Google I/O '17)

Slide 23

Slide 23 text

You will be surprised...: Compiling for the Web with WebAssembly (Google I/O '17) function add(a, b) { return a + b }

Slide 24

Slide 24 text

V8 - JS Compiling for the Web with WebAssembly (Google I/O '17)

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

There were many attempts to optimize:

Slide 27

Slide 27 text

There were many attempts to optimize: Compiling for the Web with WebAssembly (Google I/O '17)

Slide 28

Slide 28 text

Even games!

Slide 29

Slide 29 text

V8 - JS Compiling for the Web with WebAssembly (Google I/O '17)

Slide 30

Slide 30 text

We need a lot of Performance!!!

Slide 31

Slide 31 text

We need it in SMALL devices!!!

Slide 32

Slide 32 text

No content

Slide 33

Slide 33 text

And in 2015 came WebAssembly!

Slide 34

Slide 34 text

JS!

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

What is WebAssembly WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust/Java/Python, enabling deployment on the web for client and server applications. © Wikipedia

Slide 37

Slide 37 text

Virtual Architecture https://hacks.mozilla.org/2017/02/a-crash-course-in-assembly/

Slide 38

Slide 38 text

What is WebАssembly The kind of binary format being considered for WebAssembly can be natively decoded much faster than JavaScript can be parsed (experiments show more than 20× faster). On mobile, large compiled codes can easily take 20–40 seconds just to parse, so native decoding (especially when combined with other techniques like streaming for better-than-gzip compression) is critical to providing a good cold- load user experience. from the FAQ of WebAssembly

Slide 39

Slide 39 text

What is WebAssembly Efficient and fast The Wasm stack machine is designed to be encoded in a size- and load-time- efficient binary format. WebAssembly aims to execute at native speed by taking advantage of common hardware capabilities available on a wide range of platforms.

Slide 40

Slide 40 text

What is WebAssembly Efficient and fast The Wasm stack machine is designed to be encoded in a size- and load-time- efficient binary format. WebAssembly aims to execute at native speed by taking advantage of common hardware capabilities available on a wide range of platforms. Safe WebAssembly describes a memory-safe, sandboxed execution environmentthat may even be implemented inside existing JavaScript virtual machines. When embedded in the web, WebAssembly will enforce the same- origin and permissions security policies of the browser.

Slide 41

Slide 41 text

What is WebAssembly Efficient and fast The Wasm stack machine is designed to be encoded in a size- and load-time- efficient binary format. WebAssembly aims to execute at native speed by taking advantage of common hardware capabilities available on a wide range of platforms. Safe WebAssembly describes a memory-safe, sandboxed execution environment that may even be implemented inside existing JavaScript virtual machines. When embedded in the web, WebAssembly will enforce the same- origin and permissions security policies of the browser. Open and debuggable WebAssembly is designed to be pretty-printedin a textual format for debugging, testing, experimenting, optimizing, learning, teaching, and writing programs by hand. The textual format will be used when viewing the source of Wasm modules on the web.

Slide 42

Slide 42 text

What is WebAssembly Efficient and fast The Wasm stack machine is designed to be encoded in a size- and load-time- efficient binary format. WebAssembly aims to execute at native speed by taking advantage of common hardware capabilities available on a wide range of platforms. Safe WebAssembly describes a memory-safe, sandboxed execution environment that may even be implemented inside existing JavaScript virtual machines. When embedded in the web, WebAssembly will enforce the same- origin and permissions security policies of the browser. Open and debuggable WebAssembly is designed to be pretty-printed in a textual format for debugging, testing, experimenting, optimizing, learning, teaching, and writing programs by hand. The textual format will be used when viewing the source of Wasm modules on the web. Part of the open web platform WebAssembly is designed to maintain the versionless, feature-tested, and backwards-compatible nature of the web. WebAssembly modules will be able to call into and out of the JavaScript context and access browser functionality through the same Web APIs accessible from JavaScript. WebAssembly also supports non-webembeddings.

Slide 43

Slide 43 text

Its very very fresh • April 2015 - WebAssembly Community Group started • June 2015 - The first public announcement • March 2016 - Definition of core feature with multiple interoperable implementations • October 2016 - Browser Preview announced with multiple interoperable implementations • February 2017 - Official logo chosen • March 2017 - Cross-browser consensus and end of Browser Preview

Slide 44

Slide 44 text

It is shipped with:

Slide 45

Slide 45 text

It is shipped with:

Slide 46

Slide 46 text

In the greater scheme of things, the arrival of WebAssembly means that you will not be forced anymore to use JavaScript for the web, because it is the only thing that run in the browser!

Slide 47

Slide 47 text

No content

Slide 48

Slide 48 text

WebAssembly is NOT a replacement for HTML/JavaScript

Slide 49

Slide 49 text

WebAssembly is PART of the infrastructure...

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

V8 - WebAssembly Compiling for the Web with WebAssembly (Google I/O '17)

Slide 52

Slide 52 text

V8 - WebAssembly Compiling for the Web with WebAssembly (Google I/O '17)

Slide 53

Slide 53 text

What is it? Compiling for the Web with WebAssembly (Google I/O '17)

Slide 54

Slide 54 text

WebAssembly binary code Compiling for the Web with WebAssembly (Google I/O '17)

Slide 55

Slide 55 text

WebAssembly language Compiling for the Web with WebAssembly (Google I/O '17)

Slide 56

Slide 56 text

Current WebAssembly runs at 1.2x true native!

Slide 57

Slide 57 text

So, how can we use WebAssembly?

Slide 58

Slide 58 text

Disclaimer: we’ll now get low level.

Slide 59

Slide 59 text

The founding principle ... is to integrate well with the existing JavaScript world.

Slide 60

Slide 60 text

The founding principle ... is to integrate well with the existing JavaScript world. This ranges from technical things, such as interoperability and sharing the security policies (same-origin),

Slide 61

Slide 61 text

The founding principle ... is to integrate well with the existing JavaScript world. This ranges from technical things, such as interoperability and sharing the security policies (same-origin), to tooling integration, such as as supporting the View Source functionality of web browsers.

Slide 62

Slide 62 text

The founding principle Both Binary

Slide 63

Slide 63 text

The founding principle Both Binary ... and text format:

Slide 64

Slide 64 text

Ref: https://tomassetti.me/introduction-to-webassembly/

Slide 65

Slide 65 text

Why C??

Slide 66

Slide 66 text

Why C??

Slide 67

Slide 67 text

Why C?? • Objective of the initial release (MVP)

Slide 68

Slide 68 text

Why C?? • Objective of the initial release (MVP) • MVP is not Most Valuable Professional

Slide 69

Slide 69 text

Why C?? • Objective of the initial release (MVP) • MVP is not Most Valuable Professional • MVP is Minimal Viable Product

Slide 70

Slide 70 text

Why C?? • Objective of the initial release (MVP) • MVP is not Most Valuable Professional • MVP is Minimal Viable Product • The MVP of WebAssembly does not support garbage collection

Slide 71

Slide 71 text

Why C?? • Objective of the initial release (MVP) • MVP is not Most Valuable Professional • MVP is Minimal Viable Product • The MVP of WebAssembly does not support garbage collection • Rely on LLVM (one of the most used set of compiler tools)

Slide 72

Slide 72 text

MVP Feature Tracking issue Status Phase Specification 1077 in progress Proposed spec text available Threads 1073 in progress Feature proposal Fixed-width SIMD 1075 in progress Feature proposal Exception handling 1078 in progress Feature proposal Garbage collection 1079 in progress Feature proposal Bulk memory operations 1114 in progress Feature proposal Web Content Security Policy 1122 in progress Pre-proposal ECMAScript module integration 1087 in progress Feature proposal Tail Call 1144 in progress Feature proposal Non-trapping float-to-int conversions 1143 in progress Implementation phase Multi-value 1146 in progress Implementation phase Host bindings 1148 in progress Feature proposal Sign-extension operators 1178 in progress Implementation phase Import/Export Mutable Globals 1179 in progress Implementation phase Type Reflection for WebAssembly JavaScript API 1181 in progress Feature proposal Unmanaged closures 1182 in progress Feature proposal JavaScript BigInt to WebAssembly i64 integration 1186 in progress Proposed Spec Text Available Custom Annotation Syntax in the Text Format 1192 in progress Feature proposal

Slide 73

Slide 73 text

Enough theory!

Slide 74

Slide 74 text

Hello, world! •Infrastructure: •Emscripten •WebAssembly Binary Toolkit •Binaryen

Slide 75

Slide 75 text

Hello, world! #include int main() { printf("Hello, world!"); return 0; }

Slide 76

Slide 76 text

Hello, world! ╭─[email protected] ~/Webassembly/Example1 ╰─➤ emcc hello.c -s WASM=1 -o hello.html

Slide 77

Slide 77 text

Hello, world! ╭─[email protected] ~/Webassembly/Example1 ╰─➤ emcc hello.c -s WASM=1 -o hello.html

Slide 78

Slide 78 text

Hello, world!

Slide 79

Slide 79 text

As you see, WebAssembly does not cancel HTML/JavaScript

Slide 80

Slide 80 text

Wasm Engine actually lives inside JS engine,

Slide 81

Slide 81 text

... so they can talk to each other natively

Slide 82

Slide 82 text

External calls: step 1 – the code (C) extern int print_value(int x); void call_func(int input) { print_value(input * 3); }

Slide 83

Slide 83 text

External calls: step 2 – interop (JS) if ('WebAssembly' in window) { var importObj = { env: { _print_value: x => document.getElementById('wasm').innerHTML = 'Value:' + x } }; WebAssembly.instantiateStreaming(fetch('call_func.wasm'), importObj).then(result => result.instance.exports._call_func(9)); }

Slide 84

Slide 84 text

External calls: step 3 – all together (HTML)

Slide 85

Slide 85 text

And move data back> and

Slide 86

Slide 86 text

Since we are low level • Only binary data can be moved

Slide 87

Slide 87 text

Since we are low level • Only binary data can be moved • The data is moved in chunks called pages

Slide 88

Slide 88 text

Since we are low level • Only binary data can be moved • The data is moved in chunks called pages • Each page is 64K

Slide 89

Slide 89 text

Since we are low level • Only binary data can be moved • The data is moved in chunks called pages • Each page is 64K • Memory access is done via offsets

Slide 90

Slide 90 text

Moving data: step 1 – the code (C) #define NUM_VALS 8 int input_array[NUM_VALS]; int scalar_add() { int product = 0; for(int i=0; i

Slide 91

Slide 91 text

Moving data: step 2 – interop (JS) if ('WebAssembly' in window) { // Add memory object to the import object var memObj = new WebAssembly.Memory({initial: 256, maximum: 256}); var importObj = { env: { memory: memObj} }; // Set the import object in instantiateStreaming WebAssembly.instantiateStreaming(fetch('scalarAdd.wasm'), importObj) .then(result => { // Get the addresses of the input array offset = result.instance.exports._getInputArrayOffset(); // Create and initialize array var inputArray = new Uint32Array(memObj.buffer, offset, 8); inputArray.fill(6); // Compute the product product = result.instance.exports._scalar_add(); document.getElementById('wasm').innerHTML = 'Scalar add product: ' + product; }); }

Slide 92

Slide 92 text

Moving data: step 2 – interop (JS) if ('WebAssembly' in window) { // Add memory object to the import object var memObj = new WebAssembly.Memory({initial: 256, maximum: 256}); var importObj = { env: { memory: memObj} }; // Set the import object in instantiateStreaming WebAssembly.instantiateStreaming(fetch('scalarAdd.wasm'), importObj) .then(result => { // Get the addresses of the input array offset = result.instance.exports._getInputArrayOffset(); // Create and initialize array var inputArray = new Uint32Array(memObj.buffer, offset, 8); inputArray.fill(6); // Compute the product product = result.instance.exports._scalar_add(); document.getElementById('wasm').innerHTML = 'Scalar add product: ' + product; }); }

Slide 93

Slide 93 text

Moving data: step 2 – interop (JS) if ('WebAssembly' in window) { // Add memory object to the import object var memObj = new WebAssembly.Memory({initial: 256, maximum: 256}); var importObj = { env: { memory: memObj} }; // Set the import object in instantiateStreaming WebAssembly.instantiateStreaming(fetch('scalarAdd.wasm'), importObj) .then(result => { // Get the addresses of the input array offset = result.instance.exports._getInputArrayOffset(); // Create and initialize array var inputArray = new Uint32Array(memObj.buffer, offset, 8); inputArray.fill(6); // Compute the product product = result.instance.exports._scalar_add(); document.getElementById('wasm').innerHTML = 'Scalar add product: ' + product; }); }

Slide 94

Slide 94 text

Moving data: step 2 – interop (JS) if ('WebAssembly' in window) { // Add memory object to the import object var memObj = new WebAssembly.Memory({initial: 256, maximum: 256}); var importObj = { env: { memory: memObj} }; // Set the import object in instantiateStreaming WebAssembly.instantiateStreaming(fetch('scalarAdd.wasm'), importObj) .then(result => { // Get the addresses of the input array offset = result.instance.exports._getInputArrayOffset(); // Create and initialize array var inputArray = new Uint32Array(memObj.buffer, offset, 8); inputArray.fill(6); // Compute the product product = result.instance.exports._scalar_add(); document.getElementById('wasm').innerHTML = 'Scalar add product: ' + product; }); }

Slide 95

Slide 95 text

Moving data: step 2 – interop (JS) if ('WebAssembly' in window) { // Add memory object to the import object var memObj = new WebAssembly.Memory({initial: 256, maximum: 256}); var importObj = { env: { memory: memObj} }; // Set the import object in instantiateStreaming WebAssembly.instantiateStreaming(fetch('scalarAdd.wasm'), importObj) .then(result => { // Get the addresses of the input array offset = result.instance.exports._getInputArrayOffset(); // Create and initialize array var inputArray = new Uint32Array(memObj.buffer, offset, 8); inputArray.fill(6); // Compute the product product = result.instance.exports._scalar_add(); document.getElementById('wasm').innerHTML = 'Scalar add product: ' + product; }); }

Slide 96

Slide 96 text

Moving data: step 2 – interop (JS) if ('WebAssembly' in window) { // Add memory object to the import object var memObj = new WebAssembly.Memory({initial: 256, maximum: 256}); var importObj = { env: { memory: memObj} }; // Set the import object in instantiateStreaming WebAssembly.instantiateStreaming(fetch('scalarAdd.wasm'), importObj) .then(result => { // Get the addresses of the input array offset = result.instance.exports._getInputArrayOffset(); // Create and initialize array var inputArray = new Uint32Array(memObj.buffer, offset, 8); inputArray.fill(6); // Compute the product product = result.instance.exports._scalar_add(); document.getElementById('wasm').innerHTML = 'Scalar add product: ' + product; }); }

Slide 97

Slide 97 text

Moving data: step 3 – all together (HTML)

Slide 98

Slide 98 text

Cool! It works on your machine!

Slide 99

Slide 99 text

What about debugging?

Slide 100

Slide 100 text

Hello, world! ╭─[email protected] ~/Webassembly/Example1 ╰─➤ emcc hello.c -s -g WASM=1 -o hello.html

Slide 101

Slide 101 text

Hello, world! ╭─[email protected] ~/Webassembly/Example1 ╰─➤ emcc hello.c -s -g WASM=1 -o hello.html

Slide 102

Slide 102 text

... there are also other options: • -g4 and –source-map-base http://localhost:8080/ • emcc add.c -O1 -g4 -s WASM=1 -s SIDE_MODULE=1 -s EXPORTED_FUNCTIONS='["_add"]' -o add.wasm --source-map-base http://localhost:8080/ *http://webassemblycode.com/using-browsers-debug-webassembly/

Slide 103

Slide 103 text

Oh, that’s boring!

Slide 104

Slide 104 text

Give me

Slide 105

Slide 105 text

Currently there are: •JWebAssembly

Slide 106

Slide 106 text

Currently there are: •JWebAssembly •TeaVM

Slide 107

Slide 107 text

JWebAssembly: Java public class Add { @Export public static int add( int a, int b ) { return a + b; } }

Slide 108

Slide 108 text

JWebAssembly: Java public static void main(String[] args) throws Exception { JWebAssembly webAsm = new JWebAssembly(); webAsm.addFile(new File(”<..>/Add.class")); String text = webAsm.compileToText(); System.out.println(text); }

Slide 109

Slide 109 text

JWebAssembly: Output (module (export "add" (func $local/samples/mitia/Add.add)) (func $local/samples/mitia/Add.add (param i32) (param i32) (result i32) get_local 0 get_local 1 i32.add return ) )

Slide 110

Slide 110 text

TeaVM https://binji.github.io/gotosthlm-talk/#/25

Slide 111

Slide 111 text

TeaVM: Step 1 – setup (Maven) ... org.teavm teavm-classlib ${project.version} org.teavm teavm-jso-apis ${project.version} provided org.teavm teavm-interop ${project.version} ...

Slide 112

Slide 112 text

TeaVM: Step 2 – the code (Java) public class WasmFunctions { @Export(name = "thePurposeOfLife") public static int getThePurposeOfLife(){ return 43; } public static void main(String[] args) { } }

Slide 113

Slide 113 text

TeaVM: Step 3 – compile to Wasm (Maven) maven-war-plugin 2.4 ${project.build.directory}/generated/wasm false

Slide 114

Slide 114 text

TeaVM: Step 4 – compile to Wasm (Maven) org.teavm teavm-maven-plugin ${project.version} wasm-client compile ${project.build.directory}/generated/wasm/wasm local.mitia.wasm.WasmFunctions true WEBASSEMBLY FULL 8

Slide 115

Slide 115 text

TeaVM: Step 5 – all together (JS/HTML) JS: if ('WebAssembly' in window) { // Set the import object in instantiateStreaming WebAssembly.instantiateStreaming(fetch('wasm /classes.wasm')) .then(result => { //the Purpse of Life is: result = result.instance.exports.thePurposeOfLife(); document.getElementById('wasm').innerHTML = 'The Purpose of life according to teavm wasm from java: ' + result; }); } HTML:

Slide 116

Slide 116 text

Demo time

Slide 117

Slide 117 text

What about ?

Slide 118

Slide 118 text

What about ?

Slide 119

Slide 119 text

s

Slide 120

Slide 120 text

Kotlin way: Kotlin as a JVM Language

Slide 121

Slide 121 text

Kotlin way: Kotlin as a JVM Language Kotlin/Native

Slide 122

Slide 122 text

Kotlin way: Kotlin as a JVM Language Kotlin/Native LLVM

Slide 123

Slide 123 text

Kotlin way: Kotlin as a JVM Language Kotlin/Native LLVM WebAssembly

Slide 124

Slide 124 text

Kotlin way: Kotlin as a JVM Language Kotlin/Native LLVM WebAssembly

Slide 125

Slide 125 text

Kotlin way: step 1 – the code (kt) import kotlinx.interop.wasm.dom.* import kotlinx.wasm.jsinterop.* fun main(args: Array) { println("Hello Kotlin/Native!") }

Slide 126

Slide 126 text

Kotlin way: step 2 – the build (gradle) buildscript { repositories { jcenter() maven { url "http://kotlin.bintray.com/kotlinx" } maven { url "https://plugins.gradle.org/m2/" } maven { url "https://dl.bintray.com/jetbrains/kotlin-native-dependencies" } } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "com.moowork.gradle:gradle-node-plugin:$gradle_node_version" classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:$kotlin_native_version" } } apply plugin: 'konan' konanArtifacts { program('wasmFunctions', targets: ['wasm32']) { srcDir 'src/main/kotlin' libraries { useRepo 'lib' klib 'dom' } } }

Slide 127

Slide 127 text

Kotlin way: step 2 – the build (gradle) buildscript { repositories { jcenter() maven { url "http://kotlin.bintray.com/kotlinx" } maven { url "https://plugins.gradle.org/m2/" } maven { url "https://dl.bintray.com/jetbrains/kotlin-native-dependencies" } } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "com.moowork.gradle:gradle-node-plugin:$gradle_node_version" classpath "org.jetbrains.kotlin:kotlin-native-gradle-plugin:$kotlin_native_version" } } apply plugin: 'konan' konanArtifacts { program('wasmFunctions', targets: ['wasm32']) { srcDir 'src/main/kotlin' libraries { useRepo 'lib' klib 'dom' } } }

Slide 128

Slide 128 text

No content

Slide 129

Slide 129 text

Competitors?

Slide 130

Slide 130 text

C# https://www.slideshare.net/sweko/blazor-c-for-the-web

Slide 131

Slide 131 text

Rust https://rustwasm.github.io/book/

Slide 132

Slide 132 text

Go https://github.com/golang/go/wiki/WebAssembly

Slide 133

Slide 133 text

WASI https://hacks.mozilla.org/2019/03/standardizing-wasi-a-webassembly-system-interface/

Slide 134

Slide 134 text

No content

Slide 135

Slide 135 text

No content

Slide 136

Slide 136 text

Bloody enterprise

Slide 137

Slide 137 text

Real world: 0 500 1000 1500 2000 2500 JS Asm.js Wasm Sorting 10k entries Sorting 10k entries

Slide 138

Slide 138 text

No content

Slide 139

Slide 139 text

Isn’t it already outdated?

Slide 140

Slide 140 text

Or not even born?

Slide 141

Slide 141 text

Their main problem is:

Slide 142

Slide 142 text

Their main problem is: THEY ARE PRIVATE!

Slide 143

Slide 143 text

On the other hand WebAssembly: IS A STANDARD!

Slide 144

Slide 144 text

On the other hand WebAssembly: IS A STANDARD! AVAILABLE EVERYWHERE!

Slide 145

Slide 145 text

On the other hand WebAssembly: IS A STANDARD! AVAILABLE EVERYWHERE! FOR FREE!

Slide 146

Slide 146 text

No content

Slide 147

Slide 147 text

So...

Slide 148

Slide 148 text

So... You can run, you can hide

Slide 149

Slide 149 text

But you can’t escape WebAssembly :)

Slide 150

Slide 150 text

Never forget! Compiling for the Web with WebAssembly (Google I/O '17)

Slide 151

Slide 151 text

No content

Slide 152

Slide 152 text

Are we back to the applets?

Slide 153

Slide 153 text

Are we back to the applets?

Slide 154

Slide 154 text

Play: https://wasdk.github.io/WasmFiddle

Slide 155

Slide 155 text

Thank you J