From b2118cec0a87651ebcb759d8147ba6dc5b8c79c5 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Mon, 9 Nov 2026 00:21:43 -0500 Subject: [PATCH] Emit the string helper on demand and pin the import surface Targeting the Anomalous rite ABI starts with what a native object requires, because a freestanding consumer has to supply every undefined symbol deliberately. Anomalous ADR 0049 records the current cost: the compiler's "unconditional unused string helper imports strlen, calloc, and memcpy", and the fixture satisfies them with fatal trap stubs that fail the proof if reached. They were unconditional because __ny_string_concat was built into every module while its only caller looked it up on demand. The helper is now built on first use, like the runtime failure function beside it. An object for a program that concatenates nothing imports exactly the five native runtime hooks -- nyrt_abi_version, nyrt_context_begin, nyrt_context_end, nyrt_fail and nyrt_profile_site -- and no libc at all, which is the ABI Anomalous reverse-engineered rather than was given. nil.native-symbol-surface pins that boundary by reading the ELF symbol table directly, so it does not depend on binutils. It also compiles a program that does concatenate and requires the helper's dependencies to come back, because otherwise the first assertion would pass just as well if the helper had been dropped entirely. Linux: 573 registered, 0 failed, 3 environment skips. The test is ELF only and skips elsewhere; it is gated on the native backend. Co-Authored-By: Claude Opus 5 --- CMakeLists.txt | 10 ++ nilcompiler/src/llvm_backend.cpp | 15 ++- tests/tools/native_symbol_surface.py | 136 +++++++++++++++++++++++++++ 3 files changed, 158 insertions(+), 3 deletions(-) create mode 100644 tests/tools/native_symbol_surface.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 9c4ca481..509af34f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -685,6 +685,16 @@ if(BUILD_TESTING) if(NIL_ENABLE_LLVM) set(NIL_UI_TEST_ROUTES all) endif() + # What a native object is allowed to import. A freestanding or kernel + # consumer has to supply every undefined symbol deliberately, so this + # boundary widens only on purpose. + if(NIL_ENABLE_LLVM) + add_test(NAME nil.native-symbol-surface + COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/native_symbol_surface.py" + --compiler $ --assembler $) + set_tests_properties(nil.native-symbol-surface PROPERTIES + LABELS "native;abi;rc" SKIP_RETURN_CODE 77 TIMEOUT 180) + endif() add_test(NAME nil.ui-models COMMAND $ run --compiler $ --interpreter $ diff --git a/nilcompiler/src/llvm_backend.cpp b/nilcompiler/src/llvm_backend.cpp index 5a2aae9a..523621fc 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -1548,7 +1548,15 @@ 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. + auto get_string_concat_function = [&]() -> llvm::Function * { + if (auto *existing = impl_->module->getFunction("__ny_string_concat")) + return existing; llvm::FunctionType *concat_type = llvm::FunctionType::get( llvm::PointerType::getUnqual(ctx), {llvm::PointerType::getUnqual(ctx), llvm::PointerType::getUnqual(ctx)}, @@ -1672,7 +1680,8 @@ bool NativeCodegen::generateModule(const nil_module &mod) { if (saved_ip) impl_->builder->SetInsertPoint(saved_ip); - } + return concat_fn; + }; auto coerce_to_native_size = [&](llvm::Value *value) -> llvm::Value * { if (!value || !value->getType()->isIntegerTy()) @@ -8319,7 +8328,7 @@ bool NativeCodegen::generateModule(const nil_module &mod) { << fn.name << "'\n"; return false; } - auto *concat = impl_->module->getFunction("__ny_string_concat"); + auto *concat = get_string_concat_function(); if (!concat) { std::cerr << "[NativeCodegen] internal string concat helper is " "missing in function '" diff --git a/tests/tools/native_symbol_surface.py b/tests/tools/native_symbol_surface.py new file mode 100644 index 00000000..dc4187f3 --- /dev/null +++ b/tests/tools/native_symbol_surface.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Pin what a native object imports. + +A relocatable object emitted for a program that uses no hosted facility must +import the native runtime ABI and nothing else. A freestanding or kernel +target supplies those hooks deliberately; anything beyond them it has to +satisfy with stubs it should never need, and a libc symbol arriving by +accident is exactly the kind of drift that is invisible on a hosted host. + +The ELF symbol table is read directly rather than shelling out to nm, so the +contract does not depend on binutils being installed. +""" +from __future__ import annotations + +import argparse +from pathlib import Path +import struct +import subprocess +import sys +import tempfile + +# The native runtime ABI an emitted object is allowed to require. Adding a +# name here widens the boundary every freestanding consumer must implement, +# so it is a deliberate decision rather than a test fixup. +runtime_abi = { + 'nyrt_abi_version', + 'nyrt_context_begin', + 'nyrt_context_end', + 'nyrt_fail', + 'nyrt_profile_site', +} + +# Emitted only for the string-concatenation helper. Their presence in a +# program that concatenates proves the helper is still generated; their +# absence elsewhere proves it is generated on demand. +concat_imports = {'strlen', 'memcpy', 'calloc'} + + +def undefined_symbols(path: Path) -> set[str]: + data = path.read_bytes() + if data[:4] != b'\x7fELF': + raise SystemExit(f'not an ELF object: {path}') + if data[4] != 2 or data[5] != 1: + raise SystemExit('expected a little-endian 64-bit object') + section_offset, = struct.unpack_from(' str: + end = data.index(b'\0', table_offset + index) + return data[table_offset + index:end].decode('utf-8', 'replace') + + undefined: set[str] = set() + for index in range(section_count): + header = section(index) + if text(names['offset'], header['name']) != '.symtab': + continue + strings = section(header['link']) + if not header['entry_size']: + raise SystemExit('symbol table has no entry size') + for position in range(header['offset'], header['offset'] + header['size'], + header['entry_size']): + name_index, _info, _other, shndx = struct.unpack_from(' set[str]: + path = root / f'{name}.ny' + path.write_text(source, newline='\n') + nil = root / f'{name}.nil' + obj = root / f'{name}.o' + for command in ([compiler, '--no-stdlib', '--no-bundle', '--unmanaged', '-o', nil, path], + [assembler, '--unmanaged', '-o', obj, nil]): + result = subprocess.run(list(map(str, command)), stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=120) + assert result.returncode == 0, (command, result.returncode, result.stdout, result.stderr) + return undefined_symbols(obj) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--compiler', type=Path, required=True) + parser.add_argument('--assembler', type=Path, required=True) + args = parser.parse_args() + if sys.platform != 'linux': + print('SKIP: the native symbol surface is pinned on ELF hosts') + return 77 + + checks = 0 + with tempfile.TemporaryDirectory(prefix='nil-symbol-surface-') as directory: + root = Path(directory) + plain = emit(args.compiler, args.assembler, root, 'plain', + 'fn main() -> i64 {\n let total: i64 = 0;\n return total;\n}\n') + assert plain <= runtime_abi, ( + 'an object that uses no hosted facility imports only the native runtime ABI; ' + f'unexpected: {sorted(plain - runtime_abi)}') + checks += 1 + assert not (plain & concat_imports), ( + 'the string concatenation helper must be emitted on demand, not in every object; ' + f'present: {sorted(plain & concat_imports)}') + checks += 1 + + # The helper still has to exist when a program actually concatenates, + # or the first assertion would pass for the wrong reason. + 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') + assert concat_imports <= concat, ( + 'a concatenating program must still import the helper dependencies; ' + f'missing: {sorted(concat_imports - concat)}') + checks += 1 + assert concat <= runtime_abi | concat_imports, ( + 'concatenation must not widen the import surface further; ' + f'unexpected: {sorted(concat - runtime_abi - concat_imports)}') + checks += 1 + + print(f'Native symbol surface: {checks} checks passed') + return 0 + + +if __name__ == '__main__': + raise SystemExit(main())