diff --git a/compiler/parser/parser.c b/compiler/parser/parser.c index cae76a735..76ea1b027 100644 --- a/compiler/parser/parser.c +++ b/compiler/parser/parser.c @@ -7264,8 +7264,14 @@ ASTNode* parse_function_definition(Parser* parser) { /* #2809: an optional result type, `-> Point? { ... }`: * the `?` sits between the name and the body. A `-> expr` * body never puts `{` (or a contract clause) right after - * a postfix `?`. */ - if (after_name && after_name->type == TOKEN_QUESTION) { + * a postfix `?`. A fallible result, `-> f32! { ... }` + * or `-> Point! { ... }`, puts `!` there the same way: + * the type keywords (`float`, `byte`) took the switch's + * keyword arm, but a scalar spelt as a name (`f32`, + * `u8`, `i32`) or a struct fell through to the `-> expr` + * path, leaving the `{` dangling. */ + if (after_name && (after_name->type == TOKEN_QUESTION || + after_name->type == TOKEN_EXCLAIM)) { Token* after_q = peek_ahead(parser, 2); if (after_q && (after_q->type == TOKEN_LEFT_BRACE || after_q->type == TOKEN_REQUIRES || diff --git a/docs/api/index.html b/docs/api/index.html index 5e998e750..9a29b62df 100644 --- a/docs/api/index.html +++ b/docs/api/index.html @@ -284,7 +284,7 @@

io

ipc

std.ipc — a process's channel to its parent: a report pipe, or a two-way socket that can also pass open file descriptors.

- 40 exports + 55 exports

json

@@ -484,7 +484,7 @@

stream

string

std.string - String Module Import with: import std.string Building strings incrementally? Do NOT loop `d = "${d}${piece}"` / `string.concat(d, piece)` — each iteration re-copies the whole prefix, so the loop is O(n²) in total bytes (issue #1346).

- 104 exports + 105 exports

supervise

@@ -1639,6 +1639,13 @@

Search Results

  • frame_writer_flush_rawipc
  • frame_writer_pending_rawipc
  • frame_writer_free_rawipc
  • +
  • shared_buffer_new_rawipc
  • +
  • shared_buffer_map_rawipc
  • +
  • shared_buffer_fd_rawipc
  • +
  • shared_buffer_length_rawipc
  • +
  • shared_buffer_data_rawipc
  • +
  • shared_buffer_readonly_rawipc
  • +
  • shared_buffer_free_rawipc
  • parent_channelipc
  • parent_channel_kindipc
  • stdio_channelipc
  • @@ -1659,6 +1666,14 @@

    Search Results

  • frame_writer_flushipc
  • frame_writer_pendingipc
  • frame_writer_freeipc
  • +
  • shared_bufferipc
  • +
  • shared_buffer_fdipc
  • +
  • shared_buffer_mapipc
  • +
  • shared_buffer_map_readonlyipc
  • +
  • shared_buffer_lengthipc
  • +
  • shared_buffer_viewipc
  • +
  • shared_buffer_read_viewipc
  • +
  • shared_buffer_freeipc
  • TIMED_OUT_BETWEEN_FRAMESipc
  • TIMED_OUT_INSIDE_FRAMEipc
  • parse_rawjson
  • @@ -2819,6 +2834,7 @@

    Search Results

  • to_long_rawstring
  • to_float_rawstring
  • to_f32_rawstring
  • +
  • to_double_rawstring
  • try_intstring
  • get_intstring
  • try_longstring
  • diff --git a/docs/api/ipc.html b/docs/api/ipc.html index 15d280ac4..42d54d4e4 100644 --- a/docs/api/ipc.html +++ b/docs/api/ipc.html @@ -33,6 +33,13 @@

    Exports

  • frame_writer_flush_raw
  • frame_writer_pending_raw
  • frame_writer_free_raw
  • +
  • shared_buffer_new_raw
  • +
  • shared_buffer_map_raw
  • +
  • shared_buffer_fd_raw
  • +
  • shared_buffer_length_raw
  • +
  • shared_buffer_data_raw
  • +
  • shared_buffer_readonly_raw
  • +
  • shared_buffer_free_raw
  • parent_channel
  • parent_channel_kind
  • stdio_channel
  • @@ -53,6 +60,14 @@

    Exports

  • frame_writer_flush
  • frame_writer_pending
  • frame_writer_free
  • +
  • shared_buffer
  • +
  • shared_buffer_fd
  • +
  • shared_buffer_map
  • +
  • shared_buffer_map_readonly
  • +
  • shared_buffer_length
  • +
  • shared_buffer_view
  • +
  • shared_buffer_read_view
  • +
  • shared_buffer_free
  • TIMED_OUT_BETWEEN_FRAMES
  • TIMED_OUT_INSIDE_FRAME
  • @@ -249,6 +264,41 @@

    frame_writer_free_raw extern
    frame_writer_free_raw(w)

    w: ptr

    +
    +

    shared_buffer_new_raw extern

    +
    shared_buffer_new_raw(size) -> (ptr, string)
    +

    size: int

    +
    +
    +

    shared_buffer_map_raw extern

    +
    shared_buffer_map_raw(fd, size, readonly) -> (ptr, string)
    +

    fd: int, size: int, readonly: int

    +
    +
    +

    shared_buffer_fd_raw extern

    +
    shared_buffer_fd_raw(b) -> int
    +

    b: ptr

    +
    +
    +

    shared_buffer_length_raw extern

    +
    shared_buffer_length_raw(b) -> int
    +

    b: ptr

    +
    +
    +

    shared_buffer_data_raw extern

    +
    shared_buffer_data_raw(b) -> ptr
    +

    b: ptr

    +
    +
    +

    shared_buffer_readonly_raw extern

    +
    shared_buffer_readonly_raw(b) -> int
    +

    b: ptr

    +
    +
    +

    shared_buffer_free_raw extern

    +
    shared_buffer_free_raw(b)
    +

    b: ptr

    +

    parent_channel fn

    parent_channel() -> int
    @@ -366,6 +416,54 @@

    frame_writer_free fn

    w: ptr

    Free a frame writer and what it still has queued. The descriptor is not closed.

    +
    +

    shared_buffer fn

    +
    shared_buffer(size) -> (ptr, string)
    +

    size: int

    +

    A new buffer of `size` bytes (at least 1), zeroed, mapped for reading and writing: (buf, "") or (null, err). It holds a close-on-exec descriptor (shared_buffer_fd) to pass to another process. Its size cannot change: on Linux and FreeBSD the descriptor is sealed against growing and shrinking, so a process it is passed to cannot shrink it under this side's mapping. The memory is anonymous: no file, name or grant is involved.

    +
    +
    +

    shared_buffer_fd fn

    +
    shared_buffer_fd(b) -> int
    +

    b: ptr

    +

    The descriptor of a buffer shared_buffer made, to pass with send_fd (the receiver gets its own; this one stays the buffer's, and shared_buffer_free closes it). -1 for a buffer shared_buffer_map made, or for null.

    +
    +
    +

    shared_buffer_map fn

    +
    shared_buffer_map(fd, size) -> (ptr, string)
    +

    fd: int, size: int

    +

    Map the buffer whose descriptor `fd` arrived (recv, recv_fd), for reading and writing: (buf, "") or (null, err). `size` must be the size it was made with, checked against the descriptor (fstat): a mismatch, a closed or invalid descriptor, or one that is not shared memory is an error. The descriptor stays the caller's: close it once mapped, the mapping stays.

    +
    +
    +

    shared_buffer_map_readonly fn

    +
    shared_buffer_map_readonly(fd, size) -> (ptr, string)
    +

    fd: int, size: int

    +

    shared_buffer_map, mapped read-only: a store through its view panics instead of reaching the memory. Only this side's mapping is read-only; the descriptor still lets the process that holds it write.

    +
    +
    +

    shared_buffer_length fn

    +
    shared_buffer_length(b) -> int
    +

    b: ptr

    +

    The buffer's size in bytes; 0 for null.

    +
    +
    +

    shared_buffer_view fn

    +
    shared_buffer_view(b) -> byte[]
    +

    b: ptr

    +

    The buffer's bytes as a bounded `byte[]`, its index checked, to read and write. Valid until shared_buffer_free; it owns nothing, so `free` of it is refused. A buffer mapped with shared_buffer_map_readonly has no writable view: this panics for one (use shared_buffer_read_view). Null is the empty slice.

    +
    +
    +

    shared_buffer_read_view fn

    +
    shared_buffer_read_view(b) -> byte[]
    +

    b: ptr

    +

    The buffer's bytes as a bounded, read-only `byte[]`: a store through it is refused (at compile time where the checker sees it, else a panic). Works on any buffer, and is the only view of one mapped read-only. Same validity as shared_buffer_view.

    +
    +
    +

    shared_buffer_free fn

    +
    shared_buffer_free(b)
    +

    b: ptr

    +

    Unmap the buffer, and close its descriptor if shared_buffer made it. Another process's mapping of the same memory stays. Null is ignored.

    +

    TIMED_OUT_BETWEEN_FRAMES const

    TIMED_OUT_BETWEEN_FRAMES = "ipc.read_frame: timed out before a frame began"
    diff --git a/docs/api/string.html b/docs/api/string.html index 5d08358b3..14f842225 100644 --- a/docs/api/string.html +++ b/docs/api/string.html @@ -85,6 +85,7 @@

    Exports

  • to_long_raw
  • to_float_raw
  • to_f32_raw
  • +
  • to_double_raw
  • try_int
  • get_int
  • try_long
  • @@ -604,6 +605,12 @@

    to_f32_raw extern

    to_f32_raw(str, out_value) -> int

    str: string, out_value: ptr

    +
    +

    to_double_raw extern

    +
    to_double_raw(str, out_value) -> int
    +

    str: string, out_value: ptr

    +

    TODO: delete string_to_double_raw once nothing in the aether-lang-dev org's repos or in friends-and-family repos calls it; it is string_to_float_raw under its old name, the same 8-byte `float` slot.

    +

    try_int extern

    try_int(s) -> int
    diff --git a/docs/stdlib-reference.md b/docs/stdlib-reference.md index d59e71ddc..da20d46d9 100644 --- a/docs/stdlib-reference.md +++ b/docs/stdlib-reference.md @@ -44,7 +44,7 @@ header comment is the authoritative description. | `std.intarr` | Fixed-size packed-int buffer. | 15 | [guide](../std/intarr/README.md) · [source](../std/intarr/module.ae) | | `std.intmap` | Hash map from `long` keys to `long` values, for integer-keyed counting and lookup. | 12 | [guide](../std/intmap/README.md) · [source](../std/intmap/module.ae) | | `std.io` | Console output, whole-file reads and writes, file descriptors, environment variables. | 48 | [full section](#io-stdio) | -| `std.ipc` | The channel to a parent process started by `std.os`: a report pipe, or a two-way socket that passes descriptors. | 40 | [guide](../std/ipc/README.md) · [source](../std/ipc/module.ae) | +| `std.ipc` | The channel to a parent process started by `std.os`: a report pipe, or a two-way socket that passes descriptors and shared memory. | 55 | [guide](../std/ipc/README.md) · [source](../std/ipc/module.ae) | | `std.json` | JSON parsing, building and serialisation. | 52 | [full section](#json-stdjson) | | `std.jsonpath` | RFC 9535 JSONPath queries over parsed JSON, with a reusable compiled path. | 10 | [guide](../std/jsonpath/README.md) · [source](../std/jsonpath/module.ae) | | `std.ksuid` | KSUID: 160-bit lexicographically sortable identifier. | 1 | [guide](../std/ksuid/README.md) · [source](../std/ksuid/module.ae) | @@ -85,7 +85,7 @@ header comment is the authoritative description. | `std.strarr` | Growable string array whose backing is a `string[]`, for sorting runtime-built lists. | 15 | [guide](../std/strarr/README.md) · [source](../std/strarr/module.ae) | | `std.strbuilder` | Amortised-O(1) string building. | 18 | [guide](../std/strbuilder/README.md) · [source](../std/strbuilder/module.ae) | | `std.stream` | Credit-windowed streams between actors: memory stays bounded however fast the producer is. | 11 | [guide](../std/stream/README.md) · [source](../std/stream/module.ae) | -| `std.string` | Managed strings: construction, search, slicing, case, split and join. | 104 | [full section](#strings-stdstring) | +| `std.string` | Managed strings: construction, search, slicing, case, split and join. | 105 | [full section](#strings-stdstring) | | `std.supervise` | Supervisors that restart dead actors in place, by strategy and within a restart budget. | 9 | [guide](../std/supervise/README.md) · [source](../std/supervise/module.ae) | | `std.sync` | Atomic 64-bit integer cell (load, store, add, sub, compare-and-swap) for refcounts and lock-free reclamation. | 7 | [guide](../std/sync/README.md) · [source](../std/sync/module.ae) | | `std.tar` | Streaming tar archives: a ustar writer, a ustar, pax and GNU reader. | 24 | [full section](#posix-ustar-archives-stdtar) | @@ -3252,6 +3252,11 @@ main() { - `ipc.read_frame(ch, max)` → `(string, string)` - One whole frame; a header announcing more than `max` is an error and nothing is buffered. End of stream is an error, so `("", "")` is an empty frame - `ipc.read_frame_timeout(ch, max, timeout_ms)` → `(string, string)` - `read_frame` with a deadline over the whole frame (on Windows, with a timeout that is not negative, only on an anonymous pipe such as `os.run_stdio`'s, to within about a timer tick). A timeout is `ipc.TIMED_OUT_BETWEEN_FRAMES` when no byte of a frame had arrived (the stream is still usable) or `ipc.TIMED_OUT_INSIDE_FRAME` when one had (close the channel) - `ipc.wait_readable(ch, timeout_ms)` → `(int, string)` - `poll`: 1 when a read will not block (a closed peer included), 0 on a timeout. On Windows only on an anonymous pipe such as `os.run_stdio`'s (`PeekNamedPipe`, polled to within about a timer tick); any other descriptor there is a `not a pipe` error +- `ipc.shared_buffer(size)` → `(ptr, string)` - A zeroed buffer of `size` bytes two processes can map: anonymous memory (a size-sealed memfd on Linux and FreeBSD, an unlinked `shm_open` object on macOS), with a close-on-exec descriptor to pass with `send_fd`. No grant needed. Unsupported on Windows +- `ipc.shared_buffer_map(fd, size)` / `ipc.shared_buffer_map_readonly(fd, size)` → `(ptr, string)` - Map a buffer from a received descriptor; `size` is checked against it (`fstat`), and a mismatch, a closed descriptor or one that is not shared memory is an error. The descriptor stays the caller's +- `ipc.shared_buffer_fd(buf)` → `int`, `ipc.shared_buffer_length(buf)` → `int` - Its descriptor (`-1` on a mapping) and its size +- `ipc.shared_buffer_view(buf)` / `ipc.shared_buffer_read_view(buf)` → `byte[]` - Its bytes as a bounded slice, writable or read-only (a read-only mapping has only the latter), valid until `shared_buffer_free` +- `ipc.shared_buffer_free(buf)` - Unmap it, and close its descriptor on the side that made it ### Signal numbers (`std.signal`) diff --git a/new_changelogs/20261126T232841Z-fixed-result-type-named-scalar.md b/new_changelogs/20261126T232841Z-fixed-result-type-named-scalar.md new file mode 100644 index 000000000..90caa9a4f --- /dev/null +++ b/new_changelogs/20261126T232841Z-fixed-result-type-named-scalar.md @@ -0,0 +1,6 @@ +- **`-> f32! { ... }` declares a fallible function, as `-> float! { ... }` + does.** A result type whose payload is a scalar spelt as a name (`f32`, + `int64`, `uint8`, `uint16`, `uint32`, `size_t`, `int32_t`, `longdouble`) + or a struct (`-> Point! { ... }`) was read as the start of an expression + body, so the `{` after it was a top-level parse error. Only the type + keywords (`int`, `float`, `byte`, ...) worked. diff --git a/new_changelogs/20261127T035617Z-added-ipc-shared-buffer.md b/new_changelogs/20261127T035617Z-added-ipc-shared-buffer.md new file mode 100644 index 000000000..0ba0e8ff8 --- /dev/null +++ b/new_changelogs/20261127T035617Z-added-ipc-shared-buffer.md @@ -0,0 +1,13 @@ +- **`std.ipc` shared buffers: memory two processes map, passed as a + descriptor.** `ipc.shared_buffer(size)` makes a zeroed buffer and holds its + close-on-exec descriptor (`shared_buffer_fd`) to pass with `ipc.send_fd`; + the receiver maps it with `shared_buffer_map(fd, size)` (or + `shared_buffer_map_readonly`), the size checked against the descriptor, and + both sides read and write it through a bounded `byte[]` + (`shared_buffer_view`, `shared_buffer_read_view`) while the channel carries + only short messages. Each buffer is its own handle, freed with + `shared_buffer_free`. Linux and FreeBSD make a memfd whose size is sealed, + so no holder can shrink it under another's mapping; macOS and the other + BSDs an `shm_open` object unlinked at once. No sandbox grant is needed: a + child under `sandbox.spawn_socket` with none maps and makes buffers. + Windows reports it unsupported, as it does descriptor passing. diff --git a/new_changelogs/20261127T052210Z-fixed-worker-own-thread-exit.md b/new_changelogs/20261127T052210Z-fixed-worker-own-thread-exit.md new file mode 100644 index 000000000..9e80a7ba5 --- /dev/null +++ b/new_changelogs/20261127T052210Z-fixed-worker-own-thread-exit.md @@ -0,0 +1,10 @@ +- **A program that ends right after a `worker.run_detached` job finishes no + longer exits while that job's thread is still exiting.** The thread was + detached at launch, and its job counted as done (`worker.pending()` back + to 0) before the thread had freed the job, woken waiters and returned, so + `main` could return into process exit with the thread half way out. Wine + crashed on that overlap, about once in a thousand runs. Threads std.worker + starts outside the pool (`run_detached`, and `run` when the pool cannot + start) are now joined once their job is done: at the next launch, and at + exit. A job still running at exit is left to end with the process, as + before. diff --git a/new_changelogs/20261127T204516Z-fixed-string-to-double-raw-kept.md b/new_changelogs/20261127T204516Z-fixed-string-to-double-raw-kept.md new file mode 100644 index 000000000..62b457b83 --- /dev/null +++ b/new_changelogs/20261127T204516Z-fixed-string-to-double-raw-kept.md @@ -0,0 +1,8 @@ +- **`string.to_double_raw` is back, as `to_float_raw` under its old name.** + 0.948.0 made `to_float` the correctly rounded 64-bit parse and kept + `to_double`, `try_double` and `get_double` for the code still calling + them, but removed `to_double_raw`, so a program calling it failed to + link (`_string_to_double_raw` undefined). It fills the same 8-byte + `float` slot as `to_float_raw` and returns the same 1 or 0. Like the + other old names, it is to be deleted once nothing calls it; new code + uses `to_float_raw`. diff --git a/std/ipc/README.md b/std/ipc/README.md index 1be9cf357..137894519 100644 --- a/std/ipc/README.md +++ b/std/ipc/README.md @@ -1,7 +1,7 @@ # std.ipc A channel to the parent process: a report pipe, or a two-way socket that -can also pass open file descriptors. +can also pass open file descriptors, and shared memory passed over it. When a program is spawned by `std.os`, it may inherit an extra descriptor that its parent holds the other end of. `std.ipc` finds it and reads, @@ -331,6 +331,87 @@ gone is an error, not SIGPIPE. It works on Windows too (anonymous pipes, handed back as binary CRT descriptors), which is why a host that has to run there uses it. +## Shared buffers + +Bulk data, a frame of pixels say, is cheaper shared than sent: one side +makes a buffer, passes its descriptor over a socket channel, the other maps +it, and from then on both read and write the same memory, while the channel +carries only short messages saying what changed. + +- `shared_buffer(size) -> (buf, err)` makes a zeroed buffer of `size` bytes, + mapped for reading and writing, with a close-on-exec descriptor. +- `shared_buffer_fd(buf) -> int` is that descriptor, to pass with `send_fd`; + the buffer keeps it, and `shared_buffer_free` closes it. `-1` for a + buffer `shared_buffer_map` made. +- `shared_buffer_map(fd, size) -> (buf, err)` maps a buffer whose descriptor + arrived (`recv`, `recv_fd`). `size` must be the size it was made with, + checked against the descriptor (`fstat`): a mismatch is an error, as is a + closed or invalid descriptor, or one that is not shared memory (a socket, + a pipe). The descriptor stays the caller's: close it once mapped. +- `shared_buffer_map_readonly(fd, size) -> (buf, err)` maps it read-only on + this side. The descriptor still lets whoever holds it write, so it is a + guard against this side's own mistakes, not a boundary. +- `shared_buffer_length(buf) -> int` is its size. +- `shared_buffer_view(buf) -> byte[]` is its bytes, as a bounded slice whose + index is checked; `shared_buffer_read_view(buf) -> byte[]` the same, + read-only (the only view of a read-only mapping: `shared_buffer_view` + panics for one). A view is valid until `shared_buffer_free` and owns + nothing, so `free` of it is refused. +- `shared_buffer_free(buf)` unmaps the buffer (and closes its descriptor, on + the side that made it). The other side's mapping stays. + +Each buffer is a handle of its own; nothing is kept in the module. Nothing +orders the two sides' accesses either: write, then say so over the channel, +and read only after hearing it. + +```aether,fragment +import std.ipc +import std.io + +// The parent: one buffer for the life of the child, passed once. +buf, err = ipc.shared_buffer(640 * 480 * 3) +if err == "" { + ipc.send_fd(ch, ipc.shared_buffer_fd(buf), "921600") + pixels = ipc.shared_buffer_view(buf) + // Each frame: the child writes into the buffer and says so. + note, ferr = ipc.read_frame(ch, 64) // "frame 1 ready" + if ferr == "" { + first = pixels[0] + ipc.write_frame(ch, "ack") + } + ipc.shared_buffer_free(buf) +} + +// The child: map what arrived, then write frames into it. +size_text, fd, rerr = ipc.recv(ch, 64) +mine, merr = ipc.shared_buffer_map(fd, 921600) +io.fd_close(fd) +``` + +How it is made: + +- **Linux, FreeBSD 13 and later, NetBSD:** an anonymous `memfd`, its size + sealed once set (`F_SEAL_SHRINK`, `F_SEAL_GROW`, `F_SEAL_SEAL`), so no + holder of the descriptor can shrink it under another's mapping (an access + past the end of a shrunk object is a `SIGBUS`), and on Linux 6.3 and later + sealed non-executable (`MFD_NOEXEC_SEAL`). Sealing is always on and not a + choice: an unsealed buffer would only add a way to crash the other side. +- **macOS, OpenBSD and other POSIX systems:** `shm_open` under a random + name, created exclusively and unlinked at once, so no name is left behind + for anything else to open. Such an object cannot be sealed, and macOS + keeps its size to whole pages (16 KiB on Apple silicon), so there the size + check tells sizes apart to the page. FreeBSD before `memfd_create`: + `shm_open(SHM_ANON)`. +- **Windows**, and builds without processes: every call returns an error + saying it is unsupported, since std.ipc passes no descriptors there. + +No grant is needed to make or map a buffer, inside a sandbox or out: the +memory is anonymous and reaches no file, socket or program, as `malloc`'s +does. `memfd_create` is called through libc, not `syscall()`, which the +sandbox preload holds to a native grant. A child under +`sandbox.spawn_socket` with no grants maps a buffer it is passed and makes +one of its own (`tests/integration/std_ipc_shared_buffer`). + ## Descriptors only go down A descriptor travels from the parent to a child, never the other way. The @@ -395,7 +476,7 @@ bounds how many descriptors one message is looked at for. return a `not a pipe` error rather than guess. `os.run_socket`, `os.socketpair`, `send_fd`, `recv_fd` and `recv` report that they are unsupported; Windows passes handles with `DuplicateHandle`, a different - shape. + shape. So are the shared buffers, which travel as descriptors. - **Builds without a filesystem** (WASM, embedded): every function exists and reports that it is unavailable. @@ -408,5 +489,8 @@ does: passing descriptors hands out authority. `send_fd`, `recv_fd`, `recv`, `write_frame`, `read_frame`, `read_frame_timeout`, `wait_readable`, `wait_writable`, `write_some`, `frame_writer`, `frame_writer_put`, `frame_writer_flush`, -`frame_writer_pending`, `frame_writer_free`, and the constants +`frame_writer_pending`, `frame_writer_free`, `shared_buffer`, +`shared_buffer_fd`, `shared_buffer_map`, `shared_buffer_map_readonly`, +`shared_buffer_length`, `shared_buffer_view`, `shared_buffer_read_view`, +`shared_buffer_free`, and the constants `TIMED_OUT_BETWEEN_FRAMES` and `TIMED_OUT_INSIDE_FRAME`. diff --git a/std/ipc/aether_ipc.c b/std/ipc/aether_ipc.c index d96ca577d..2090bb777 100644 --- a/std/ipc/aether_ipc.c +++ b/std/ipc/aether_ipc.c @@ -1592,3 +1592,277 @@ const char* ipc_frame_writer_flush_raw(void* p, int timeout_ms) { return ""; } #endif /* AETHER_HAS_FILESYSTEM */ + +/* ---- Shared buffers ---- + * + * A block of memory two processes map at once, so bulk data crosses between + * them without going through the socket: one side creates it, passes its + * descriptor over a socket channel (send_fd), and each side maps it. Each + * buffer is its own handle, holding the mapping (and, on the side that made + * it, the descriptor); nothing about a buffer lives in the module. + * + * Linux, FreeBSD and NetBSD: an anonymous memfd, close-on-exec, its size + * sealed once set (F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL), so no holder + * of the descriptor can shrink it under a mapping and make that mapping + * fault. On Linux 6.3 and later it is also made non-executable + * (MFD_NOEXEC_SEAL), so the descriptor cannot be run as a program. macOS, + * OpenBSD and other POSIX systems: shm_open under a random name, unlinked at + * once, so no name stays behind and nothing else can open it; such an object + * cannot be sealed. FreeBSD before memfd_create: shm_open(SHM_ANON). + * Android: a memfd from API 30; before it a buffer cannot be made (bionic + * has neither memfd_create nor shm_open), though one received is mapped. + * + * No grant: the memory is anonymous, reaching no file, socket or program. + * memfd_create is called through libc's wrapper, not syscall(), which the + * sandbox preload holds to a native grant for a raw call. + * + * Windows and builds without processes: every call says it is unsupported + * (std.ipc passes no descriptors there). */ + +typedef struct { void* _0; const char* _1; } _tuple_ptr_string_ipc; + +static _tuple_ptr_string_ipc ipc_shared_failed(const char* err) { + _tuple_ptr_string_ipc out = { NULL, err }; + return out; +} + +#if AETHER_HAS_FILESYSTEM && AETHER_HAS_PROCESS && !defined(_WIN32) && !defined(__wasi__) + +#include +#include +#include + +#if defined(__linux__) +/* glibc declares memfd_create only under _GNU_SOURCE; the symbol is there + * from 2.27, musl's from 1.1.20. */ +#ifndef MFD_CLOEXEC +#define MFD_CLOEXEC 0x0001U +#define MFD_ALLOW_SEALING 0x0002U +int memfd_create(const char* name, unsigned int flags); +#endif +#ifndef MFD_NOEXEC_SEAL +#define MFD_NOEXEC_SEAL 0x0008U +#endif +#ifndef F_ADD_SEALS +#define F_ADD_SEALS (1024 + 9) +#define F_GET_SEALS (1024 + 10) +#endif +#ifndef F_SEAL_SEAL +#define F_SEAL_SEAL 0x0001 +#define F_SEAL_SHRINK 0x0002 +#define F_SEAL_GROW 0x0004 +#endif +#endif + +/* Bionic has memfd_create from API 30, and no shm_open at all. */ +#if defined(MFD_CLOEXEC) && defined(F_ADD_SEALS) && (!defined(__ANDROID__) || __ANDROID_API__ >= 30) +#define IPC_SHARED_MEMFD 1 +#else +#define IPC_SHARED_MEMFD 0 +#endif + +typedef struct { + unsigned char* data; /* the mapping */ + size_t len; /* the bytes the buffer holds */ + size_t map_len; /* the bytes mapped (len, page-rounded on macOS) */ + int fd; /* the creator's descriptor; -1 on a mapping */ + int readonly; +} IpcSharedBuffer; + +/* The size the object takes for `n` bytes: macOS rounds a shm object up to + * a page (fstat says so), everywhere else it is exactly `n`. */ +static size_t ipc_shared_object_size(size_t n) { +#if defined(__APPLE__) + long page = sysconf(_SC_PAGESIZE); + if (page <= 0) page = 4096; + return (n + (size_t)page - 1) / (size_t)page * (size_t)page; +#else + return n; +#endif +} + +#if !IPC_SHARED_MEMFD && !defined(SHM_ANON) && !defined(__ANDROID__) +/* shm_open under a name nobody can guess, created exclusively and unlinked + * at once; at most 31 characters (macOS refuses longer, PSHMNAMLEN). */ +static int ipc_shared_shm_anon(void) { + for (int attempt = 0; attempt < 64; attempt++) { + unsigned long long r; +#if defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__) + r = ((unsigned long long)arc4random() << 32) | arc4random(); +#else + int u = open("/dev/urandom", O_RDONLY | O_CLOEXEC); + if (u < 0) return -1; + ssize_t got = read(u, &r, sizeof r); + close(u); + if (got != (ssize_t)sizeof r) { errno = EIO; return -1; } +#endif + char name[32]; + snprintf(name, sizeof name, "/aei%x_%016llx", (unsigned)getpid() & 0xffffffu, r); + int fd = shm_open(name, O_CREAT | O_EXCL | O_RDWR, 0600); + if (fd >= 0) { + shm_unlink(name); + int fl = fcntl(fd, F_GETFD); + if (fl < 0 || fcntl(fd, F_SETFD, fl | FD_CLOEXEC) < 0) { + int e = errno; + close(fd); + errno = e; + return -1; + } + return fd; + } + if (errno != EEXIST) return -1; + } + errno = EEXIST; + return -1; +} +#endif + +/* A fresh anonymous object, close-on-exec, of size 0. `sealable` is set + * when its size can be sealed. -1 with errno set. */ +static int ipc_shared_anon(int* sealable) { + *sealable = 0; +#if IPC_SHARED_MEMFD +#if defined(__linux__) + int fd = memfd_create("aether-ipc-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING | MFD_NOEXEC_SEAL); + if (fd < 0 && errno == EINVAL) /* before Linux 6.3: no MFD_NOEXEC_SEAL */ + fd = memfd_create("aether-ipc-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING); +#else + int fd = memfd_create("aether-ipc-shared", MFD_CLOEXEC | MFD_ALLOW_SEALING); +#endif + if (fd >= 0) *sealable = 1; + return fd; +#elif defined(SHM_ANON) + return shm_open(SHM_ANON, O_RDWR | O_CREAT | O_CLOEXEC, 0600); +#elif defined(__ANDROID__) + errno = ENOSYS; /* before API 30: no memfd_create, and bionic has no shm_open */ + return -1; +#else + return ipc_shared_shm_anon(); +#endif +} + +_tuple_ptr_string_ipc ipc_shared_buffer_new_raw(int size) { + if (size <= 0) return ipc_shared_failed("ipc.shared_buffer: the size must be at least 1 byte"); + int sealable = 0; + int fd = ipc_shared_anon(&sealable); + if (fd < 0) return ipc_shared_failed(ipc_errno_msg("ipc.shared_buffer: cannot create it", errno)); + if (ftruncate(fd, (off_t)size) != 0) { + int e = errno; + close(fd); + return ipc_shared_failed(ipc_errno_msg("ipc.shared_buffer: cannot size it", e)); + } +#if IPC_SHARED_MEMFD + if (sealable && fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_SEAL) != 0) { + int e = errno; + close(fd); + return ipc_shared_failed(ipc_errno_msg("ipc.shared_buffer: cannot seal its size", e)); + } +#endif + size_t map_len = ipc_shared_object_size((size_t)size); + void* mem = mmap(NULL, map_len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (mem == MAP_FAILED) { + int e = errno; + close(fd); + return ipc_shared_failed(ipc_errno_msg("ipc.shared_buffer: cannot map it", e)); + } + IpcSharedBuffer* b = (IpcSharedBuffer*)malloc(sizeof *b); + if (!b) { + munmap(mem, map_len); + close(fd); + return ipc_shared_failed("ipc.shared_buffer: out of memory"); + } + b->data = (unsigned char*)mem; + b->len = (size_t)size; + b->map_len = map_len; + b->fd = fd; + b->readonly = 0; + _tuple_ptr_string_ipc out = { b, "" }; + return out; +} + +_tuple_ptr_string_ipc ipc_shared_buffer_map_raw(int fd, int size, int readonly) { + const char* what = readonly ? "ipc.shared_buffer_map_readonly" : "ipc.shared_buffer_map"; + char text[96]; + if (fd < 0) { + snprintf(text, sizeof text, "no descriptor (%d)", fd); + return ipc_shared_failed(ipc_msg(what, text)); + } + if (size <= 0) return ipc_shared_failed(ipc_msg(what, "the size must be at least 1 byte")); + struct stat st; + if (fstat(fd, &st) != 0) return ipc_shared_failed(ipc_errno_msg(what, errno)); + /* macOS reports a shm object as neither a file nor anything below, so + * what is refused is what cannot be shared memory. */ + if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode) || S_ISDIR(st.st_mode) || + S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) + return ipc_shared_failed(ipc_msg(what, "the descriptor is not shared memory")); + size_t map_len = ipc_shared_object_size((size_t)size); + if (st.st_size < 0 || (unsigned long long)st.st_size != (unsigned long long)map_len) { + snprintf(text, sizeof text, "the buffer holds %lld bytes, not %d", + (long long)st.st_size, size); + return ipc_shared_failed(ipc_msg(what, text)); + } + void* mem = mmap(NULL, map_len, readonly ? PROT_READ : (PROT_READ | PROT_WRITE), + MAP_SHARED, fd, 0); + if (mem == MAP_FAILED) return ipc_shared_failed(ipc_errno_msg(what, errno)); + IpcSharedBuffer* b = (IpcSharedBuffer*)malloc(sizeof *b); + if (!b) { + munmap(mem, map_len); + return ipc_shared_failed(ipc_msg(what, "out of memory")); + } + b->data = (unsigned char*)mem; + b->len = (size_t)size; + b->map_len = map_len; + b->fd = -1; + b->readonly = readonly ? 1 : 0; + _tuple_ptr_string_ipc out = { b, "" }; + return out; +} + +int ipc_shared_buffer_fd_raw(void* p) { + return p ? ((IpcSharedBuffer*)p)->fd : -1; +} + +int ipc_shared_buffer_length_raw(void* p) { + return p ? (int)((IpcSharedBuffer*)p)->len : 0; +} + +void* ipc_shared_buffer_data_raw(void* p) { + return p ? ((IpcSharedBuffer*)p)->data : NULL; +} + +int ipc_shared_buffer_readonly_raw(void* p) { + return p ? ((IpcSharedBuffer*)p)->readonly : 0; +} + +void ipc_shared_buffer_free_raw(void* p) { + IpcSharedBuffer* b = (IpcSharedBuffer*)p; + if (!b) return; + munmap(b->data, b->map_len); + if (b->fd >= 0) close(b->fd); + free(b); +} + +#else /* no descriptor passing: Windows, WASI, builds without processes */ + +#if defined(_WIN32) +#define IPC_SHARED_UNSUPPORTED "unsupported on Windows (std.ipc passes no descriptors there)" +#else +#define IPC_SHARED_UNSUPPORTED "unavailable in this build" +#endif + +_tuple_ptr_string_ipc ipc_shared_buffer_new_raw(int size) { + (void)size; + return ipc_shared_failed("ipc.shared_buffer: " IPC_SHARED_UNSUPPORTED); +} +_tuple_ptr_string_ipc ipc_shared_buffer_map_raw(int fd, int size, int readonly) { + (void)fd; (void)size; + return ipc_shared_failed(readonly ? "ipc.shared_buffer_map_readonly: " IPC_SHARED_UNSUPPORTED + : "ipc.shared_buffer_map: " IPC_SHARED_UNSUPPORTED); +} +int ipc_shared_buffer_fd_raw(void* p) { (void)p; return -1; } +int ipc_shared_buffer_length_raw(void* p) { (void)p; return 0; } +void* ipc_shared_buffer_data_raw(void* p) { (void)p; return NULL; } +int ipc_shared_buffer_readonly_raw(void* p) { (void)p; return 0; } +void ipc_shared_buffer_free_raw(void* p) { (void)p; } + +#endif diff --git a/std/ipc/module.ae b/std/ipc/module.ae index daf6360dd..32cb46b29 100644 --- a/std/ipc/module.ae +++ b/std/ipc/module.ae @@ -43,6 +43,14 @@ // frame_writer_flush(w, ms) -> string without ever waiting // frame_writer_pending(w) -> long longer than the caller // frame_writer_free(w) says +// shared_buffer(size) -> (buf, err) memory two processes map: +// shared_buffer_fd(buf) -> int its descriptor, for send_fd +// shared_buffer_map(fd, size) -> (buf, err) map a received one +// shared_buffer_map_readonly(fd, size) the same, read-only here +// shared_buffer_length(buf) -> int its size in bytes +// shared_buffer_view(buf) -> byte[] its bytes, bounds-checked +// shared_buffer_read_view(buf) -> byte[] the same, read-only +// shared_buffer_free(buf) unmap it // // (write/write_close were originally named `send`/`send_close` per the // design discussion; renamed because `send` is a reserved keyword in @@ -83,10 +91,15 @@ exports( ipc_stdio_channel_raw, ipc_wait_writable_raw, ipc_write_some_raw, ipc_frame_writer_new_raw, ipc_frame_writer_put_raw, ipc_frame_writer_flush_raw, ipc_frame_writer_pending_raw, ipc_frame_writer_free_raw, + ipc_shared_buffer_new_raw, ipc_shared_buffer_map_raw, ipc_shared_buffer_fd_raw, + ipc_shared_buffer_length_raw, ipc_shared_buffer_data_raw, ipc_shared_buffer_readonly_raw, + ipc_shared_buffer_free_raw, parent_channel, parent_channel_kind, stdio_channel, write, write_close, read, send_fd, recv_fd, recv, write_frame, read_frame, read_frame_timeout, wait_readable, wait_writable, write_some, frame_writer, frame_writer_put, frame_writer_flush, frame_writer_pending, frame_writer_free, + shared_buffer, shared_buffer_fd, shared_buffer_map, shared_buffer_map_readonly, + shared_buffer_length, shared_buffer_view, shared_buffer_read_view, shared_buffer_free, TIMED_OUT_BETWEEN_FRAMES, TIMED_OUT_INSIDE_FRAME ) @@ -114,6 +127,13 @@ extern ipc_frame_writer_put_raw(w: ptr, data: @aether string) -> string extern ipc_frame_writer_flush_raw(w: ptr, timeout_ms: int) -> string extern ipc_frame_writer_pending_raw(w: ptr) -> long extern ipc_frame_writer_free_raw(w: @frees ptr) +extern ipc_shared_buffer_new_raw(size: int) -> (ptr, string) +extern ipc_shared_buffer_map_raw(fd: int, size: int, readonly: int) -> (ptr, string) +extern ipc_shared_buffer_fd_raw(b: ptr) -> int +extern ipc_shared_buffer_length_raw(b: ptr) -> int +extern ipc_shared_buffer_data_raw(b: ptr) -> ptr +extern ipc_shared_buffer_readonly_raw(b: ptr) -> int +extern ipc_shared_buffer_free_raw(b: @frees ptr) // Aether-side wrappers. parent_channel returns the raw int from // the extern; -1 sentinel for "no parent channel." @@ -373,3 +393,87 @@ frame_writer_pending(w: ptr) -> long { frame_writer_free(w: ptr) { ipc_frame_writer_free_raw(w) } + +// ---- Shared buffers ---- +// Memory two processes map at once, for bulk data that should not be copied +// through the channel: one side makes a buffer, passes its descriptor with +// send_fd, the other maps it, and from then on both read and write the same +// bytes, while the channel carries only small messages saying what changed. +// Each buffer is a handle of its own, freed with shared_buffer_free; no +// state is kept in the module. Nothing orders the two sides' reads and +// writes: say over the channel when a write is done, and read after that. + +// A new buffer of `size` bytes (at least 1), zeroed, mapped for reading and +// writing: (buf, "") or (null, err). It holds a close-on-exec descriptor +// (shared_buffer_fd) to pass to another process. Its size cannot change: on +// Linux and FreeBSD the descriptor is sealed against growing and shrinking, +// so a process it is passed to cannot shrink it under this side's mapping. +// The memory is anonymous: no file, name or grant is involved. +shared_buffer(size: int) -> { + return ipc_shared_buffer_new_raw(size) +} + +// The descriptor of a buffer shared_buffer made, to pass with send_fd (the +// receiver gets its own; this one stays the buffer's, and +// shared_buffer_free closes it). -1 for a buffer shared_buffer_map made, or +// for null. +shared_buffer_fd(b: ptr) -> int { + return ipc_shared_buffer_fd_raw(b) +} + +// Map the buffer whose descriptor `fd` arrived (recv, recv_fd), for reading +// and writing: (buf, "") or (null, err). `size` must be the size it was made +// with, checked against the descriptor (fstat): a mismatch, a closed or +// invalid descriptor, or one that is not shared memory is an error. The +// descriptor stays the caller's: close it once mapped, the mapping stays. +shared_buffer_map(fd: int, size: int) -> { + return ipc_shared_buffer_map_raw(fd, size, 0) +} + +// shared_buffer_map, mapped read-only: a store through its view panics +// instead of reaching the memory. Only this side's mapping is read-only; +// the descriptor still lets the process that holds it write. +shared_buffer_map_readonly(fd: int, size: int) -> { + return ipc_shared_buffer_map_raw(fd, size, 1) +} + +// The buffer's size in bytes; 0 for null. +shared_buffer_length(b: ptr) -> int { + return ipc_shared_buffer_length_raw(b) +} + +// The buffer's bytes as a bounded `byte[]`, its index checked, to read and +// write. Valid until shared_buffer_free; it owns nothing, so `free` of it is +// refused. A buffer mapped with shared_buffer_map_readonly has no writable +// view: this panics for one (use shared_buffer_read_view). Null is the empty +// slice. +shared_buffer_view(b: @into ptr) -> byte[] { + if b == null { + return null + } + if ipc_shared_buffer_readonly_raw(b) != 0 { + panic("ipc.shared_buffer_view: the buffer is mapped read-only; read it with shared_buffer_read_view") + } + n = ipc_shared_buffer_length_raw(b) + // A sub-slice of the bounded view is marked as one, so free and append + // refuse it: the memory is a mapping, not an allocation. + return (ipc_shared_buffer_data_raw(b) as byte[])[0..n][0..n] +} + +// The buffer's bytes as a bounded, read-only `byte[]`: a store through it is +// refused (at compile time where the checker sees it, else a panic). Works +// on any buffer, and is the only view of one mapped read-only. Same +// validity as shared_buffer_view. +shared_buffer_read_view(b: @into ptr) -> byte[] { + if b == null { + return null + } + n = ipc_shared_buffer_length_raw(b) + return __slice_readonly((ipc_shared_buffer_data_raw(b) as byte[])[0..n][0..n]) +} + +// Unmap the buffer, and close its descriptor if shared_buffer made it. +// Another process's mapping of the same memory stays. Null is ignored. +shared_buffer_free(b: ptr) { + ipc_shared_buffer_free_raw(b) +} diff --git a/std/ipc/test_ipc.ae b/std/ipc/test_ipc.ae index f765b5d89..9e8f38784 100644 --- a/std/ipc/test_ipc.ae +++ b/std/ipc/test_ipc.ae @@ -16,6 +16,7 @@ import std.io import std.bytes import std.string import std.list +import std.dir // 0 when a child process inherits `fd`, as it would when the descriptor // is not close-on-exec: the shell's redirection from it fails otherwise. @@ -54,6 +55,33 @@ read_fd(fd: int, n: int) -> string { return s } +// Entries in this process's descriptor table, or -1 where it cannot be +// listed (/proc/self/fd on Linux, /dev/fd elsewhere). +open_fds() -> int { + path = "/proc/self/fd" + if fs.exists(path) == 0 { path = "/dev/fd" } + entries, err = dir.list(path) + if err != "" { return -1 } + n = dir.list_count(entries) + dir.list_free(entries) + return n +} + +// The mappings of shared buffers this process holds, on Linux (their memfd +// is named "aether-ipc-shared"); -1 elsewhere. +shared_mappings() -> int { + if fs.exists("/proc/self/maps") == 0 { return -1 } + maps, err = fs.read("/proc/self/maps") + if err != "" { return -1 } + n = 0 + at = string.index_of(maps, "aether-ipc-shared") + while at >= 0 { + n = n + 1 + at = string.index_of_from(maps, "aether-ipc-shared", at + 1) + } + return n +} + main() { fw = spec.init() on_windows = string.equals(os.platform(), "windows") @@ -83,6 +111,19 @@ main() { _fd, terr = ipc.read_frame_timeout(3, 16, 10) spec.assert_err(terr, "ipc.read_frame_timeout on no pipe") } + spec.it("reports shared buffers as unsupported") callback { + b, berr = ipc.shared_buffer(4096) + spec.assert_null(b, "ipc.shared_buffer gives no buffer") + spec.assert_err_contains(berr, "unsupported on Windows", "ipc.shared_buffer") + m, merr = ipc.shared_buffer_map(3, 4096) + spec.assert_null(m, "ipc.shared_buffer_map gives no buffer") + spec.assert_err_contains(merr, "unsupported on Windows", "ipc.shared_buffer_map") + _r, rerr = ipc.shared_buffer_map_readonly(3, 4096) + spec.assert_err_contains(rerr, "unsupported on Windows", "ipc.shared_buffer_map_readonly") + spec.assert_eq(ipc.shared_buffer_fd(null), -1, "no descriptor") + spec.assert_eq(ipc.shared_buffer_length(null), 0, "no length") + ipc.shared_buffer_free(null) + } } return spec.run_summary(fw) } @@ -531,5 +572,128 @@ main() { } } + spec.describe(fw, "ipc.shared_buffer") { + spec.it("is zeroed, sized, and close-on-exec") callback { + b, err = ipc.shared_buffer(10000) + spec.assert_ok(err, "shared_buffer") + spec.assert_eq(ipc.shared_buffer_length(b), 10000, "its length") + v = ipc.shared_buffer_view(b) + spec.assert_eq(v.len, 10000, "the view is bounded at its length") + spec.assert_eq(v[0] + v[5000] + v[9999], 0, "zeroed") + fd = ipc.shared_buffer_fd(b) + spec.assert_true(fd >= 0, "it holds a descriptor") + spec.assert_not_eq(child_sees_fd(fd), 0, "a child does not inherit it") + ipc.shared_buffer_free(b) + } + + // Sent over a socket pair and received, as another process would: + // the receiver's mapping is the same memory, both ways. + spec.it("maps the same memory through a passed descriptor") callback { + b, err = ipc.shared_buffer(65536) + spec.assert_ok(err, "shared_buffer") + a, c, _ = os.socketpair() + spec.assert_ok(ipc.send_fd(a, ipc.shared_buffer_fd(b), "buf"), "send_fd") + _p, fd, rerr = ipc.recv(c, 16) + spec.assert_ok(rerr, "recv") + m, merr = ipc.shared_buffer_map(fd, 65536) + spec.assert_ok(merr, "shared_buffer_map") + io.fd_close(fd) + spec.assert_eq(ipc.shared_buffer_fd(m), -1, "a mapping holds no descriptor") + v = ipc.shared_buffer_view(b) + w = ipc.shared_buffer_view(m) + v[0] = 1 + v[65535] = 255 + spec.assert_eq(w[0], 1, "a write at the start shows through") + spec.assert_eq(w[65535], 255, "and one at the end") + w[100] = 77 + spec.assert_eq(v[100], 77, "and the other way") + ipc.shared_buffer_free(m) + spec.assert_eq(v[100], 77, "the creator's mapping outlives the other") + io.fd_close(a) + io.fd_close(c) + ipc.shared_buffer_free(b) + } + + spec.it("refuses a size it was not made with") callback { + // Whole 16 KiB pages (Apple silicon's), so macOS's rounding + // leaves each wrong size a different object size. + b, _ = ipc.shared_buffer(32768) + fd = ipc.shared_buffer_fd(b) + m, e1 = ipc.shared_buffer_map(fd, 65536) + spec.assert_null(m, "no mapping larger than the buffer") + spec.assert_err_contains(e1, "the buffer holds", "too large") + _m2, e2 = ipc.shared_buffer_map(fd, 16384) + spec.assert_err_contains(e2, "the buffer holds", "too small") + // macOS keeps a shm object to whole pages, so a size inside the + // same page is told apart only where the size is exact. + if string.equals(os.platform(), "darwin") == 0 { + _m3, e3 = ipc.shared_buffer_map(fd, 32767) + spec.assert_err_contains(e3, "the buffer holds 32768 bytes, not 32767", "one byte off") + } + _m4, e4 = ipc.shared_buffer_map(fd, 0) + spec.assert_err(e4, "a size of 0") + ipc.shared_buffer_free(b) + } + + spec.it("refuses a closed, invalid or unmappable descriptor") callback { + _m1, e1 = ipc.shared_buffer_map(-1, 4096) + spec.assert_err_contains(e1, "no descriptor", "-1") + a, c, _ = os.socketpair() + io.fd_close(c) + _m2, e2 = ipc.shared_buffer_map(c, 4096) + spec.assert_err_contains(e2, "ipc.shared_buffer_map", "a closed descriptor") + _m3, e3 = ipc.shared_buffer_map(a, 4096) + spec.assert_err_contains(e3, "not shared memory", "a socket") + io.fd_close(a) + } + + spec.it("refuses a size below 1") callback { + b, e = ipc.shared_buffer(0) + spec.assert_null(b, "no buffer") + spec.assert_err_contains(e, "at least 1 byte", "size 0") + _b2, e2 = ipc.shared_buffer(-5) + spec.assert_err(e2, "a negative size") + } + + spec.it("maps read-only, with a read-only view") callback { + b, _ = ipc.shared_buffer(4096) + v = ipc.shared_buffer_view(b) + v[7] = 9 + r, rerr = ipc.shared_buffer_map_readonly(ipc.shared_buffer_fd(b), 4096) + spec.assert_ok(rerr, "shared_buffer_map_readonly") + rv = ipc.shared_buffer_read_view(r) + spec.assert_eq(rv[7], 9, "it reads the buffer") + v[8] = 10 + spec.assert_eq(rv[8], 10, "and sees later writes") + spec.assert_eq(ipc.shared_buffer_read_view(b)[7], 9, "a read view of a writable buffer") + ipc.shared_buffer_free(r) + ipc.shared_buffer_free(b) + } + + spec.it("leaves no descriptor or mapping behind once freed") callback { + fds = open_fds() + maps = shared_mappings() + k = 0 + while k < 50 { + b, _ = ipc.shared_buffer(65536) + m, _e = ipc.shared_buffer_map(ipc.shared_buffer_fd(b), 65536) + r, _e2 = ipc.shared_buffer_map_readonly(ipc.shared_buffer_fd(b), 65536) + ipc.shared_buffer_free(r) + ipc.shared_buffer_free(m) + ipc.shared_buffer_free(b) + k = k + 1 + } + spec.assert_eq(open_fds(), fds, "the descriptor table is as it was") + spec.assert_eq(shared_mappings(), maps, "and so are the mappings") + } + + spec.it("null is no buffer") callback { + spec.assert_eq(ipc.shared_buffer_fd(null), -1, "fd") + spec.assert_eq(ipc.shared_buffer_length(null), 0, "length") + spec.assert_eq(ipc.shared_buffer_view(null).len, 0, "view") + ipc.shared_buffer_free(null) + } + } + return spec.run_summary(fw) } diff --git a/std/string/aether_string.c b/std/string/aether_string.c index e0d9f361d..36f3edcb7 100644 --- a/std/string/aether_string.c +++ b/std/string/aether_string.c @@ -1918,6 +1918,7 @@ float string_get_f32(const void* s) { // friends-and-family repos uses them. The old names of the 64-bit parse. int string_try_double(const void* s) { return string_try_float(s); } double string_get_double(const void* s) { return string_get_float(s); } +int string_to_double_raw(const void* str, double* out_value) { return string_to_float_raw(str, out_value); } // Printf-style string formatting AetherString* string_format(const char* fmt, ...) { diff --git a/std/string/aether_string.h b/std/string/aether_string.h index b573a544b..e3fe16c74 100644 --- a/std/string/aether_string.h +++ b/std/string/aether_string.h @@ -343,9 +343,11 @@ int string_try_f32(const void* s); float string_get_f32(const void* s); // 32-bit: Aether `f32` lowers to C float // TODO: delete once nothing in the aether-lang-dev org's repos or in // friends-and-family repos uses them: string_try_float / string_get_float -// under their old names, for std.string's to_double. +// under their old names, for std.string's to_double, and +// string_to_float_raw as string_to_double_raw. int string_try_double(const void* s); double string_get_double(const void* s); +int string_to_double_raw(const void* str, double* out_value); // string_to_float_raw's old name // Base-N split-return — same shape as try_long/get_long, with a radix // parameter (2..36). 64-bit out-slot; safe across LLP64. int string_try_int_radix(const void* s, int radix); diff --git a/std/string/module.ae b/std/string/module.ae index 02b4d11f2..9f8b60c88 100644 --- a/std/string/module.ae +++ b/std/string/module.ae @@ -34,7 +34,7 @@ exports( string_to_cstr, string_from_int, string_from_long, string_from_float, string_from_double, string_from_int_radix, string_pad_start, string_pad_end, - string_to_int_raw, string_to_long_raw, string_to_float_raw, string_to_f32_raw, + string_to_int_raw, string_to_long_raw, string_to_float_raw, string_to_f32_raw, string_to_double_raw, string_try_int, string_get_int, string_try_long, string_get_long, string_try_float, string_get_float, string_try_f32, string_get_f32, string_try_double, string_get_double, @@ -378,6 +378,10 @@ extern string_to_long_raw(str: string, out_value: ptr) -> int // (4-byte float) slot for to_f32_raw. extern string_to_float_raw(str: string, out_value: ptr) -> int extern string_to_f32_raw(str: string, out_value: ptr) -> int +// TODO: delete string_to_double_raw once nothing in the aether-lang-dev +// org's repos or in friends-and-family repos calls it; it is +// string_to_float_raw under its old name, the same 8-byte `float` slot. +extern string_to_double_raw(str: string, out_value: ptr) -> int extern string_to_int_radix_raw(str: string, radix: int, out_value: ptr) -> int // Parsing — split-return helpers for the Go-style wrappers. diff --git a/std/worker/aether_worker.c b/std/worker/aether_worker.c index 530c2a966..ce79e206b 100644 --- a/std/worker/aether_worker.c +++ b/std/worker/aether_worker.c @@ -210,11 +210,145 @@ static void run_job(WorkerJob* job) { } #if AETHER_WORKER_HAS_THREADS +/* ---- own threads: reaped, never left exiting --------------------------- */ + +/* A job that runs on a thread of its own (run_detached, and run/submit when + * the pool cannot start) used to be pthread_detach'ed at launch. Its job + * retires (g_pending drops) while the thread still has work left: freeing + * the job, a lock round to wake waiters, the return through the thread + * trampoline and the thread's exit. A program that waits for pending() == 0 + * and returns from main therefore exits while that thread is still exiting, + * and Wine crashes on that overlap (SIGSEGV in the Wine process after the + * program's last output, about 1 run in 1000 of + * tests/regression/test_worker_pool.ae). POSIX allows it, Windows' ExitProcess + * allows it, but no runtime should depend on how a platform settles a thread + * caught half way out. + * + * So each such thread is kept joinable and listed here. Its last act is to + * set `done`; a thread marked done has nothing left but to return, so a join + * on it is immediate. Finished threads are joined at the next launch (the + * list stays as long as the number of own threads still running) and at + * process exit, from an atexit handler. A thread still inside its job at exit + * is detached then, not waited on: a detached job may block for good, and + * waiting on it would hang the exit, so it ends with the process, as before. + * Under g_lock. */ +typedef struct OwnThread { + pthread_t th; + atomic_int done; + WorkerJob* job; + struct OwnThread* next; +} OwnThread; + +static OwnThread* g_own = NULL; +static int g_own_atexit = 0; + static void* worker_entry(void* arg) { - run_job((WorkerJob*)arg); + OwnThread* t = (OwnThread*)arg; + run_job(t->job); + /* Last touch: t belongs to the reaper now. Under g_lock, so a fork + * (which holds it) sees each thread either still in its job or done. */ + pthread_mutex_lock(&g_lock); + atomic_store(&t->done, 1); + pthread_mutex_unlock(&g_lock); return NULL; } +/* Unlink every finished thread under the lock, then join and free them + * outside it. */ +static void own_reap(void) { + OwnThread* finished = NULL; + pthread_mutex_lock(&g_lock); + OwnThread** pp = &g_own; + while (*pp) { + OwnThread* t = *pp; + if (atomic_load(&t->done)) { + *pp = t->next; + t->next = finished; + finished = t; + } else { + pp = &t->next; + } + } + pthread_mutex_unlock(&g_lock); + while (finished) { + OwnThread* t = finished; + finished = t->next; + pthread_join(t->th, NULL); + free(t); + } +} + +/* At exit: join what has finished, and detach what is still inside its + * job, which ends with the process. Its OwnThread stays allocated: the + * thread still writes `done` into it. */ +static void own_reap_at_exit(void) { + own_reap(); + pthread_mutex_lock(&g_lock); + for (OwnThread* t = g_own; t; t = t->next) pthread_detach(t->th); + g_own = NULL; + pthread_mutex_unlock(&g_lock); +} + +/* Across a fork: a thread that has finished but is not yet joined would + * come into the child as a joinable thread nobody joins, which a child that + * exits without exec (one whose exec failed) is left holding. So the fork is + * made under g_lock with every done thread joined first; a done thread has + * only its return left, so each join is immediate, and since a thread marks + * itself done under g_lock, none can finish between the joins and the fork. + * The child has none of the threads still in their jobs, only the list's + * copy, which it forgets: they are not its to join or detach. */ +#if !defined(_WIN32) +static void own_fork_prepare(void) { + pthread_mutex_lock(&g_lock); + OwnThread** pp = &g_own; + while (*pp) { + OwnThread* t = *pp; + if (atomic_load(&t->done)) { + *pp = t->next; + pthread_join(t->th, NULL); + free(t); + } else { + pp = &t->next; + } + } +} +static void own_fork_parent(void) { pthread_mutex_unlock(&g_lock); } +static void own_fork_child(void) { + g_own = NULL; /* the parent's threads, not here; their nodes stay the parent's */ + pthread_mutex_unlock(&g_lock); +} +#endif + +/* Start `job` on a thread of its own. 0 on success, else the job is still + * the caller's. */ +static int own_spawn(WorkerJob* job) { + own_reap(); + OwnThread* t = (OwnThread*)calloc(1, sizeof(OwnThread)); + if (!t) return -1; + t->job = job; + atomic_init(&t->done, 0); + pthread_mutex_lock(&g_lock); + if (!g_own_atexit) { + g_own_atexit = 1; + atexit(own_reap_at_exit); +#if !defined(_WIN32) + pthread_atfork(own_fork_prepare, own_fork_parent, own_fork_child); +#endif + } + /* Listed before it starts, so the reaper never misses it; the thread + * reads only t->job until it sets done, and t->th is written here, + * under the lock the reaper takes. */ + if (pthread_create(&t->th, NULL, worker_entry, t) != 0) { + pthread_mutex_unlock(&g_lock); + free(t); + return -1; + } + t->next = g_own; + g_own = t; + pthread_mutex_unlock(&g_lock); + return 0; +} + /* ---- bounded pool (#1205) ---------------------------------------------- */ static int default_pool_size(void) { @@ -302,18 +436,16 @@ static int launch(AetherWorkerClosure work, AetherWorkerClosure done, int detach #if AETHER_WORKER_HAS_THREADS /* run() submits to the bounded pool; run_detached() (and a pool that - * failed to start) spawns a fresh self-reaping thread so a truly - * long-blocking job never starves the pool. */ + * failed to start) gets a thread of its own, so a truly long-blocking + * job never starves the pool. own_spawn joins it once it is done. */ if (!detached && pool_submit(job)) { return 1; } - pthread_t th; - if (pthread_create(&th, NULL, worker_entry, job) != 0) { + if (own_spawn(job) != 0) { atomic_fetch_sub(&g_pending, 1); free(job); return 0; } - pthread_detach(th); /* self-reaping; we never join */ #else /* Cooperative / threadless build: no off-thread execution. Run the work * synchronously here; the completion still flows through the poster/drain @@ -347,11 +479,7 @@ int aether_worker_submit(AetherWorkerClosure work) { job->work = work; job->raw = 1; if (pool_submit(job)) return 1; - pthread_t th; - if (pthread_create(&th, NULL, worker_entry, job) == 0) { - pthread_detach(th); - return 1; - } + if (own_spawn(job) == 0) return 1; free(job); return 0; #else diff --git a/tests/ae_sweep_prune.txt b/tests/ae_sweep_prune.txt index 4940709c9..df3a1725e 100644 --- a/tests/ae_sweep_prune.txt +++ b/tests/ae_sweep_prune.txt @@ -277,6 +277,7 @@ tests/integration/std_dl/ tests/integration/std_ipc_bash_chain/ tests/integration/std_ipc_roundtrip/ tests/integration/std_ipc_socket/ +tests/integration/std_ipc_shared_buffer/ tests/integration/std_guest/ tests/integration/std_guest_invoke/ tests/integration/std_mem_byte_access/ diff --git a/tests/integration/fs_open_binary_mode/test_fs_open_binary_mode.sh b/tests/integration/fs_open_binary_mode/test_fs_open_binary_mode.sh index e72a2bb62..687846749 100644 --- a/tests/integration/fs_open_binary_mode/test_fs_open_binary_mode.sh +++ b/tests/integration/fs_open_binary_mode/test_fs_open_binary_mode.sh @@ -36,12 +36,12 @@ main() { if oerr != "" { println("open w: ${oerr}"); return 1 } n, werr = fs.pwrite(f, string.bytes("ab\ncd\n"), 0) _ = fs.close(f) - sz, serr = fs.size(p) + sz, _serr = fs.size(p) println("pwrite ${n} ${werr} size ${sz}") // 2. "r" + pread reads the bytes back exactly g, gerr = fs.open(p, "r") if gerr != "" { println("open r: ${gerr}"); return 1 } - got, gn, perr = fs.pread(g, 16, 0) + got, gn, _perr = fs.pread(g, 16, 0) _ = fs.close(g) println("pread ${gn} ${got == "ab\ncd\n"}") // 3. a file holding CRLF and a 0x1A byte is read verbatim through "r" @@ -72,10 +72,16 @@ pread 6 true crlf 6 true append size 8 wt true ' -got="$(AETHER_HOME="$ROOT" "$AE" run "$tmp/main.ae" -- "$tmp" 2>&1 | grep -v -E "^warning|^ *-->|^ *[0-9]* [|]|^ *[|]|^Type checking|^$")" +# The program's stdout alone is compared. The compiler's diagnostics go to +# stderr, kept apart and shown on a failure: filtering them out of a merged +# stream with patterns broke on Windows, where they end in CRLF, so the blank +# line after each warning arrived as a lone "\r" that "^$" does not match. +got="$(AETHER_HOME="$ROOT" "$AE" run "$tmp/main.ae" -- "$tmp" 2>"$tmp/stderr.txt")" if [ "$got" != "$want" ]; then echo " [FAIL] fs_open_binary_mode: output differs" printf '%s\n' "$got" | head -8 | sed 's/^/ /' + echo " stderr:" + head -20 "$tmp/stderr.txt" | sed 's/^/ /' exit 1 fi echo " [PASS] fs_open_binary_mode: fs.open handles are byte-exact through pwrite/pread and read_all; a+ appends" diff --git a/tests/integration/std_ipc_shared_buffer/child.ae b/tests/integration/std_ipc_shared_buffer/child.ae new file mode 100644 index 000000000..dc336ab72 --- /dev/null +++ b/tests/integration/std_ipc_shared_buffer/child.ae @@ -0,0 +1,74 @@ +// The child for host.ae: given a shared buffer's descriptor over its socket +// channel, it maps the buffer, checks what the parent wrote, then writes +// FRAMES frames into it, sending only "frame N ready" over the channel for +// each and waiting for the parent's "ack N". Under sandbox.spawn_socket it +// runs with no grants at all. + +import std.ipc +import std.io +import std.string + +extern exit(code: int) + +const FRAMES = 3 + +fail(ch: int, msg: string) { + ipc.write_frame(ch, "FAIL ${msg}") + exit(1) +} + +main() { + ch = ipc.parent_channel() + if ch < 0 { + println("FAIL no parent channel") + exit(1) + } + + payload, fd, rerr = ipc.recv(ch, 64) + if rerr != "" { fail(ch, "recv: ${rerr}") } + if fd < 0 { fail(ch, "no descriptor came") } + size, serr = string.to_int(payload) + if serr != "" { fail(ch, "size '${payload}': ${serr}") } + + // The wrong size is refused before the right one maps. + bad, berr = ipc.shared_buffer_map(fd, size * 2) + if bad != null || berr == "" { fail(ch, "a mapping of twice the size was not refused") } + + buf, merr = ipc.shared_buffer_map(fd, size) + if merr != "" { fail(ch, "map: ${merr}") } + io.fd_close(fd) + v = ipc.shared_buffer_view(buf) + if v.len != size { fail(ch, "view of ${v.len} bytes, not ${size}") } + + i = 0 + while i < size { + if v[i] != i % 251 { fail(ch, "byte ${i} is ${v[i]}, not ${i % 251}") } + i = i + 1 + } + + // A buffer of its own, made here: anonymous memory needs no grant. + own, oerr = ipc.shared_buffer(4096) + if oerr != "" { fail(ch, "shared_buffer in the child: ${oerr}") } + ov = ipc.shared_buffer_view(own) + ov[4095] = 1 + ipc.shared_buffer_free(own) + + n = 1 + while n <= FRAMES { + i = 0 + while i < size { + v[i] = (i * 7 + n) % 256 + i = i + 1 + } + werr = ipc.write_frame(ch, "frame ${n} ready") + if werr != "" { fail(ch, "write_frame: ${werr}") } + ack, aerr = ipc.read_frame(ch, 64) + if aerr != "" { fail(ch, "read ack: ${aerr}") } + if ack != "ack ${n}" { fail(ch, "ack was '${ack}'") } + n = n + 1 + } + + ipc.shared_buffer_free(buf) + ipc.write_frame(ch, "done") + io.fd_close(ch) +} diff --git a/tests/integration/std_ipc_shared_buffer/host.ae b/tests/integration/std_ipc_shared_buffer/host.ae new file mode 100644 index 000000000..0b890e1b3 --- /dev/null +++ b/tests/integration/std_ipc_shared_buffer/host.ae @@ -0,0 +1,95 @@ +// std.ipc shared buffers across processes. Usage: +// +// host plain the child under os.run_socket +// host sandboxed the child under sandbox.spawn_socket, granted +// nothing but reading its own directory (Linux) +// +// The parent makes a buffer of a 640x480 RGB frame's size, fills it, passes +// its descriptor to the child, and reads each frame the child writes into +// it, checking every byte, while the channel carries only short messages. +// Prints PASS, or FAIL and a reason, and exits 0 or 1. + +import std.ipc +import std.os +import std.io +import std.list +import std.sandbox +import std.string + +extern exit(code: int) + +const SIZE = 921600 +const FRAMES = 3 + +fail(msg: string) { + println("FAIL ${msg}") + exit(1) +} + +dirname(path: string) -> string { + i = string.length(path) - 1 + while i > 0 && string.char_at(path, i) != 47 { + i = i - 1 + } + return string.substring(path, 0, i) +} + +main() { + if os.args_count() < 3 { fail("usage: host plain|sandboxed ") } + mode = os.args_get(1) + child = os.args_get(2) + + buf, err = ipc.shared_buffer(SIZE) + if err != "" { fail("shared_buffer: ${err}") } + v = ipc.shared_buffer_view(buf) + i = 0 + while i < SIZE { + v[i] = i % 251 + i = i + 1 + } + + argv = list.new() + ch = -1 + pid = -1 + serr = "" + g = sandbox.new("shared-buffer-child") { + } + if mode == "sandboxed" { + sandbox.grant_fs_read(g, "${dirname(child)}/*") + ch, pid, serr = sandbox.spawn_socket(g, child, argv, null) + } else { + ch, pid, serr = os.run_socket(child, argv, null) + } + list.free(argv) + if serr != "" { fail("spawn: ${serr}") } + + ferr = ipc.send_fd(ch, ipc.shared_buffer_fd(buf), "${SIZE}") + if ferr != "" { fail("send_fd: ${ferr}") } + + n = 1 + while n <= FRAMES { + msg, rerr = ipc.read_frame_timeout(ch, 256, 30000) + if rerr != "" { fail("frame ${n}: ${rerr}") } + if msg != "frame ${n} ready" { fail("the child said '${msg}'") } + i = 0 + while i < SIZE { + if v[i] != (i * 7 + n) % 256 { fail("frame ${n}: byte ${i} is ${v[i]}") } + i = i + 1 + } + aerr = ipc.write_frame(ch, "ack ${n}") + if aerr != "" { fail("ack: ${aerr}") } + n = n + 1 + } + last, lerr = ipc.read_frame_timeout(ch, 256, 30000) + if lerr != "" || last != "done" { fail("the child ended with '${last}' ${lerr}") } + io.fd_close(ch) + code, werr = os.wait_pid(pid) + if werr != "" { fail("wait: ${werr}") } + if code != 0 { fail("the child exited ${code}") } + + // The child's mapping is gone; this side's is still the buffer. + if v[SIZE - 1] != ((SIZE - 1) * 7 + FRAMES) % 256 { fail("the last frame is gone") } + ipc.shared_buffer_free(buf) + sandbox.free(g) + println("PASS ${mode}: ${FRAMES} frames of ${SIZE} bytes through a shared buffer") +} diff --git a/tests/integration/std_ipc_shared_buffer/test_std_ipc_shared_buffer.sh b/tests/integration/std_ipc_shared_buffer/test_std_ipc_shared_buffer.sh new file mode 100755 index 000000000..89f7b7362 --- /dev/null +++ b/tests/integration/std_ipc_shared_buffer/test_std_ipc_shared_buffer.sh @@ -0,0 +1,65 @@ +#!/bin/sh +# std.ipc shared buffers across processes: host.ae makes a buffer, passes its +# descriptor to child.ae over an os.run_socket channel, and each side reads +# what the other wrote into it. On Linux the same child runs again under +# sandbox.spawn_socket (the preload, Landlock and seccomp), granted nothing +# but reading its own directory: creating and mapping a buffer need no grant. +# +# Skips on Windows, where std.ipc passes no descriptors. + +set -e + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" +AE="$ROOT/build/ae" + +case "$(uname -s 2>/dev/null)" in + MINGW*|MSYS*|CYGWIN*) + echo " [SKIP] std_ipc_shared_buffer: std.ipc passes no descriptors on Windows" + exit 0 ;; +esac +if [ ! -x "$AE" ]; then + echo " [SKIP] std_ipc_shared_buffer: ae not built" + exit 0 +fi + +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP" || true' EXIT +export AETHER_HOME="$ROOT" + +fail() { + echo " [FAIL] std_ipc_shared_buffer: $1" + sed 's/^/ /' "$2" + exit 1 +} + +mkdir "$TMP/bin" +for a in host child; do + "$AE" build "$SCRIPT_DIR/$a.ae" -o "$TMP/bin/$a" > "$TMP/build.log" 2>&1 || fail "cannot build $a.ae" "$TMP/build.log" +done + +"$TMP/bin/host" plain "$TMP/bin/child" > "$TMP/plain.out" 2>&1 || fail "plain" "$TMP/plain.out" +grep -q "^PASS plain" "$TMP/plain.out" || fail "plain: no PASS" "$TMP/plain.out" +echo " [PASS] std_ipc_shared_buffer: frames through a buffer a child maps" + +if [ "$(uname -s)" != Linux ]; then + echo " [SKIP] std_ipc_shared_buffer: sandbox.spawn_socket contains a child on Linux only" + exit 0 +fi +# Under the ASan sweep the child is an ASan program confined through the +# sandbox's preload library, which ASan refuses to start under (its runtime +# not first), and the sandbox gives it none of the sweep's ASAN_OPTIONS; the +# same reason tests/ae_sweep_prune_asan.txt leaves the sandbox tests out +# (SANDBOX). The buffer itself was held to ASan above. +if [ "${AETHER_SANITIZER:-}" = asan ]; then + echo " [SKIP] std_ipc_shared_buffer: sandboxed: an ASan child does not start under the sandbox's preload" + exit 0 +fi +if [ ! -f "$ROOT/build/libaether_sandbox.so" ]; then + echo " [SKIP] std_ipc_shared_buffer: build/libaether_sandbox.so not built" + exit 0 +fi +"$TMP/bin/host" sandboxed "$TMP/bin/child" > "$TMP/sandboxed.out" 2>&1 || fail "sandboxed" "$TMP/sandboxed.out" +grep -q "^PASS sandboxed" "$TMP/sandboxed.out" || fail "sandboxed: no PASS" "$TMP/sandboxed.out" +echo " [PASS] std_ipc_shared_buffer: the same under sandbox.spawn_socket, with no grant" +exit 0 diff --git a/tests/regression/test_result_type_named_scalar.ae b/tests/regression/test_result_type_named_scalar.ae new file mode 100644 index 000000000..c64316190 --- /dev/null +++ b/tests/regression/test_result_type_named_scalar.ae @@ -0,0 +1,92 @@ +// Regression: `-> T! { ... }` declares a fallible function for a scalar +// spelt as a name (`f32`, `int64`, `uint8`, `size_t`, `longdouble`, ...) +// and for a struct, as it does for the type keywords (`float!`, `byte!`, +// `int!`). The return-type lookahead took `-> f32!` for an expression body, +// so the `{` after it was a top-level parse error. +// +// Self-asserting: prints FAIL + exits 1 on any mismatch, PASS at the end. + +extern exit(code: int) + +struct Point { x: int y: int } + +half(x: f32) -> f32! { + if x < 0.0 { return 0.0, "negative" } + return x / 2.0 +} + +wide(x: int64) -> int64! { + return x + 1 +} + +low_byte(x: uint8) -> uint8! { + if x == 0 { return x, "zero" } + return x +} + +halfword(x: uint16) -> uint16! { + return x +} + +word(x: uint32) -> uint32! { + return x +} + +big(x: uint64) -> uint64! { + return x +} + +count(x: size_t) -> size_t! { + return x +} + +signed(x: int32_t) -> int32_t! { + return x +} + +precise(x: longdouble) -> longdouble! { + return x +} + +origin(ok: int) -> Point! { + if ok == 0 { return Point { x: 0, y: 0 }, "no point" } + return Point { x: 1, y: 2 } +} + +// `!` propagation inside a named-scalar fallible. +quarter(x: f32) -> f32! { + h = half(x)! + return half(h)! +} + +fail(msg: string) { + println("FAIL: ${msg}") + exit(1) +} + +main() { + a = half(3.0) or 99.0 + if a != 1.5 { fail("half(3.0) = ${a}") } + b = half(-1.0) or 99.0 + if b != 99.0 { fail("half(-1.0) did not fail") } + if (wide(41) or 0) != 42 { fail("wide") } + u8 = 7 as uint8 + if (low_byte(u8) or 0) != 7 { fail("low_byte") } + _z, zerr = low_byte(0 as uint8) + if zerr != "zero" { fail("low_byte(0) error '${zerr}'") } + if (halfword(7 as uint16) or 0) != 7 { fail("halfword") } + if (word(8 as uint32) or 0) != 8 { fail("word") } + if (big(9 as uint64) or 0) != 9 { fail("big") } + if (count(10 as size_t) or 0) != 10 { fail("count") } + if (signed(-11 as int32_t) or 0) != -11 { fail("signed") } + _l, lerr = precise(1.25 as longdouble) + if lerr != "" { fail("precise") } + p, perr = origin(1) + if perr != "" || p.x != 1 || p.y != 2 { fail("origin(1)") } + _q, qerr = origin(0) + if qerr != "no point" { fail("origin(0) error '${qerr}'") } + q = quarter(8.0) or 0.0 + if q != 2.0 { fail("quarter(8.0) = ${q}") } + if (quarter(-8.0) or 5.0) != 5.0 { fail("quarter(-8.0) did not fail") } + println("PASS") +} diff --git a/tests/regression/test_string_to_double_raw.ae b/tests/regression/test_string_to_double_raw.ae new file mode 100644 index 000000000..f5fb499f6 --- /dev/null +++ b/tests/regression/test_string_to_double_raw.ae @@ -0,0 +1,48 @@ +// Regression: std.string's to_double_raw is still there, the 64-bit parse +// under its old name. +// +// When to_float became the correctly rounded 64-bit parse, to_double_raw +// went: its job was to_float_raw's now. Code calling it stopped +// compiling, while to_double, try_double and get_double had been kept for +// that code under their old names. It is kept as they are, until nothing +// calls it, and parses as to_float_raw does: into an 8-byte `float` slot, +// to binary64, 1 for a number and 0 for anything else. + +import std.string +extern calloc(count: int, size: int) -> ptr +extern free(p: ptr) + +extern exit(code: int) + +fail(msg: string) { + println("FAIL: ${msg}") + exit(1) +} + +main() { + println("=== std.string to_double_raw ===") + slot = calloc(1, 8) + other = calloc(1, 8) + + if string.to_double_raw("0.1", slot) != 1 { fail("to_double_raw(\"0.1\") was refused") } + got = (slot as float[])[0] + if got != 0.1 { fail("to_double_raw(\"0.1\") is ${got}, not 0.1 to 64 bits") } + println(" PASS: to_double_raw parses to 64 bits") + + for text in ["2.5", "-1e300", "3.141592653589793", "1e-310"] { + a = string.to_double_raw(text, slot) + b = string.to_float_raw(text, other) + if a != b { fail("to_double_raw and to_float_raw disagree on accepting \"${text}\"") } + if (slot as float[])[0] != (other as float[])[0] { fail("to_double_raw(\"${text}\") is not to_float_raw's value") } + } + println(" PASS: to_double_raw is to_float_raw") + + for bad in ["", "abc", "1.5x"] { + if string.to_double_raw(bad, slot) != 0 { fail("to_double_raw accepted \"${bad}\"") } + } + println(" PASS: to_double_raw refuses what is not a number") + + free(slot) + free(other) + println("PASS") +}