diff --git a/CMakeLists.txt b/CMakeLists.txt index 84968999..e69001db 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -44,16 +44,39 @@ endif() add_library(nilruntime_freestanding STATIC nilruntime-freestanding/freestanding_runtime.cpp) target_compile_features(nilruntime_freestanding PRIVATE cxx_std_17) +# Deliberately not position-independent. Every consumer of this archive links +# at a fixed address with no dynamic linker, and under PIC the weak host +# failure hook has to be reached through a GOT -- which is a section a kernel +# or vessel profile rejects outright. The link test pins that the resulting +# program has no GOT at all. set_target_properties(nilruntime_freestanding PROPERTIES CXX_EXTENSIONS OFF - POSITION_INDEPENDENT_CODE ON) + POSITION_INDEPENDENT_CODE OFF) if(NOT MSVC) # No hosted assumptions, no unwinder, no type information: a kernel or # loader links this archive without providing any of them. + # -fno-pic is explicit because POSITION_INDEPENDENT_CODE OFF only stops + # CMake adding -fPIC; a host whose compiler defaults to PIE (Ubuntu's does) + # would still emit GOT-indirect code without it. target_compile_options(nilruntime_freestanding PRIVATE - -ffreestanding -fno-exceptions -fno-rtti) + -ffreestanding -fno-exceptions -fno-rtti -fno-pic -fno-pie) + # General registers only. The runtime has no floating point of its own, but + # at -O2 the compiler vectorizes its zero and copy loops into SSE, and a + # kernel profile that denies inherited x87/SIMD state -- by leaving CR0.TS + # set, which is the ordinary way to do it -- faults on the first such + # instruction. A consumer cannot opt out of what is already in the archive, + # so the archive gives up the registers it does not need. + include(CheckCXXCompilerFlag) + check_cxx_compiler_flag(-mgeneral-regs-only NIL_GENERAL_REGS_ONLY) + if(NIL_GENERAL_REGS_ONLY) + target_compile_options(nilruntime_freestanding PRIVATE -mgeneral-regs-only) + endif() endif() +# Shipped in the SDK beside the hosted runtime. A freestanding consumer has no +# other way to resolve the hooks an emitted object imports. +install(TARGETS nilruntime_freestanding ARCHIVE DESTINATION ".") + add_subdirectory(nilcompiler) add_subdirectory(nilinterpreter) add_subdirectory(nillsp) diff --git a/docs/README.md b/docs/README.md index 1fc65ce4..4d40a5ea 100644 --- a/docs/README.md +++ b/docs/README.md @@ -55,6 +55,9 @@ do not assume every documented combination is accepted by every backend yet. ## Architecture and design - [Advanced implementation topics](advanced/index.md) +- [Freestanding native targets](advanced/freestanding-targets.md) — the contract + a target with no C library links against: the entry, the runtime hooks, who + owns memory, and what is not qualified. - [Design documents](design/README.md) - [NIL-0006: AI control module](design/NIL-0006-ai-module.md) - [nypm package-manager proposal](design/nypm.md) diff --git a/docs/advanced/freestanding-targets.md b/docs/advanced/freestanding-targets.md new file mode 100644 index 00000000..187891f8 --- /dev/null +++ b/docs/advanced/freestanding-targets.md @@ -0,0 +1,279 @@ +# Freestanding native targets + +A **freestanding** Ny object is one emitted for a target with no C library, +no operating-system services and no host allocator: a kernel, a bootloader, or +a userspace process on a system that supplies its own entry and memory. This +page is the contract such a consumer links against. It exists so that +consuming a Ny object is a matter of reading a document rather than inspecting +the emitted code and implementing what it appears to need. + +Freestanding targets are a **capability, not a qualified release target**. The +[v1 release profile](../release/v1-profile.md) excludes them deliberately, and +that exclusion is unchanged by this page. The hook names and signatures below +are version 1 of this boundary, reported by `nyrt_abi_version`; they may change +while the release candidate is open. + +## Emitting + +```sh +nilcompiler --no-stdlib --no-bundle --unmanaged -o program.nil program.ny +nilassembler --unmanaged --freestanding --no-red-zone -o program.o program.nil +``` + +| Option | Effect | +| --- | --- | +| `--freestanding` | Emits the entry as `__ny_entry()` and defines no C `main`. | +| `--no-red-zone` | Marks every generated definition `noredzone`. | +| `--code-model ` | The code model generated code assumes. The default keeps the target's own, which on x86-64 is `small`. | +| `--emit-llvm ` | Writes the generated LLVM IR, so an attribute that does not survive into an object can still be inspected. | + +**Where the object may be linked.** The small model materializes every address +as a 32-bit absolute, so an object linked above 4 GiB fails with truncated +relocations rather than misbehaving at run time. A consumer whose kernel places +user code high — above the 512 GiB boundary, for instance, because its own +branch of the page tables occupies the first entry — passes +`--code-model large`. Code and read-only data then arrive in `.ltext` and +`.lrodata`, which a linker script must name, and the object links at any +address. The shipped runtime archive needs no such option: it reaches its own +statics relative to the instruction pointer and imports nothing. + +The options are independent. `--no-red-zone` is separate from `--freestanding` +because they answer different questions: a target whose interrupt entry +switches stacks can keep the red zone in its userspace code, while a +kernel-reentrant one cannot, and that is the consumer's call rather than a +consequence of having no libc. + +## Entry + +A freestanding object exports `__ny_entry` and no `main`: + +```c +long __ny_entry(void); // returns what Ny's main returned +``` + +It takes no arguments. The host supplies the process or task entry — there is +no C runtime to call `__ny_entry` for it — and interprets the return value. +Argument-vector derivation is not emitted at all for this target, rather than +emitted and fed zeroes, so nothing in the object reaches for an environment +that does not exist. + +`__ny_entry` performs, in order: + +1. `nyrt_abi_version()`, and `nyrt_fail` if it is not the expected version. + This happens before any user code runs. +2. `nyrt_context_begin(0, NULL)`. +3. Global initialisation. +4. The program's `main`. +5. `nyrt_context_end()`. +6. Return. + +## The hooks a host must satisfy + +Five, always: + +```c +uint32_t nyrt_abi_version(void); +void nyrt_context_begin(int argc, const char *const *argv); +void nyrt_context_end(void); +void nyrt_profile_site(const char *file, const char *function, uint64_t line); +void nyrt_fail(const char *message); // must not return +``` + +`nyrt_fail` receives a message describing what went wrong and must not return +into the program: its invariants are already broken. `nyrt_profile_site` is an +attribution point for a hosted capture facility; accepting and ignoring the +call is correct on a target that has none, and keeps generated code identical +across hosted and freestanding builds. + +Three more, **only if the program allocates** — today, only if it +concatenates a string: + +```c +void *nyrt_alloc(uint64_t size); // zeroed, NULL on failure +void *nyrt_mem_copy(void *destination, const void *source, uint64_t size); +uint64_t nyrt_str_length(const char *text); +``` + +These replace `calloc`, `memcpy` and `strlen`. A freestanding object imports no +libc symbol under any configuration; an object for a program that never +allocates imports only the first five names. The helper that needs them is +built on first use, so the import surface reflects what the program does. + +`nyrt_alloc` returns zeroed memory and `NULL` when it cannot satisfy the +request. Generated code checks for `NULL` and reports it through `nyrt_fail`, +so an allocator with nothing to give fails the program rather than being +allowed to lie. + +## Reaching a symbol the host supplies + +A freestanding consumer's own call boundary — its system calls, its trap or +interrupt gate, its rights model — belongs to that consumer, and is usually +unstable while it is being designed. It must not enter the standard library. +What NIL supplies is the ability to reach it: + +```ny +@interop("host") +fn anomalous_rite_console_write(message: text) -> i64 +end fn +``` + +`host` is the one library name that names no library. It means the declared Ny +function **is** an external symbol of exactly that name, called with the +platform's ordinary C convention, and whoever links the object defines it. The +object imports that name and nothing else; a declaration nobody calls imports +nothing at all. + +The symbol name is the declared name, so it is visible in the source and in +the object's import surface, where a reader and the symbol-surface test can +both see it. Names beginning `nyrt_` or `__ny_` are refused, because the +native runtime ABI is NIL's. + +**Nothing checks the host's signature.** No part of the toolchain can see the +definition, so the type profile is deliberately narrow and anything outside it +is refused rather than guessed: + +| Ny type | Passed as | +| --- | --- | +| `i64` | a 64-bit integer | +| `f64` | a double | +| `text` | a pointer to NUL-terminated bytes | + +A function may return one of those or no value. Aggregates, arrays and +anything else are rejected with a diagnostic naming the profile. The `text` +representation is the one a Ny string already has natively; a host receives the +bytes in place and must not assume it may write to them or that they outlive +the call. + +This is native-only. The interpreter refuses a `host` call by name rather than +searching for a library, because a machine that happened to have one would bind +an unrelated symbol. + +## The runtime NIL ships + +`nilruntime_freestanding` (`libnilruntime_freestanding.a`) implements all +eight hooks with no libc, no kernel and no heap of its own. A consumer may +link it instead of writing the boundary. It does not allocate on its own +behalf, format, read a clock or touch a device. + +Memory is the one place where generated code needs something the runtime +cannot invent, and the division is **the host owns the memory, the runtime +owns the mechanism**: + +```c +void nyrt_heap_init(void *base, uint64_t size); // install a region +uint64_t nyrt_heap_used(void); // how much is handed out +uint64_t nyrt_heap_size(void); // the installed size +``` + +The host calls `nyrt_heap_init` with storage it owns; `nyrt_alloc` bumps a +16-byte-aligned pointer through that region and zeroes what it hands out. +There is deliberately no static heap in the runtime, because the size of a +vessel's memory is the vessel's decision and a fixed array would charge every +consumer for it. + +Consequences worth knowing before depending on it: + +- **There is no free.** A bump region is released as a whole. `nyrt_context_end` + returns it to empty, which is sound because everything allocated inside it + came from generated code whose lifetime ended with the context. +- **Ending the context resets the pointer; it does not scrub the bytes.** The + region belongs to the host, so what is written in it stays the host's to + read after `__ny_entry` returns. A host that wants the bytes a program + produced reads them then; a host that wants them gone clears the region + itself, because only the host knows whether they were sensitive. +- **With no region installed, allocation fails.** `nyrt_alloc` returns `NULL` + and the program stops through `nyrt_fail`. A program that never allocates + never needs a region; one that does cannot silently proceed without it. +- **Exhaustion is a failure, not a wait.** A request that does not fit returns + `NULL`, with the same consequence. +- Calling `nyrt_heap_init` again replaces the region and discards what was + handed out of the old one. +- **There is no locking.** A region is a single bump pointer, so two + concurrent allocations race. Nothing freestanding is emitted with threads, + so this is a limit of the shipped runtime rather than of the contract: a + host that needs concurrent allocation implements `nyrt_alloc` itself. + +Failures are reported through a hook the host may replace: + +```c +void __ny_host_fail(const char *message); +``` + +The archive carries a weak definition that does nothing, so linking it alone +produces a complete program, and a host's own strong definition replaces it. A +host that wants to print, log or panic defines this symbol. Either way +`nyrt_fail` stops the caller afterwards, because the default does nothing and a +host's reporter may return anyway. + +It is a weak definition rather than a weak declaration on purpose. A weak +declaration leaves an undefined symbol that generated code calls through a +32-bit PC-relative relocation to an address the linker resolves to zero, which +cannot be represented once the consumer links above 4 GiB — so the link fails +over a symbol nobody intended to use. With a definition the archive imports +nothing at all. + +## A minimal host + +```c +#include + +extern long __ny_entry(void); +extern void nyrt_heap_init(void *base, uint64_t size); + +static unsigned char arena[64 * 1024]; // the vessel's memory, the host's choice + +__attribute__((noreturn)) void _start(void) { + nyrt_heap_init(arena, sizeof arena); + const long code = __ny_entry(); + my_exit(code); +} +``` + +Link with no C library at all: + +```sh +cc -nostdlib -static -o vessel host.c program.o libnilruntime_freestanding.a +``` + +If either side still needed libc, this link fails rather than quietly +succeeding against the build host's C library. + +## What is checked, and where + +Two registered tests pin this contract; they are the authority if this page +and the toolchain disagree. + +- `nil.native-symbol-surface` (`tests/tools/native_symbol_surface.py`) reads + the ELF symbol table directly and pins the import surface: that a + non-allocating object imports only the five hooks, that an allocating + freestanding one adds exactly the three allocation hooks and no libc name, + that a hosted object is entered through `main` and a freestanding one + through `__ny_entry` with no `main`, and that `noredzone` reaches every + generated definition when it is requested. +- `nil.freestanding-runtime` + (`tests/tools/freestanding_runtime_contract.py`) links object and archive + with `-nostdlib` and its own `_start` and runs the result, requiring the + exit status to be what Ny returned. For allocation it installs a region, + then reads the concatenated bytes back out of that region afterwards, and + separately requires that the same program with no region installed stops + through `nyrt_fail` with a message instead of continuing. + +## What this does not provide + +- **No qualification.** See the [v1 release profile](../release/v1-profile.md). + Capability and release qualification are separate decisions. +- **No evidence that any particular kernel boots a Ny vessel.** Everything + above is checked on a hosted Linux build host by inspecting and running what + the toolchain produces. Whether a vessel runs under a given operating system + is testable only in that system's own repository. +- **No system-call bindings.** A consuming operating system's own ABI — + its call structures, its trap or interrupt gate, its rights model — belongs + to that system and stays in its repository, particularly while it is + unstable. What NIL supplies is the capability to express it: freestanding + objects, exact record layout through + [owned scalar buffers](owned-buffers.md), the + [native register assembly](inline-assembly.md) profile, `@interop("host")` + for reaching a symbol the consumer defines, and no imports a consumer did not + ask for. +- **No threads, TLS, unwinding or hosted I/O.** None of these are emitted for + a freestanding target, and none are supplied by the shipped runtime. diff --git a/docs/advanced/index.md b/docs/advanced/index.md index 122baf9e..8f162dc3 100644 --- a/docs/advanced/index.md +++ b/docs/advanced/index.md @@ -48,6 +48,14 @@ function annotations in v3, with class ancestry and method metadata added in class-bearing v4 artifacts. Legacy v1 inputs still fail explicitly when their omitted metadata is required. +[Freestanding native targets](freestanding-targets.md) records the boundary a +consumer with no C library links against: `nilassembler --freestanding` emits +`__ny_entry()` and no C `main`, `--no-red-zone` and `--emit-llvm` are separate +options answering separate questions, and `nilruntime_freestanding` supplies +the runtime hooks without libc, a kernel or a heap of its own. Memory is the +host's: it installs a region and the runtime bumps through it. Freestanding +targets are a capability and not a qualified release target. + The first [native register assembly](inline-assembly.md) profile has explicit x86_64 targeting, checked `i64` operands, preserved NIL instructions, and a bounded straight-line instruction set. It is native-only; interpreter routes diff --git a/nilassembler/main.cpp b/nilassembler/main.cpp index 6995f0a4..efb7b0fd 100644 --- a/nilassembler/main.cpp +++ b/nilassembler/main.cpp @@ -43,6 +43,7 @@ struct command_line { bool unmanaged = false; bool freestanding = false; bool no_red_zone = false; + std::string code_model; std::string emit_llvm; bool embed_context = false; }; @@ -50,13 +51,17 @@ struct command_line { void print_usage(std::ostream &stream) { stream << "Usage: nilassembler [-o ] [--unmanaged] [--freestanding]" - " [--no-red-zone] [--emit-llvm ] [--embed-context] \n" + " [--no-red-zone] [--code-model ] [--emit-llvm ]" + " [--embed-context] \n" << "\n" << "Options:\n" << " -o, --output Write the host relocatable object to \n" << " --unmanaged Use manual native memory management\n" << " --freestanding Emit the entry as __ny_entry() with no C main wrapper\n" << " --no-red-zone Mark generated definitions noredzone\n" + << " --code-model Code model to generate for: small or large.\n" + << " The default keeps the target's own. A target\n" + << " placing this object above 4 GiB needs large.\n" << " --emit-llvm Also write the generated LLVM IR\n" << " --embed-context Retain AI annotations in x86_64 ELF/COFF or x86_64/arm64 Mach-O objects\n" << " --version Show the nilassembler version\n" @@ -70,6 +75,7 @@ bool parse_command_line(int argc, char **argv, command_line &result, bool unmanaged_seen = false; bool freestanding_seen = false; bool no_red_zone_seen = false; + bool code_model_seen = false; bool emit_llvm_seen = false; bool embed_context_seen = false; for (int index = 1; index < argc; ++index) { @@ -121,6 +127,23 @@ bool parse_command_line(int argc, char **argv, command_line &result, result.no_red_zone = true; continue; } + if (options && argument == "--code-model") { + if (code_model_seen) { + error = "the code-model option was provided more than once"; + return false; + } + if (++index >= argc) { + error = "missing model after " + argument; + return false; + } + result.code_model = argv[index]; + if (result.code_model != "small" && result.code_model != "large") { + error = "the code model must be small or large"; + return false; + } + code_model_seen = true; + continue; + } if (options && argument == "--emit-llvm") { if (emit_llvm_seen) { error = "the emit-llvm option was provided more than once"; @@ -177,8 +200,8 @@ bool parse_command_line(int argc, char **argv, command_line &result, if (result.help || result.version) { if (!result.input.empty() || output_seen || unmanaged_seen || - freestanding_seen || no_red_zone_seen || emit_llvm_seen || - embed_context_seen || + freestanding_seen || no_red_zone_seen || code_model_seen || + emit_llvm_seen || embed_context_seen || (result.help && result.version)) { error = "--help and --version must be used without input or output paths"; return false; @@ -449,6 +472,11 @@ int run_assembler(const command_line &arguments) { : ny::MemoryMode::SAFE_GC); native.setFreestandingEntry(arguments.freestanding); native.setDisableRedZone(arguments.no_red_zone); + if (arguments.code_model == "small") { + native.setCodeModel(ny::NativeCodegen::CodeModel::small); + } else if (arguments.code_model == "large") { + native.setCodeModel(ny::NativeCodegen::CodeModel::large); + } native.setEmbedContext(arguments.embed_context); if (!native.initialize()) { std::cerr << "nilassembler: failed to initialize the LLVM target\n"; diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index 02fd19c2..49ffdec1 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -1197,6 +1197,7 @@ struct NativeCodegen::Impl { bool embed_context = false; bool freestanding_entry = false; bool disable_red_zone = false; + NativeCodegen::CodeModel code_model = NativeCodegen::CodeModel::host; llvm::Function *current_function = nullptr; // State matching generateModule usage @@ -1378,6 +1379,8 @@ void NativeCodegen::setDisableRedZone(bool enabled) { impl_->disable_red_zone = enabled; } +void NativeCodegen::setCodeModel(CodeModel model) { impl_->code_model = model; } + bool NativeCodegen::emitLlvmIr(const std::string &path) { if (!impl_->module) { std::cerr << "[NativeCodegen] no module to write\n"; @@ -1420,9 +1423,25 @@ bool NativeCodegen::initialize() { #else const auto &target_spec = target_triple; #endif + // An absent code model leaves the target's own default, which on x86-64 is + // the small model: every address is materialized as a 32-bit absolute, so an + // object linked above 4 GiB fails with truncated relocations. A consumer + // whose kernel places user code high asks for `large` instead. + std::optional code_model; + switch (impl_->code_model) { + case CodeModel::small: + code_model = llvm::CodeModel::Small; + break; + case CodeModel::large: + code_model = llvm::CodeModel::Large; + break; + case CodeModel::host: + break; + } auto target_machine = std::unique_ptr( target->createTargetMachine(target_spec, "generic", "", target_options, - std::optional())); + std::optional(), + code_model)); if (!target_machine) { std::cerr << "[NativeCodegen] Failed to create target machine for '" << target_triple << "'" << std::endl; @@ -1576,11 +1595,19 @@ bool NativeCodegen::generateModule(const nil_module &mod) { // Generate __ny_string_concat(i8* s1, i8* s2) -> i8* // (Helper for string concatenation) // - // Built on first use, not on every module. The helper calls strlen, memcpy - // and calloc, so emitting it unconditionally left those three undefined in - // the object of a program that never concatenates a string -- which a - // freestanding or kernel target then has to satisfy with stubs it should - // never need. + // Built on first use, not on every module. The helper needs a length, a + // copy and an allocation, so emitting it unconditionally left those three + // undefined in the object of a program that never concatenates a string -- + // which a freestanding or kernel target then has to satisfy with stubs it + // should never need. + // + // Which three it calls depends on the target. A hosted object calls strlen, + // memcpy and calloc. A freestanding one has no libc to call, so it goes + // through nyrt_str_length, nyrt_mem_copy and nyrt_alloc, which the + // freestanding runtime implements over a region its host installs. The + // shape of the emitted helper is otherwise identical, including the null + // check: an allocator with no region returns null exactly as a hosted one + // does under pressure, and the same failure path reports it. auto get_string_concat_function = [&]() -> llvm::Function * { if (auto *existing = impl_->module->getFunction("__ny_string_concat")) return existing; @@ -1599,16 +1626,21 @@ bool NativeCodegen::generateModule(const nil_module &mod) { auto *s1 = concat_fn->getArg(0); auto *s2 = concat_fn->getArg(1); - // Declare dependencies - auto *strlen_fn = impl_->module->getFunction("strlen"); + // Declare dependencies, under the names this target can resolve. + const bool freestanding = impl_->freestanding_entry; + const char *const length_name = + freestanding ? "nyrt_str_length" : "strlen"; + const char *const copy_name = freestanding ? "nyrt_mem_copy" : "memcpy"; + + auto *strlen_fn = impl_->module->getFunction(length_name); if (!strlen_fn) { auto *ft = llvm::FunctionType::get( native_size_type, {llvm::PointerType::getUnqual(ctx)}, false); strlen_fn = llvm::Function::Create(ft, llvm::Function::ExternalLinkage, - "strlen", *impl_->module); + length_name, *impl_->module); } - auto *memcpy_fn = impl_->module->getFunction("memcpy"); + auto *memcpy_fn = impl_->module->getFunction(copy_name); if (!memcpy_fn) { // void* memcpy(void* dest, const void* src, size_t n) auto *ft = llvm::FunctionType::get(llvm::PointerType::getUnqual(ctx), @@ -1617,7 +1649,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { native_size_type}, false); memcpy_fn = llvm::Function::Create(ft, llvm::Function::ExternalLinkage, - "memcpy", *impl_->module); + copy_name, *impl_->module); } // len1 = strlen(s1) @@ -1648,7 +1680,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { impl_->builder->SetInsertPoint(length_success); llvm::Value *new_str = nullptr; - if (impl_->memory_mode == MemoryMode::SAFE_GC) { + if (impl_->memory_mode == MemoryMode::SAFE_GC || freestanding) { auto *runtime_type = llvm::FunctionType::get(llvm::PointerType::getUnqual(ctx), {llvm::Type::getInt64Ty(ctx)}, false); @@ -7240,6 +7272,171 @@ bool NativeCodegen::generateModule(const nil_module &mod) { return false; } + // A symbol the consumer supplies. `host` is the one library name that + // names no library: it means the declared Ny function *is* an external + // symbol of exactly that name, called with the platform's ordinary C + // convention, and whoever links the object defines it. + // + // This is the capability a freestanding consumer needs and the one + // thing it could not express. A kernel's own call boundary is its own + // and is usually unstable, so it must not enter the standard library; + // what belongs here is the ability to reach it. The object imports the + // name and nothing else, and the name is written in the source where a + // reader and the symbol-surface test can both see it. + // + // Deliberately unverified: nothing here can check the host's + // signature, so the type profile is kept narrow -- i64, f64 and text + // parameters, those or no value returned -- and anything outside it is + // refused rather than guessed. `text` is a pointer to NUL-terminated + // bytes, which is already how a Ny string is represented natively. + if (lib_name == "host") { + const std::string encoded_count = + minstr.args.size() >= 3 ? minstr.args[2] : std::string{}; + if (encoded_count.empty() || + encoded_count.find_first_not_of("0123456789") != + std::string::npos || + minstr.args.size() < 4) { + std::cerr << "[NativeCodegen] host symbol '" << func_name + << "' has no declared argument count and return type in " + "function '" + << fn.name << "'\n"; + return false; + } + const std::size_t declared_count = + static_cast(std::stoull(encoded_count)); + // The call site encodes only the count and the return type; the + // declaration also carries the parameter types. Accept either, and + // require any parameter list to match the count exactly. + const bool has_parameter_types = minstr.args.size() > 4; + if (has_parameter_types && minstr.args.size() != declared_count + 4) { + std::cerr << "[NativeCodegen] host symbol '" << func_name + << "' declares " << declared_count + << " arguments and a parameter list of a different " + "length in function '" + << fn.name << "'\n"; + return false; + } + if (func_name.empty() || + (!std::isalpha(static_cast(func_name.front())) && + func_name.front() != '_') || + func_name.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789_") != + std::string::npos) { + std::cerr << "[NativeCodegen] host symbol '" << func_name + << "' is not a valid external symbol name in function '" + << fn.name << "'\n"; + return false; + } + // The runtime ABI is ours; a host symbol must not shadow it. + if (func_name.rfind("__ny_", 0) == 0 || + func_name.rfind("nyrt_", 0) == 0) { + std::cerr << "[NativeCodegen] host symbol '" << func_name + << "' is reserved by the native runtime ABI in function '" + << fn.name << "'\n"; + return false; + } + auto host_kind = [](const std::string &type) -> std::string { + const std::string normalized = normalize_nil_type(type); + if (normalized == "text" || normalized == "string") + return "text"; + if (normalized == "i64" || normalized == "f64") + return normalized; + return {}; + }; + auto host_type = [&](const std::string &kind) -> llvm::Type * { + if (kind == "text") + return llvm::PointerType::getUnqual(ctx); + if (kind == "f64") + return llvm::Type::getDoubleTy(ctx); + return llvm::Type::getInt64Ty(ctx); + }; + const std::string declared_return = normalize_nil_type(minstr.args[3]); + const bool returns_value = + declared_return != "void" && !declared_return.empty(); + const std::string return_kind = + returns_value ? host_kind(declared_return) : std::string{"void"}; + if (return_kind.empty()) { + std::cerr << "[NativeCodegen] host symbol '" << func_name + << "' returns '" << minstr.args[3] + << "', which is outside the supported host profile of " + "i64, f64, text or no value, in function '" + << fn.name << "'\n"; + return false; + } + std::vector parameter_kinds(declared_count, "i64"); + if (has_parameter_types) { + for (std::size_t index = 0; index < declared_count; ++index) { + parameter_kinds[index] = host_kind(minstr.args[4 + index]); + if (parameter_kinds[index].empty()) { + std::cerr << "[NativeCodegen] host symbol '" << func_name + << "' takes '" << minstr.args[4 + index] + << "', which is outside the supported host profile " + "of i64, f64 and text, in function '" + << fn.name << "'\n"; + return false; + } + } + } + // Operands were pushed left to right, so they come back in reverse. + std::vector call_arguments(declared_count, nullptr); + for (std::size_t position = declared_count; position-- > 0;) { + llvm::Value *value = impl_->popValue(); + if (value == nullptr) { + std::cerr << "[NativeCodegen] host symbol '" << func_name + << "' is missing an operand in function '" << fn.name + << "'\n"; + return false; + } + const std::string actual = host_kind(impl_->nilType(value)); + const std::string &expected = parameter_kinds[position]; + // Without a declared parameter list the operand's own kind is the + // only statement available, and it must still be one this profile + // admits. + if (actual.empty() || + (has_parameter_types && actual != expected)) { + std::cerr << "[NativeCodegen] host symbol '" << func_name + << "' received an operand of type '" + << impl_->nilType(value) << "' where '" + << (has_parameter_types ? expected : std::string{"i64, f64 or text"}) + << "' was required in function '" + << fn.name << "'\n"; + return false; + } + if (!has_parameter_types) + parameter_kinds[position] = actual; + call_arguments[position] = + parameter_kinds[position] == "i64" + ? impl_->coerceToI64(value) + : value; + } + std::vector parameter_types; + parameter_types.reserve(declared_count); + for (const std::string &kind : parameter_kinds) + parameter_types.push_back(host_type(kind)); + auto *host_function_type = llvm::FunctionType::get( + returns_value ? host_type(return_kind) + : llvm::Type::getVoidTy(ctx), + parameter_types, false); + if (auto *existing = impl_->module->getFunction(func_name)) { + if (existing->getFunctionType() != host_function_type) { + std::cerr << "[NativeCodegen] host symbol '" << func_name + << "' is used with two different signatures in " + "function '" + << fn.name << "'\n"; + return false; + } + } + auto host_callee = + impl_->module->getOrInsertFunction(func_name, host_function_type); + auto *result = impl_->builder->CreateCall( + host_function_type, host_callee.getCallee(), call_arguments); + if (returns_value) + impl_->pushValue(result, return_kind == "text" ? "text" + : return_kind); + break; + } + // External interop still lacks a declared, versioned native ABI and // the former generic path guessed argument layouts while ignoring the // encoded library. That could silently bind an unrelated host symbol. @@ -9157,6 +9354,8 @@ int NativeCodegen::executeJIT(const std::vector &program_args) { expose_runtime_symbol("nyrt_any_v1_is_type", &nyrt_any_v1_is_type); expose_runtime_symbol("nyrt_alloc", &nyrt_alloc); expose_runtime_symbol("nyrt_free", &nyrt_free); + expose_runtime_symbol("nyrt_mem_copy", &nyrt_mem_copy); + expose_runtime_symbol("nyrt_str_length", &nyrt_str_length); expose_runtime_symbol("nyrt_arg_count", &nyrt_arg_count); expose_runtime_symbol("nyrt_arg", &nyrt_arg); expose_runtime_symbol("nyrt_exit", &nyrt_exit); diff --git a/nilcompiler/src/llvm_backend.hpp b/nilcompiler/src/llvm_backend.hpp index 2fffebc0..48cbe3d8 100644 --- a/nilcompiler/src/llvm_backend.hpp +++ b/nilcompiler/src/llvm_backend.hpp @@ -62,6 +62,13 @@ class NativeCodegen { // stacks does not, so this stays independent of the freestanding entry // rather than being implied by it. void setDisableRedZone(bool enabled); + // Selects the code model generated code assumes. The default keeps the + // host's small model, in which an address is reachable as a 32-bit absolute. + // A freestanding consumer that places an object above 4 GiB needs `large`, + // because the small model's R_X86_64_32 relocations cannot reach there and + // fail at link time rather than at run time. + enum class CodeModel { host, small, large }; + void setCodeModel(CodeModel model); // Write the generated LLVM IR, so what the backend produced can be // inspected and asserted rather than inferred from an object. diff --git a/nilcompiler/src/native_runtime.cpp b/nilcompiler/src/native_runtime.cpp index c8569b54..974913c2 100644 --- a/nilcompiler/src/native_runtime.cpp +++ b/nilcompiler/src/native_runtime.cpp @@ -1025,6 +1025,24 @@ std::uint64_t nyrt_any_v1_unbox(const void *box, const char *type, void *nyrt_alloc(std::uint64_t size) noexcept { return allocate_owned(size); } +// A freestanding object reaches its length and copy through the runtime +// rather than libc, so the hosted runtime answers to those names too. Without +// them, an object emitted with --freestanding could only ever be linked +// against the freestanding archive, and the choice of runtime would stop +// being the host's. +void *nyrt_mem_copy(void *destination, const void *source, + std::uint64_t size) noexcept { + if (destination == nullptr || source == nullptr || size == 0) + return destination; + return std::memcpy(destination, source, static_cast(size)); +} + +std::uint64_t nyrt_str_length(const char *text) noexcept { + if (text == nullptr) + return 0; + return static_cast(std::strlen(text)); +} + std::int32_t nyrt_free(void *pointer) noexcept { if (pointer == nullptr) return 1; diff --git a/nilcompiler/src/native_runtime.hpp b/nilcompiler/src/native_runtime.hpp index 65d769cb..c5ee085b 100644 --- a/nilcompiler/src/native_runtime.hpp +++ b/nilcompiler/src/native_runtime.hpp @@ -115,6 +115,13 @@ std::int32_t nyrt_any_v1_is_type(const void *box, const char *type, void *nyrt_alloc(std::uint64_t size) noexcept; std::int32_t nyrt_free(void *pointer) noexcept; +// What a freestanding object calls instead of memcpy and strlen, because it +// has no libc to call. Defined here as well as in the freestanding runtime so +// that which runtime such an object links against stays the host's choice. +void *nyrt_mem_copy(void *destination, const void *source, + std::uint64_t size) noexcept; +std::uint64_t nyrt_str_length(const char *text) noexcept; + // Each address names an initialized, live eight-byte word. Frames are LIFO // and remain registered until the generated function returns. This internal // ABI is for compiler/embedding code, not arbitrary Ny pointer values. diff --git a/nilcompiler/src/vm.cpp b/nilcompiler/src/vm.cpp index 19555a4c..a158a019 100644 --- a/nilcompiler/src/vm.cpp +++ b/nilcompiler/src/vm.cpp @@ -2700,6 +2700,17 @@ void VM::executeInstruction(const Instruction &instr) { // Dynamically dispatch to native function std::string lib_name = instr.args[0]; std::string fn_name = instr.args[1]; + // `host` means a symbol the consumer supplies at link time, which exists + // only in a native object. Refuse it here rather than letting the dynamic + // loader look for a library called `host`: a machine that happened to have + // one would bind an unrelated symbol, and this route cannot satisfy the + // contract in any case. + if (lib_name == "host") { + throw std::runtime_error( + "INTEROP_CALL: '" + fn_name + + "' is a host-supplied symbol, which only a native object can " + "resolve; this route has no host to supply it"); + } int arg_count = std::stoi(instr.args[2]); if (arg_count < 0) throw std::runtime_error("INTEROP_CALL: argument count must not be negative"); diff --git a/nilruntime-freestanding/freestanding_runtime.cpp b/nilruntime-freestanding/freestanding_runtime.cpp index 4a478b22..1cf958d9 100644 --- a/nilruntime-freestanding/freestanding_runtime.cpp +++ b/nilruntime-freestanding/freestanding_runtime.cpp @@ -4,20 +4,40 @@ */ // The native runtime ABI for a target with no operating system. // -// An object emitted by `nilassembler --freestanding` imports exactly five -// symbols -- nyrt_abi_version, nyrt_context_begin, nyrt_context_end, -// nyrt_fail and nyrt_profile_site -- and nothing else. This translation unit -// supplies them without calling into libc, a kernel, or an allocator, so a -// freestanding host can link it instead of reimplementing the boundary or -// satisfying it with stubs that fail if reached. +// An object emitted by `nilassembler --freestanding` imports five symbols -- +// nyrt_abi_version, nyrt_context_begin, nyrt_context_end, nyrt_fail and +// nyrt_profile_site -- plus, only if the program allocates, nyrt_alloc, +// nyrt_mem_copy and nyrt_str_length. It imports nothing else, and no libc at +// all. This translation unit supplies all of them without calling into libc +// or a kernel, so a freestanding host can link it instead of reimplementing +// the boundary or satisfying it with stubs that fail if reached. // -// What it deliberately does not do: allocate, format, read a clock, or touch -// a device. Those belong to a host. nyrt_fail reports through a weak hook the -// host may define; the default stops the caller rather than returning into a -// program whose invariants have already been broken. +// What it deliberately does not do: own memory, format, read a clock, or +// touch a device. Those belong to a host. nyrt_fail reports through a weak +// hook the host may define; the default stops the caller rather than +// returning into a program whose invariants have already been broken. // -// pinned: this file must not gain an #include of a hosted header. The -// freestanding link test asserts the resulting archive imports nothing. +// Allocation is the one case where generated code needs memory and this +// translation unit must answer. The answer is mechanism without policy: the +// host owns the memory and installs it with nyrt_heap_init, and nyrt_alloc +// bumps a pointer through that region. Nothing here declares a static heap, +// because the size of a vessel's memory is the vessel's decision and a fixed +// array would charge every consumer for it. With no region installed +// nyrt_alloc returns null, which generated code already treats as a failure +// and reports through nyrt_fail -- so a program that never allocates never +// needs a region, and one that does cannot silently proceed without it. +// There is no free: a bump region is released as a whole, and +// nyrt_context_end returns it to empty. +// +// There is no locking. A region is a single bump pointer and two concurrent +// allocations would race, which is correct for the targets this serves -- +// nothing freestanding is emitted with threads -- and is a limit a host +// should know rather than discover. +// +// pinned: this file must not gain an #include of a hosted header. That is +// what the freestanding link test can check, by asserting the resulting +// archive imports nothing but the weak failure hook. That it declares no heap +// of its own is a rule, not a test: a static array here would still link. #include namespace { @@ -27,13 +47,34 @@ int entry_argc = 0; const char *const *entry_argv = nullptr; bool context_active = false; +// The host's region, installed by nyrt_heap_init. Null until then, which is +// the state in which allocation fails rather than inventing memory. +unsigned char *heap_base = nullptr; +std::uint64_t heap_size = 0; +std::uint64_t heap_used = 0; + +// Every allocation starts at this boundary, which is the strictest alignment +// a scalar on the supported targets requires. Generated code receives raw +// bytes and may store any type into them. +constexpr std::uint64_t heap_alignment = 16; + } // namespace extern "C" { -// A host that can report a failure defines this. The default below is weak so -// linking the archive alone still produces a complete program. -__attribute__((weak)) void __ny_host_fail(const char *message) noexcept; +// A host that can report a failure defines this. The definition here is weak, +// so linking the archive alone still produces a complete program and a host's +// own strong definition replaces it. +// +// A weak *definition* rather than a weak declaration, deliberately. A weak +// declaration leaves an undefined symbol that generated code must call +// through a 32-bit PC-relative relocation to an address the linker resolves +// to zero -- which cannot be represented once the consumer links above 4 GiB, +// and fails the link for a symbol nobody intended to use. A definition is +// always reachable and needs no null check. +__attribute__((weak)) void __ny_host_fail(const char *message) noexcept { + (void)message; +} // Must equal the version the generated entry checks for; a mismatch makes the // entry call nyrt_fail before running any user code. @@ -49,6 +90,17 @@ void nyrt_context_end() noexcept { context_active = false; entry_argc = 0; entry_argv = nullptr; + // The region belongs to the host and may outlive the context, but nothing + // allocated inside it does: every pointer handed out came from generated + // code whose lifetime ended with the context. + // + // Only the pointer is reset. The bytes are deliberately left, because the + // region is the host's and what a program wrote into it is the host's to + // read once the program has returned -- for many freestanding hosts that is + // the only channel out of a Ny object, which exports nothing but its entry. + // A host that needs them gone clears the region, since only it knows + // whether they were sensitive. + heap_used = 0; } // Profiling attribution is a hosted capture facility. Accepting and ignoring @@ -62,17 +114,73 @@ void nyrt_profile_site(const char *file, const char *function, } [[noreturn]] void nyrt_fail(const char *message) noexcept { - if (__ny_host_fail) __ny_host_fail(message); - // No host reporter, or one that returned anyway: a failed program must not - // continue. Stop here rather than unwinding into broken state. + __ny_host_fail(message); + // The default reporter does nothing, and a host's may return anyway: either + // way a failed program must not continue. Stop here rather than unwinding + // into broken state. for (;;) { } } +// Installs the region allocation draws from. Exported rather than imported: +// a host calls this, it does not have to implement anything. Calling it again +// replaces the region and discards what was handed out of the old one, so a +// host that reinstalls must be done with the previous contents. +void nyrt_heap_init(void *base, std::uint64_t size) noexcept { + heap_base = static_cast(base); + heap_size = base ? size : 0; + heap_used = 0; +} + +// Bumps through the host's region. Returns null when no region is installed +// or the request does not fit, which is the same answer a hosted allocator +// gives under pressure and which generated code already checks. +void *nyrt_alloc(std::uint64_t size) noexcept { + if (!heap_base) return nullptr; + // A zero-sized request still has to return a distinct address, so it is + // served as one alignment unit rather than aliasing the next allocation. + if (size == 0) size = 1; + const std::uint64_t padding = + (heap_alignment - (heap_used % heap_alignment)) % heap_alignment; + if (padding > heap_size - heap_used) return nullptr; + const std::uint64_t start = heap_used + padding; + // Checked against the space left rather than by adding, so a size near the + // top of the range cannot wrap past the test that is meant to catch it. + if (size > heap_size - start) return nullptr; + unsigned char *const block = heap_base + start; + heap_used = start + size; + // Zeroed because the helper this serves replaced calloc, and generated code + // is entitled to assume a fresh block holds no earlier vessel's bytes. + for (std::uint64_t index = 0; index < size; ++index) block[index] = 0; + return block; +} + +// Byte copy and string length, supplied here because a freestanding object +// has no libc to call and these are not the host's decision to make. +void *nyrt_mem_copy(void *destination, const void *source, + std::uint64_t size) noexcept { + unsigned char *out = static_cast(destination); + const unsigned char *in = static_cast(source); + for (std::uint64_t index = 0; index < size; ++index) out[index] = in[index]; + return destination; +} + +std::uint64_t nyrt_str_length(const char *text) noexcept { + if (!text) return 0; + std::uint64_t length = 0; + while (text[length] != '\0') ++length; + return length; +} + // Reads what the entry recorded. Not part of the five imported symbols; a // host links this only if it wants the values. int __ny_entry_argc() noexcept { return entry_argc; } const char *const *__ny_entry_argv() noexcept { return entry_argv; } int __ny_context_active() noexcept { return context_active ? 1 : 0; } +// How much of the region has been handed out. For a host that wants to see +// whether a vessel allocated at all, or how close it came to its bound. +std::uint64_t nyrt_heap_used() noexcept { return heap_used; } +std::uint64_t nyrt_heap_size() noexcept { return heap_size; } + } // extern "C" diff --git a/notebook/2026-11-09-anomalous-abi.md b/notebook/2026-11-09-anomalous-abi.md index 9e08e6d9..49d8f8c9 100644 --- a/notebook/2026-11-09-anomalous-abi.md +++ b/notebook/2026-11-09-anomalous-abi.md @@ -2,9 +2,9 @@ Working log for making NIL emit code that an Anomalous vessel can consume. Anomalous is a separate project at `exec-anomalous`, an experimental operating -system in Rust that has adopted Ny as its implementation language (its ADR -0016). It will eventually support several major ABIs and also ships its own; -its own is the one targeted here. +system in Rust that has adopted Ny as its implementation language (its +decision record 0016). It will eventually support several major ABIs and also +ships its own; its own is the one targeted here. ## What the Anomalous ABI is @@ -18,7 +18,8 @@ following. `rite_status` is a `u16` with `ok`, `would_block`, `denied`, `bad_operation`, `bad_payload`, `limit_exceeded`, `interrupted`, `faulted`. The crate states the ABI is not stable while Anomalous is pre-alpha. -**The rite gate** is the kernel/user boundary (their ADR 0019). A vessel +**The rite gate** is the kernel/user boundary (their decision record +0019). A vessel writes the call into a fixed mailbox, zeroes scratch registers, and issues `int $0xf3`; the scheduler gate is `0xf2`. The reply is read back from the mailbox: forty bytes of `header_size`, `status`, `sequence`, `trace_id`. The @@ -31,7 +32,8 @@ hosted runtime along. ## Why the work was NIL-side -Anomalous ADR 0049 qualifies a bounded freestanding Ny object and records +Anomalous decision record 0049 qualifies a bounded freestanding Ny object +and records exactly what that cost them. The SDK emitted Linux host-targeted ELF plus a generated C `main(int, char **)` wrapper, so a "separate narrow assembly shim calls the generated C wrapper with zero arguments and implements only its @@ -61,8 +63,8 @@ VM, or CI. emitted at all. - **`nilassembler --no-red-zone`** marks every generated definition `noredzone`. Deliberately independent of `--freestanding`: the two answer - different questions, and ADR 0049 describes a working configuration whose - userspace red zone is fine because interrupt entry switches stacks. + different questions, and that record describes a working configuration + whose userspace red zone is fine because interrupt entry switches stacks. - **`nilassembler --emit-llvm `** writes the generated IR. The red-zone attribute does not survive into an object, so without this the guarantee could only be asserted, not checked. @@ -100,29 +102,116 @@ Nothing here shows that a vessel boots under the Anomalous kernel or issues a rite. That needs the `int $0xf3` path and their repository. What these changes remove is the reason they needed a reverse-engineered shim and trap stubs. +## Allocation: the host owns the memory + +Decided with the maintainer on 2026-11-09, choosing between a bump allocator +over a host-installed region, imported `nyrt_alloc`/`nyrt_free` hooks the host +must implement, and a static arena inside the runtime. The region won. + +What settled it was the import surface. Imported allocation hooks would have +taken the boundary a freestanding consumer must implement from five symbols to +seven, and the whole point of this work was to shrink what they implement, not +move it. A static arena inside the runtime keeps the surface at five but makes +the size of a vessel's memory a NIL decision, charged to every consumer in +BSS. A region the host installs keeps both properties: the host implements +nothing, and the memory is still theirs. + +So `nilruntime_freestanding` gained `nyrt_heap_init(base, size)`, exported +rather than imported, and `nyrt_alloc` bumps a 16-byte-aligned, zeroed pointer +through that region. `nyrt_heap_used()` and `nyrt_heap_size()` are there for a +host that wants to see whether a vessel allocated at all. There is no free: a +bump region is released as a whole, and `nyrt_context_end` returns it to +empty, which is sound because everything allocated inside it came from +generated code whose lifetime ended with the context. Nothing in the runtime +declares a heap of its own. + +The emission side changed with it. `__ny_string_concat` called `strlen`, +`memcpy` and `calloc`; under `--freestanding` it now calls `nyrt_str_length`, +`nyrt_mem_copy` and `nyrt_alloc` instead. The helper's shape is otherwise +identical, including the null check -- an allocator with no region returns +null exactly as a hosted one does under pressure, and the existing failure +path reports it through `nyrt_fail` with a message naming the operation. So +"no region installed" needed no new failure semantics; it reuses the one that +was already pinned. + +The two new names are also defined in the hosted runtime. Without that, an +object emitted with `--freestanding` could only ever link against the +freestanding archive, and which runtime to link would have stopped being the +host's choice. + +Measured, not asserted: a freestanding concatenating object imports +`nyrt_abi_version`, `nyrt_alloc`, `nyrt_context_begin`, `nyrt_context_end`, +`nyrt_fail`, `nyrt_mem_copy`, `nyrt_profile_site`, `nyrt_str_length` -- eight +names, no libc symbol at all. The hosted object for the same program still +imports `calloc`, `memcpy` and `strlen`, unchanged. The archive still imports +nothing but the weak `__ny_host_fail`. Checked with `nm -u` directly as well +as through the test. + +`nil.native-symbol-surface` is now 12 checks: the three added ones pin that a +freestanding allocating object reaches memory through the runtime hooks, that +no libc name survives in it, and that allocation widens the surface by exactly +those three names and nothing else. + +`nil.freestanding-runtime` is now 8 checks, and the two added cases run rather +than inspect. The first installs a 4 KiB array in the driver, runs a program +that concatenates `"left"` and `"right"`, and afterwards searches the driver's +own array for `leftright` -- so what is proved is that the bytes landed in +memory the host owns, which no symbol inspection could show. It also requires +`nyrt_heap_used()` to be zero on return, pinning the reset at context end. The +second links the same program with no region installed and requires it to stop +through `nyrt_fail` with a non-null message, because an allocator that cannot +say no is worse than none. Each case is the other's control: the success path +proves allocation works, the starved path proves it was really the allocator +being called. + +## The ABI document + +`docs/advanced/freestanding-targets.md`, linked from `docs/README.md` and +`docs/advanced/index.md`. It states the emission flags, the `__ny_entry` +contract and the exact order of the entry sequence, the five always-required +hooks with C signatures, the three allocation hooks and the fact that they +appear only if the program allocates, what `nilruntime_freestanding` supplies, +the heap division and its four consequences, the weak `__ny_host_fail`, a +minimal host, and which test pins which claim. It names the tests as the +authority if the page and the toolchain disagree. + +It also states what the contract does not provide, which is the part worth +keeping honest: no release qualification, no evidence that any kernel boots a +Ny vessel, no system-call bindings, and no threads, TLS, unwinding or hosted +I/O. + +Writing it turned up one thing worth noting: NIL's repository policy forbids +the retired `ADR nnnn` spelling repository-wide, and the 2026-11-09 notebook +entry cited Anomalous's decision records in exactly that form, so +`ny.repository-policy` had been failing since `00eced9`. The citations are +reworded. An exemption would have been the wrong fix -- the rule exists to +stop NIL's own retired spelling creeping back, and a hole in it would hide +real drift. + ## Open, in the order they probably matter -1. **Allocation.** The moment a vessel concatenates a string it needs - `calloc`, and the freestanding runtime deliberately has none. A bump - allocator in the runtime, or a host-delegated hook, is a decision about who - owns vessel memory rather than a gap to fill quietly. The maintainer - expects later features to need the shipped runtime, so this is the next - real question. -2. **A written ABI document.** The contract is currently pinned by tests and - described here. Anomalous should be able to read it rather than infer it - from our test file: the five hooks and their signatures, `__ny_entry`, the - flags, and what a host must supply. -3. **Rite bindings stay in Anomalous.** Agreed with the maintainer: their ABI +1. **A vessel that allocates more than one string.** The bump region is never + reclaimed inside a context, so a vessel that concatenates in a loop + exhausts it and stops. That is the correct behaviour for the current + contract and the wrong behaviour for a long-running vessel. Whether the + answer is reclamation, a per-operation scope, or a region the host rotates + is a question that needs a real vessel to ask it; guessing now would build + the wrong thing precisely. +2. **Rite bindings stay in Anomalous.** Agreed with the maintainer: their ABI is theirs and is explicitly unstable, so it should not enter `nilstd`. NIL supplies the capability -- freestanding objects, exact record layout, inline assembly, no unconditional imports. -4. `docs/release/v1-profile.md` still lists freestanding targets as not +3. `docs/release/v1-profile.md` still lists freestanding targets as not qualified for release. That remains true and deliberate; qualification is a separate decision from capability. +4. **Still nothing here proves a vessel boots or issues a rite.** That needs + the `int $0xf3` path and their repository. What is now removed is the + reason they needed a reverse-engineered shim, trap stubs for libc imports + they never wanted, and an allocator they would have had to implement. ## Branch state -All of the above is on `anomalous-abi-symbol-surface`, pushed, unmerged. It +All of the above is on `anomalous-abi-symbol-surface`, unmerged. It also carries `72c9547`, the macOS desktop acceptance record, because the branch was cut from `macos-ui-acceptance-record` before that merged. Merging this branch therefore brings the macOS documentation with it and makes diff --git a/scripts/package-sdk.py b/scripts/package-sdk.py index 6e6729a1..ff9fde61 100755 --- a/scripts/package-sdk.py +++ b/scripts/package-sdk.py @@ -27,12 +27,14 @@ ) from sdk_qualification import TOOLS, collect_qualification, qualification_errors, source_identity from sdk_sources import is_source, module_declarations, module_artifact_path -from sdk_runtime import STATIC_NAMES, SHARED_NAMES, RUNTIME_PAIRS, shared_library_valid +from sdk_runtime import (STATIC_NAMES, SHARED_NAMES, RUNTIME_PAIRS, + FREESTANDING_STATIC_NAMES, shared_library_valid) REQUIRED_TOOLS = TOOLS MANIFEST_NAME = "manifest.json" NATIVE_RUNTIME_ARCHIVE_NAMES = STATIC_NAMES +FREESTANDING_RUNTIME_ARCHIVE_NAMES = FREESTANDING_STATIC_NAMES def arguments() -> argparse.Namespace: @@ -167,9 +169,27 @@ def validate_stage_input(stage_dir: Path) -> tuple[Path, Path]: "staged native runtime fails supported archive framing and required " "symbol-index offset validation: {}".format(runtime_source) ) + freestanding_names = sorted( + set(FREESTANDING_RUNTIME_ARCHIVE_NAMES).intersection(actual_files) + ) + if len(freestanding_names) != 1: + raise SystemExit( + "staged SDK must contain exactly one freestanding runtime archive " + "from {}: found {}".format( + list(FREESTANDING_RUNTIME_ARCHIVE_NAMES), freestanding_names + ) + ) + freestanding_source = stage_dir / freestanding_names[0] + if not is_static_archive(freestanding_source): + raise SystemExit( + "staged freestanding runtime fails supported archive framing and " + "required symbol-index offset validation: {}".format( + freestanding_source + ) + ) expected_files = {executable_name(name) for name in REQUIRED_TOOLS} | { "LICENSE", - runtime_source.name, shared_source.name, + runtime_source.name, shared_source.name, freestanding_source.name, } missing_files = sorted(expected_files - actual_files) extra_files = sorted(actual_files - expected_files) @@ -188,7 +208,7 @@ def validate_stage_input(stage_dir: Path) -> tuple[Path, Path]: tool = stage_dir / executable_name(name) if os.name != "nt" and not os.access(tool, os.X_OK): raise SystemExit("staged SDK tool is not executable: {}".format(tool)) - return runtime_source, shared_source + return runtime_source, shared_source, freestanding_source def logical_module_name(source: Path, nilstd: Path) -> str: @@ -223,7 +243,7 @@ def logical_module_name(source: Path, nilstd: Path) -> str: def compile_standard_library( compiler: Path, nilstd: Path, stage_dir: Path, runtime_source: Path, - shared_source: Path | None = None + shared_source: Path | None = None, freestanding_source: Path | None = None ) -> tuple[list[dict[str, Any]], int]: sources = sorted((path for path in nilstd.rglob("*") if path.is_file() and is_source(path)), key=lambda path: path.relative_to(nilstd).as_posix()) @@ -245,6 +265,9 @@ def compile_standard_library( shutil.copyfile(runtime_source, runtime_destination) if shared_source is not None: shutil.copyfile(shared_source, runtime_directory / shared_source.name) + if freestanding_source is not None: + shutil.copyfile(freestanding_source, + runtime_directory / freestanding_source.name) artifact_paths: set[str] = set() for module_name in sorted(groups): module_sources = groups[module_name] @@ -358,6 +381,8 @@ def compile_standard_library( runtime_source.unlink() if shared_source is not None: shared_source.unlink() + if freestanding_source is not None: + freestanding_source.unlink() return modules, len(sources) @@ -396,7 +421,7 @@ def main() -> int: "explicitly pass --allow-dirty-source for a development SDK" ) - runtime_source, shared_source = validate_stage_input(stage_dir) + runtime_source, shared_source, freestanding_source = validate_stage_input(stage_dir) nilstd = stage_dir / "nilstd" docs = stage_dir / "docs" compiler = stage_dir / executable_name("nilcompiler") @@ -411,10 +436,14 @@ def main() -> int: raise SystemExit("compiled SDK documentation is missing from {}".format(docs)) modules, source_file_count = compile_standard_library( - compiler, nilstd, stage_dir, runtime_source, shared_source + compiler, nilstd, stage_dir, runtime_source, shared_source, + freestanding_source ) packaged_runtime = stage_dir / "nillib" / "native" / runtime_source.name packaged_shared = stage_dir / "nillib" / "native" / shared_source.name + packaged_freestanding = ( + stage_dir / "nillib" / "native" / freestanding_source.name + ) tools = [] for name in REQUIRED_TOOLS: path = stage_dir / executable_name(name) @@ -472,6 +501,14 @@ def main() -> int: "bytes": packaged_shared.stat().st_size, "sha256": sha256(packaged_shared), }, + # Recorded separately from the hosted runtime because a consumer + # chooses one or the other, and a freestanding consumer must be able to + # pin the archive it links by content rather than by trusting a path. + "native_freestanding_runtime": { + "path": packaged_freestanding.relative_to(stage_dir).as_posix(), + "bytes": packaged_freestanding.stat().st_size, + "sha256": sha256(packaged_freestanding), + }, "standard_library": { "format": nil_library_format({ nil_library_version(stage_dir / module["artifact"]["path"]) diff --git a/scripts/sdk_runtime.py b/scripts/sdk_runtime.py index 4cff100a..d7dfeece 100644 --- a/scripts/sdk_runtime.py +++ b/scripts/sdk_runtime.py @@ -15,6 +15,12 @@ # static-default/DLL pair. Neither platform permits shipping both archives. RUNTIME_PAIRS = {"libnil.so": ("libnil.a",), "libnil.dylib": ("libnil.a",), "nil.dll": ("nil.lib", "libnil.a")} +# The runtime for a target with no operating system. Shipped beside the hosted +# one rather than instead of it: a consumer with no C library links this, and +# an object emitted with --freestanding has no other way to resolve its hooks +# than reaching into a build tree, which a pinned generation cannot do. +FREESTANDING_STATIC_NAMES = ("libnilruntime_freestanding.a", + "nilruntime_freestanding.lib") def shared_library_valid(path: Path) -> bool: diff --git a/scripts/validate-sdk.py b/scripts/validate-sdk.py index 15c5cce7..bcc2f5b2 100755 --- a/scripts/validate-sdk.py +++ b/scripts/validate-sdk.py @@ -26,7 +26,9 @@ ) from sdk_qualification import LEGACY_TOOLS, APERTURE_TOOLS, TOOLS, qualification_errors from sdk_sources import is_source, module_artifact_path, canonical_std_namespace -from sdk_runtime import STATIC_NAMES, SHARED_NAMES, RUNTIME_PAIRS, shared_library_valid, shared_runtime_smoke +from sdk_runtime import (STATIC_NAMES, SHARED_NAMES, RUNTIME_PAIRS, + FREESTANDING_STATIC_NAMES, shared_library_valid, + shared_runtime_smoke) REQUIRED_TOOLS = TOOLS @@ -42,6 +44,12 @@ "nillib/native/" + name for name in NATIVE_RUNTIME_ARCHIVE_NAMES ) SHARED_RUNTIME_PATHS = tuple("nillib/native/" + name for name in SHARED_NAMES) +FREESTANDING_RUNTIME_PATHS = tuple( + "nillib/native/" + name for name in FREESTANDING_STATIC_NAMES +) +# Synthesised by the linker rather than supplied by anyone, so its presence +# says nothing about what the archive needs from a host. +LINKER_SYNTHESISED_SYMBOLS = frozenset({"_GLOBAL_OFFSET_TABLE_"}) SHA256_PATTERN = re.compile(r"[0-9a-f]{64}") REVISION_PATTERN = re.compile(r"(?:[0-9a-f]{40}|[0-9a-f]{64})") MODULE_PATTERN = re.compile( @@ -319,6 +327,7 @@ def validate_exact_layout( key.startswith("nillib/") and not key.endswith(".nil") and key not in NATIVE_RUNTIME_PATHS + SHARED_RUNTIME_PATHS + + FREESTANDING_RUNTIME_PATHS ): errors.append("nillib contains a non-NIL artifact: {}".format(key)) if (key.startswith("docs/") and not key.endswith(".html") @@ -358,6 +367,7 @@ def validate_manifest_metadata(manifest: dict[str, Any], errors: list[str]) -> N "tools", "native_runtime", "native_shared_runtime", + "native_freestanding_runtime", "standard_library", "documentation", "payload", @@ -467,6 +477,117 @@ def validate_native_runtime( ) +def validate_freestanding_runtime( + value: Any, files: dict[str, Path], errors: list[str] +) -> None: + """The archive a consumer with no C library links against. + + Validated like the hosted archive, and additionally required to import + nothing but the weak host failure hook: an archive that had picked up a + libc dependency would link on a hosted build host and fail on the target + it exists for, which is the drift this record is here to catch. + """ + key = validate_file_record(value, "native_freestanding_runtime", files, errors) + if key is None: + return + if key not in FREESTANDING_RUNTIME_PATHS: + errors.append( + "native_freestanding_runtime.path must be one of {}".format( + list(FREESTANDING_RUNTIME_PATHS) + ) + ) + return + archive = files.get(key) + if archive is not None and not is_static_archive(archive): + errors.append( + "native_freestanding_runtime fails supported archive framing and " + "required symbol-index offset validation: {}".format(key) + ) + return + if archive is not None: + unexpected = sorted( + freestanding_archive_imports(archive) - LINKER_SYNTHESISED_SYMBOLS + ) + if unexpected: + errors.append( + "native_freestanding_runtime must import nothing but the weak " + "host failure hook; found: {}".format(unexpected) + ) + + +def freestanding_archive_imports(archive: Path) -> set[str]: + """Undefined, non-weak symbol names in an ELF static archive. + + The ELF symbol tables are read directly rather than through nm, so the + check does not depend on binutils being installed where an SDK is + validated. A non-ELF archive returns nothing: the import surface is + pinned on ELF hosts by the repository's own tests, and this record must + not fail a Windows or macOS package for lacking a reader. + """ + try: + data = archive.read_bytes() + except OSError: + return set() + if not data.startswith(b"!\n"): + return set() + undefined: set[str] = set() + offset = 8 + while offset + 60 <= len(data): + header = data[offset:offset + 60] + if header[58:60] != b"`\n": + break + try: + size = int(header[48:58].decode("ascii").strip() or "0") + except ValueError: + break + body = data[offset + 60:offset + 60 + size] + offset += 60 + size + (size & 1) + if body[:4] != b"\x7fELF" or body[4] != 2 or body[5] != 1: + continue + undefined |= elf_undefined_symbols(body) + return undefined + + +def elf_undefined_symbols(data: bytes) -> set[str]: + """Named SHN_UNDEF symbols in one little-endian 64-bit ELF object.""" + try: + section_offset = int.from_bytes(data[0x28:0x30], "little") + section_size = int.from_bytes(data[0x3a:0x3c], "little") + section_count = int.from_bytes(data[0x3c:0x3e], "little") + names_index = int.from_bytes(data[0x3e:0x40], "little") + + def section(index: int) -> tuple[int, int, int, int, int]: + base = section_offset + index * section_size + name = int.from_bytes(data[base:base + 4], "little") + offset = int.from_bytes(data[base + 0x18:base + 0x20], "little") + size = int.from_bytes(data[base + 0x20:base + 0x28], "little") + link = int.from_bytes(data[base + 0x28:base + 0x2c], "little") + entry = int.from_bytes(data[base + 0x38:base + 0x40], "little") + return name, offset, size, link, entry + + def text(table: int, index: int) -> str: + end = data.index(b"\0", table + index) + return data[table + index:end].decode("utf-8", "replace") + + names_offset = section(names_index)[1] + undefined: set[str] = set() + for index in range(section_count): + name, offset, size, link, entry = section(index) + if text(names_offset, name) != ".symtab" or not entry: + continue + strings = section(link)[1] + for position in range(offset, offset + size, entry): + name_index = int.from_bytes(data[position:position + 4], "little") + info = data[position + 4] + shndx = int.from_bytes(data[position + 6:position + 8], "little") + # STB_WEAK is a host-supplied hook, not a requirement. + if name_index and shndx == 0 and info >> 4 != 2: + undefined.add(text(strings, name_index)) + return undefined + except (IndexError, ValueError): + return set() + + def validate_shared_runtime(value: Any, files: dict[str, Path], errors: list[str]) -> None: key = validate_file_record(value, "native_shared_runtime", files, errors) if key is None: @@ -1257,6 +1378,9 @@ def main() -> int: validate_tools(manifest.get("tools"), files, errors) validate_native_runtime(manifest.get("native_runtime"), files, errors) validate_shared_runtime(manifest.get("native_shared_runtime"), files, errors) + validate_freestanding_runtime( + manifest.get("native_freestanding_runtime"), files, errors + ) module_count = validate_standard_library( manifest.get("standard_library"), files, errors ) diff --git a/tests/sdk_qualification_tests.py b/tests/sdk_qualification_tests.py index 203eeeef..0bda1f8d 100644 --- a/tests/sdk_qualification_tests.py +++ b/tests/sdk_qualification_tests.py @@ -508,13 +508,26 @@ def setUp(self): header[54:56] = (56).to_bytes(2, "little") header[56:58] = (1).to_bytes(2, "little") self.shared.write_bytes(header) + # A staged SDK carries the freestanding runtime beside the hosted pair. + # A consumer with no C library links this one and nothing else. + self.freestanding = self.root / "libnilruntime_freestanding.a" + self.freestanding.write_bytes(sysv_archive()) def test_both_runtime_forms_required_and_returned(self): - self.assertEqual(self.package.validate_stage_input(self.root), (self.static, self.shared)) + self.assertEqual(self.package.validate_stage_input(self.root), + (self.static, self.shared, self.freestanding)) self.shared.unlink() with self.assertRaisesRegex(SystemExit, "matching shared native runtime"): self.package.validate_stage_input(self.root) + def test_freestanding_runtime_is_required_and_must_be_an_archive(self): + self.freestanding.unlink() + with self.assertRaisesRegex(SystemExit, "freestanding runtime archive"): + self.package.validate_stage_input(self.root) + self.freestanding.write_bytes(b"not an archive") + with self.assertRaisesRegex(SystemExit, "freestanding runtime fails supported archive framing"): + self.package.validate_stage_input(self.root) + def test_new_packages_require_executable_aperture(self): aperture = self.root / self.package.executable_name("aperture") aperture.unlink() @@ -545,6 +558,7 @@ def test_sealed_tool_inventory_accepts_historical_tools_and_rejects_mismatch(sel native.mkdir(parents=True) self.static.rename(native / self.static.name) self.shared.rename(native / self.shared.name) + self.freestanding.rename(native / self.freestanding.name) (self.root / "manifest.json").write_text("{}", newline='\n') def records(names): @@ -627,9 +641,11 @@ def test_windows_pair_accepts_mingw_and_msvc_static_names(self): header[150:152] = (0x2000).to_bytes(2, "little") # IMAGE_FILE_DLL. header[152:154] = (0x20b).to_bytes(2, "little") # PE32+. self.shared.write_bytes(header) - self.assertEqual(self.package.validate_stage_input(self.root), (self.static, self.shared)) + self.assertEqual(self.package.validate_stage_input(self.root), + (self.static, self.shared, self.freestanding)) msvc_static = self.static.rename(self.root / "nil.lib") - self.assertEqual(self.package.validate_stage_input(self.root), (msvc_static, self.shared)) + self.assertEqual(self.package.validate_stage_input(self.root), + (msvc_static, self.shared, self.freestanding)) self.static.write_bytes(msvc_static.read_bytes()) with self.assertRaisesRegex(SystemExit, "exactly one native runtime archive"): self.package.validate_stage_input(self.root) diff --git a/tests/tools/freestanding_runtime_contract.py b/tests/tools/freestanding_runtime_contract.py index 5f44aa18..cb25368b 100644 --- a/tests/tools/freestanding_runtime_contract.py +++ b/tests/tools/freestanding_runtime_contract.py @@ -1,20 +1,45 @@ #!/usr/bin/env python3 """Link and run a freestanding program with no C library at all. -`nilassembler --freestanding` emits an object importing only the five native -runtime hooks, and nilruntime_freestanding supplies them. This builds the two -together with -nostdlib and its own `_start`, so nothing from a hosted -toolchain can satisfy a symbol by accident: if either side still needed libc, -the link fails rather than quietly succeeding on the build host. +`nilassembler --freestanding` emits an object importing the five native +runtime hooks, plus three more if it allocates, and nilruntime_freestanding +supplies them. This builds the two together with -nostdlib and its own +`_start`, so nothing from a hosted toolchain can satisfy a symbol by accident: +if either side still needed libc, the link fails rather than quietly +succeeding on the build host. Running it then proves the entry sequence itself works -- runtime ABI check, context begin, user main, context end -- because the process exit status is the value Ny returned. + +The archive is also required to use general registers only. It has no floating +point of its own, but at -O2 the compiler vectorizes its zero and copy loops +into SSE, and a kernel profile that denies inherited x87/SIMD state faults on +the first such instruction -- a consumer cannot opt out of what is already in +the archive. The compile flag is the guarantee; the check below is the +tripwire, and it needs a disassembler, so it reports rather than skips the +whole test when none is installed. + +A freestanding consumer links at a fixed address with no dynamic linker, so +the link is `-no-pie` and the result must contain no global offset table. That +is not cosmetic: under PIC the weak host failure hook is reached through a GOT, +and a GOT is a section a kernel or vessel profile rejects outright, so an +archive that quietly became position-independent would link here and be +refused by the consumer it exists for. + +Allocation is checked the same way: by running it. The host owns the memory, +so the driver installs its own array and afterwards reads the concatenated +bytes back out of it, which no amount of symbol inspection could show. The +case with no region installed is checked too, because an allocator that +cannot say no is worse than none. """ from __future__ import annotations import argparse from pathlib import Path +import re +import shutil +import struct import subprocess import sys import tempfile @@ -23,6 +48,43 @@ # cannot be mistaken for success. expected_exit = 7 +# Distinct from expected_exit and from each other, so a wrong answer names +# which assertion inside the freestanding program failed rather than just +# differing from 7. +missing_bytes_exit = 91 +heap_not_reset_exit = 92 +reached_user_code_exit = 93 +reported_failure_exit = 23 +failure_without_message_exit = 24 + +# A program that reaches a symbol its consumer defines. The driver below +# supplies it, inspects what Ny passed, and returns a value Ny returns in +# turn, so the check covers the whole round trip rather than the link alone. +host_symbol = 'anomalous_probe_emit' +host_message = 'from ny' +host_program = ( + 'module host_probe\n\n' + '@interop("host")\n' + f'fn {host_symbol}(message: text) -> i64\n' + 'end fn\n\n' + 'fn main() -> i64 {\n' + f' let greeting: text = "{host_message}";\n' + f' return {host_symbol}(greeting);\n' + '}\n' +) + +# Distinct from every other exit above. +wrong_text_exit = 71 + +concat_program = ( + 'fn main() -> i64 {\n' + ' let a: text = "left";\n' + ' let b: text = "right";\n' + ' let joined: text = a + b;\n' + f' return {expected_exit};\n' + '}\n' +) + driver_source = """ extern "C" int __ny_entry(); @@ -35,8 +97,9 @@ } """ -# Linking succeeds with the weak default in place; this one replaces it, which -# is how a host reports a failure instead of stopping silently. +# Linking succeeds with the archive's weak definition in place; this one +# replaces it with a strong definition, which is how a host reports a failure +# instead of stopping silently. host_fail_source = """ extern "C" int __ny_entry(); extern "C" void __ny_host_fail(const char *message) { (void)message; } @@ -49,6 +112,94 @@ """ +# The host owns the memory: it installs a region of its own and the runtime +# bumps through it. Afterwards the driver reads the region back, so the check +# is that the concatenated bytes really landed in host memory -- not merely +# that an allocator was called. It also requires the region to be empty again, +# because the context ended and nothing allocated inside it outlives that. +heap_source = f""" +extern "C" int __ny_entry(); +extern "C" void nyrt_heap_init(void *base, unsigned long long size); +extern "C" unsigned long long nyrt_heap_used(); + +static unsigned char arena[4096]; + +static bool arena_holds(const char *needle) {{ + unsigned long long length = 0; + while (needle[length] != '\\0') ++length; + if (length == 0 || length > sizeof arena) return false; + for (unsigned long long start = 0; start + length <= sizeof arena; ++start) {{ + unsigned long long index = 0; + while (index < length && + arena[start + index] == static_cast(needle[index])) + ++index; + if (index == length) return true; + }} + return false; +}} + +extern "C" [[noreturn]] void _start() {{ + nyrt_heap_init(arena, sizeof arena); + long code = __ny_entry(); + if (!arena_holds("leftright")) code = {missing_bytes_exit}; + else if (nyrt_heap_used() != 0) code = {heap_not_reset_exit}; + asm volatile("syscall" :: "a"(60L), "D"(code) : "rcx", "r11", "memory"); + __builtin_unreachable(); +}} +""" + +# The same program with no region installed. nyrt_alloc has nothing to hand +# out, returns null, and the generated null check reports it through nyrt_fail +# with a message naming the operation. A vessel must not reach the code after +# a failed allocation, so arriving at the exit below at all is the failure. +starved_source = f""" +extern "C" int __ny_entry(); + +[[noreturn]] static void leave(long code) {{ + asm volatile("syscall" :: "a"(60L), "D"(code) : "rcx", "r11", "memory"); + __builtin_unreachable(); +}} + +extern "C" void __ny_host_fail(const char *message) {{ + leave(message ? {reported_failure_exit} : {failure_without_message_exit}); +}} + +extern "C" [[noreturn]] void _start() {{ + __ny_entry(); + leave({reached_user_code_exit}); +}} +""" + + +# Defines the symbol Ny declared. Nothing in Ny checked this signature; the +# contract is the documented one -- a text argument arrives as a pointer to +# NUL-terminated bytes -- so the driver verifies the bytes it was handed and +# returns a length Ny passes back as its own result. +host_driver_source = f""" +extern "C" int __ny_entry(); + +[[noreturn]] static void leave(long code) {{ + asm volatile("syscall" :: "a"(60L), "D"(code) : "rcx", "r11", "memory"); + __builtin_unreachable(); +}} + +extern "C" long {host_symbol}(const char *message) {{ + static const char expected[] = "{host_message}"; + if (message == nullptr) leave({wrong_text_exit}); + unsigned long index = 0; + for (; expected[index] != '\\0'; ++index) {{ + if (message[index] != expected[index]) leave({wrong_text_exit}); + }} + if (message[index] != '\\0') leave({wrong_text_exit}); + return static_cast(index); +}} + +extern "C" [[noreturn]] void _start() {{ + leave(__ny_entry()); +}} +""" + + def run(command, timeout=180): result = subprocess.run(list(map(str, command)), stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout) @@ -61,9 +212,12 @@ def checked(command, timeout=180): return result -def build(compiler, assembler, archive, cxx, root: Path, name: str, driver: str) -> Path: +def build(compiler, assembler, archive, cxx, root: Path, name: str, driver: str, + program_source: str | None = None) -> Path: source = root / f'{name}.ny' - source.write_text(f'fn main() -> i64 {{\n return {expected_exit};\n}}\n', newline='\n') + if program_source is None: + program_source = f'fn main() -> i64 {{\n return {expected_exit};\n}}\n' + source.write_text(program_source, newline='\n') nil = root / f'{name}.nil' obj = root / f'{name}.o' checked([compiler, '--no-stdlib', '--no-bundle', '--unmanaged', '-o', nil, source]) @@ -71,11 +225,62 @@ def build(compiler, assembler, archive, cxx, root: Path, name: str, driver: str) driver_path = root / f'{name}_driver.cpp' driver_path.write_text(driver, newline='\n') program = root / name - checked([cxx, '-nostdlib', '-static', '-fno-exceptions', '-fno-rtti', - '-o', program, driver_path, obj, archive]) + checked([cxx, '-nostdlib', '-static', '-no-pie', '-fno-exceptions', + '-fno-rtti', '-o', program, driver_path, obj, archive]) return program +def indirection_sections(program: Path) -> list[str]: + """Names of any GOT/PLT sections in a linked ELF program. + + Read from the section header table directly, so the check needs no + binutils where an SDK is built. + """ + data = program.read_bytes() + if data[:4] != b'\x7fELF' or data[4] != 2 or data[5] != 1: + raise SystemExit(f'expected a little-endian 64-bit program: {program}') + section_offset, = struct.unpack_from(' int: + return struct.unpack_from(' str: + start = names_base + name_offset(index) + end = data.index(b'\0', start) + return data[start:end].decode('utf-8', 'replace') + + found = [] + for index in range(section_count): + section = text(index) + if section.startswith('.got') or section.startswith('.plt') or section == '.iplt': + found.append(section) + return found + + +def non_general_register_instructions(archive: Path) -> list[str] | None: + """Disassembled lines using x87, MMX or SIMD registers, or None. + + None means no disassembler was available, which is reported rather than + treated as a pass. + """ + for tool in ('objdump', 'llvm-objdump'): + executable = shutil.which(tool) + if executable is None: + continue + result = run([executable, '-d', archive], timeout=120) + if result.returncode != 0: + continue + pattern = re.compile(r'%(?:x|y|z)mm[0-9]|%mm[0-7]|\b(?:f[il]?(?:ld|st|add|mul|div|sub)' + r'|emms|femms)\b') + return [line.strip() for line in result.stdout.splitlines() + if pattern.search(line)] + return None + + def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--compiler', type=Path, required=True) @@ -101,6 +306,26 @@ def main() -> int: f'got {result.returncode}, stderr: {result.stderr!r}') checks += 1 + # General registers only, so a profile that denies inherited x87 and + # SIMD state can run what this archive contains. + simd = non_general_register_instructions(args.archive) + if simd is None: + print('NOTE: no disassembler found; the general-register-only ' + 'guarantee rests on the compile flag alone') + else: + assert not simd, ( + 'the freestanding runtime must use general registers only; ' + f'found {len(simd)}: {simd[:4]}') + checks += 1 + + # No GOT, no PLT. A consumer that forbids those sections is the reason + # this archive exists, so the absence is pinned rather than assumed. + indirections = indirection_sections(program) + assert not indirections, ( + 'a freestanding program must link with no indirection tables; ' + f'found: {indirections}') + checks += 1 + # The failure reporter is weak so the archive links alone, and # replaceable so a host can observe a failure. overridden = build(args.compiler, args.assembler, args.archive, args.cxx, @@ -112,6 +337,54 @@ def main() -> int: f'got {result.returncode}') checks += 1 + # Allocation over a region the host owns. The program concatenates, + # and the driver finds the result inside its own array afterwards. + allocating = build(args.compiler, args.assembler, args.archive, args.cxx, + root, 'heap', heap_source, program_source=concat_program) + checks += 1 + result = run([allocating], timeout=60) + assert result.returncode != missing_bytes_exit, ( + 'the concatenated bytes must appear in the region the host installed') + assert result.returncode != heap_not_reset_exit, ( + 'ending the context must return the region to empty') + assert result.returncode == expected_exit, ( + 'an allocating freestanding program must run and return what Ny ' + f'returned; got {result.returncode}, stderr: {result.stderr!r}') + checks += 1 + + # And with no region installed, which is the default. Allocation has + # to fail loudly rather than hand back memory it does not have. + starved = build(args.compiler, args.assembler, args.archive, args.cxx, + root, 'starved', starved_source, + program_source=concat_program) + checks += 1 + result = run([starved], timeout=60) + assert result.returncode != reached_user_code_exit, ( + 'a failed allocation must not return into the program') + assert result.returncode != failure_without_message_exit, ( + 'the failure must name the operation that could not allocate') + assert result.returncode == reported_failure_exit, ( + 'allocating with no region installed must report through nyrt_fail; ' + f'got {result.returncode}, stderr: {result.stderr!r}') + checks += 1 + + # A host symbol, linked and called. Ny returns what the host returned, + # so the exit status is the message's length and proves both that the + # pointer was a real NUL-terminated string and that the result came + # back through Ny's own return. + reaching = build(args.compiler, args.assembler, args.archive, args.cxx, + root, 'host', host_driver_source, + program_source=host_program) + checks += 1 + result = run([reaching], timeout=60) + assert result.returncode != wrong_text_exit, ( + 'the host symbol must receive the exact NUL-terminated bytes Ny ' + 'passed') + assert result.returncode == len(host_message), ( + 'Ny must return what the host symbol returned; expected ' + f'{len(host_message)}, got {result.returncode}') + checks += 1 + print(f'Freestanding runtime: {checks} checks passed') return 0 diff --git a/tests/tools/native_symbol_surface.py b/tests/tools/native_symbol_surface.py index 0d9410f6..343dd6ff 100644 --- a/tests/tools/native_symbol_surface.py +++ b/tests/tools/native_symbol_surface.py @@ -35,6 +35,11 @@ # absence elsewhere proves it is generated on demand. concat_imports = {'strlen', 'memcpy', 'calloc'} +# What the same helper calls on a target with no libc. The host owns the +# memory and installs it; the runtime bumps through it. These are the only +# names allocation is allowed to add, and no libc name may appear beside them. +freestanding_concat_imports = {'nyrt_str_length', 'nyrt_mem_copy', 'nyrt_alloc'} + def undefined_symbols(path: Path) -> set[str]: data = path.read_bytes() @@ -104,8 +109,40 @@ def definitions_without_noredzone(ir: Path) -> list[str]: return [name for name, group in definitions if group not in groups_with] +def absolute_relocation_count(obj: Path) -> int: + """Number of 32-bit absolute relocations in an ELF relocatable object. + + These are what confine an object to the low 4 GiB: the linker has nowhere + to put a higher address, so the link fails rather than the program + misbehaving. Read from the section headers directly, so the check needs no + binutils. + """ + data = obj.read_bytes() + if data[:4] != b'\x7fELF' or data[4] != 2 or data[5] != 1: + raise SystemExit(f'expected a little-endian 64-bit object: {obj}') + section_offset, = struct.unpack_from(' int: # The helper still has to exist when a program actually concatenates, # or the first assertion would pass for the wrong reason. + concatenating = ('fn main() -> i64 {\n let a: text = "left";\n' + ' let b: text = "right";\n' + ' let joined: text = a + b;\n' + ' return 0;\n}\n') concat, _ = emit(args.compiler, args.assembler, root, 'concat', - 'fn main() -> i64 {\n let a: text = "left";\n' - ' let b: text = "right";\n let joined: text = a + b;\n' - ' return 0;\n}\n') + concatenating) assert concat_imports <= concat, ( 'a concatenating program must still import the helper dependencies; ' f'missing: {sorted(concat_imports - concat)}') @@ -164,6 +205,29 @@ def main() -> int: f'unexpected: {sorted(concat - runtime_abi - concat_imports)}') checks += 1 + # The same program with no libc to call. Allocation is the one place + # generated code needs memory, and on a freestanding target it asks + # the runtime rather than the C library: the helper's three + # dependencies become runtime hooks, and no libc name may survive -- + # a freestanding consumer satisfying calloc at all is the reverse- + # engineered-shim problem this exists to remove. + free_concat, _ = emit(args.compiler, args.assembler, root, + 'free_concat', concatenating, freestanding=True) + assert freestanding_concat_imports <= free_concat, ( + 'a freestanding concatenating program must reach memory through the ' + 'runtime hooks; missing: ' + f'{sorted(freestanding_concat_imports - free_concat)}') + checks += 1 + assert not (free_concat & concat_imports), ( + 'a freestanding object must import no libc symbol at all; ' + f'present: {sorted(free_concat & concat_imports)}') + checks += 1 + assert free_concat <= runtime_abi | freestanding_concat_imports, ( + 'freestanding concatenation must not widen the import surface ' + 'further; unexpected: ' + f'{sorted(free_concat - runtime_abi - freestanding_concat_imports)}') + checks += 1 + # A hosted object is entered through the C runtime's main; a # freestanding one is entered through a named symbol instead, because # a target with no C runtime has nothing to call main for it and @@ -182,6 +246,63 @@ def main() -> int: f'unexpected: {sorted(free - runtime_abi)}') checks += 1 + # A symbol the consumer supplies. The declared name is the symbol, so + # it must appear in the import surface exactly as written and nothing + # else may arrive with it -- and a declaration nobody calls must add + # no import at all, or every consumer would owe a definition for a + # capability the program did not use. + host_symbol = 'anomalous_probe_emit' + declaration = ('module host_probe\n\n' + '@interop("host")\n' + f'fn {host_symbol}(message: text) -> i64\n' + 'end fn\n\n') + unused, _ = emit(args.compiler, args.assembler, root, 'host_unused', + declaration + 'fn main() -> i64 {\n return 0;\n}\n', + freestanding=True) + assert host_symbol not in unused, ( + 'a host symbol that is never called must not be imported; ' + f'imports: {sorted(unused)}') + checks += 1 + called, _ = emit(args.compiler, args.assembler, root, 'host_called', + declaration + 'fn main() -> i64 {\n' + ' let greeting: text = "from ny";\n' + f' return {host_symbol}(greeting);\n' + '}\n', + freestanding=True) + assert host_symbol in called, ( + 'a called host symbol must be imported under exactly its declared ' + f'name; imports: {sorted(called)}') + checks += 1 + assert called <= runtime_abi | {host_symbol}, ( + 'reaching a host symbol must not widen the import surface ' + f'further; unexpected: {sorted(called - runtime_abi - {host_symbol})}') + checks += 1 + assert not (called & concat_imports), ( + 'reaching a host symbol must not import a libc name; ' + f'present: {sorted(called & concat_imports)}') + checks += 1 + + # Where the object may be linked. The default small model puts every + # address in a 32-bit absolute relocation, which a consumer placing + # user code above 4 GiB cannot satisfy -- its link fails over the + # string constants of a program that never asked to be low. The large + # model removes them, and the first assertion keeps the second from + # passing because the program had no addresses to materialize. + emit(args.compiler, args.assembler, root, 'small', concatenating, + freestanding=True) + small_absolutes = absolute_relocation_count(root / 'small.o') + assert small_absolutes > 0, ( + 'the default code model is expected to use 32-bit absolute ' + 'relocations; this check would otherwise prove nothing') + checks += 1 + emit(args.compiler, args.assembler, root, 'large', concatenating, + freestanding=True, code_model='large') + large_absolutes = absolute_relocation_count(root / 'large.o') + assert large_absolutes == 0, ( + 'an object emitted for the large code model must have no 32-bit ' + f'absolute relocations; found {large_absolutes}') + checks += 1 + # The red zone is a separate decision from the entry shape: a target # whose interrupt entry switches stacks keeps it, a kernel-reentrant # one cannot. So it is its own option and is checked on its own.