From e75be42aa40b79c7cb496bb454e7b582d63725b2 Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Thu, 19 Nov 2026 12:16:31 +0900 Subject: [PATCH 1/3] 0.2.0: openkal 0.26 - openkal ^0.26.0; openkal-dos-tools carries the same version (one archive) - no code changes: what 0.26 requires is of openkal.process, which is absent here, and what a program receives is bounded by DOS alone (the command tail's 127 bytes, the environment block read where it lies) --- README.md | 10 ++++++++++ mcpp.toml | 4 ++-- tools/mcpp.toml | 2 +- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 470ed55..b30d307 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,16 @@ DPMI host CWSDPMI is DPMI 0.90 and refuses 0504h (measured), which is the case accepts the request for raw mode and stays cooked (measured); `kal_terminal_get_mode` reports what is in effect. +0.2.0 is written against openkal 0.26, and nothing but the specification's +version changes; `openkal-dos-tools` carries the same version, as the two are one +archive. What 0.26 requires is of `openkal.process`, which is absent here: a +start bounded by the environment alone (clause 7.6) and a unit claimed only +where a reference can be made (clause 7.18). What a program receives is bounded +by DOS alone already: the command tail of the segment prefix holds at most 127 +bytes, the room `src/start.cpp` keeps for its words is that bound's, and the +variables are read from the environment block where it lies, however many it +holds. + An i386 ok image (`i686-openkal`) runs on DOS as on firmware: the platform's runner `hosts` include `dos-i686`, so `mcpp pack --pkg-format single-file --systems dos-i686` builds openkal-run's core runner as a program of this row, diff --git a/mcpp.toml b/mcpp.toml index 912b07a..5917a85 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -8,7 +8,7 @@ [package] namespace = "mcpplibs" name = "openkal-dos" -version = "0.1.1" +version = "0.2.0" description = "An implementation of openkal on DOS through DPMI (technical experiment only)" license = "Apache-2.0" provides = ["mcpp:kernel-abi=openkal"] @@ -23,7 +23,7 @@ provides-interfaces = ["openkal.abort", "openkal.env", "openkal.exec", "openkal. "openkal.stream", "openkal.terminal", "openkal.time"] [dependencies] -openkal = "^0.25.0" +openkal = "^0.26.0" # With no C library this package runs the initialisers and calls `main'; `standalone' is the # arrangement beneath a C library written above openkal (openkal-musl names it so on diff --git a/tools/mcpp.toml b/tools/mcpp.toml index 228a642..d8468a3 100644 --- a/tools/mcpp.toml +++ b/tools/mcpp.toml @@ -4,7 +4,7 @@ [package] namespace = "mcpplibs" name = "openkal-dos-tools" -version = "0.1.1" +version = "0.2.0" description = "okdos: seals an ELF32 i386 executable as a DOS program behind openkal-dos's DPMI stub (technical experiment only)" license = "Apache-2.0" authors = ["mcpplibs"] From 2fe9539e81b61a3797e49339a3479d14e44bdeba Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 23 Nov 2026 06:43:51 +0900 Subject: [PATCH 2/3] 0.3.0: openkal.process through EXEC, a started program run to its end first, with its streams and no other handle; the tail divided as DOS's C compilers divide it --- .github/workflows/ci.yml | 15 +- README.md | 77 ++++++- examples/files/mcpp.toml | 3 +- examples/hello/mcpp.toml | 3 +- mcpp.toml | 11 +- src/dos.h | 20 ++ src/env.cpp | 29 ++- src/fs.cpp | 16 ++ src/kal.cpp | 11 +- src/process.cpp | 435 ++++++++++++++++++++++++++++++++++++ src/start.cpp | 56 ++++- tests/fault/mcpp.toml | 3 +- tests/fault/src/main.cpp | 2 +- tests/stack-small/mcpp.toml | 3 +- tests/stack/mcpp.toml | 3 +- tests/starts/mcpp.toml | 14 ++ tests/starts/src/main.c | 98 ++++++++ tools/mcpp.toml | 2 +- 18 files changed, 764 insertions(+), 37 deletions(-) create mode 100644 src/process.cpp create mode 100644 tests/starts/mcpp.toml create mode 100644 tests/starts/src/main.c diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fce1562..a615408 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ on: env: XLINGS_VERSION: v2026.10.26.1 XLINGS_NON_INTERACTIVE: '1' - MCPP_VERSION: 2026.11.16.1 + MCPP_VERSION: 2026.11.22.1 LLVM: llvm@23.1.3 jobs: @@ -102,7 +102,7 @@ jobs: # ones: the stub and the runtime agree on the hand-over's version. - name: This repository's openkal-dos and okdos run: | - for p in examples/hello examples/files tests/fault tests/stack tests/stack-small; do + for p in examples/hello examples/files tests/starts tests/fault tests/stack tests/stack-small; do printf '\n[target.i686-dos-musl.dependencies]\nmcpplibs.openkal-dos = { path = "%s", override = true }\nmcpplibs.openkal-dos-tools = { path = "%s/tools", override = true }\n' \ "$GITHUB_WORKSPACE" "$GITHUB_WORKSPACE" >> "$p/mcpp.toml" done @@ -126,6 +126,17 @@ jobs: tr -d '\r' < out.txt | grep -qx 'read 3: appended' tr -d '\r' < out.txt | grep -qx 'resized to 40' tr -d '\r' < out.txt | grep -qx 'removed: true' + # A PROGRAM STARTS PROGRAMS (0.3.0): posix_spawn starts the program again by EXEC, with a + # vector, a variable, a stream placed on a file and on NUL; a copy finds no handle of its + # starter's; an absent name and a tail beyond DOS's 126 bytes are refused. + - name: starts (status 42) + working-directory: tests/starts + run: | + set +e; mcpp run --target i686-dos-musl > out.txt; rc=$?; set -e + cat out.txt + if tr -d '\r' < out.txt | grep -q '^ FAIL'; then echo "::error::a check of tests/starts failed"; exit 1; fi + [ "$rc" = 42 ] || { echo "::error::starts ended with $rc, not 42"; exit 1; } + tr -d '\r' < out.txt | grep -qx 'all held' - name: a page fault (status 139) working-directory: tests/fault run: | diff --git a/README.md b/README.md index b30d307..cda323d 100644 --- a/README.md +++ b/README.md @@ -9,14 +9,15 @@ interfaces, its hand-over and its stub may change in any release. A program names the target and nothing else. The row `i686-dos-musl`, its compile and link conventions, its seal and its runner are the openkal -platform's ([openkal-platform][plat] 0.28.0): the same C library and C++ +platform's ([openkal-platform][plat], from 0.28.0; 0.32.0 holds this release): the same C library and C++ run-time as on every other system, openkal-musl and openkal-llvm-runtime, with this implementation beneath them, so a DOS program is written in C++23 with `import std`: ```toml [target.i686-dos-musl] -platform = "openkal-platform@0.28.0" +platform = "openkal-platform@0.32.0" +runner = { enabled = true } # the platform states the machine runner off until a project enables it ``` ```sh @@ -102,7 +103,8 @@ C library states `c-abi = false` for the row and calls openkal directly. |---|---| | `stream` | DOS handles: 0, 1 and 2, and a file's (int 21h, 3Fh and 40h) through the transfer buffer; a handle's properties from IOCTL 4400h | | `memory` | DPMI blocks (0501h, 0502h), 4 KiB granular; the free memory from 0500h | -| `env` | the arguments from the command tail (offset 80h of the segment prefix), the variables from the environment block, the program's name, the system name `dos` | +| `env` | the arguments from the command tail (offset 80h of the segment prefix), divided as DOS's C compilers divide it (0.3.0), the first element as its starter gave it (`KAL_ARG0`, 0.3.0), the variables from the environment block, the program's name, the system name `dos` | +| `process` | EXEC (int 21h, 4B00h), the started program run to its end before the start returns, its status from 4Dh (0.3.0) | | `time` | the BIOS tick count at 0040:006C (54.925494 ms, made monotonic across midnight); the wall clock from int 21h 2Ah and 2Ch, read as UTC; a sleep by int 15h, 86h | | `fs` | the current directory and each volume as supplied directories (`C:\WORK`, `C:`, `Z:`), a directory held as its name; open, create (5Bh refuses a name that exists), truncate, seek, transfers at an offset, find first and next for enquiry and listing, make and remove a directory, remove, rename, a file's time (5700h, 5701h) and a volume's capacity (36h) | | `terminal` | the console's mode by bit 5 of its device word (cooked: line assembly and echo; raw: every byte as typed), ANSI.SYS's sequences where it answers int 2Fh 1A00h, the size from the BIOS data area | @@ -121,8 +123,7 @@ name that exists, which is the rename that does not replace first and is not atomic. A name that holds DOS's `\` or a volume's `:` is refused, as a name that ascends is. -Absent (openkal clause 6.2): contexts, processes as openkal states them, the -network, and regions --- DOS cannot reserve an address apart from backing it: the +Absent (openkal clause 6.2): contexts, the network, and regions --- DOS cannot reserve an address apart from backing it: the DPMI host CWSDPMI is DPMI 0.90 and refuses 0504h (measured), which is the case `openkal/region.h` names for leaving the interface out. DOSBox Staging's console accepts the request for raw mode and stays cooked (measured); @@ -130,7 +131,7 @@ accepts the request for raw mode and stays cooked (measured); 0.2.0 is written against openkal 0.26, and nothing but the specification's version changes; `openkal-dos-tools` carries the same version, as the two are one -archive. What 0.26 requires is of `openkal.process`, which is absent here: a +archive. What 0.26 requires is of `openkal.process`, which was absent until 0.3.0: a start bounded by the environment alone (clause 7.6) and a unit claimed only where a reference can be made (clause 7.18). What a program receives is bounded by DOS alone already: the command tail of the segment prefix holds at most 127 @@ -150,6 +151,68 @@ with the image in its `.oke` section, and the runner places the image through lists, resizes (the extension reads as zero) and removes them, and returns 9 (measured under DOSBox Staging). +## Starting a program (0.3.0) + +`openkal.process` is provided through EXEC (int 21h, 4B00h). DOS runs one +program: EXEC suspends the caller until the program it started ends, so +`kal_process_spawn` returns after the end and `kal_process_wait` answers the +status at once, int 21h 4Dh's (`KAL_PROCESS_PROP_RUNS_TO_END`, openkal clause +7.19). A program ended by Ctrl-C is reported ended with 130, one ended by a +critical error ended with its code. `TERMINATE` and `CHANNEL` are not claimed; +`BOUND_LIFETIME` is, a started program being unable to outlive its starter; +`EXIT_STATUS`, `STREAM_PASSING`, `NULL_STREAMS` and `ONE_STRING` are claimed. A +started program of this implementation enters protected mode through the DPMI +host already resident, as a client of its own. + +| what a start gives | how it reaches the started program | +|---|---| +| the vector after the first element | the command tail: a blank before each element, and an element that is empty or holds a blank or a quote quoted, its quotes preceded by a backslash and the backslashes before a quote doubled; `KAL_SPAWN_ONE_STRING` joins the elements as they are | +| the first element | `KAL_ARG0=\|` among the variables: DOS gives a program no first element, only the name EXEC was given; a program of this implementation reads it where the name is its own, and does not list it among its variables | +| the variables | an environment block of their own in conventional memory (DPMI 0100h) | +| the directory it runs in | DOS's current drive and directory for the call, restored after it | +| the three streams | for the call, the caller's handle table (PSP:34h) holds at positions 0, 1 and 2 the caller's own handles, those it placed, or NUL opened for the position, then DOS's AUX and PRN at 3 and 4, and nothing else; the table is restored after | +| the resource preference | `KAL_RESOURCES` among the variables, which `kal_env_resources` reads | + +THE STARTED PROGRAM RECEIVES NO OTHER HANDLE (clause 7.13). DOS gives a started +program every handle of its starter that was opened to be inherited, which is +every handle DOS's 3Ch, 3Dh and 5Bh open: the stub's own file, the files a +program holds. Measured: a copy that probes DOS handles 5 to 19 finds only its +own program's file, which its stub opens, while its starter holds a file open; +with the caller's handle table left as it was, it finds the starter's too. + +THE BOUNDS ARE DOS'S (clause 7.6): the command tail holds 126 bytes before its +carriage return and an environment 32 KiB, and a start beyond either is +`kal_err_no_space`; nothing is shortened. A start that cannot happen is refused +by its reason before DOS is asked (a name that is not there, a directory, an +entry without `=`), and EXEC's own refusals are mapped: not found, access +denied, no memory, an environment DOS does not take (`kal_err_no_space`), a file +that is no program (`kal_err_not_program`). + +THE TAIL IS DIVIDED AS DOS'S C COMPILERS DIVIDE IT. Blanks separate; a double +quote begins or ends a part in which they do not; backslashes before a quote are +halved, and an odd one makes the quote a character; other backslashes are +themselves. 0.2.0 divided at blanks alone, so `"a b"` arrived as two arguments +with their quotes, and no starter could pass an argument holding a blank. + +`kal_interfaces()` names the nine interfaces the manifest states. Until 0.3.0 +it named five, leaving out `exec`, `fs` and `terminal`. + +`tests/starts`, C beneath openkal-musl on openkal-platform 0.31.2's row with this +repository's openkal-dos, run by dirun under DOSBox Staging 0.83.0-2 (where the +program is itself started by REDIR, a DJGPP program): `posix_spawn` starts the +program again with the first element `kid`, `a b`, an empty argument, `q"uote` +and `C:\A B\`, and a variable set by `setenv`, and `waitpid` reads its status 3; +a copy's standard output placed on a file writes the file, and on `/dev/null` +writes nothing; a copy finds no handle of its starter's; an absent name is +`ENOENT`; a tail of more than 126 bytes is `E2BIG`. The program ends with 42. + +The examples and tests name openkal-platform 0.31.2, whose group holds openkal +0.26 (under 0.28.0 the build refused the specification's version), and enable +its runner. `tests/fault` writes at offset 0x7ffffff0 of the block rather than +0xfffffff0: under the platform's runner the program is a DPMI client started by +REDIR, and the address 16 bytes below its block is REDIR's memory, where the +write did not fault (measured with openkal-dos 0.2.0, status 3 in place of 139). + ## The row's conventions The row compiles for `i386-unknown-none-elf` at `-march=i486`: DOSBox Staging @@ -172,7 +235,7 @@ Windows and refuses a file that is no ELF32 i386 executable; and that the examples and the tests, built for `i686-dos-musl` with this repository's openkal-dos and seal and run under DOSBox Staging, print what they state and end with their statuses: `examples/hello` 7 (unoptimised and optimised), -`examples/files` 9, `tests/fault` 139, `tests/stack` 0 (sixty-four frames of +`examples/files` 9, `tests/starts` 42 (0.3.0), `tests/fault` 139, `tests/stack` 0 (sixty-four frames of 8 KiB within the default stack) and `tests/stack-small` 139 (the same recursion with a stack of 64 KiB, stopped by the guard page). diff --git a/examples/files/mcpp.toml b/examples/files/mcpp.toml index 6857402..43197c8 100644 --- a/examples/files/mcpp.toml +++ b/examples/files/mcpp.toml @@ -10,4 +10,5 @@ kind = "bin" main = "src/main.cpp" [target.i686-dos-musl] -platform = "openkal-platform@0.28.0" +platform = "openkal-platform@0.31.2" +runner = { enabled = true } diff --git a/examples/hello/mcpp.toml b/examples/hello/mcpp.toml index 18b5c60..c5d96ae 100644 --- a/examples/hello/mcpp.toml +++ b/examples/hello/mcpp.toml @@ -10,4 +10,5 @@ kind = "bin" main = "src/main.cpp" [target.i686-dos-musl] -platform = "openkal-platform@0.28.0" +platform = "openkal-platform@0.31.2" +runner = { enabled = true } diff --git a/mcpp.toml b/mcpp.toml index 5917a85..3a0554f 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -8,19 +8,20 @@ [package] namespace = "mcpplibs" name = "openkal-dos" -version = "0.2.0" +version = "0.3.0" description = "An implementation of openkal on DOS through DPMI (technical experiment only)" license = "Apache-2.0" provides = ["mcpp:kernel-abi=openkal"] authors = ["mcpplibs"] repo = "https://github.com/mcpplibs/openkal-dos" -# The interfaces DOS has a counterpart for. Absent (openkal clause 6.2): contexts, processes as -# openkal states them, the network, and regions --- the DPMI host reserves no address apart from -# backing it (CWSDPMI is DPMI 0.90 and refuses 0504h, measured). +# The interfaces DOS has a counterpart for; `openkal.process' is EXEC, a started program run to its +# end before the start returns (0.3.0, openkal clause 7.19). Absent (openkal clause 6.2): contexts, +# the network, and regions --- the DPMI host reserves no address apart from backing it (CWSDPMI is +# DPMI 0.90 and refuses 0504h, measured). [kernel-abi] provides-interfaces = ["openkal.abort", "openkal.env", "openkal.exec", "openkal.fs", "openkal.memory", - "openkal.stream", "openkal.terminal", "openkal.time"] + "openkal.process", "openkal.stream", "openkal.terminal", "openkal.time"] [dependencies] openkal = "^0.26.0" diff --git a/src/dos.h b/src/dos.h index 39fb825..7d5e71c 100644 --- a/src/dos.h +++ b/src/dos.h @@ -8,6 +8,7 @@ // THE BLOCK is [loadable segments][the record's page][the guard page][the stack]; the stack's top // is the block's end. #pragma once +#include namespace okdos { @@ -78,6 +79,25 @@ void install_faults(); void guard_stack(); void check_stack(); +// openkal.process (process.cpp, 0.3.0) and the volume (fs.cpp): the whole name of a program beneath +// a directory, in `out' (kPathMax bytes), or the reason there is none; a directory's whole name. +constexpr u32 kPathMax = 128; +int program_path(kal_dir base, const char* name, kal_uintptr len, char* out); +const char* directory_path(kal_dir d); + +// THE NAME A STARTED PROGRAM OBSERVES AS ITS OWN (0.3.0, clause 7.6). DOS gives a program no first +// element: the name EXEC was given is written after its environment, and a program finds its file +// by it. A starter of this implementation writes `KAL_ARG0=|' among +// the variables; the program it starts reads the first element there where the name is its own, +// and a variable inherited through a program that does not read it names another program's file. +// The variable is the implementation's and is not among the variables a program enumerates. +inline constexpr char kArg0[] = "KAL_ARG0="; +inline constexpr u32 kArg0Len = sizeof kArg0 - 1; +inline bool names_arg0(const char* e) { + for (u32 i = 0; i < kArg0Len; ++i) if (e[i] != kArg0[i]) return false; + return true; +} + // Days from 1970-01-01 to a civil date (H. Hinnant's algorithm). inline long long days_from_civil(long long y, unsigned m, unsigned d) { y -= m <= 2; diff --git a/src/env.cpp b/src/env.cpp index 41aea21..b323293 100644 --- a/src/env.cpp +++ b/src/env.cpp @@ -1,6 +1,7 @@ // openkal.env on DOS: the arguments are the command tail of the program's segment prefix (PSP), -// split at blanks; position zero is the name DOS started the program by; the variables are the -// environment block's NAME=VALUE strings. +// divided as DOS's C compilers divide it (start.cpp); position zero is the starter's first element +// where it travelled (KAL_ARG0, dos.h), the name DOS started the program by otherwise; the variables +// are the environment block's NAME=VALUE strings, KAL_ARG0 not among them. #include #include "dos.h" @@ -21,12 +22,12 @@ kal_intptr give(const char* s, kal_uintptr n, char* out, kal_uintptr cap) { const char* environment() { return reinterpret_cast(low(static_cast(self().h->env_segment) * 16u)); } -// The I-th NAME=VALUE string, or null. +// The I-th NAME=VALUE string, or null; the implementation's KAL_ARG0 is passed over. const char* variable(kal_uintptr index) { const char* p = environment(); - for (kal_uintptr i = 0; *p; ++i) { - if (i == index) return p; - p += length(p) + 1; + for (kal_uintptr i = 0; *p; p += length(p) + 1) { + if (names_arg0(p)) continue; + if (i++ == index) return p; } return nullptr; } @@ -76,6 +77,20 @@ kal_intptr kal_env_loader(char*, kal_uintptr) { return -kal_err_not_found; } kal_intptr kal_env_system(char* out, kal_uintptr cap) { return give("dos", 3, out, cap); } -int kal_env_resources(void) { return KAL_RESOURCES_ECONOMY; } +// THE RESOURCE PREFERENCE (openkal 0.23): KAL_RESOURCES where a starter wrote one (0.3.0), as the +// other implementations read it; economy otherwise, this environment's memory being small. +int kal_env_resources(void) { + char v[16]; + const kal_intptr n = kal_env_var("KAL_RESOURCES", 13, v, sizeof v); + const auto is = [&](const char* w) { + const kal_uintptr k = length(w); + if (n != static_cast(k)) return false; + for (kal_uintptr i = 0; i < k; ++i) if (v[i] != w[i]) return false; + return true; + }; + return is("performance") ? KAL_RESOURCES_PERFORMANCE + : is("balanced") ? KAL_RESOURCES_BALANCED + : KAL_RESOURCES_ECONOMY; +} } // extern "C" diff --git a/src/fs.cpp b/src/fs.cpp index f1f5a13..26bfefb 100644 --- a/src/fs.cpp +++ b/src/fs.cpp @@ -226,6 +226,22 @@ void preopen_table() { namespace okdos { bool append_handle(u16 handle) { return handle < 256 && g_append[handle]; } + +// WHAT openkal.process NEEDS OF THE VOLUME (process.cpp, 0.3.0): the whole name of a program beneath +// a directory, with the reason there is none to start, and a directory's whole name. +int program_path(kal_dir base, const char* name, kal_uintptr len, char* out) { + if (int e = join(base, name, len, out)) return e; + if (len == 1 && name[0] == '.') return kal_err_is_directory; + const int a = attributes(out); + if (a < 0) return kal_err_not_found; + if (a & 0x10) return kal_err_is_directory; + return kal_ok; +} + +const char* directory_path(kal_dir d) { + const directory* x = dir_of(d); + return x ? x->path : nullptr; +} } extern "C" { diff --git a/src/kal.cpp b/src/kal.cpp index f59211a..282e53a 100644 --- a/src/kal.cpp +++ b/src/kal.cpp @@ -2,9 +2,9 @@ // // DOS divides its services as openkal does for three interfaces: handles 0 to 2 are the standard // streams (int 21h, 3Fh and 40h), the program ends with a status (4Ch), and memory beyond the -// first megabyte is the DPMI host's (int 31h, 0501h). The interfaces DOS has no counterpart for -// --- contexts, processes as openkal states them, the network --- are absent rather than present -// and failing (openkal clause 6.2). +// first megabyte is the DPMI host's (int 31h, 0501h). A program is started by EXEC and has ended +// when EXEC returns (process.cpp, 0.3.0). The interfaces DOS has no counterpart for --- contexts, +// the network --- are absent rather than present and failing (openkal clause 6.2). #include #include #include @@ -171,8 +171,11 @@ int kal_memory_info(kal_memory_status* out) { // ── version ───────────────────────────────────────────────────────────────── kal_u64 kal_version(void) { return KAL_VERSION; } +// The interfaces the manifest states (`[kernel-abi] provides-interfaces'). Until 0.3.0 the word +// named five of the eight, leaving out exec, fs and terminal, which the implementation provides. kal_u64 kal_interfaces(void) { - return KAL_IFACE_ABORT | KAL_IFACE_STREAM | KAL_IFACE_MEMORY | KAL_IFACE_ENV | KAL_IFACE_TIME; + return KAL_IFACE_ABORT | KAL_IFACE_STREAM | KAL_IFACE_MEMORY | KAL_IFACE_ENV | KAL_IFACE_TIME + | KAL_IFACE_EXEC | KAL_IFACE_FS | KAL_IFACE_TERMINAL | KAL_IFACE_PROCESS; } } // extern "C" diff --git a/src/process.cpp b/src/process.cpp new file mode 100644 index 0000000..401eb2e --- /dev/null +++ b/src/process.cpp @@ -0,0 +1,435 @@ +// openkal.process on DOS (0.3.0): a program started by EXEC (int 21h, 4B00h), which returns when the +// started program has ended; its status is then int 21h, 4Dh's. +// +// DOS RUNS ONE PROGRAM. EXEC suspends the caller until the program it started ends, so +// kal_process_spawn returns after the end and kal_process_wait answers at once: +// KAL_PROCESS_PROP_RUNS_TO_END (clause 7.19). No running program remains to end or to speak to, so +// TERMINATE and CHANNEL are not claimed; a started program cannot outlive its starter, so +// BOUND_LIFETIME holds of every start and is claimed. The started program is a DOS program: one of +// this implementation enters protected mode through the DPMI host already resident, as a client +// of its own. +// +// WHAT THE STARTED PROGRAM RECEIVES (clause 7.13). Its streams are DOS handles 0, 1 and 2, each the +// caller's own, a stream the caller placed, or the device NUL; the handles AUX and PRN (3 and 4) +// that DOS gives every program; and no other handle: for the call, the caller's handle table +// (PSP:34h) holds the three positions and DOS's two devices and nothing else, and it is restored +// after. Its variables are an environment block of their own, in conventional memory (DPMI 0100h). +// Its directory is the one it was given, made DOS's current directory for the call. Its vector is +// the command tail, each element quoted where it holds a blank or a quote, by the convention DOS's C +// compilers and start.cpp divide a tail by; the first element travels in KAL_ARG0 (dos.h). +// +// THE BOUNDS ARE DOS'S (clause 7.6): a command tail of 126 bytes and an environment of 32 KiB. A +// start beyond either is kal_err_no_space; nothing is shortened. +#include +#include +#include + +#include "dos.h" + +namespace { + +using namespace okdos; + +u32 length(const char* s) { u32 n = 0; while (s[n]) ++n; return n; } + +// A name in the transfer buffer at `at', for DS:DX. +void put_name(const char* name, u32 at) { copy(transfer() + at, name, length(name) + 1); } + +// ── the programs started ──────────────────────────────────────────────────── + +struct started { + bool used; + int status; + int terminated; + kal_u64 id; + kal_u64 started_ns; +}; + +started* g_started = nullptr; +kal_uintptr g_count = 0; +kal_uintptr g_cap = 0; +constexpr kal_uintptr kSelf = ~kal_uintptr{0}; +kal_u64 g_starts = 0; + +// A free row, the table doubled where there is none; zero where there is no memory. +kal_uintptr take_row() { + for (kal_uintptr i = 0; i < g_count; ++i) + if (!g_started[i].used) return i + 1; + if (g_count == g_cap) { + const kal_uintptr cap = g_cap ? 2 * g_cap : 16; + auto* grown = static_cast(kal_alloc(cap * sizeof(started), alignof(started))); + if (!grown) return 0; + for (kal_uintptr i = 0; i < g_count; ++i) grown[i] = g_started[i]; + if (g_started) kal_free(g_started, g_cap * sizeof(started), alignof(started)); + g_started = grown; + g_cap = cap; + } + g_started[g_count] = started{}; + return ++g_count; +} + +started* row(kal_process p) { + if (p.h == 0 || p.h > g_count) return nullptr; + started* s = &g_started[p.h - 1]; + return s->used ? s : nullptr; +} + +// ── the command tail ──────────────────────────────────────────────────────── + +constexpr u32 kTail = 126; // the bytes of a tail before its carriage return + +bool needs_quotes(const char* a, kal_uintptr n) { + if (n == 0) return true; + for (kal_uintptr i = 0; i < n; ++i) + if (a[i] == ' ' || a[i] == '\t' || a[i] == '"') return true; + return false; +} + +// The tail after the first element: a blank, then each element, quoted where it must be --- +// a quote preceded by a backslash, and the backslashes before a quote doubled (start.cpp's +// division). A byte DOS ends a tail at, a carriage return or a NUL, cannot be carried. +int command_tail(const char** argv, const kal_uintptr* lens, kal_uintptr argc, bool one_string, + char* out, u32& n) { + n = 0; + const auto put = [&](char c) { + if (n >= kTail) return false; + out[n++] = c; + return true; + }; + for (kal_uintptr i = 1; i < argc; ++i) { + const char* a = argv[i]; + const kal_uintptr len = lens[i]; + for (kal_uintptr k = 0; k < len; ++k) + if (a[k] == '\r' || a[k] == '\0') return kal_err_invalid; + if (!put(' ')) return kal_err_no_space; + const bool quote = !one_string && needs_quotes(a, len); + if (quote && !put('"')) return kal_err_no_space; + kal_uintptr slashes = 0; + for (kal_uintptr k = 0; k < len; ++k) { + if (a[k] == '\\') { ++slashes; if (!put('\\')) return kal_err_no_space; continue; } + if (quote && a[k] == '"') { + for (kal_uintptr s = 0; s <= slashes; ++s) if (!put('\\')) return kal_err_no_space; + } + slashes = 0; + if (!put(a[k])) return kal_err_no_space; + } + if (quote) { + for (kal_uintptr s = 0; s < slashes; ++s) if (!put('\\')) return kal_err_no_space; + if (!put('"')) return kal_err_no_space; + } + } + return kal_ok; +} + +// ── the environment block ─────────────────────────────────────────────────── + +constexpr u32 kEnvironment = 32768; // DOS's bound upon a program's environment + +bool well_formed(const char* e, kal_uintptr n) { + kal_uintptr k = 0; + while (k < n && e[k] != '=') ++k; + if (k == 0 || k == n) return false; + for (kal_uintptr i = 0; i < n; ++i) if (e[i] == '\0') return false; + return true; +} + +constexpr char kResources[] = "KAL_RESOURCES="; +bool names_resources(const char* e, kal_uintptr n) { + const u32 k = sizeof kResources - 1; + if (n < k) return false; + for (u32 i = 0; i < k; ++i) if (e[i] != kResources[i]) return false; + return true; +} + +// A block of conventional memory (DPMI 0100h): its segment and selector. +struct dos_block { + u16 segment = 0, selector = 0; + bool take(u32 bytes) { + u32 ax = 0x0100, bx = (bytes + 15) / 16, dx = 0; + int carry; + __asm__ volatile("int $0x31\n\tsbb %3, %3" : "+a"(ax), "+b"(bx), "=d"(dx), "=r"(carry) : : "memory", "cc"); + if (carry) return false; + segment = static_cast(ax); + selector = static_cast(dx); + return true; + } + ~dos_block() { + if (!selector) return; + u32 dx = selector; + __asm__ volatile("int $0x31" : "+d"(dx) : "a"(0x0101) : "memory", "cc"); + } +}; + +// ── what the call changes, and restores ───────────────────────────────────── + +// The caller's handle table: PSP:32h its size, PSP:34h its address. +u8* handle_table(u32& size) { + const u8* psp = low(static_cast(self().h->psp_segment) * 16u); + size = psp[0x32] | (psp[0x33] << 8); + const u32 off = psp[0x34] | (psp[0x35] << 8), seg = psp[0x36] | (psp[0x37] << 8); + return low(seg * 16u + off); +} + +void close_handle(u16 h) { + rm_regs r{}; + r.eax = 0x3e00; r.ebx = h; + dos(r); +} + +int exec_error(u32 code) { + switch (code) { + case 2: case 3: return kal_err_not_found; + case 5: return kal_err_permission; + case 4: case 8: return kal_err_no_memory; + case 0x0a: return kal_err_no_space; // an environment DOS does not take + case 0x0b: return kal_err_not_program; + default: return kal_err_io; + } +} + +constexpr kal_uintptr kKnownFlags = KAL_SPAWN_BOUND_LIFETIME | KAL_SPAWN_ONE_STRING | KAL_SPAWN_NULL_IN + | KAL_SPAWN_NULL_OUT | KAL_SPAWN_NULL_ERR | KAL_SPAWN_RESOURCES_BALANCED + | KAL_SPAWN_RESOURCES_PERFORMANCE | KAL_SPAWN_RESOURCES_ECONOMY; + +// Offsets in the transfer buffer: the program's name, the tail, the parameter block, two FCBs. +constexpr u32 kAtName = 0, kAtTail = 128, kAtBlock = 260, kAtFcb1 = 280, kAtFcb2 = 320, kAtEnd = 360; + +} // namespace + +extern "C" { + +kal_uintptr kal_process_props(void) { + return KAL_PROCESS_PROP_RUNS_TO_END | KAL_PROCESS_PROP_EXIT_STATUS | KAL_PROCESS_PROP_STREAM_PASSING + | KAL_PROCESS_PROP_NULL_STREAMS | KAL_PROCESS_PROP_ONE_STRING | KAL_PROCESS_PROP_BOUND_LIFETIME; +} + +int kal_process_spawn(const kal_spawn* how, const char* path, kal_uintptr path_len, + const char** argv, const kal_uintptr* argv_lens, kal_uintptr argc, + const char** envp, const kal_uintptr* envp_lens, kal_uintptr envc, + const kal_spawn_streams* streams, kal_process* out) { + if (!how || !path || path_len == 0 || !out || !self().h) return kal_err_invalid; + if ((argc && (!argv || !argv_lens)) || (envc && (!envp || !envp_lens))) return kal_err_invalid; + for (kal_uintptr i = 0; i < envc; ++i) + if (!envp[i] || !well_formed(envp[i], envp_lens[i])) return kal_err_invalid; + const kal_uintptr prefs = how->flags & (KAL_SPAWN_RESOURCES_BALANCED | KAL_SPAWN_RESOURCES_PERFORMANCE + | KAL_SPAWN_RESOURCES_ECONOMY); + if (prefs & (prefs - 1)) return kal_err_invalid; + if (how->flags & ~kKnownFlags) return kal_err_not_supported; + if (how->grants || how->job) return kal_err_not_supported; + const kal_uintptr nulls[3] = {KAL_SPAWN_NULL_IN, KAL_SPAWN_NULL_OUT, KAL_SPAWN_NULL_ERR}; + const kal_uintptr placed[3] = {streams ? streams->in.h : 0, streams ? streams->out.h : 0, + streams ? streams->err.h : 0}; + for (int i = 0; i < 3; ++i) + if (placed[i] && (how->flags & nulls[i])) return kal_err_invalid; + const char* work = directory_path(how->work); + if (!work) return kal_err_invalid; + + // The program, named beneath `base': a start that cannot happen is reported by its reason + // before DOS is asked. + char file[kPathMax]; + if (const int e = program_path(how->base, path, path_len, file); e != kal_ok) return e; + + char tail[kTail]; + u32 tail_len = 0; + if (const int e = command_tail(argv, argv_lens, argc, (how->flags & KAL_SPAWN_ONE_STRING) != 0, tail, tail_len); + e != kal_ok) + return e; + + // The variables: the caller's, with the preference in place of its KAL_RESOURCES where one is + // asked for and the first element in place of any KAL_ARG0; two terminators end the block. + const char* pref = prefs == KAL_SPAWN_RESOURCES_PERFORMANCE ? "KAL_RESOURCES=performance" + : prefs == KAL_SPAWN_RESOURCES_ECONOMY ? "KAL_RESOURCES=economy" + : prefs == KAL_SPAWN_RESOURCES_BALANCED ? "KAL_RESOURCES=balanced" : nullptr; + const u32 file_len = length(file); + const kal_uintptr arg0_len = argc ? argv_lens[0] : 0; + for (kal_uintptr k = 0; k < arg0_len; ++k) + if (argv[0][k] == '\0') return kal_err_invalid; + unsigned long bytes = 2 + kArg0Len + file_len + 1 + arg0_len + 1 + (pref ? length(pref) + 1 : 0); + for (kal_uintptr i = 0; i < envc; ++i) { + if ((pref && names_resources(envp[i], envp_lens[i])) || (envp_lens[i] >= kArg0Len && names_arg0(envp[i]))) + continue; + bytes += envp_lens[i] + 1; + } + if (bytes > kEnvironment) return kal_err_no_space; + dos_block env; + if (!env.take(static_cast(bytes))) return kal_err_no_memory; + char* o = reinterpret_cast(low(static_cast(env.segment) * 16u)); + for (kal_uintptr i = 0; i < envc; ++i) { + if ((pref && names_resources(envp[i], envp_lens[i])) || (envp_lens[i] >= kArg0Len && names_arg0(envp[i]))) + continue; + copy(o, envp[i], static_cast(envp_lens[i])); + o += envp_lens[i]; + *o++ = 0; + } + if (pref) { copy(o, pref, length(pref) + 1); o += length(pref) + 1; } + if (argc) { + copy(o, kArg0, kArg0Len); o += kArg0Len; + copy(o, file, file_len); o += file_len; + *o++ = '|'; + copy(o, argv[0], static_cast(arg0_len)); o += arg0_len; + *o++ = 0; + } + *o++ = 0; + *o = 0; + + const kal_uintptr index = take_row(); + if (!index) return kal_err_no_memory; + + // The streams: a handle of the caller's for each position, or NUL opened for it. + u32 table_size = 0; + u8* table = handle_table(table_size); + if (table_size > 255) table_size = 255; + u16 null_handle[3] = {0xffff, 0xffff, 0xffff}; + u8 entry[3]; + int failed = kal_ok; + for (int i = 0; i < 3 && failed == kal_ok; ++i) { + kal_uintptr h = placed[i]; + if (how->flags & nulls[i]) { + put_name("NUL", kAtEnd); + rm_regs r{}; + r.eax = i == 0 ? 0x3d00 : 0x3d01; r.edx = kAtEnd; + if (!dos(r)) { failed = kal_err_io; break; } + null_handle[i] = static_cast(r.eax & 0xffff); + h = null_handle[i]; + } + if (h == 0) h = static_cast(i); + if (h >= table_size || table[h] == 0xff) failed = kal_err_invalid; + else entry[i] = table[h]; + } + const auto close_nulls = [&] { + for (u16 h : null_handle) if (h != 0xffff) close_handle(h); + }; + if (failed != kal_ok) { close_nulls(); return failed; } + + // The directory it runs in: DOS's current drive and directory for the call. + rm_regs drive{}; + drive.eax = 0x1900; + dos(drive); + const u32 old_drive = drive.eax & 0xff; + char old_dir[68] = {static_cast('A' + old_drive), ':', '\\', 0}; + rm_regs cwd{}; + cwd.eax = 0x4700; cwd.edx = 0; cwd.esi = kAtEnd; + if (dos(cwd)) { + const char* rest = reinterpret_cast(transfer() + kAtEnd); + u32 n = 0; + while (rest[n] && n < 64) { old_dir[3 + n] = rest[n]; ++n; } + old_dir[3 + n] = 0; + } + const auto enter = [&](const char* dir) { + const char letter = dir[0] >= 'a' ? static_cast(dir[0] - 32) : dir[0]; + rm_regs d{}; + d.eax = 0x0e00; d.edx = static_cast(letter - 'A'); + dos(d); + char whole[kPathMax + 2]; + u32 n = length(dir); + copy(whole, dir, n + 1); + if (n == 2) { whole[2] = '\\'; whole[3] = 0; } + put_name(whole, kAtEnd); + rm_regs c{}; + c.eax = 0x3b00; c.edx = kAtEnd; + return dos(c); + }; + if (!enter(work)) { enter(old_dir); close_nulls(); return kal_err_not_found; } + + // The call: the name, the tail and the parameter block in the transfer buffer. + u8* tb = transfer(); + for (u32 i = 0; i < kAtEnd; ++i) tb[i] = 0; + put_name(file, kAtName); + tb[kAtTail] = static_cast(tail_len); + copy(tb + kAtTail + 1, tail, tail_len); + tb[kAtTail + 1 + tail_len] = '\r'; + const u16 tbs = self().h->tb_segment; + const auto word = [&](u32 at, u16 v) { tb[at] = static_cast(v); tb[at + 1] = static_cast(v >> 8); }; + word(kAtBlock, env.segment); + word(kAtBlock + 2, kAtTail); word(kAtBlock + 4, tbs); + word(kAtBlock + 6, kAtFcb1); word(kAtBlock + 8, tbs); + word(kAtBlock + 10, kAtFcb2); word(kAtBlock + 12, tbs); + + u8 saved[256]; + for (u32 i = 0; i < table_size; ++i) saved[i] = table[i]; + for (u32 i = 0; i < table_size; ++i) table[i] = i < 3 ? entry[i] : i < 5 ? saved[i] : 0xff; + const kal_u64 started_ns = kal_time_monotonic(); + rm_regs x{}; + x.eax = 0x4b00; x.edx = kAtName; x.ebx = kAtBlock; + const bool ran = dos(x); + for (u32 i = 0; i < table_size; ++i) table[i] = saved[i]; + enter(old_dir); + close_nulls(); + if (!ran) return exec_error(x.eax & 0xffff); + + rm_regs end{}; + end.eax = 0x4d00; + dos(end); + started& r = g_started[index - 1]; + r = started{true, static_cast(end.eax & 0xff), 0, ++g_starts, started_ns}; + // Ended by Ctrl-C (1) or by a critical error (2): an end the program did not choose. + const u32 type = (end.eax >> 8) & 0xff; + if (type == 1) { r.status = 130; r.terminated = 1; } + else if (type == 2) r.terminated = 1; + *out = kal_process{index}; + return kal_ok; +} + +int kal_process_wait(kal_process p, int* status, int* terminated) { + started* r = row(p); + if (!r) return kal_err_invalid; + if (status) *status = r->status; + if (terminated) *terminated = r->terminated; + return kal_ok; +} + +int kal_process_terminate(kal_process p) { return row(p) ? kal_err_not_supported : kal_err_invalid; } + +void kal_process_close(kal_process p) { if (started* r = row(p)) r->used = false; } + +int kal_process_channel(kal_stream*, kal_stream*) { return kal_err_not_supported; } +void kal_process_channel_close(kal_stream) {} + +const kal_u32* kal_process_stop_requested(void) { return nullptr; } +int kal_process_end_as_requested(void) { return kal_err_invalid; } + +int kal_process_self(kal_process* out) { + if (!out) return kal_err_invalid; + *out = kal_process{kSelf}; + return kal_ok; +} + +int kal_process_open_id(kal_u64, kal_process*) { return kal_err_not_supported; } + +// WHAT IS KNOWN OF A PROGRAM: this program's identifier is its segment prefix's segment; a started +// program's is the count of starts (DOS gives it a segment prefix the starter never sees), with when +// it started on the monotonic clock and that it has ended. +int kal_process_info(kal_process p, kal_u32 wanted, kal_program_info* out) { + if (!out || out->self_size < 2 * sizeof(kal_u32)) return kal_err_invalid; + kal_program_info info{}; + info.self_size = out->self_size; + if (p.h == kSelf) { + info.id = self().h->psp_segment; + info.present = KAL_PINFO_ID | KAL_PINFO_ENDED; + } else if (const started* r = row(p)) { + info.id = r->id; + info.started_ns = r->started_ns; + info.ended = 1; + info.present = KAL_PINFO_ID | KAL_PINFO_STARTED | KAL_PINFO_ENDED; + } else { + return kal_err_invalid; + } + info.present &= wanted; + const kal_uintptr n = out->self_size < sizeof info ? out->self_size : sizeof info; + copy(out, &info, static_cast(n)); + return kal_ok; +} + +int kal_process_job_enter(kal_job*) { return kal_err_not_supported; } +int kal_process_job_terminate(kal_job) { return kal_err_not_supported; } +void kal_process_job_close(kal_job) {} +int kal_process_job_create(kal_job*, char*, kal_uintptr, kal_uintptr*) { return kal_err_not_supported; } +int kal_process_job_open(const char*, kal_uintptr, kal_job*) { return kal_err_not_supported; } +int kal_process_job_observe(kal_job, const char*, kal_uintptr, kal_u32*) { return kal_err_not_supported; } +int kal_process_job_retire(kal_job, const char*, kal_uintptr, const kal_program_identity*, kal_u32*) { + return kal_err_not_supported; +} +int kal_process_job_usage(kal_job, kal_job_usage*) { return kal_err_not_supported; } +int kal_process_job_limit(kal_job, kal_uintptr, kal_u64) { return kal_err_not_supported; } + +} // extern "C" diff --git a/src/start.cpp b/src/start.cpp index 76713a9..7f898d7 100644 --- a/src/start.cpp +++ b/src/start.cpp @@ -32,6 +32,33 @@ using namespace okdos; char tail[128]; char* words[66]; +u32 length(const char* s) { u32 n = 0; while (s[n]) ++n; return n; } + +bool same_name(const char* a, const char* b, u32 n) { + const auto up = [](char c) { return c >= 'a' && c <= 'z' ? static_cast(c - 32) : c; }; + for (u32 i = 0; i < n; ++i) if (up(a[i]) != up(b[i])) return false; + return true; +} + +// THE FIRST ELEMENT (0.3.0): the starter's, from KAL_ARG0 where it names this program's file +// (dos.h); the name DOS started the program by otherwise. +const char* first_element(const handoff* h) { + const char* e = reinterpret_cast(low(static_cast(h->env_segment) * 16u)); + for (; *e; e += length(e) + 1) { + if (!names_arg0(e)) continue; + const char* v = e + kArg0Len; + u32 k = 0; + while (v[k] && v[k] != '|') ++k; + if (v[k] == '|' && k == length(h->name) && same_name(v, h->name, k)) return v + k + 1; + } + return h->name; +} + +// THE TAIL IS DIVIDED AS DOS'S C COMPILERS DIVIDE IT (0.3.0): blanks separate; a double quote +// begins or ends a part in which they do not; backslashes before a quote are halved, and an odd +// one makes the quote a character; other backslashes are themselves. 0.2.0 divided at blanks +// alone, so `"a b"' arrived as two arguments with their quotes, and no starter could pass an +// argument holding a blank. The words are written over the tail, which is never shorter. void record_arguments(const handoff* h) { state& s = self(); const u8* psp = low(static_cast(h->psp_segment) * 16u); @@ -39,13 +66,32 @@ void record_arguments(const handoff* h) { if (n > 127) n = 127; copy(tail, psp + 0x81, n); tail[n] = 0; + for (u32 i = 0; i < n; ++i) if (tail[i] == '\r') { n = i; break; } int argc = 0; - words[argc++] = const_cast(h->name); - for (u32 i = 0; i < n;) { - while (i < n && (tail[i] == ' ' || tail[i] == '\t' || tail[i] == '\r')) tail[i++] = 0; + words[argc++] = const_cast(first_element(h)); + const auto blank = [](char c) { return c == ' ' || c == '\t'; }; + u32 i = 0, o = 0; + while (i < n) { + while (i < n && blank(tail[i])) ++i; if (i >= n) break; - words[argc++] = &tail[i]; - while (i < n && tail[i] != ' ' && tail[i] != '\t' && tail[i] != '\r') ++i; + char* word = &tail[o]; + bool quoted = false; + while (i < n && (quoted || !blank(tail[i]))) { + if (tail[i] == '\\') { + u32 k = 0; + while (i < n && tail[i] == '\\') { ++k; ++i; } + const bool quote = i < n && tail[i] == '"'; + for (u32 b = 0; b < (quote ? k / 2 : k); ++b) tail[o++] = '\\'; + if (quote && (k & 1)) { tail[o++] = '"'; ++i; } + continue; + } + if (tail[i] == '"') { quoted = !quoted; ++i; continue; } + tail[o++] = tail[i++]; + } + // The terminator: over the separator just passed, or the byte after the tail. + tail[o++] = 0; + if (o > i) i = o; + words[argc++] = word; } words[argc] = nullptr; s.argc = argc; diff --git a/tests/fault/mcpp.toml b/tests/fault/mcpp.toml index b82f15b..ec39852 100644 --- a/tests/fault/mcpp.toml +++ b/tests/fault/mcpp.toml @@ -9,4 +9,5 @@ kind = "bin" main = "src/main.cpp" [target.i686-dos-musl] -platform = "openkal-platform@0.28.0" +platform = "openkal-platform@0.31.2" +runner = { enabled = true } diff --git a/tests/fault/src/main.cpp b/tests/fault/src/main.cpp index c9fd2a8..e1681d1 100644 --- a/tests/fault/src/main.cpp +++ b/tests/fault/src/main.cpp @@ -3,7 +3,7 @@ int main() { std::printf("before the fault\n"); std::fflush(stdout); - volatile int* nowhere = reinterpret_cast(0xfffffff0u); + volatile int* nowhere = reinterpret_cast(0x7ffffff0u); *nowhere = 1; std::printf("after the fault\n"); return 3; diff --git a/tests/stack-small/mcpp.toml b/tests/stack-small/mcpp.toml index 5c74d28..5c3d44f 100644 --- a/tests/stack-small/mcpp.toml +++ b/tests/stack-small/mcpp.toml @@ -13,4 +13,5 @@ main = "src/main.cpp" ldflags = ["-z stack-size=65536"] [target.i686-dos-musl] -platform = "openkal-platform@0.28.0" +platform = "openkal-platform@0.31.2" +runner = { enabled = true } diff --git a/tests/stack/mcpp.toml b/tests/stack/mcpp.toml index be5d42f..ca6208c 100644 --- a/tests/stack/mcpp.toml +++ b/tests/stack/mcpp.toml @@ -9,4 +9,5 @@ kind = "bin" main = "src/main.cpp" [target.i686-dos-musl] -platform = "openkal-platform@0.28.0" +platform = "openkal-platform@0.31.2" +runner = { enabled = true } diff --git a/tests/starts/mcpp.toml b/tests/starts/mcpp.toml new file mode 100644 index 0000000..31b56d2 --- /dev/null +++ b/tests/starts/mcpp.toml @@ -0,0 +1,14 @@ +# openkal.process on DOS (0.3.0), through the C library: posix_spawn starts this program again by +# EXEC with a vector, a variable and a stream placed on a file or on NUL, waitpid reads its status, +# and the starts DOS cannot make are refused by their reasons. The program ends with 42. +[package] +name = "starts" +version = "0.1.0" + +[targets.starts] +kind = "bin" +main = "src/main.c" + +[target.i686-dos-musl] +platform = "openkal-platform@0.31.2" +runner = { enabled = true } diff --git a/tests/starts/src/main.c b/tests/starts/src/main.c new file mode 100644 index 0000000..3a76cbc --- /dev/null +++ b/tests/starts/src/main.c @@ -0,0 +1,98 @@ +/* Started with no argument, the program starts copies of itself by posix_spawn; a copy's errand is + * its second argument. */ +#include +#include +#include +#include +#include +#include +#include + +#include + +extern char** environ; + +static int failures; +static void check(int ok, const char* what) { + printf(" %s %s\n", ok ? "ok " : "FAIL", what); + if (!ok) ++failures; +} + +static const char* self; + +static int start(char* const* argv, const posix_spawn_file_actions_t* fa, int* status) { + pid_t pid; + const int rc = posix_spawn(&pid, self, fa, NULL, argv, environ); + if (rc != 0) return rc; + if (waitpid(pid, status, 0) != pid) return errno; + return 0; +} + +int main(int argc, char** argv) { + if (argc >= 2 && strcmp(argv[1], "vector") == 0) { + const char* v = getenv("OKSTARTS"); + const int ok = argc == 6 && strcmp(argv[0], "kid") == 0 && strcmp(argv[2], "a b") == 0 + && strcmp(argv[3], "") == 0 && strcmp(argv[4], "q\"uote") == 0 + && strcmp(argv[5], "C:\\A B\\") == 0 && v && strcmp(v, "set") == 0; + return ok ? 3 : 1; + } + if (argc >= 2 && strcmp(argv[1], "handles") == 0) { + /* No handle of its starter's but the three streams and DOS's AUX and PRN: of the DOS + * handles from 5, one answers a seek, the program's own file, which its stub holds. */ + int open = 0; + for (unsigned long h = 5; h < 20; ++h) { + kal_u64 at; + if (kal_fs_seek((struct kal_file){ h }, 0, KAL_SEEK_CURRENT, &at) == kal_ok) ++open; + } + return open == 1 ? 5 : 10 + open; + } + if (argc >= 2 && strcmp(argv[1], "write") == 0) { + printf("written by the copy\n"); + return 4; + } + self = argv[0]; + printf("starts, as %s\n", self); + int status = -1; + + setenv("OKSTARTS", "set", 1); + char* vector[] = { "kid", "vector", "a b", "", "q\"uote", "C:\\A B\\", NULL }; + check(start(vector, NULL, &status) == 0 && WIFEXITED(status) && WEXITSTATUS(status) == 3, + "a copy receives its first element, an argument with a blank, an empty one, one with a quote " + "and one ending in a backslash, and the variable set; its status comes back"); + + posix_spawn_file_actions_t fa; + posix_spawn_file_actions_init(&fa); + posix_spawn_file_actions_addopen(&fa, 1, "SPAWNED.TXT", O_WRONLY | O_CREAT | O_TRUNC, 0644); + char* write[] = { "kid", "write", NULL }; + const int placed = start(write, &fa, &status); + posix_spawn_file_actions_destroy(&fa); + char text[64] = {0}; + FILE* f = fopen("SPAWNED.TXT", "r"); + if (f) { fgets(text, sizeof text, f); fclose(f); } + check(placed == 0 && WEXITSTATUS(status) == 4 && strncmp(text, "written by the copy", 19) == 0, + "a copy's standard output placed on a file is written there"); + + posix_spawn_file_actions_init(&fa); + posix_spawn_file_actions_addopen(&fa, 1, "/dev/null", O_WRONLY, 0); + const int nulled = start(write, &fa, &status); + posix_spawn_file_actions_destroy(&fa); + check(nulled == 0 && WEXITSTATUS(status) == 4, "a copy's standard output on the null device"); + + FILE* held = fopen("HELD.TXT", "w"); + char* handles[] = { "kid", "handles", NULL }; + check(held && start(handles, NULL, &status) == 0 && WEXITSTATUS(status) == 5, + "a copy receives no handle of its starter's beyond its streams, a file held open included"); + if (held) fclose(held); + + pid_t pid; + char* absent[] = { "absent", NULL }; + check(posix_spawn(&pid, "C:\\ABSENT.EXE", NULL, NULL, absent, environ) == ENOENT, + "a name that is not there is ENOENT"); + static char longer[200]; + memset(longer, 'x', sizeof longer - 1); + char* toolong[] = { "kid", "write", longer, NULL }; + check(posix_spawn(&pid, self, NULL, NULL, toolong, environ) == E2BIG, + "a command tail beyond DOS's 126 bytes is E2BIG, not shortened"); + puts(failures ? "FAILED" : "all held"); + return failures ? 1 : 42; +} diff --git a/tools/mcpp.toml b/tools/mcpp.toml index d8468a3..31df851 100644 --- a/tools/mcpp.toml +++ b/tools/mcpp.toml @@ -4,7 +4,7 @@ [package] namespace = "mcpplibs" name = "openkal-dos-tools" -version = "0.2.0" +version = "0.3.0" description = "okdos: seals an ELF32 i386 executable as a DOS program behind openkal-dos's DPMI stub (technical experiment only)" license = "Apache-2.0" authors = ["mcpplibs"] From 29e6e4506a713341708717d2a2ca87072e9ed7ca Mon Sep 17 00:00:00 2001 From: Sunrisepeak Date: Mon, 23 Nov 2026 07:12:17 +0900 Subject: [PATCH 3/3] The tail's quoting and division as functions of their own, each loop within two levels --- src/process.cpp | 42 ++++++++++++++++++++++++++++-------------- src/start.cpp | 19 +++++++++++-------- 2 files changed, 39 insertions(+), 22 deletions(-) diff --git a/src/process.cpp b/src/process.cpp index 401eb2e..f0da803 100644 --- a/src/process.cpp +++ b/src/process.cpp @@ -85,6 +85,33 @@ bool needs_quotes(const char* a, kal_uintptr n) { return false; } +template +bool put_plain(const char* a, kal_uintptr len, Put& put) { + for (kal_uintptr k = 0; k < len; ++k) if (!put(a[k])) return false; + return true; +} + +template +bool put_backslashes(kal_uintptr count, Put& put) { + for (kal_uintptr s = 0; s < count; ++s) if (!put('\\')) return false; + return true; +} + +// An element in quotes: a quote preceded by a backslash, and the backslashes before a quote, or +// before the closing one, doubled. +template +bool put_quoted(const char* a, kal_uintptr len, Put& put) { + if (!put('"')) return false; + kal_uintptr slashes = 0; + for (kal_uintptr k = 0; k < len; ++k) { + if (a[k] == '\\') { ++slashes; if (!put('\\')) return false; continue; } + if (a[k] == '"' && !put_backslashes(slashes + 1, put)) return false; + slashes = 0; + if (!put(a[k])) return false; + } + return put_backslashes(slashes, put) && put('"'); +} + // The tail after the first element: a blank, then each element, quoted where it must be --- // a quote preceded by a backslash, and the backslashes before a quote doubled (start.cpp's // division). A byte DOS ends a tail at, a carriage return or a NUL, cannot be carried. @@ -103,20 +130,7 @@ int command_tail(const char** argv, const kal_uintptr* lens, kal_uintptr argc, b if (a[k] == '\r' || a[k] == '\0') return kal_err_invalid; if (!put(' ')) return kal_err_no_space; const bool quote = !one_string && needs_quotes(a, len); - if (quote && !put('"')) return kal_err_no_space; - kal_uintptr slashes = 0; - for (kal_uintptr k = 0; k < len; ++k) { - if (a[k] == '\\') { ++slashes; if (!put('\\')) return kal_err_no_space; continue; } - if (quote && a[k] == '"') { - for (kal_uintptr s = 0; s <= slashes; ++s) if (!put('\\')) return kal_err_no_space; - } - slashes = 0; - if (!put(a[k])) return kal_err_no_space; - } - if (quote) { - for (kal_uintptr s = 0; s < slashes; ++s) if (!put('\\')) return kal_err_no_space; - if (!put('"')) return kal_err_no_space; - } + if (!(quote ? put_quoted(a, len, put) : put_plain(a, len, put))) return kal_err_no_space; } return kal_ok; } diff --git a/src/start.cpp b/src/start.cpp index 7f898d7..2739cb5 100644 --- a/src/start.cpp +++ b/src/start.cpp @@ -54,6 +54,16 @@ const char* first_element(const handoff* h) { return h->name; } +// A run of backslashes at `i', written at `o': halved before a quote, with the quote written as a +// character after an odd run; itself otherwise. +void backslashes(u32 n, u32& i, u32& o) { + u32 k = 0; + while (i < n && tail[i] == '\\') { ++k; ++i; } + const bool quote = i < n && tail[i] == '"'; + for (u32 b = 0; b < (quote ? k / 2 : k); ++b) tail[o++] = '\\'; + if (quote && (k & 1)) { tail[o++] = '"'; ++i; } +} + // THE TAIL IS DIVIDED AS DOS'S C COMPILERS DIVIDE IT (0.3.0): blanks separate; a double quote // begins or ends a part in which they do not; backslashes before a quote are halved, and an odd // one makes the quote a character; other backslashes are themselves. 0.2.0 divided at blanks @@ -77,14 +87,7 @@ void record_arguments(const handoff* h) { char* word = &tail[o]; bool quoted = false; while (i < n && (quoted || !blank(tail[i]))) { - if (tail[i] == '\\') { - u32 k = 0; - while (i < n && tail[i] == '\\') { ++k; ++i; } - const bool quote = i < n && tail[i] == '"'; - for (u32 b = 0; b < (quote ? k / 2 : k); ++b) tail[o++] = '\\'; - if (quote && (k & 1)) { tail[o++] = '"'; ++i; } - continue; - } + if (tail[i] == '\\') { backslashes(n, i, o); continue; } if (tail[i] == '"') { quoted = !quoted; ++i; continue; } tail[o++] = tail[i++]; }