@ecmaos-apps/cmatrix-src 0.0.0-stage → 2.0.0-ecmaos.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -2
- package/build/build.sh +62 -0
- package/package.json +40 -4
- package/share/licenses/cmatrix/COPYING +674 -0
- package/share/licenses/cmatrix/SOURCE +27 -0
- package/sources/cmatrix-2.0.tar.gz +0 -0
- package/sources/ncurses-6.5.tar.gz +0 -0
- package/toolchain/emscripten-version +1 -0
- package/toolchain/rust-wali-version +3 -0
- package/toolchain/wali/asyncify-reach.mjs +107 -0
- package/toolchain/wali/asyncify.sh +57 -0
- package/toolchain/wali/build-sysroot.sh +158 -0
- package/toolchain/wali/patches/compiler-rt/0001-wasm-compare-result.patch +18 -0
- package/toolchain/wali/patches/musl/0001-environment-through-imports.patch +143 -0
- package/toolchain/wali/patches/musl/0002-setjmp-with-wasm-exceptions.patch +133 -0
- package/toolchain/wali/patches/musl/0003-unknown-syscall-is-enosys.patch +31 -0
- package/toolchain/wali/patches/musl/0004-return-from-main-is-exit.patch +53 -0
- package/toolchain/wali/patches/musl/0005-posix-spawn-through-the-host.patch +278 -0
- package/toolchain/wali/patches/musl/0006-detached-thread-frees-its-stack.patch +34 -0
- package/toolchain/wali/patches/musl/0007-wordexp-without-fork.patch +62 -0
- package/toolchain/wali/patches/musl/0008-progname-from-argv.patch +34 -0
- package/toolchain/wali/patches/musl/0009-no-basename-in-string-h.patch +15 -0
- package/toolchain/wali/patches/musl/0010-ssize-max-is-pointer-sized.patch +15 -0
- package/toolchain/wali/patches/musl/0011-startup-without-malloc.patch +85 -0
- package/toolchain/wali/patches/musl/0012-floatscan-fixes-from-musl.patch +39 -0
- package/toolchain/wali/patches/musl/0013-strptime-from-musl-with-glibc-s-and-z.patch +169 -0
- package/toolchain/wali/patches/musl/0014-wordexp-fixes-from-musl.patch +43 -0
- package/toolchain/wali/patches/musl/0015-long-double-is-ieee-quad.patch +202 -0
- package/toolchain/wali/patches/musl/0016-wordexp-nocmd-and-undef.patch +285 -0
- package/toolchain/wali/rust.sh +116 -0
- package/toolchain/wali/signal-checks.mjs +373 -0
- package/toolchain/wali-version +13 -0
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# shellcheck shell=bash
|
|
2
|
+
# SPDX-License-Identifier: MIT OR Apache-2.0
|
|
3
|
+
# Sourced by the build scripts of Rust programs, after utils/check-wali.sh. Builds with the nightly pinned in
|
|
4
|
+
# utils/rust-wali-version for wasm32-wali-linux-musl, linked by wali-cc (the clang driver flavor, so its link flags and
|
|
5
|
+
# the signal checks and Asyncify it adds apply) against the WALI sysroot's musl, std built along (-Z build-std).
|
|
6
|
+
#
|
|
7
|
+
# wali_cargo [cargo build arguments] build in the current crate; the program is target/wasm32-wali-linux-musl/release/
|
|
8
|
+
# wali_rust_licenses OUT_DIR the license texts of every crate the build used, one file per crate, in OUT_DIR
|
|
9
|
+
#
|
|
10
|
+
# std asks for a backtrace through libunwind, which WebAssembly cannot walk; a stub that finds no frames stands in, and a
|
|
11
|
+
# program checks after linking that nothing is left for the host to supply (`env` imports). rustix, which many crates
|
|
12
|
+
# use, makes raw syscalls on the architectures it knows, which wasm32 is not; it is told to go through libc.
|
|
13
|
+
|
|
14
|
+
_rust_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
|
|
15
|
+
# shellcheck source=../rust-wali-version
|
|
16
|
+
source "$_rust_dir/rust-wali-version"
|
|
17
|
+
command -v rustup > /dev/null || { echo "rust.sh: rustup not found" >&2; return 1 2>/dev/null || exit 1; }
|
|
18
|
+
rustup run "$RUST_TOOLCHAIN" rustc --version > /dev/null 2>&1 || { echo "rust.sh: install the toolchain: rustup toolchain install $RUST_TOOLCHAIN --component rust-src" >&2; return 1 2>/dev/null || exit 1; }
|
|
19
|
+
[ -d "$(rustup run "$RUST_TOOLCHAIN" rustc --print sysroot)/lib/rustlib/src/rust/library" ] || { echo "rust.sh: add rust-src: rustup component add rust-src --toolchain $RUST_TOOLCHAIN" >&2; return 1 2>/dev/null || exit 1; }
|
|
20
|
+
|
|
21
|
+
_rust_std_lock="$(rustup run "$RUST_TOOLCHAIN" rustc --print sysroot)/lib/rustlib/src/rust/library/Cargo.lock"
|
|
22
|
+
_rust_stub=$(mktemp -d)/unwind_stub.o
|
|
23
|
+
# _URC_END_OF_STACK (5) at once, and no frame, address or function for the questions a backtrace asks of a frame
|
|
24
|
+
cat > "${_rust_stub%.o}.c" <<'STUB'
|
|
25
|
+
typedef unsigned long uintptr;
|
|
26
|
+
int _Unwind_Backtrace(void *trace, void *arg) { (void)trace; (void)arg; return 5; }
|
|
27
|
+
uintptr _Unwind_GetIP(void *context) { (void)context; return 0; }
|
|
28
|
+
uintptr _Unwind_GetIPInfo(void *context, int *before) { (void)context; if (before) *before = 0; return 0; }
|
|
29
|
+
uintptr _Unwind_GetCFA(void *context) { (void)context; return 0; }
|
|
30
|
+
void *_Unwind_FindEnclosingFunction(void *pc) { (void)pc; return 0; }
|
|
31
|
+
uintptr _Unwind_GetRegionStart(void *context) { (void)context; return 0; }
|
|
32
|
+
uintptr _Unwind_GetLanguageSpecificData(void *context) { (void)context; return 0; }
|
|
33
|
+
uintptr _Unwind_GetDataRelBase(void *context) { (void)context; return 0; }
|
|
34
|
+
uintptr _Unwind_GetTextRelBase(void *context) { (void)context; return 0; }
|
|
35
|
+
STUB
|
|
36
|
+
"$WALI_CC" -c -O2 "${_rust_stub%.o}.c" -o "$_rust_stub"
|
|
37
|
+
|
|
38
|
+
# Crates that many others use know Linux only on the architectures they list, and wasm32 is not one: linux-raw-sys,
|
|
39
|
+
# which rustix takes Linux's constants and structures from, and rustix's own ioctl encoding; and mio refuses every wasm
|
|
40
|
+
# target but WASI, where on WALI its Unix code applies. And libc gives SIG_IGN as 1, Linux's, where WALI's musl has -2
|
|
41
|
+
# (a table can hold a function at index 1): std ignores SIGPIPE at start, which would have made the host take function 1
|
|
42
|
+
# for its handler. The libc std is built with is patched too, so every program needs the patches. WALI uses the x86_64 kernel
|
|
43
|
+
# ABI with 32-bit pointers, which is x32's, so wasm32 is given x32's linux-raw-sys modules and the x86 family's ioctl
|
|
44
|
+
# numbers: each version the crate locks is copied, edited, and patched in through the crate's .cargo/config.toml.
|
|
45
|
+
_WALI_PATCHES=(
|
|
46
|
+
'linux-raw-sys|src/lib.rs|s/all(target_arch = "x86_64", target_pointer_width = "32")/any(all(target_arch = "x86_64", target_pointer_width = "32"), target_arch = "wasm32")/g; s/^\(\s*\)target_arch = "x86_64",$/\1target_arch = "x86_64",\n\1target_arch = "wasm32",/'
|
|
47
|
+
'rustix|src/ioctl/linux.rs|s/^\(\s*\)target_arch = "x86_64",$/\1target_arch = "x86_64",\n\1target_arch = "wasm32",/'
|
|
48
|
+
'mio|src/lib.rs|s/^#\[cfg(all(target_family = "wasm", not(target_os = "wasi")))\]$/#[cfg(all(target_family = "wasm", not(target_os = "wasi"), not(target_os = "linux")))]/'
|
|
49
|
+
'libc|src/unix/mod.rs|s/^pub const SIG_IGN: sighandler_t = 1 as sighandler_t;$/#[cfg(not(all(target_arch = "wasm32", target_os = "linux")))]\npub const SIG_IGN: sighandler_t = 1 as sighandler_t;\n\/\/ WALI'"'"'s musl: a WebAssembly table can have a function at index 1, so ignoring a signal is -2\n#[cfg(all(target_arch = "wasm32", target_os = "linux"))]\npub const SIG_IGN: sighandler_t = -2isize as sighandler_t;/'
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
wali_patch_crates() {
|
|
53
|
+
# once is enough: a second build in the same tree keeps the patches it has
|
|
54
|
+
grep -q '\.wali-patches/' .cargo/config.toml 2>/dev/null && return 0
|
|
55
|
+
cargo "+$RUST_TOOLCHAIN" fetch --locked > /dev/null 2>&1 || true
|
|
56
|
+
local entry name file edit version dir copy n=0 patched=
|
|
57
|
+
mkdir -p .cargo .wali-patches
|
|
58
|
+
for entry in "${_WALI_PATCHES[@]}"; do
|
|
59
|
+
IFS='|' read -r name file edit <<< "$entry"
|
|
60
|
+
for version in $(awk -v want="$name" '$0 == "name = \"" want "\"" { getline; gsub(/version = |"/, ""); print }' Cargo.lock "$_rust_std_lock" | sort -u); do
|
|
61
|
+
dir=$(ls -d "${CARGO_HOME:-$HOME/.cargo}"/registry/src/*/"$name-$version" 2>/dev/null | head -1)
|
|
62
|
+
[ -n "$dir" ] || { echo "rust.sh: $name $version was not fetched" >&2; return 1; }
|
|
63
|
+
[ -f "$dir/$file" ] || continue
|
|
64
|
+
copy="$PWD/.wali-patches/$name-$version"
|
|
65
|
+
rm -rf "$copy" && cp -r "$dir" "$copy" && chmod -R u+w "$copy"
|
|
66
|
+
sed -i "$edit" "$copy/$file"
|
|
67
|
+
# a version the edit finds nothing in needs none (mio 0.8 has no refusal), and is left as it is
|
|
68
|
+
if cmp -s "$dir/$file" "$copy/$file"; then rm -rf "$copy"; continue; fi
|
|
69
|
+
# a crate's own config may not end its last line
|
|
70
|
+
[ -n "$patched" ] || { printf '\n[patch.crates-io]\n' >> .cargo/config.toml; patched=1; }
|
|
71
|
+
echo "$name-wali-$n = { path = \"$copy\", package = \"$name\" }" >> .cargo/config.toml
|
|
72
|
+
n=$((n + 1))
|
|
73
|
+
done
|
|
74
|
+
done
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
wali_cargo() {
|
|
78
|
+
# The libc crate learned WALI's ABI (64-bit long, as wali-cc's clang has it) in a later 0.2 than many crates lock; one
|
|
79
|
+
# that predates it takes this target for 32-bit and calls musl with the wrong signatures, which wasm-ld turns into
|
|
80
|
+
# traps (`sysconf_bitcast_invalid`). So every libc in the lock becomes the one std is built with, and with the
|
|
81
|
+
# patches below that is the only change to the lock: the other versions stay as they were.
|
|
82
|
+
local locked= std_libc version
|
|
83
|
+
std_libc=$(awk '/^name = "libc"$/ { getline; gsub(/version = |"/, ""); print; exit }' "$_rust_std_lock")
|
|
84
|
+
for version in $(awk '/^name = "libc"$/ { getline; gsub(/version = |"/, ""); print }' Cargo.lock 2>/dev/null | sort -u); do
|
|
85
|
+
[ "$version" = "$std_libc" ] || cargo "+$RUST_TOOLCHAIN" update -q -p "libc@$version" --precise "$std_libc" || return 1
|
|
86
|
+
done
|
|
87
|
+
wali_patch_crates || return 1
|
|
88
|
+
CARGO_TARGET_WASM32_WALI_LINUX_MUSL_LINKER="$WALI_CC" CC_wasm32_wali_linux_musl="$WALI_CC" AR_wasm32_wali_linux_musl="$WALI_AR" \
|
|
89
|
+
RUSTFLAGS="--remap-path-prefix=$HOME=/build --remap-path-prefix=${CARGO_HOME:-$HOME/.cargo}=/cargo --remap-path-prefix=$PWD=/src -Z unstable-options -C target-feature=+atomics,+bulk-memory,+exception-handling -C link-self-contained=no -C linker-flavor=wasm-lld-cc -C link-arg=$_rust_stub --cfg rustix_use_libc" \
|
|
90
|
+
cargo "+$RUST_TOOLCHAIN" build --release $locked -Z build-std=std,panic_abort --target wasm32-wali-linux-musl "$@"
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
# A program the host could not start: one that imports what the WALI host has not got
|
|
94
|
+
wali_check_imports() {
|
|
95
|
+
node -e 'const m = new WebAssembly.Module(require("fs").readFileSync(process.argv[1])); const bad = WebAssembly.Module.imports(m).filter(i => i.module !== "wali").map(i => `${i.module}.${i.name}`); if (bad.length) { console.error(`${process.argv[1]}: imports what the WALI host has not got: ${bad.join(" ")}`); process.exit(1) }' "$1"
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
wali_rust_licenses() {
|
|
99
|
+
# the crates the program is built from: normal and build dependencies for this target, with the features the build
|
|
100
|
+
# used (the arguments after OUT_DIR), not the ones only its tests use
|
|
101
|
+
local out=$1; shift
|
|
102
|
+
mkdir -p "$out"
|
|
103
|
+
local used
|
|
104
|
+
used=$(cargo "+$RUST_TOOLCHAIN" tree --target wasm32-wali-linux-musl -e normal,build --prefix none -f '{p}' "$@" | sed 's/ (.*//; s/ /@/' | sort -u)
|
|
105
|
+
cargo "+$RUST_TOOLCHAIN" metadata --format-version 1 | node -e '
|
|
106
|
+
const fs = require("fs"), path = require("path")
|
|
107
|
+
const meta = JSON.parse(fs.readFileSync(0, "utf8"))
|
|
108
|
+
const used = new Set(process.argv[2].split("\n").filter(Boolean).map(line => line.replace(/@v/, "@")))
|
|
109
|
+
for (const pkg of meta.packages) {
|
|
110
|
+
if (!used.has(`${pkg.name}@${pkg.version}`)) continue
|
|
111
|
+
const dir = path.dirname(pkg.manifest_path)
|
|
112
|
+
const texts = fs.readdirSync(dir).filter(name => /^(LICEN[CS]E|COPYING|UNLICENSE|COPYRIGHT|NOTICE)/i.test(name)).sort()
|
|
113
|
+
const body = texts.map(name => `---- ${name}\n\n${fs.readFileSync(path.join(dir, name), "utf8").trim()}\n`).join("\n")
|
|
114
|
+
fs.writeFileSync(path.join(process.argv[1], `${pkg.name}-${pkg.version}`), `${pkg.name} ${pkg.version} (${pkg.license ?? "see the texts"})\n${pkg.repository ?? ""}\n\n${body || "(the crate ships no license file; its license is the one named above)\n"}`)
|
|
115
|
+
}' "$out" "$used"
|
|
116
|
+
}
|
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Puts a signal check at the top of every loop of a linked WALI program, so a signal reaches a program that is busy
|
|
4
|
+
* computing: Linux interrupts it wherever it is, but a WebAssembly thread can only be ended from outside, not
|
|
5
|
+
* interrupted, and the host runs handlers when an import returns. Each loop reads a word the kernel sets as it raises
|
|
6
|
+
* a signal on one of the process's threads (or stops it), and when it is set calls the import `wali.__ecmaos_poll`,
|
|
7
|
+
* whose return delivers what is pending, as any import's does. The word is at a fixed address, so a loop reads it
|
|
8
|
+
* with one load (a global holding a thread's own address costs a tight loop up to a fifth of its speed, against a few
|
|
9
|
+
* percent): address 8, at the bottom of the main thread's stack, which wali-cc lays out first (the program exports
|
|
10
|
+
* the address as `__ecmaos_signal_word`, for the host).
|
|
11
|
+
*
|
|
12
|
+
* The stack pointer (global 0, as wasm-ld lays a program out) is lowered by 128 bytes around the call: LLVM lets a
|
|
13
|
+
* leaf function keep up to that much below it without moving it (a red zone), which a handler would overwrite. The
|
|
14
|
+
* program exports it as `__ecmaos_stack_pointer`, so the host can run a handler on an alternate stack (`sigaltstack`).
|
|
15
|
+
*
|
|
16
|
+
* The program is rewritten in place, in binary: the import is added after the others, so every function the program
|
|
17
|
+
* defines moves up one, and each reference to one (calls, `ref.func`, the element segments, exports, start, the name
|
|
18
|
+
* section) follows. DWARF's sections, whose code offsets move, are dropped.
|
|
19
|
+
*
|
|
20
|
+
* Usage: signal-checks.mjs <program.wasm>. WALI's wali-cc and wali-c++ run it on each program they link.
|
|
21
|
+
*/
|
|
22
|
+
import { readFileSync, writeFileSync } from 'node:fs'
|
|
23
|
+
|
|
24
|
+
const RED_ZONE = 128, WORD = 8
|
|
25
|
+
/** The main thread's stack, which wali-cc puts first in memory, so global 0, the stack pointer, starts at its size */
|
|
26
|
+
const STACK_SIZE = 8388608
|
|
27
|
+
const POLL_MODULE = 'wali', POLL_NAME = '__ecmaos_poll', WORD_EXPORT = '__ecmaos_signal_word', STACK_POINTER_EXPORT = '__ecmaos_stack_pointer', GLOBAL_EXPORT = '__ecmaos_global_'
|
|
28
|
+
|
|
29
|
+
// --- encoding ---
|
|
30
|
+
|
|
31
|
+
class Reader {
|
|
32
|
+
constructor(bytes, at = 0) { this.bytes = bytes; this.at = at }
|
|
33
|
+
byte() { return this.bytes[this.at++] }
|
|
34
|
+
u32() {
|
|
35
|
+
let result = 0, shift = 0, byte
|
|
36
|
+
do { byte = this.bytes[this.at++]; result |= (byte & 0x7f) << shift; shift += 7 } while (byte & 0x80)
|
|
37
|
+
return result >>> 0
|
|
38
|
+
}
|
|
39
|
+
s32() {
|
|
40
|
+
let result = 0, shift = 0, byte
|
|
41
|
+
do { byte = this.bytes[this.at++]; result |= (byte & 0x7f) << shift; shift += 7 } while (byte & 0x80)
|
|
42
|
+
return shift < 32 && (byte & 0x40) ? result | (-1 << shift) : result
|
|
43
|
+
}
|
|
44
|
+
/** Any LEB128, signed or not, of any width: only skipped */
|
|
45
|
+
skipLeb() { while (this.bytes[this.at++] & 0x80);}
|
|
46
|
+
skip(n) { this.at += n }
|
|
47
|
+
name() { const length = this.u32(); const text = new TextDecoder().decode(this.bytes.subarray(this.at, this.at + length)); this.at += length; return text }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const u32 = value => {
|
|
51
|
+
const out = []
|
|
52
|
+
do { let byte = value & 0x7f; value >>>= 7; if (value) byte |= 0x80; out.push(byte) } while (value)
|
|
53
|
+
return out
|
|
54
|
+
}
|
|
55
|
+
const s32 = value => {
|
|
56
|
+
const out = []
|
|
57
|
+
for (;;) {
|
|
58
|
+
const byte = value & 0x7f
|
|
59
|
+
value >>= 7
|
|
60
|
+
if ((value === 0 && !(byte & 0x40)) || (value === -1 && (byte & 0x40))) { out.push(byte); return out }
|
|
61
|
+
out.push(byte | 0x80)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const name = text => { const bytes = new TextEncoder().encode(text); return [...u32(bytes.length), ...bytes] }
|
|
65
|
+
const vector = items => [...u32(items.length), ...items.flat()]
|
|
66
|
+
|
|
67
|
+
// --- instructions ---
|
|
68
|
+
|
|
69
|
+
/** A block type: empty (0x40), a value type, or a type index (an s33) */
|
|
70
|
+
function skipBlockType(r) {
|
|
71
|
+
const byte = r.bytes[r.at]
|
|
72
|
+
if (byte === 0x40 || (byte >= 0x69 && byte <= 0x7f)) return r.skip(1)
|
|
73
|
+
if (byte === 0x63 || byte === 0x64) { r.skip(1); return r.skipLeb() }
|
|
74
|
+
r.skipLeb()
|
|
75
|
+
}
|
|
76
|
+
function skipValType(r) {
|
|
77
|
+
const byte = r.byte()
|
|
78
|
+
if (byte === 0x63 || byte === 0x64) r.skipLeb()
|
|
79
|
+
}
|
|
80
|
+
function skipMemarg(r) {
|
|
81
|
+
const align = r.u32()
|
|
82
|
+
if (align & 0x40) r.u32()
|
|
83
|
+
r.skipLeb()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Copies an expression (a function's body or a constant expression), renumbering function indices with `fn` and,
|
|
88
|
+
* when `atLoop` is given, adding what it returns after each loop's header. Stops after the `end` that closes it.
|
|
89
|
+
*/
|
|
90
|
+
function copyExpression(r, out, fn, atLoop) {
|
|
91
|
+
let depth = 1, from = r.at
|
|
92
|
+
const flush = () => { for (let i = from; i < r.at; i++) out.push(r.bytes[i]) }
|
|
93
|
+
const funcref = () => { flush(); out.push(...u32(fn(r.u32()))); from = r.at }
|
|
94
|
+
while (depth) {
|
|
95
|
+
const op = r.byte()
|
|
96
|
+
switch (op) {
|
|
97
|
+
case 0x02: case 0x04: case 0x06: skipBlockType(r); depth++; break
|
|
98
|
+
case 0x03: skipBlockType(r); depth++; if (atLoop) { flush(); out.push(...atLoop()); from = r.at } break
|
|
99
|
+
case 0x1f: { // try_table
|
|
100
|
+
skipBlockType(r); depth++
|
|
101
|
+
for (let n = r.u32(); n--;) { const kind = r.byte(); if (kind < 2) r.u32(); r.u32() }
|
|
102
|
+
break
|
|
103
|
+
}
|
|
104
|
+
case 0x0b: depth--; break
|
|
105
|
+
case 0x18: r.u32(); depth--; break // delegate ends its try
|
|
106
|
+
case 0x05: case 0x19: case 0x00: case 0x01: case 0x0f: case 0x1a: case 0x1b: case 0x0a: case 0xd1: case 0xd3: case 0xd5: break
|
|
107
|
+
case 0x07: case 0x08: case 0x09: case 0x0c: case 0x0d: case 0xd4: case 0xd6: r.u32(); break
|
|
108
|
+
case 0x0e: for (let n = r.u32() + 1; n--;) r.u32(); break
|
|
109
|
+
case 0x10: case 0x12: case 0xd2: funcref(); break
|
|
110
|
+
case 0x11: case 0x13: r.u32(); r.u32(); break
|
|
111
|
+
case 0x14: case 0x15: r.u32(); break
|
|
112
|
+
case 0x1c: for (let n = r.u32(); n--;) skipValType(r); break
|
|
113
|
+
case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: r.u32(); break
|
|
114
|
+
case 0x3f: case 0x40: r.u32(); break
|
|
115
|
+
case 0x41: case 0x42: r.skipLeb(); break
|
|
116
|
+
case 0x43: r.skip(4); break
|
|
117
|
+
case 0x44: r.skip(8); break
|
|
118
|
+
case 0xd0: r.skipLeb(); break
|
|
119
|
+
case 0xfc: {
|
|
120
|
+
const sub = r.u32()
|
|
121
|
+
if (sub <= 7) break
|
|
122
|
+
if (sub === 8 || sub === 10 || sub === 12 || sub === 14) { r.u32(); r.u32() } else if (sub <= 17) r.u32()
|
|
123
|
+
else throw new Error(`unknown instruction 0xfc ${sub}`)
|
|
124
|
+
break
|
|
125
|
+
}
|
|
126
|
+
case 0xfd: {
|
|
127
|
+
const sub = r.u32()
|
|
128
|
+
if (sub <= 0x0b || sub === 0x5c || sub === 0x5d) skipMemarg(r)
|
|
129
|
+
else if (sub === 0x0c || sub === 0x0d) r.skip(16)
|
|
130
|
+
else if (sub >= 0x15 && sub <= 0x22) r.skip(1)
|
|
131
|
+
else if (sub >= 0x54 && sub <= 0x5b) { skipMemarg(r); r.skip(1) }
|
|
132
|
+
break
|
|
133
|
+
}
|
|
134
|
+
case 0xfe: {
|
|
135
|
+
const sub = r.u32()
|
|
136
|
+
if (sub === 0x03) r.skip(1)
|
|
137
|
+
else if (sub <= 0x02 || (sub >= 0x10 && sub <= 0x4e)) skipMemarg(r)
|
|
138
|
+
else throw new Error(`unknown instruction 0xfe ${sub}`)
|
|
139
|
+
break
|
|
140
|
+
}
|
|
141
|
+
default:
|
|
142
|
+
if (op >= 0x28 && op <= 0x3e) skipMemarg(r)
|
|
143
|
+
else if (!(op >= 0x45 && op <= 0xc4)) throw new Error(`unknown instruction 0x${op.toString(16)} at ${r.at - 1}`)
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
flush()
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// --- the module ---
|
|
150
|
+
|
|
151
|
+
const program = process.argv[2]
|
|
152
|
+
if (!program) {
|
|
153
|
+
console.error('usage: signal-checks.mjs <program.wasm>')
|
|
154
|
+
process.exit(2)
|
|
155
|
+
}
|
|
156
|
+
const bytes = readFileSync(program)
|
|
157
|
+
// what a configure script links to see whether it can, say, is still a program; anything else is left alone
|
|
158
|
+
if (bytes.length < 8 || bytes.readUInt32LE(0) !== 0x6d736100) process.exit(0)
|
|
159
|
+
|
|
160
|
+
const sections = []
|
|
161
|
+
for (const r = new Reader(bytes, 8); r.at < bytes.length;) {
|
|
162
|
+
const id = r.byte(), size = r.u32()
|
|
163
|
+
sections.push({ id, body: bytes.subarray(r.at, r.at + size) })
|
|
164
|
+
r.skip(size)
|
|
165
|
+
}
|
|
166
|
+
const section = id => sections.find(s => s.id === id)
|
|
167
|
+
const customName = s => new Reader(s.body).name()
|
|
168
|
+
// an object file (a relocatable link, -r) is not a program yet: its link checks it
|
|
169
|
+
if (sections.some(s => s.id === 0 && customName(s) === 'linking')) process.exit(0)
|
|
170
|
+
|
|
171
|
+
// the types: a `() -> ()` to give the import and the check, added if the program has none
|
|
172
|
+
const types = []
|
|
173
|
+
{
|
|
174
|
+
const r = new Reader(section(1).body)
|
|
175
|
+
for (let n = r.u32(); n--;) {
|
|
176
|
+
const start = r.at
|
|
177
|
+
if (r.byte() !== 0x60) throw new Error(`${program}: a type other than a function's`)
|
|
178
|
+
const params = r.u32(); for (let i = params; i--;) skipValType(r)
|
|
179
|
+
const results = r.u32(); for (let i = results; i--;) skipValType(r)
|
|
180
|
+
types.push([...r.bytes.subarray(start, r.at)])
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
let voidType = types.findIndex(type => type.length === 3 && type[1] === 0 && type[2] === 0)
|
|
184
|
+
if (voidType < 0) { voidType = types.length; types.push([0x60, 0, 0]) }
|
|
185
|
+
|
|
186
|
+
// the imports: how many functions and globals, and whether this was done already
|
|
187
|
+
const imports = []
|
|
188
|
+
let importedFunctions = 0, importedGlobals = 0
|
|
189
|
+
{
|
|
190
|
+
const r = new Reader(section(2)?.body ?? new Uint8Array([0]))
|
|
191
|
+
for (let n = r.u32(); n--;) {
|
|
192
|
+
const start = r.at
|
|
193
|
+
const module = r.name(), field = r.name(), kind = r.byte()
|
|
194
|
+
if (module === POLL_MODULE && field === POLL_NAME) process.exit(0)
|
|
195
|
+
if (kind === 0) { r.u32(); importedFunctions++ }
|
|
196
|
+
else if (kind === 1) { skipValType(r); const flags = r.u32(); r.u32(); if (flags & 1) r.u32() }
|
|
197
|
+
else if (kind === 2) { const flags = r.u32(); r.u32(); if (flags & 1) r.u32() }
|
|
198
|
+
else if (kind === 3) { skipValType(r); r.byte(); importedGlobals++ }
|
|
199
|
+
else if (kind === 4) { r.byte(); r.u32() }
|
|
200
|
+
imports.push([...r.bytes.subarray(start, r.at)])
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
if (importedGlobals) throw new Error(`${program}: imports a global, so global 0 is not the stack pointer`)
|
|
204
|
+
const poll = importedFunctions
|
|
205
|
+
imports.push([...name(POLL_MODULE), ...name(POLL_NAME), 0, ...u32(voidType)])
|
|
206
|
+
const fn = index => index < importedFunctions ? index : index + 1
|
|
207
|
+
|
|
208
|
+
// the functions it defines: the check goes after them
|
|
209
|
+
const functions = []
|
|
210
|
+
{
|
|
211
|
+
const r = new Reader(section(3).body)
|
|
212
|
+
for (let n = r.u32(); n--;) functions.push(r.u32())
|
|
213
|
+
}
|
|
214
|
+
const check = importedFunctions + 1 + functions.length
|
|
215
|
+
functions.push(voidType)
|
|
216
|
+
|
|
217
|
+
const globals = []
|
|
218
|
+
{
|
|
219
|
+
const r = new Reader(section(6).body)
|
|
220
|
+
for (let n = r.u32(); n--;) {
|
|
221
|
+
const type = [...r.bytes.subarray(r.at, r.at + 2)]
|
|
222
|
+
r.skip(2)
|
|
223
|
+
const init = []
|
|
224
|
+
copyExpression(r, init, fn)
|
|
225
|
+
globals.push([...type, ...init])
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (globals[0]?.[0] !== 0x7f || globals[0][1] !== 1) throw new Error(`${program}: global 0 is not a mutable i32, so not the stack pointer`)
|
|
229
|
+
const stackTop = new Reader(Uint8Array.from(globals[0]), 3)
|
|
230
|
+
if (globals[0][2] !== 0x41 || stackTop.s32() !== STACK_SIZE) throw new Error(`${program}: the stack does not come first in memory, so address ${WORD} is not free`)
|
|
231
|
+
const word = globals.length
|
|
232
|
+
globals.push([0x7f, 0, 0x41, ...s32(WORD), 0x0b])
|
|
233
|
+
|
|
234
|
+
// each loop reads the word and calls the check when it is set. The load is a plain one: an atomic one costs a tight
|
|
235
|
+
// loop a third of its speed, and engines do not take a load of shared memory out of a loop (a C program's volatile
|
|
236
|
+
// spin is the same load). The `if` is hinted as rarely taken (the branch hints section), or the call in the loop
|
|
237
|
+
// costs bzip2 half its speed again.
|
|
238
|
+
const head = [0x41, ...s32(WORD), 0x28, 2, 0]
|
|
239
|
+
const atLoop = [...head, 0x04, 0x40, 0x10, ...u32(check), 0x0b]
|
|
240
|
+
// the check: the import, called below the red zone
|
|
241
|
+
const checkBody = [0, // no locals
|
|
242
|
+
0x23, 0, 0x41, ...s32(RED_ZONE), 0x6b, 0x24, 0,
|
|
243
|
+
0x10, ...u32(poll),
|
|
244
|
+
0x23, 0, 0x41, ...s32(RED_ZONE), 0x6a, 0x24, 0,
|
|
245
|
+
0x0b]
|
|
246
|
+
|
|
247
|
+
let loops = 0
|
|
248
|
+
const bodies = []
|
|
249
|
+
/** Per function that has a loop, its index and where in its body each check's `if` is */
|
|
250
|
+
const hints = []
|
|
251
|
+
{
|
|
252
|
+
const r = new Reader(section(10).body)
|
|
253
|
+
for (let n = r.u32(); n--;) {
|
|
254
|
+
const size = r.u32(), end = r.at + size
|
|
255
|
+
// the locals, as they are
|
|
256
|
+
const out = []
|
|
257
|
+
const start = r.at
|
|
258
|
+
for (let groups = r.u32(); groups--;) { r.u32(); skipValType(r) }
|
|
259
|
+
out.push(...r.bytes.subarray(start, r.at))
|
|
260
|
+
const branches = []
|
|
261
|
+
copyExpression(r, out, fn, () => {
|
|
262
|
+
loops++
|
|
263
|
+
// a hint's offset counts from the start of the body, its locals included
|
|
264
|
+
branches.push(out.length + head.length)
|
|
265
|
+
return atLoop
|
|
266
|
+
})
|
|
267
|
+
if (r.at !== end) throw new Error(`${program}: a function body ends at ${r.at}, not ${end}`)
|
|
268
|
+
if (branches.length) hints.push([...u32(fn(importedFunctions + bodies.length)), ...vector(branches.map(at => [...u32(at), 1, 0]))])
|
|
269
|
+
bodies.push([...u32(out.length), ...out])
|
|
270
|
+
}
|
|
271
|
+
bodies.push([...u32(checkBody.length), ...checkBody])
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** The exports, renumbered, and for the host the word's global and the stack pointer (a handler's alternate stack) */
|
|
275
|
+
function exportsRenumbered(body) {
|
|
276
|
+
const r = new Reader(body), out = []
|
|
277
|
+
const n = r.u32()
|
|
278
|
+
// the other mutable globals (the thread pointer of the TLS above all), which a forked child starts with the values its
|
|
279
|
+
// parent has (the host copies them, `bin/wali-host.mjs` `drive`)
|
|
280
|
+
const state = globals.map((g, index) => g[1] === 1 && index !== 0 ? index : -1).filter(index => index >= 0)
|
|
281
|
+
out.push(...u32(n + 2 + state.length))
|
|
282
|
+
for (let i = n; i--;) {
|
|
283
|
+
const field = r.name(), kind = r.byte(), index = r.u32()
|
|
284
|
+
out.push(...name(field), kind, ...u32(kind === 0 ? fn(index) : index))
|
|
285
|
+
}
|
|
286
|
+
out.push(...name(WORD_EXPORT), 3, ...u32(word))
|
|
287
|
+
out.push(...name(STACK_POINTER_EXPORT), 3, 0)
|
|
288
|
+
for (const index of state) out.push(...name(`${GLOBAL_EXPORT}${index}`), 3, ...u32(index))
|
|
289
|
+
return out
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function elementsRenumbered(body) {
|
|
293
|
+
const r = new Reader(body), out = []
|
|
294
|
+
const n = r.u32()
|
|
295
|
+
out.push(...u32(n))
|
|
296
|
+
for (let i = n; i--;) {
|
|
297
|
+
const flags = r.u32()
|
|
298
|
+
out.push(...u32(flags))
|
|
299
|
+
if (flags & 2 && !(flags & 1)) out.push(...u32(r.u32())) // a table index
|
|
300
|
+
if (!(flags & 1)) copyExpression(r, out, fn) // the offset
|
|
301
|
+
const expressions = flags & 4
|
|
302
|
+
if (flags & 3) { // an element kind, or a reference type
|
|
303
|
+
const at = r.at; expressions ? skipValType(r) : r.byte(); out.push(...r.bytes.subarray(at, r.at))
|
|
304
|
+
}
|
|
305
|
+
const count = r.u32()
|
|
306
|
+
out.push(...u32(count))
|
|
307
|
+
for (let j = count; j--;) expressions ? copyExpression(r, out, fn) : out.push(...u32(fn(r.u32())))
|
|
308
|
+
}
|
|
309
|
+
return out
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* The name section, renumbered: the function, local and label names are by function index (Binaryen finds the stack
|
|
314
|
+
* pointer by its name, for one), and the import and the check get theirs
|
|
315
|
+
*/
|
|
316
|
+
function namesRenumbered(body) {
|
|
317
|
+
const r = new Reader(body), out = [...name('name')]
|
|
318
|
+
r.name()
|
|
319
|
+
while (r.at < body.length) {
|
|
320
|
+
const id = r.byte(), size = r.u32(), end = r.at + size
|
|
321
|
+
let content
|
|
322
|
+
if (id === 1) {
|
|
323
|
+
const entries = []
|
|
324
|
+
for (let n = r.u32(); n--;) {
|
|
325
|
+
const index = fn(r.u32())
|
|
326
|
+
entries.push([index, r.name()])
|
|
327
|
+
}
|
|
328
|
+
entries.push([poll, POLL_NAME], [check, '__ecmaos_signal_check'])
|
|
329
|
+
entries.sort((a, b) => a[0] - b[0])
|
|
330
|
+
content = vector(entries.map(([index, text]) => [...u32(index), ...name(text)]))
|
|
331
|
+
} else if (id === 2 || id === 3) {
|
|
332
|
+
// per function, its locals' or labels' names, which stay as they are
|
|
333
|
+
const count = r.u32()
|
|
334
|
+
content = [...u32(count)]
|
|
335
|
+
for (let n = count; n--;) {
|
|
336
|
+
const index = r.u32(), at = r.at
|
|
337
|
+
for (let m = r.u32(); m--;) { r.u32(); r.name() }
|
|
338
|
+
content.push(...u32(fn(index)), ...r.bytes.subarray(at, r.at))
|
|
339
|
+
}
|
|
340
|
+
} else content = [...r.bytes.subarray(r.at, end)]
|
|
341
|
+
r.at = end
|
|
342
|
+
out.push(id, ...u32(content.length))
|
|
343
|
+
for (const byte of content) out.push(byte)
|
|
344
|
+
}
|
|
345
|
+
return out
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const rebuilt = {
|
|
349
|
+
1: vector(types),
|
|
350
|
+
2: vector(imports),
|
|
351
|
+
3: [...u32(functions.length), ...functions.flatMap(type => u32(type))],
|
|
352
|
+
6: vector(globals),
|
|
353
|
+
7: exportsRenumbered(section(7).body),
|
|
354
|
+
8: section(8) && u32(fn(new Reader(section(8).body).u32())),
|
|
355
|
+
9: section(9) && elementsRenumbered(section(9).body),
|
|
356
|
+
10: vector(bodies)
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
const parts = [bytes.subarray(0, 8)]
|
|
360
|
+
for (const s of sections) {
|
|
361
|
+
if (s.id === 0 && (customName(s).startsWith('.debug') || customName(s) === 'metadata.code.branch_hint')) continue
|
|
362
|
+
// the hints go before the code they are about
|
|
363
|
+
if (s.id === 10) {
|
|
364
|
+
const hinted = [...name('metadata.code.branch_hint'), ...vector(hints)]
|
|
365
|
+
parts.push(new Uint8Array([0, ...u32(hinted.length)]), Uint8Array.from(hinted))
|
|
366
|
+
}
|
|
367
|
+
const body = s.id === 0 && customName(s) === 'name' ? namesRenumbered(s.body) : rebuilt[s.id] ?? s.body
|
|
368
|
+
parts.push(new Uint8Array([s.id, ...u32(body.length)]), Uint8Array.from(body))
|
|
369
|
+
}
|
|
370
|
+
const result = new Uint8Array(Buffer.concat(parts))
|
|
371
|
+
if (!WebAssembly.validate(result)) throw new Error(`${program}: the rewritten module does not validate`)
|
|
372
|
+
writeFileSync(program, result)
|
|
373
|
+
if (process.env.SIGNAL_CHECKS_VERBOSE) console.error(`signal-checks: ${program}: ${loops} loops`)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# The WALI toolchain programs are built with (utils/check-wali.sh): WALI's musl at a commit, and the LLVM release
|
|
2
|
+
# whose compiler-rt and libc++ go into the sysroot. clang and wasm-ld come from the system and must be this LLVM
|
|
3
|
+
# major. Binaryen's wasm-opt (also from the system, this major) rewrites a program that links fork so it can (utils/wali/asyncify.sh).
|
|
4
|
+
# The Linux UAPI headers (linux/*.h, asm/*.h) are sabotage's sanitized copy of a long-term kernel's, for
|
|
5
|
+
# x86_64, whose structures this target shares; they are only compiled against. Changing anything here (or a patch in
|
|
6
|
+
# utils/wali/patches) builds a new sysroot.
|
|
7
|
+
MUSL_COMMIT=243ec00c3ffb910375db487d7eb24ea76d1e2c9f
|
|
8
|
+
MUSL_SHA256=abc909cd96ef88ba01da29a29951f77e3ad97cdb2b4faa272f46fa154880d432
|
|
9
|
+
LLVM_VERSION=23.1.3
|
|
10
|
+
LLVM_SHA256=c44186a7762ed28954be72e5ff6df9808e0779d4f1bf014ecc4e7e211d31ee34
|
|
11
|
+
KERNEL_HEADERS_VERSION=4.19.88-2
|
|
12
|
+
KERNEL_HEADERS_SHA256=dc7abf734487553644258a3822cfd429d74656749e309f2b25f09f4282e05588
|
|
13
|
+
BINARYEN_VERSION=133
|