@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.
Files changed (32) hide show
  1. package/README.md +8 -2
  2. package/build/build.sh +62 -0
  3. package/package.json +40 -4
  4. package/share/licenses/cmatrix/COPYING +674 -0
  5. package/share/licenses/cmatrix/SOURCE +27 -0
  6. package/sources/cmatrix-2.0.tar.gz +0 -0
  7. package/sources/ncurses-6.5.tar.gz +0 -0
  8. package/toolchain/emscripten-version +1 -0
  9. package/toolchain/rust-wali-version +3 -0
  10. package/toolchain/wali/asyncify-reach.mjs +107 -0
  11. package/toolchain/wali/asyncify.sh +57 -0
  12. package/toolchain/wali/build-sysroot.sh +158 -0
  13. package/toolchain/wali/patches/compiler-rt/0001-wasm-compare-result.patch +18 -0
  14. package/toolchain/wali/patches/musl/0001-environment-through-imports.patch +143 -0
  15. package/toolchain/wali/patches/musl/0002-setjmp-with-wasm-exceptions.patch +133 -0
  16. package/toolchain/wali/patches/musl/0003-unknown-syscall-is-enosys.patch +31 -0
  17. package/toolchain/wali/patches/musl/0004-return-from-main-is-exit.patch +53 -0
  18. package/toolchain/wali/patches/musl/0005-posix-spawn-through-the-host.patch +278 -0
  19. package/toolchain/wali/patches/musl/0006-detached-thread-frees-its-stack.patch +34 -0
  20. package/toolchain/wali/patches/musl/0007-wordexp-without-fork.patch +62 -0
  21. package/toolchain/wali/patches/musl/0008-progname-from-argv.patch +34 -0
  22. package/toolchain/wali/patches/musl/0009-no-basename-in-string-h.patch +15 -0
  23. package/toolchain/wali/patches/musl/0010-ssize-max-is-pointer-sized.patch +15 -0
  24. package/toolchain/wali/patches/musl/0011-startup-without-malloc.patch +85 -0
  25. package/toolchain/wali/patches/musl/0012-floatscan-fixes-from-musl.patch +39 -0
  26. package/toolchain/wali/patches/musl/0013-strptime-from-musl-with-glibc-s-and-z.patch +169 -0
  27. package/toolchain/wali/patches/musl/0014-wordexp-fixes-from-musl.patch +43 -0
  28. package/toolchain/wali/patches/musl/0015-long-double-is-ieee-quad.patch +202 -0
  29. package/toolchain/wali/patches/musl/0016-wordexp-nocmd-and-undef.patch +285 -0
  30. package/toolchain/wali/rust.sh +116 -0
  31. package/toolchain/wali/signal-checks.mjs +373 -0
  32. package/toolchain/wali-version +13 -0
@@ -0,0 +1,27 @@
1
+ cmatrix 2.0 (GPL-3.0-or-later AND X11)
2
+
3
+ programs/cmatrix.wasm is built from the upstream source below, with the changes listed under it. Together they
4
+ are the complete corresponding source of the binary; this is the offer of it.
5
+
6
+ Upstream source
7
+ cmatrix-2.0.tar.gz (cmatrix 2.0, GPL-3.0-or-later)
8
+ sha256 ad93ba39acd383696ab6a9ebbed1259ecf2d3cf9f49d6b97038c66f80749e99a
9
+ from https://github.com/abishekvashok/cmatrix/archive/refs/tags/v2.0.tar.gz
10
+ ncurses-6.5.tar.gz (ncurses 6.5, X11)
11
+ sha256 136d91bc269a9a5785e5f9e980bc76ab57428f604ce3e5a5a90cebc767971cc6
12
+ from https://ftpmirror.gnu.org/ncurses/ncurses-6.5.tar.gz
13
+
14
+ Changes and build scripts (in wasm/ of the package, and in the repository under core/utils-copyleft/wasm/)
15
+ wasm/cmatrix/build.sh
16
+ the build, without autotools or CMake (the defines CMake would give, and none for the Linux console fonts or TIOCSTI); patches cmatrix.c so TERM=xterm.js (or unset) falls back to xterm-256color; builds ncurses with built-in terminfo entries
17
+
18
+ The changes were made in 2026; the repository history dates each one.
19
+
20
+ Toolchain: WALI's musl and the LLVM runtimes (musl 243ec00c3ffb910375db487d7eb24ea76d1e2c9f, LLVM 23.1.3), with the patches in utils/wali/patches;
21
+ utils/wali-version in the repository pins them, and utils/wali/build-sysroot.sh builds them. Its compiler then
22
+ puts a signal check in each loop of the linked program (utils/wali/signal-checks.mjs).
23
+
24
+ Where to get it
25
+ - /sources/cmatrix-2.0.tar.gz on the site that served this program, and the other archives listed above in the same place
26
+ - the sources/ and wasm/ directories of the npm package @ecmaos/coreutils-copyleft, in the version that holds this file
27
+ - https://github.com/ecmaos/ecmaos (core/utils-copyleft), at the tag of the release that holds this file
Binary file
Binary file
@@ -0,0 +1 @@
1
+ 6.0.9
@@ -0,0 +1,3 @@
1
+ # The Rust toolchain that builds the Rust programs for WALI (utils/wali/rust.sh): wasm32-wali-linux-musl is a tier-3
2
+ # target, so it is a pinned nightly with rust-src, whose std is built with the program (-Z build-std).
3
+ RUST_TOOLCHAIN=nightly-2026-10-25
@@ -0,0 +1,107 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Prints the functions of a linked WALI program that can reach `wali.SYS_fork`, by name, comma separated: what
4
+ * asyncify.sh hands Asyncify as the only functions to rewrite, when a port says where its calls through a pointer reach
5
+ * fork.
6
+ *
7
+ * Binaryen takes a call through a pointer to reach whatever any function in the table does, so a program that forks
8
+ * anywhere has every function that calls through a pointer rewritten, and every caller of those: dash grew by half and
9
+ * ran a shell loop 40 to 65% slower (two measurements). Most of those calls cannot reach fork (a comparison function, a stdio write), and the
10
+ * port knows which can (dash runs its builtins through a pointer, and `eval` and `.` among them run commands). This
11
+ * follows the direct calls, and the calls through a pointer of only the functions it is told of: such a call reaches a
12
+ * table entry of its type (the engine traps on any other) that reaches fork. A function it does not name cannot be on
13
+ * the stack when fork is called, so it needs nothing saved. If the port misses one, the child of a fork under that call
14
+ * traps when it rewinds; the table is what the program's element segments put in it.
15
+ *
16
+ * Usage: asyncify-reach.mjs <program.wasm> <function,function...> [import,import... | all]. The program needs its function
17
+ * names (wasm-ld leaves them out of a program linked with -O2) and wasm-opt must be on the PATH. Imports named in the
18
+ * third argument (`SYS_tgkill`, `__ecmaos_poll`) are reached like fork is: the program is to unwind at them too, for a
19
+ * signal handler that forks (the host runs handlers where an import returns; `ECMAOS_WALI_ASYNCIFY_SIGNALS` in
20
+ * asyncify.sh). `all` is every wali import the program has but those that do not return.
21
+ *
22
+ * Also: `asyncify-reach.mjs --imports <program.wasm>` prints those imports, comma separated, and
23
+ * `asyncify-reach.mjs --mark <program.wasm> <import,import...>` adds them to the program as its `ecmaos.asyncify-signals`
24
+ * section, which tells the host where a handler's fork can unwind.
25
+ */
26
+ import { execFileSync } from 'node:child_process'
27
+ import { readFileSync, writeFileSync } from 'node:fs'
28
+
29
+ /** The wali imports that never return to a program, which no handler is delivered after */
30
+ const ENDS = new Set(['SYS_fork', 'SYS_vfork', 'SYS_exit', 'SYS_exit_group', '__proc_exit', 'SYS_execve', 'SYS_rt_sigreturn'])
31
+ const SECTION = 'ecmaos.asyncify-signals'
32
+
33
+ if (process.argv[2] === '--mark') {
34
+ const [, , , file, names] = process.argv
35
+ const uleb = n => { const out = []; do { let byte = n & 0x7f; n >>>= 7; if (n) byte |= 0x80; out.push(byte) } while (n); return out }
36
+ const name = Buffer.from(SECTION), payload = Buffer.from(names)
37
+ const body = Buffer.concat([Buffer.from(uleb(name.length)), name, payload])
38
+ writeFileSync(file, Buffer.concat([readFileSync(file), Buffer.from([0, ...uleb(body.length)]), body]))
39
+ process.exit(0)
40
+ }
41
+
42
+ const imports = process.argv[2] === '--imports'
43
+ const [program, throughPointers = '', extraImports = ''] = imports ? process.argv.slice(3) : process.argv.slice(2)
44
+ const indirect = new Set(throughPointers.split(',').filter(Boolean).map(name => `$${name}`))
45
+ const text = execFileSync('wasm-opt', [
46
+ program, '--print', '--enable-threads', '--enable-bulk-memory', '--enable-sign-ext', '--enable-mutable-globals',
47
+ '--enable-nontrapping-float-to-int', '--enable-multivalue', '--enable-reference-types', '--enable-exception-handling'
48
+ ], { encoding: 'utf8', maxBuffer: 1 << 30 })
49
+
50
+ /** A function type as its parameter and result types, which a call_indirect's type and a function's own share */
51
+ const signatureOf = text => {
52
+ const params = [...text.matchAll(/\(param ([^)]*)\)/g)].flatMap(m => m[1].split(' ').filter(t => /^(i32|i64|f32|f64|v128|\S*ref)/.test(t)))
53
+ const results = [...text.matchAll(/\(result ([^)]*)\)/g)].flatMap(m => m[1].split(' '))
54
+ return `${params.join(' ')}->${results.join(' ')}`
55
+ }
56
+ const types = new Map()
57
+ const table = new Set()
58
+ const functions = new Map()
59
+ const signatures = new Map()
60
+ const waliImports = new Map()
61
+ let fork, current
62
+ for (const line of text.split('\n')) {
63
+ let m
64
+ if ((m = line.match(/^ \(type (\$\S+) (\(func.*\))\)$/))) types.set(m[1], signatureOf(m[2]))
65
+ else if ((m = line.match(/^ \(import "wali" "(\S+)" \(func (\$\S+)/))) {
66
+ waliImports.set(m[1], m[2])
67
+ if (m[1] === 'SYS_fork') fork = m[2]
68
+ }
69
+ else if ((m = line.match(/^ \(elem \S+ \([^)]*\) (.*)\)$/))) m[1].split(' ').forEach(name => table.add(name))
70
+ else if ((m = line.match(/^ \(func (\$\S+)(.*)$/))) {
71
+ functions.set(m[1], current = { direct: new Set(), indirect: new Set() })
72
+ const type = m[2].match(/^ \(type (\$[^\s)]+)\)/)
73
+ signatures.set(m[1], type ? types.get(type[1]) : signatureOf(m[2]))
74
+ } else if (current && line.startsWith(' (')) current = undefined
75
+ else if (current) {
76
+ for (const [, callee] of line.matchAll(/\((?:return_)?call (\$[^\s)]+)/g)) current.direct.add(callee)
77
+ for (const [, type] of line.matchAll(/\((?:return_)?call_indirect \S+ \(type (\$[^\s)]+)\)/g)) current.indirect.add(types.get(type))
78
+ }
79
+ }
80
+ if (imports) {
81
+ console.log([...waliImports.keys()].filter(name => !ENDS.has(name)).join(','))
82
+ process.exit(0)
83
+ }
84
+ if (fork === undefined) { console.error(`${program}: does not import wali.SYS_fork`); process.exit(1) }
85
+ const seeds = extraImports === 'all' ? [...waliImports.keys()].filter(name => !ENDS.has(name)) : extraImports.split(',').filter(Boolean)
86
+ for (const name of seeds) {
87
+ if (!waliImports.has(name)) { console.error(`${program}: does not import wali.${name}`); process.exit(1) }
88
+ }
89
+ for (const name of indirect) {
90
+ if (!functions.has(name)) { console.error(`${program}: no function ${name.slice(1)} to follow the calls through a pointer of (a program linked with -O2 has no function names)`); process.exit(1) }
91
+ }
92
+
93
+ const reaches = new Set([fork, ...seeds.map(name => waliImports.get(name))])
94
+ const reachedTypes = new Set()
95
+ for (let changed = true; changed;) {
96
+ changed = false
97
+ for (const [name, calls] of functions) {
98
+ if (reaches.has(name)) continue
99
+ if ([...calls.direct].some(callee => reaches.has(callee)) || (indirect.has(name) && [...calls.indirect].some(type => reachedTypes.has(type)))) {
100
+ reaches.add(name)
101
+ changed = true
102
+ if (table.has(name)) reachedTypes.add(signatures.get(name))
103
+ }
104
+ }
105
+ }
106
+ for (const name of [fork, ...seeds.map(name => waliImports.get(name))]) reaches.delete(name)
107
+ console.log([...reaches].map(name => name.slice(1)).join(','))
@@ -0,0 +1,57 @@
1
+ #!/usr/bin/env bash
2
+ # SPDX-License-Identifier: MIT OR Apache-2.0
3
+ # Makes a linked WALI program able to fork: Binaryen's Asyncify pass rewrites every function that can reach
4
+ # `wali.SYS_fork` so its frames can be saved (unwind) and rebuilt (rewind), which is how the host returns from the call
5
+ # in a parent and a child (bin/wali-host.mjs `drive`). wali-cc and wali-c++ run it on each program they link, after
6
+ # signal-checks.mjs; it rewrites the program in place, and leaves alone one that does not link fork (it has nothing to
7
+ # unwind, and pays nothing) or has been rewritten already.
8
+ #
9
+ # The cost falls on the programs that fork: dash grew by half and ran a pure-shell loop 39% slower. Say so in the build,
10
+ # so it is not a surprise. Two ways to change it:
11
+ # ECMAOS_WALI_NO_ASYNCIFY=1 leave the program as it is: fork then fails with ENOSYS
12
+ # ECMAOS_WALI_ASYNCIFY_ARGS more Binaryen options for the pass, such as --pass-arg=asyncify-removelist@name,... to
13
+ # keep the functions that cannot reach fork out of it (`asyncify-ignore-indirect` is
14
+ # not one to add alone: a fork reached through a function pointer then traps)
15
+ # ECMAOS_WALI_ASYNCIFY_INDIRECT the functions (comma separated) whose calls through a pointer can reach fork, such as
16
+ # dash's evalbltin, which runs a builtin. Asyncify then rewrites only the functions that
17
+ # can reach fork by direct calls and these (asyncify-reach.mjs), where it would take every
18
+ # call through a pointer for one that does: dash grows by 12% where it grows by half, and
19
+ # its shell loop is 10% slower where it is 65%. It needs the program's function names, which
20
+ # wasm-ld leaves out of a program linked with -O2 (link without it), and a function it
21
+ # misses is one whose fork traps in the child
22
+ # ECMAOS_WALI_ASYNCIFY_SIGNALS the wali imports (comma separated, such as SYS_tgkill,__ecmaos_poll, or `all`) at which a
23
+ # signal handler may fork. The host runs a handler where an import returns, so a fork in one
24
+ # unwinds through that import too, and the program has to save its frames there: every
25
+ # function that calls one of them is rewritten (a signal that arrives where the program was
26
+ # not built to unwind makes the handler's fork fail with ENOSYS). The imports are kept in
27
+ # the program's ecmaos.asyncify-signals section. A program that forks only outside its
28
+ # handlers leaves this alone; one that forks in a handler it raises itself (`raise`,
29
+ # `kill`) needs the kill calls, and one that forks in a handler a timer or another thread
30
+ # sets off needs __ecmaos_poll and every call it blocks in
31
+ #
32
+ # The features are named one by one: --all-features also turns on encodings the engines do not read.
33
+ # Usage: asyncify.sh <program.wasm>
34
+ set -euo pipefail
35
+ grep -aq SYS_fork "$1" || exit 0
36
+ grep -aq asyncify_start_unwind "$1" && exit 0
37
+ [ -z "${ECMAOS_WALI_NO_ASYNCIFY:-}" ] || exit 0
38
+ command -v wasm-opt > /dev/null || { echo "asyncify: $1 links fork, which needs wasm-opt (Binaryen, see utils/wali-version); ECMAOS_WALI_NO_ASYNCIFY=1 builds it without" >&2; exit 1; }
39
+ before=$(stat -c %s "$1")
40
+ only=
41
+ strip=
42
+ imports=wali.SYS_fork
43
+ signals=${ECMAOS_WALI_ASYNCIFY_SIGNALS:-}
44
+ reach="$(dirname "$0")/asyncify-reach.mjs"
45
+ if [ "$signals" = all ]; then signals=$(node "$reach" --imports "$1"); fi
46
+ if [ -n "$signals" ]; then imports="$imports,wali.${signals//,/,wali.}"; fi
47
+ if [ -n "${ECMAOS_WALI_ASYNCIFY_INDIRECT:-}" ]; then
48
+ only=--pass-arg=asyncify-onlylist@$(node "$reach" "$1" "$ECMAOS_WALI_ASYNCIFY_INDIRECT" "$signals")
49
+ # the names were only for the list
50
+ strip=--strip-debug
51
+ fi
52
+ # shellcheck disable=SC2086
53
+ wasm-opt "$1" --asyncify --pass-arg=asyncify-imports@"$imports" $only ${ECMAOS_WALI_ASYNCIFY_ARGS:-} -O2 $strip \
54
+ --enable-threads --enable-bulk-memory --enable-sign-ext --enable-mutable-globals --enable-nontrapping-float-to-int \
55
+ --enable-multivalue --enable-reference-types --enable-exception-handling -o "$1"
56
+ if [ -n "$signals" ]; then node "$reach" --mark "$1" "$signals"; fi
57
+ echo "wali: $(basename "$1") links fork, so Asyncify rewrote it ($before to $(stat -c %s "$1") bytes, and its functions that can reach fork run slower)" >&2
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env bash
2
+ # SPDX-License-Identifier: MIT OR Apache-2.0
3
+ # Builds the WALI sysroot into $1: WALI's musl, the Linux UAPI headers, compiler-rt's builtins and libc++, libc++abi
4
+ # and libunwind, all for wasm32-linux-muslwali with WebAssembly exception handling (C++ exceptions and
5
+ # setjmp/longjmp) and threads, from the sources pinned in utils/wali-version and the patches in utils/wali/patches.
6
+ # Run by utils/check-wali.sh when the sysroot it wants is not there; nothing here is committed. Needs clang and
7
+ # wasm-ld of the pinned LLVM major, llvm-ar, llvm-ranlib, cmake, ninja, make, curl and xz.
8
+ #
9
+ # utils/wali/build-sysroot.sh <dir> <wasm-ld>
10
+ set -euo pipefail
11
+
12
+ OUT=$1
13
+ LD=$2
14
+ HERE=$(cd "$(dirname "$0")" && pwd)
15
+ # shellcheck source=../wali-version
16
+ source "$HERE/../wali-version"
17
+ TARGET=wasm32-linux-muslwali
18
+ JOBS=$(nproc 2>/dev/null || echo 4)
19
+
20
+ WORK=$(mktemp -d)
21
+ trap 'rm -rf "$WORK"' EXIT
22
+ STAGE=$OUT.partial
23
+ rm -rf "$STAGE"
24
+ mkdir -p "$STAGE/bin" "$STAGE/resource/lib/$TARGET"
25
+
26
+ fetch() { # url sha256 file
27
+ curl -fsSL -o "$WORK/$3" "$1"
28
+ echo "$2 $WORK/$3" | sha256sum -c --quiet -
29
+ }
30
+
31
+ # The linker clang runs for this target is whatever `wasm-ld` it finds first, so the sysroot carries its own; the
32
+ # resource directory is clang's headers with compiler-rt's builtins for this target beside them.
33
+ ln -s "$LD" "$STAGE/bin/wasm-ld"
34
+ ln -s "$(clang -print-resource-dir)/include" "$STAGE/resource/include"
35
+
36
+ FEATURES="-mcpu=generic -matomics -mbulk-memory -mexception-handling"
37
+ # lrint and lround return a long, which is 8 bytes on this target; LLVM's WebAssembly backend calls them as the
38
+ # wasm32 ABI has them (a 4-byte long) where it lowers the builtins, which wasm-ld then cannot link, so they stay calls
39
+ NOLONG="-fno-builtin-lrint -fno-builtin-lrintf -fno-builtin-lrintl -fno-builtin-lround -fno-builtin-lroundf -fno-builtin-lroundl"
40
+ DRIVER="--target=$TARGET --sysroot=$STAGE -resource-dir=$STAGE/resource -B$STAGE/bin $FEATURES $NOLONG -fwasm-exceptions -pthread"
41
+ # setjmp/longjmp on wasm exceptions is a code generation option, so only a command that compiles takes it
42
+ SJLJ="-mllvm -wasm-enable-sjlj"
43
+ FLAGS="$DRIVER $SJLJ"
44
+
45
+ echo "wali: musl ${MUSL_COMMIT:0:12}" >&2
46
+ fetch "https://github.com/arjunr2/wali-musl/archive/$MUSL_COMMIT.tar.gz" "$MUSL_SHA256" musl.tar.gz
47
+ mkdir "$WORK/musl"
48
+ tar xzf "$WORK/musl.tar.gz" -C "$WORK/musl" --strip-components=1
49
+ for patch in "$HERE"/patches/musl/*.patch; do patch -s -p1 -d "$WORK/musl" < "$patch"; done
50
+ cat > "$WORK/musl/config.mak" <<EOF
51
+ ARCH = wasm32
52
+ prefix = $STAGE
53
+ includedir = \$(prefix)/include
54
+ libdir = \$(prefix)/lib/$TARGET
55
+ CC = clang
56
+ AR = llvm-ar
57
+ RANLIB = llvm-ranlib
58
+ SHARED_LIBS =
59
+ EOF
60
+ # musl compiles with -nostdinc, so its own flags are the target's and nothing of the sysroot's yet
61
+ make -s -C "$WORK/musl" -j"$JOBS" install-libs install-headers \
62
+ CFLAGS="--target=$TARGET $FEATURES -fwasm-exceptions -mllvm -wasm-enable-sjlj -pthread" > "$WORK/musl.log" 2>&1 \
63
+ || { tail -30 "$WORK/musl.log" >&2; exit 1; }
64
+
65
+ echo "wali: Linux UAPI headers $KERNEL_HEADERS_VERSION" >&2
66
+ fetch "https://github.com/sabotage-linux/kernel-headers/releases/download/v$KERNEL_HEADERS_VERSION/linux-headers-$KERNEL_HEADERS_VERSION.tar.xz" "$KERNEL_HEADERS_SHA256" headers.tar.xz
67
+ mkdir "$WORK/headers"
68
+ tar xJf "$WORK/headers.tar.xz" -C "$WORK/headers" --strip-components=1
69
+ # x86_64's: this target has its structures (a 64-bit kernel long) with 32-bit pointers, which the headers take as x32
70
+ make -s -C "$WORK/headers" ARCH=x86_64 prefix="$STAGE" install
71
+
72
+ echo "wali: LLVM $LLVM_VERSION runtimes" >&2
73
+ fetch "https://github.com/llvm/llvm-project/releases/download/llvmorg-$LLVM_VERSION/llvm-project-$LLVM_VERSION.src.tar.xz" "$LLVM_SHA256" llvm.tar.xz
74
+ mkdir "$WORK/llvm"
75
+ SRC=llvm-project-$LLVM_VERSION.src
76
+ tar xJf "$WORK/llvm.tar.xz" -C "$WORK/llvm" --strip-components=1 --wildcards \
77
+ "$SRC/cmake/*" "$SRC/compiler-rt/*" "$SRC/libc/*" "$SRC/libcxx/*" "$SRC/libcxxabi/*" "$SRC/libunwind/*" \
78
+ "$SRC/llvm/cmake/*" "$SRC/llvm/utils/lit/*" "$SRC/llvm/utils/llvm-lit/*" "$SRC/runtimes/*" "$SRC/third-party/*"
79
+ for patch in "$HERE"/patches/compiler-rt/*.patch; do patch -s -p1 -d "$WORK/llvm" < "$patch"; done
80
+
81
+ COMMON=(
82
+ -G Ninja -DCMAKE_BUILD_TYPE=Release
83
+ -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_PROCESSOR=wasm32
84
+ -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_ASM_COMPILER=clang
85
+ -DCMAKE_C_COMPILER_TARGET=$TARGET -DCMAKE_CXX_COMPILER_TARGET=$TARGET -DCMAKE_ASM_COMPILER_TARGET=$TARGET
86
+ -DCMAKE_AR="$(command -v llvm-ar)" -DCMAKE_RANLIB="$(command -v llvm-ranlib)"
87
+ -DCMAKE_C_COMPILER_WORKS=ON -DCMAKE_CXX_COMPILER_WORKS=ON
88
+ -DCMAKE_C_FLAGS="$FLAGS" -DCMAKE_CXX_FLAGS="$FLAGS" -DCMAKE_ASM_FLAGS="$FLAGS"
89
+ -DCMAKE_POSITION_INDEPENDENT_CODE=OFF
90
+ )
91
+
92
+ # crtbegin/crtend are for ELF's .init_array, which musl's own crt already covers on wasm
93
+ cmake -S "$WORK/llvm/compiler-rt/lib/builtins" -B "$WORK/builtins" "${COMMON[@]}" \
94
+ -DCOMPILER_RT_BAREMETAL_BUILD=ON -DCOMPILER_RT_DEFAULT_TARGET_ONLY=ON -DCOMPILER_RT_BUILD_CRT=OFF \
95
+ -DCOMPILER_RT_INCLUDE_TESTS=OFF -DCOMPILER_RT_HAS_FPIC_FLAG=OFF -DLLVM_ENABLE_PER_TARGET_RUNTIME_DIR=ON \
96
+ > "$WORK/builtins.log" 2>&1 || { tail -30 "$WORK/builtins.log" >&2; exit 1; }
97
+ ninja -C "$WORK/builtins" >> "$WORK/builtins.log" 2>&1 || { tail -30 "$WORK/builtins.log" >&2; exit 1; }
98
+ cp "$WORK/builtins/lib/wasm32-unknown-linux-muslwali/libclang_rt.builtins.a" "$STAGE/resource/lib/$TARGET/"
99
+ # clang looks the builtins up by the triple it normalised the target to
100
+ ln -s "$TARGET" "$STAGE/resource/lib/wasm32-unknown-linux-muslwali"
101
+
102
+ cmake -S "$WORK/llvm/runtimes" -B "$WORK/cxx" "${COMMON[@]}" \
103
+ -DCMAKE_INSTALL_PREFIX="$STAGE" -DLLVM_ENABLE_RUNTIMES="libcxx;libcxxabi;libunwind" -DLLVM_INCLUDE_TESTS=OFF \
104
+ -DLIBCXX_INSTALL_LIBRARY_DIR="lib/$TARGET" -DLIBCXXABI_INSTALL_LIBRARY_DIR="lib/$TARGET" -DLIBUNWIND_INSTALL_LIBRARY_DIR="lib/$TARGET" \
105
+ -DLIBCXX_ENABLE_SHARED=OFF -DLIBCXX_ENABLE_EXCEPTIONS=ON -DLIBCXX_ENABLE_FILESYSTEM=ON -DLIBCXX_ENABLE_THREADS=ON \
106
+ -DLIBCXX_HAS_MUSL_LIBC=ON -DLIBCXX_HAS_PTHREAD_API=ON -DLIBCXX_CXX_ABI=libcxxabi -DLIBCXX_ENABLE_ABI_LINKER_SCRIPT=OFF \
107
+ -DLIBCXX_INCLUDE_TESTS=OFF -DLIBCXX_INCLUDE_BENCHMARKS=OFF \
108
+ -DLIBCXXABI_ENABLE_SHARED=OFF -DLIBCXXABI_ENABLE_EXCEPTIONS=ON -DLIBCXXABI_ENABLE_THREADS=ON \
109
+ -DLIBCXXABI_HAS_PTHREAD_API=ON -DLIBCXXABI_USE_LLVM_UNWINDER=ON -DLIBCXXABI_ENABLE_STATIC_UNWINDER=ON \
110
+ -DLIBCXXABI_INCLUDE_TESTS=OFF \
111
+ -DLIBUNWIND_ENABLE_SHARED=OFF -DLIBUNWIND_ENABLE_THREADS=ON -DLIBUNWIND_HIDE_SYMBOLS=ON -DLIBUNWIND_INCLUDE_TESTS=OFF \
112
+ > "$WORK/cxx.log" 2>&1 || { tail -30 "$WORK/cxx.log" >&2; exit 1; }
113
+ ninja -C "$WORK/cxx" install >> "$WORK/cxx.log" 2>&1 || { tail -30 "$WORK/cxx.log" >&2; exit 1; }
114
+
115
+ # What a build passes as CC and CXX: one command each, so configure scripts and makefiles can take them as they are.
116
+ # The link flags are left off a compile (-c, -S, -E) and the code generation option off a link of objects alone,
117
+ # where clang would warn that they went unused. A program they link gets a signal check in each loop
118
+ # (signal-checks.mjs, kept beside them), and one that links fork is made able to (asyncify.sh).
119
+ cp "$(dirname "$0")/signal-checks.mjs" "$STAGE/bin/signal-checks.mjs"
120
+ cp "$(dirname "$0")/asyncify.sh" "$STAGE/bin/asyncify.sh"
121
+ cp "$(dirname "$0")/asyncify-reach.mjs" "$STAGE/bin/asyncify-reach.mjs"
122
+ for tool in cc c++; do
123
+ driver=clang; extra=""
124
+ [ "$tool" = c++ ] && driver=clang++ && extra="-stdlib=libc++"
125
+ cat > "$STAGE/bin/wali-$tool" <<EOF
126
+ #!/bin/sh
127
+ # Generated by utils/wali/build-sysroot.sh: $driver for WALI with this sysroot.
128
+ # the function table is exported so the host can call the signal handlers the program installs, and the memory is
129
+ # imported (wali.memory) so each thread's instance can be given the same one; the main thread has Linux's 8 MiB
130
+ # stack (wasm-ld's default, 64 KiB, overflows below address 0 in programs written for Linux)
131
+ link="-Wl,--shared-memory -Xlinker --import-memory=wali,memory -Wl,--export-memory -Wl,--export-table -Wl,--max-memory=2147483648 -Wl,-z,stack-size=8388608"
132
+ sjlj=
133
+ out=a.out
134
+ next=
135
+ for arg in "\$@"; do
136
+ [ -n "\$next" ] && out=\$arg && next=
137
+ case "\$arg" in
138
+ -c|-S|-E|-M|-MM) link= ;;
139
+ -x|*.c|*.cc|*.cpp|*.cxx|*.C|*.c++|*.i|*.ii|-) sjlj="$SJLJ" ;;
140
+ -o) next=1 ;;
141
+ -o*) out=\${arg#-o} ;;
142
+ esac
143
+ done
144
+ $driver $DRIVER $extra \$sjlj "\$@" \$link || exit
145
+ # each loop of the program looks for signals now and then, so they reach it while it computes
146
+ [ -z "\$link" ] || [ ! -f "\$out" ] || node "$STAGE/bin/signal-checks.mjs" "\$out"
147
+ # a program that links fork can, in a parent and in a child (a program that does not is left as it is)
148
+ [ -z "\$link" ] || [ ! -f "\$out" ] || "$STAGE/bin/asyncify.sh" "\$out"
149
+ EOF
150
+ # the paths in it are the staging directory's until it is moved into place
151
+ sed -i "s#$STAGE#$OUT#g" "$STAGE/bin/wali-$tool"
152
+ chmod +x "$STAGE/bin/wali-$tool"
153
+ done
154
+
155
+ rm -rf "$OUT"
156
+ mv "$STAGE" "$OUT"
157
+ # the links into the resource directory and the linker point at absolute paths outside it, so only the wrappers moved
158
+ echo "wali: sysroot in $OUT" >&2
@@ -0,0 +1,18 @@
1
+ ecmaOS: the soft-float comparisons (__getf2 and the rest) return int on wasm. WALI's musl has a 64-bit long, so
2
+ compiler-rt's usual `long` made them return i64 while the wasm backend calls them for i32, and wasm-ld replaced
3
+ every call with a trap.
4
+
5
+ diff --git i/compiler-rt/lib/builtins/fp_compare_impl.inc w/compiler-rt/lib/builtins/fp_compare_impl.inc
6
+ index f883338..435474f 100644
7
+ --- i/compiler-rt/lib/builtins/fp_compare_impl.inc
8
+ +++ w/compiler-rt/lib/builtins/fp_compare_impl.inc
9
+ @@ -18,6 +18,9 @@ typedef int CMP_RESULT;
10
+ #elif __SIZEOF_POINTER__ == 8 && __SIZEOF_LONG__ == 4
11
+ // LLP64 ABIs use long long instead of long.
12
+ typedef long long CMP_RESULT;
13
+ +#elif defined(__wasm__)
14
+ +// The wasm backend calls these returning i32 whatever `long` is (WALI's musl has a 64-bit long).
15
+ +typedef int CMP_RESULT;
16
+ #elif __AVR__
17
+ // AVR uses a single byte for the return value.
18
+ typedef char CMP_RESULT;
@@ -0,0 +1,143 @@
1
+ ecmaOS: the environment comes in through imports, one NAME=value string at a time the way argv does
2
+ (__cl_get_envc, __cl_get_env_len, __cl_copy_env; see core/kernel/src/bin/wali-host.mjs), not through a file
3
+ the host writes to /tmp and never removes. They go into one mapping that environ points at, as it points into the
4
+ stack on Linux, rather than through malloc and putenv, which grew a heap array by realloc from NULL for each: a
5
+ program that brings its own malloc sees none of libc's before main.
6
+
7
+ diff --git c/arch/wasm32/init_env.h i/arch/wasm32/init_env.h
8
+ index 408029b..89880fb 100644
9
+ --- c/arch/wasm32/init_env.h
10
+ +++ i/arch/wasm32/init_env.h
11
+ @@ -38,7 +38,18 @@ int __wali_deinit(void) __attribute((
12
+ ));
13
+
14
+
15
+ -int get_init_envfile(char* filebuf, int fsize) __attribute ((
16
+ +/* The environment, copied in the way argv is (ecmaOS) */
17
+ +int __cl_get_envc(void) __attribute ((
18
+ __import_module__("wali"),
19
+ - __import_name__("__get_init_envfile")
20
+ + __import_name__("__cl_get_envc")
21
+ +));
22
+ +
23
+ +int __cl_get_env_len(int) __attribute ((
24
+ + __import_module__("wali"),
25
+ + __import_name__("__cl_get_env_len")
26
+ +));
27
+ +
28
+ +int __cl_copy_env(char*, int) __attribute ((
29
+ + __import_module__("wali"),
30
+ + __import_name__("__cl_copy_env")
31
+ ));
32
+ diff --git c/src/env/initenv.c i/src/env/initenv.c
33
+ index 180cd6f..406ed40 100644
34
+ --- c/src/env/initenv.c
35
+ +++ i/src/env/initenv.c
36
+ @@ -1,89 +1,25 @@
37
+ #include "init_env.h"
38
+ -#include <stdlib.h>
39
+ -#include <fcntl.h>
40
+ -#include <unistd.h>
41
+ -#include <sys/stat.h>
42
+ #include <sys/mman.h>
43
+ -#include <string.h>
44
+ -
45
+ -#define FSIZE 1000
46
+ -
47
+ -static int read_envfile(char *filename) {
48
+ - struct stat st;
49
+ - /* Check if env file exists */
50
+ - if (!access(filename, R_OK)) {
51
+ - int fd = open(filename, O_RDONLY);
52
+ - if (fd < 0) return WALI_ENV_READ_FAIL;
53
+ -
54
+ - if (fstat(fd, &st) < 0) {
55
+ - close(fd);
56
+ - return WALI_ENV_READ_FAIL;
57
+ - }
58
+ - int size = st.st_size;
59
+ - if (size == 0) {
60
+ - close(fd);
61
+ - return 0;
62
+ - }
63
+ -
64
+ - /* Map file into memory */
65
+ - char *envc = (char*) mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
66
+ - if (envc == MAP_FAILED) {
67
+ - close(fd);
68
+ - return WALI_ENV_MALLOC_FAIL;
69
+ - }
70
+ - close(fd);
71
+ -
72
+ - char *start = envc;
73
+ - char *end = envc + size;
74
+ - char *curr = envc;
75
+ -
76
+ - /* Parse token by token */
77
+ - while (curr < end) {
78
+ - if (*curr == '\n') {
79
+ - *curr = '\0';
80
+ - if (putenv(strdup(start))) {
81
+ - munmap(envc, size);
82
+ - return WALI_ENV_READ_FAIL;
83
+ - }
84
+ - start = curr + 1;
85
+ - }
86
+ - curr++;
87
+ - }
88
+ -
89
+ - /* Handle last token if file doesn't end with newline */
90
+ - if (start < end) {
91
+ - size_t len = end - start;
92
+ - char *last = (char*) malloc(len + 1);
93
+ - if (!last) {
94
+ - munmap(envc, size);
95
+ - return WALI_ENV_MALLOC_FAIL;
96
+ - }
97
+ - memcpy(last, start, len);
98
+ - last[len] = '\0';
99
+ -
100
+ - if (putenv(last)) {
101
+ - free(last);
102
+ - munmap(envc, size);
103
+ - return WALI_ENV_READ_FAIL;
104
+ - }
105
+ - }
106
+ -
107
+ - /* Cleanup */
108
+ - munmap(envc, size);
109
+ - }
110
+ - return 0;
111
+ -}
112
+ +#include <unistd.h>
113
+
114
+ +/* ecmaOS: the host hands over each NAME=value string the way it hands over argv, so nothing is written to a file
115
+ + * (WALI's host writes the environment to /tmp and leaves it there). They go into one mapping, the array and the
116
+ + * strings after it, which environ then points at, as it points into the stack on Linux: putenv and setenv copy it
117
+ + * away from there the first time they change it, and nothing of the program's malloc is used before main (a program
118
+ + * may bring its own, and one putenv each grew the array by realloc from NULL). */
119
+ int init_env() {
120
+ - char filename[FSIZE];
121
+ - if (!filename) {
122
+ - return WALI_ENV_FILENAME_FAIL;
123
+ - }
124
+ - /* Populate env if file exists */
125
+ - int found = get_init_envfile(filename, FSIZE);
126
+ - if (found) {
127
+ - return read_envfile(filename);
128
+ + int envc = __cl_get_envc();
129
+ + size_t size = (envc + 1) * sizeof(char *);
130
+ + for (int i = 0; i < envc; i++) size += __cl_get_env_len(i) + 1;
131
+ + char **env = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
132
+ + if (env == MAP_FAILED) return WALI_ENV_MALLOC_FAIL;
133
+ + char *at = (char *)(env + envc + 1);
134
+ + for (int i = 0; i < envc; i++) {
135
+ + env[i] = at;
136
+ + __cl_copy_env(at, i);
137
+ + at += __cl_get_env_len(i) + 1;
138
+ }
139
+ + env[envc] = 0;
140
+ + __environ = env;
141
+ return 0;
142
+ }
143
+ -
@@ -0,0 +1,133 @@
1
+ ecmaOS: setjmp and longjmp on WebAssembly exception handling. The compiler (-fwasm-exceptions -mllvm
2
+ -wasm-enable-sjlj) lowers them to __wasm_setjmp, __wasm_setjmp_test and __wasm_longjmp, which this adds; the
3
+ header stops declaring them as host imports. sigsetjmp saves the signal mask before calling setjmp and siglongjmp
4
+ restores it.
5
+
6
+ diff --git c/include/setjmp.h i/include/setjmp.h
7
+ index 48b37b8..da64760 100644
8
+ --- c/include/setjmp.h
9
+ +++ i/include/setjmp.h
10
+ @@ -21,39 +21,27 @@ typedef struct __jmp_buf_tag {
11
+ #define __setjmp_attr
12
+ #endif
13
+
14
+ +/* ecmaOS: setjmp and longjmp are lowered by the compiler (wasm exception handling, -mllvm -wasm-enable-sjlj) to
15
+ + * calls into src/setjmp/wasm32/rt.c, so they are plain declarations here rather than host imports. The other names
16
+ + * are the same jump: sigsetjmp saves the signal mask in the buffer first, and siglongjmp puts it back. */
17
+ +int setjmp (jmp_buf) __setjmp_attr;
18
+ +_Noreturn void longjmp (jmp_buf, int);
19
+ +
20
+ #if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
21
+ || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \
22
+ || defined(_BSD_SOURCE)
23
+ typedef jmp_buf sigjmp_buf;
24
+ -int sigsetjmp (sigjmp_buf, int) __setjmp_attr __attribute((
25
+ - __import_module__("wali"),
26
+ - __import_name__("sigsetjmp")
27
+ -));
28
+ +void __sigsetjmp_save (sigjmp_buf, int);
29
+ +#define sigsetjmp(buf, save) (__sigsetjmp_save((buf), (save)), setjmp(buf))
30
+ _Noreturn void siglongjmp (sigjmp_buf, int);
31
+ #endif
32
+
33
+ #if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \
34
+ || defined(_BSD_SOURCE)
35
+ -int _setjmp (jmp_buf) __setjmp_attr __attribute((
36
+ - __import_module__("wali"),
37
+ - __import_name__("_setjmp")
38
+ -));
39
+ -_Noreturn void _longjmp (jmp_buf, int) __attribute((
40
+ - __import_module__("wali"),
41
+ - __import_name__("_longjmp")
42
+ -));
43
+ +#define _setjmp(buf) setjmp(buf)
44
+ +#define _longjmp(buf, val) longjmp((buf), (val))
45
+ #endif
46
+
47
+ -int setjmp (jmp_buf) __setjmp_attr __attribute((
48
+ - __import_module__("wali"),
49
+ - __import_name__("setjmp")
50
+ -));
51
+ -
52
+ -_Noreturn void longjmp (jmp_buf, int) __attribute((
53
+ - __import_module__("wali"),
54
+ - __import_name__("longjmp")
55
+ -));
56
+ -
57
+ #define setjmp setjmp
58
+
59
+ #undef __setjmp_attr
60
+ diff --git c/src/setjmp/wasm32/rt.c i/src/setjmp/wasm32/rt.c
61
+ new file mode 100644
62
+ index 0000000..eccaa6b
63
+ --- /dev/null
64
+ +++ i/src/setjmp/wasm32/rt.c
65
+ @@ -0,0 +1,37 @@
66
+ +/* ecmaOS: the runtime half of WebAssembly setjmp/longjmp. With -fwasm-exceptions and -mllvm -wasm-enable-sjlj the
67
+ + * compiler turns each setjmp() into __wasm_setjmp(), each place a longjmp() may land into __wasm_setjmp_test(), and
68
+ + * longjmp() into __wasm_longjmp(), which throws the __c_longjmp exception the function that called setjmp catches.
69
+ + * The jmp_buf holds which call of which function set it (so a stale buffer is not taken for a live one) and the
70
+ + * value to return. */
71
+ +#include <setjmp.h>
72
+ +#include <stdint.h>
73
+ +
74
+ +struct wasm_jmp {
75
+ + void *invocation;
76
+ + uint32_t label;
77
+ + struct { void *env; int val; } arg;
78
+ +};
79
+ +
80
+ +_Static_assert(sizeof(struct wasm_jmp) <= sizeof(__jmp_buf), "jmp_buf too small");
81
+ +
82
+ +void __wasm_setjmp(void *env, uint32_t label, void *invocation)
83
+ +{
84
+ + struct wasm_jmp *jb = env;
85
+ + if (!label || !invocation) __builtin_trap();
86
+ + jb->invocation = invocation;
87
+ + jb->label = label;
88
+ +}
89
+ +
90
+ +uint32_t __wasm_setjmp_test(void *env, void *invocation)
91
+ +{
92
+ + struct wasm_jmp *jb = env;
93
+ + return jb->invocation == invocation ? jb->label : 0;
94
+ +}
95
+ +
96
+ +_Noreturn void __wasm_longjmp(void *env, int val)
97
+ +{
98
+ + struct wasm_jmp *jb = env;
99
+ + jb->arg.env = env;
100
+ + jb->arg.val = val ? val : 1;
101
+ + __builtin_wasm_throw(1, &jb->arg);
102
+ +}
103
+ diff --git c/src/signal/wasm32/siglongjmp.c i/src/signal/wasm32/siglongjmp.c
104
+ new file mode 100644
105
+ index 0000000..f4abb56
106
+ --- /dev/null
107
+ +++ i/src/signal/wasm32/siglongjmp.c
108
+ @@ -0,0 +1,9 @@
109
+ +/* ecmaOS: puts back the mask sigsetjmp saved, then jumps. */
110
+ +#include <setjmp.h>
111
+ +#include <signal.h>
112
+ +
113
+ +_Noreturn void siglongjmp(sigjmp_buf buf, int ret)
114
+ +{
115
+ + if (buf->__fl) pthread_sigmask(SIG_SETMASK, (sigset_t *)buf->__ss, 0);
116
+ + longjmp(buf, ret);
117
+ +}
118
+ diff --git c/src/signal/wasm32/sigsetjmp.c i/src/signal/wasm32/sigsetjmp.c
119
+ new file mode 100644
120
+ index 0000000..c8184c4
121
+ --- /dev/null
122
+ +++ i/src/signal/wasm32/sigsetjmp.c
123
+ @@ -0,0 +1,10 @@
124
+ +/* ecmaOS: sigsetjmp is a macro (include/setjmp.h) that saves the mask here and then calls setjmp, since a function
125
+ + * that returns twice cannot be wrapped. */
126
+ +#include <setjmp.h>
127
+ +#include <signal.h>
128
+ +
129
+ +void __sigsetjmp_save(sigjmp_buf buf, int save)
130
+ +{
131
+ + buf->__fl = save;
132
+ + if (save) pthread_sigmask(SIG_SETMASK, 0, (sigset_t *)buf->__ss);
133
+ +}