1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use anyhow::{anyhow, bail, Error};
use std::cmp;
use std::env;
use walrus::ir::Value;
use walrus::{
ir::MemArg, ExportItem, FunctionId, GlobalId, GlobalKind, InitExpr, InstrSeqBuilder, MemoryId,
Module, ValType,
};
use wasm_bindgen_wasm_conventions as wasm_conventions;
const PAGE_SIZE: u32 = 1 << 16;
const ATOMIC_MEM_ARG: MemArg = MemArg {
align: 4,
offset: 0,
};
pub struct Config {
maximum_memory: u32,
thread_stack_size: u32,
enabled: bool,
}
#[derive(Clone, Copy)]
pub struct ThreadCount(walrus::LocalId);
impl Config {
pub fn new() -> Config {
Config {
maximum_memory: 1 << 30, thread_stack_size: 1 << 20, enabled: env::var("WASM_BINDGEN_THREADS").is_ok(),
}
}
pub fn is_enabled(&self, module: &Module) -> bool {
if self.enabled {
return true;
}
match wasm_conventions::get_memory(module) {
Ok(memory) => module.memories.get(memory).shared,
Err(_) => false,
}
}
pub fn maximum_memory(&mut self, max: u32) -> &mut Config {
self.maximum_memory = max;
self
}
pub fn thread_stack_size(&mut self, size: u32) -> &mut Config {
self.thread_stack_size = size;
self
}
pub fn run(&self, module: &mut Module) -> Result<Option<ThreadCount>, Error> {
if !self.is_enabled(module) {
return Ok(None);
}
let memory = wasm_conventions::get_memory(module)?;
let static_data_align = 4;
let static_data_pages = 1;
let (base, addr) =
allocate_static_data(module, memory, static_data_pages, static_data_align)?;
let mem = module.memories.get_mut(memory);
assert!(mem.shared);
let prev_max = mem.maximum.unwrap();
assert!(mem.import.is_some());
mem.maximum = Some(cmp::max(self.maximum_memory / PAGE_SIZE, prev_max));
assert!(mem.data_segments.is_empty());
let tls = Tls {
init: delete_synthetic_func(module, "__wasm_init_tls")?,
size: delete_synthetic_global(module, "__tls_size")?,
align: delete_synthetic_global(module, "__tls_align")?,
base: wasm_conventions::get_tls_base(module)
.ok_or_else(|| anyhow!("failed to find tls base"))?,
};
let thread_counter_addr = addr as i32;
let stack_alloc =
module
.globals
.add_local(ValType::I32, true, InitExpr::Value(Value::I32(0)));
let temp_stack = (base + static_data_pages * PAGE_SIZE) & !(static_data_align - 1);
let stack = Stack {
pointer: wasm_conventions::get_shadow_stack_pointer(module)
.ok_or_else(|| anyhow!("failed to find shadow stack pointer"))?,
temp: temp_stack as i32,
temp_lock: thread_counter_addr + 4,
alloc: stack_alloc,
size: self.thread_stack_size,
};
let _ = module.exports.add("__stack_alloc", stack.alloc);
let thread_count = inject_start(module, &tls, &stack, thread_counter_addr, memory)?;
inject_destroy(module, &tls, &stack, memory)?;
Ok(Some(thread_count))
}
}
impl ThreadCount {
pub fn wrap_start(self, builder: &mut walrus::FunctionBuilder, start: FunctionId) {
builder.func_body().local_get(self.0).if_else(
None,
|_| {},
|body| {
body.call(start);
},
);
}
}
fn delete_synthetic_func(module: &mut Module, name: &str) -> Result<FunctionId, Error> {
match delete_synthetic_export(module, name)? {
walrus::ExportItem::Function(f) => Ok(f),
_ => bail!("`{}` must be a function", name),
}
}
fn delete_synthetic_global(module: &mut Module, name: &str) -> Result<u32, Error> {
let id = match delete_synthetic_export(module, name)? {
walrus::ExportItem::Global(g) => g,
_ => bail!("`{}` must be a global", name),
};
let g = match module.globals.get(id).kind {
walrus::GlobalKind::Local(g) => g,
walrus::GlobalKind::Import(_) => bail!("`{}` must not be an imported global", name),
};
match g {
InitExpr::Value(Value::I32(v)) => Ok(v as u32),
_ => bail!("`{}` was not an `i32` constant", name),
}
}
fn delete_synthetic_export(module: &mut Module, name: &str) -> Result<ExportItem, Error> {
let item = module
.exports
.iter()
.find(|e| e.name == name)
.ok_or_else(|| anyhow!("failed to find `{}`", name))?;
let ret = item.item;
let id = item.id();
module.exports.delete(id);
Ok(ret)
}
fn allocate_static_data(
module: &mut Module,
memory: MemoryId,
pages: u32,
align: u32,
) -> Result<(u32, u32), Error> {
let heap_base = module
.exports
.iter()
.filter(|e| e.name == "__heap_base")
.filter_map(|e| match e.item {
ExportItem::Global(id) => Some(id),
_ => None,
})
.next();
let heap_base = match heap_base {
Some(idx) => idx,
None => bail!("failed to find `__heap_base` for injecting thread id"),
};
let (base, address) = {
let global = module.globals.get_mut(heap_base);
if global.ty != ValType::I32 {
bail!("the `__heap_base` global doesn't have the type `i32`");
}
if global.mutable {
bail!("the `__heap_base` global is unexpectedly mutable");
}
let offset = match &mut global.kind {
GlobalKind::Local(InitExpr::Value(Value::I32(n))) => n,
_ => bail!("`__heap_base` not a locally defined `i32`"),
};
let address = (*offset as u32 + (align - 1)) & !(align - 1); let base = *offset;
*offset = *offset + (pages * PAGE_SIZE) as i32;
(base, address)
};
let memory = module.memories.get_mut(memory);
memory.initial += pages;
memory.maximum = memory.maximum.map(|m| cmp::max(m, memory.initial));
Ok((base as u32, address))
}
struct Tls {
init: walrus::FunctionId,
size: u32,
align: u32,
base: GlobalId,
}
struct Stack {
pointer: GlobalId,
temp: i32,
temp_lock: i32,
alloc: GlobalId,
size: u32,
}
fn inject_start(
module: &mut Module,
tls: &Tls,
stack: &Stack,
thread_counter_addr: i32,
memory: MemoryId,
) -> Result<ThreadCount, Error> {
use walrus::ir::*;
assert!(stack.size % PAGE_SIZE == 0);
let local = module.locals.add(ValType::I32);
let thread_count = module.locals.add(ValType::I32);
let malloc = find_function(module, "__wbindgen_malloc")?;
let builder = wasm_bindgen_wasm_conventions::get_or_insert_start_builder(module);
let mut body = builder.func_body();
body.i32_const(thread_counter_addr)
.i32_const(1)
.atomic_rmw(memory, AtomicOp::Add, AtomicWidth::I32, ATOMIC_MEM_ARG)
.local_tee(thread_count)
.if_else(
None,
|body| {
with_temp_stack(body, memory, &stack, |body| {
body.i32_const(stack.size as i32)
.call(malloc)
.local_tee(local);
});
body.global_set(stack.alloc);
body.global_get(stack.alloc)
.i32_const(stack.size as i32)
.binop(BinaryOp::I32Add)
.global_set(stack.pointer);
},
|_| {},
);
body.i32_const(tls.size as i32)
.i32_const(tls.align as i32)
.drop() .call(malloc)
.global_set(tls.base)
.global_get(tls.base)
.call(tls.init);
Ok(ThreadCount(thread_count))
}
fn inject_destroy(
module: &mut Module,
tls: &Tls,
stack: &Stack,
memory: MemoryId,
) -> Result<(), Error> {
let free = find_function(module, "__wbindgen_free")?;
let mut builder =
walrus::FunctionBuilder::new(&mut module.types, &[ValType::I32, ValType::I32], &[]);
builder.name("__wbindgen_thread_destroy".into());
let mut body = builder.func_body();
let tls_base = module.locals.add(ValType::I32);
let stack_alloc = module.locals.add(ValType::I32);
body.local_get(tls_base).if_else(
None,
|body| {
body.local_get(tls_base)
.i32_const(tls.size as i32)
.call(free);
},
|body| {
body.global_get(tls.base)
.i32_const(tls.size as i32)
.call(free);
body.i32_const(i32::MIN).global_set(tls.base);
},
);
body.local_get(stack_alloc).if_else(
None,
|body| {
body.local_get(stack_alloc)
.i32_const(stack.size as i32)
.call(free);
},
|mut body| {
with_temp_stack(&mut body, memory, stack, |body| {
body.global_get(stack.alloc)
.i32_const(stack.size as i32)
.call(free);
});
body.i32_const(0).global_set(stack.alloc);
},
);
let destroy_id = builder.finish(Vec::new(), &mut module.funcs);
module.exports.add("__wbindgen_thread_destroy", destroy_id);
Ok(())
}
fn find_function(module: &Module, name: &str) -> Result<FunctionId, Error> {
let e = module
.exports
.iter()
.find(|e| e.name == name)
.ok_or_else(|| anyhow!("failed to find `{}`", name))?;
match e.item {
walrus::ExportItem::Function(f) => Ok(f),
_ => bail!("`{}` wasn't a funtion", name),
}
}
fn with_temp_stack(
body: &mut InstrSeqBuilder<'_>,
memory: MemoryId,
stack: &Stack,
block: impl Fn(&mut InstrSeqBuilder<'_>),
) {
use walrus::ir::*;
body.i32_const(stack.temp).global_set(stack.pointer);
body.loop_(None, |loop_| {
let loop_id = loop_.id();
loop_
.i32_const(stack.temp_lock)
.i32_const(0)
.i32_const(1)
.cmpxchg(memory, AtomicWidth::I32, ATOMIC_MEM_ARG)
.if_else(
None,
|body| {
body.i32_const(stack.temp_lock)
.i32_const(1)
.i64_const(-1)
.atomic_wait(memory, ATOMIC_MEM_ARG, false)
.drop()
.br(loop_id);
},
|_| {},
);
});
block(body);
body.i32_const(stack.temp_lock)
.i32_const(0)
.store(memory, StoreKind::I32 { atomic: true }, ATOMIC_MEM_ARG)
.i32_const(stack.temp_lock)
.i32_const(1)
.atomic_notify(memory, ATOMIC_MEM_ARG)
.drop();
}