From 4a0c19f7ef6488278b69cc4ed1fe335460740a92 Mon Sep 17 00:00:00 2001 From: Nathan Young Date: Mon, 9 Nov 2026 00:30:40 -0500 Subject: [PATCH] Give freestanding targets a named entry instead of a C main wrapper Anomalous ADR 0049 bridges the generated entry with "a separate narrow assembly shim [that] calls the generated C wrapper with zero arguments and implements only its observed ABI-version, context-begin, context-end and failure hooks". The shape was observed because nothing published one: the entry was always the hosted C `main(int, char **)`, so a target with no C runtime had to recognise a wrapper and invent an argument vector for it. nilassembler --freestanding emits the same entry sequence -- runtime ABI check, context begin, global initialisation, user main, context end -- as `__ny_entry()`, taking no arguments and defining no `main`. Nothing about the sequence changes; only the symbol a caller needs to know and the arguments it no longer has to fabricate. The argc/argv derivation is skipped rather than fed zeroes, so a freestanding object carries no argument-vector code at all. nil.native-symbol-surface now pins both shapes: a hosted object is entered through main, a freestanding one through __ny_entry with no main, and neither widens the import surface beyond the five runtime hooks. Linux: 573 registered, 0 failed, 3 environment skips. Co-Authored-By: Claude Opus 5 --- nilassembler/main.cpp | 18 +++++++- nilcompiler/src/llvm_backend.cpp | 64 ++++++++++++++++++---------- nilcompiler/src/llvm_backend.hpp | 8 ++++ tests/tools/native_symbol_surface.py | 45 +++++++++++++++---- 4 files changed, 102 insertions(+), 33 deletions(-) diff --git a/nilassembler/main.cpp b/nilassembler/main.cpp index 5e4d42d7..88e871d0 100644 --- a/nilassembler/main.cpp +++ b/nilassembler/main.cpp @@ -41,16 +41,19 @@ struct command_line { bool help = false; bool version = false; bool unmanaged = false; + bool freestanding = false; bool embed_context = false; }; void print_usage(std::ostream &stream) { stream - << "Usage: nilassembler [-o ] [--unmanaged] [--embed-context] \n" + << "Usage: nilassembler [-o ] [--unmanaged] [--freestanding]" + " [--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" << " --embed-context Retain AI annotations in x86_64 ELF/COFF or x86_64/arm64 Mach-O objects\n" << " --version Show the nilassembler version\n" << " -h, --help Show this help\n"; @@ -61,6 +64,7 @@ bool parse_command_line(int argc, char **argv, command_line &result, bool options = true; bool output_seen = false; bool unmanaged_seen = false; + bool freestanding_seen = false; bool embed_context_seen = false; for (int index = 1; index < argc; ++index) { const std::string argument = argv[index]; @@ -93,6 +97,15 @@ bool parse_command_line(int argc, char **argv, command_line &result, result.unmanaged = true; continue; } + if (options && argument == "--freestanding") { + if (freestanding_seen) { + error = "the freestanding option was provided more than once"; + return false; + } + freestanding_seen = true; + result.freestanding = true; + continue; + } if (options && argument == "--embed-context") { if (embed_context_seen) { error = "the embed-context option was provided more than once"; @@ -132,7 +145,7 @@ bool parse_command_line(int argc, char **argv, command_line &result, if (result.help || result.version) { if (!result.input.empty() || output_seen || unmanaged_seen || - embed_context_seen || + freestanding_seen || embed_context_seen || (result.help && result.version)) { error = "--help and --version must be used without input or output paths"; return false; @@ -401,6 +414,7 @@ int run_assembler(const command_line &arguments) { ny::NativeCodegen native; native.setMemoryMode(arguments.unmanaged ? ny::MemoryMode::UNSAFE_MANUAL : ny::MemoryMode::SAFE_GC); + native.setFreestandingEntry(arguments.freestanding); 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 523621fc..9384836b 100644 --- a/nilcompiler/src/llvm_backend.cpp +++ b/nilcompiler/src/llvm_backend.cpp @@ -1195,6 +1195,7 @@ struct NativeCodegen::Impl { MemoryMode memory_mode = MemoryMode::UNSAFE_MANUAL; bool embed_context = false; + bool freestanding_entry = false; llvm::Function *current_function = nullptr; // State matching generateModule usage @@ -1368,6 +1369,10 @@ void NativeCodegen::setEmbedContext(bool enabled) { impl_->embed_context = enabled; } +void NativeCodegen::setFreestandingEntry(bool enabled) { + impl_->freestanding_entry = enabled; +} + bool NativeCodegen::initialize() { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); @@ -8818,32 +8823,47 @@ bool NativeCodegen::generateModule(const nil_module &mod) { auto *i32_type = llvm::Type::getInt32Ty(ctx); auto *opaque_pointer_type = llvm::PointerType::getUnqual(ctx); + const bool freestanding = impl_->freestanding_entry; + // Freestanding callers have no argument vector to pass and no C runtime to + // name the entry for them, so the entry takes none and is called + // `__ny_entry`. Everything after this point is the same sequence. auto *platform_main_type = - llvm::FunctionType::get(i32_type, {i32_type, opaque_pointer_type}, false); - auto *platform_main = llvm::Function::Create(platform_main_type, - llvm::Function::ExternalLinkage, - "main", *impl_->module); - auto argument = platform_main->arg_begin(); - llvm::Value *argc_value = &*argument++; - llvm::Value *argv_value = &*argument; - argc_value->setName("argc"); - argv_value->setName("argv"); - - auto *entry = llvm::BasicBlock::Create(ctx, "entry", platform_main); - impl_->builder->SetInsertPoint(entry); + freestanding + ? llvm::FunctionType::get(i32_type, {}, false) + : llvm::FunctionType::get(i32_type, {i32_type, opaque_pointer_type}, + false); + auto *platform_main = llvm::Function::Create( + platform_main_type, llvm::Function::ExternalLinkage, + freestanding ? "__ny_entry" : "main", *impl_->module); auto *zero = llvm::ConstantInt::get(i32_type, 0); auto *one = llvm::ConstantInt::get(i32_type, 1); auto *null_argv = llvm::ConstantPointerNull::get(opaque_pointer_type); - auto *has_program_name = impl_->builder->CreateAnd( - impl_->builder->CreateICmpSGT(argc_value, zero), - impl_->builder->CreateICmpNE(argv_value, null_argv)); - auto *program_argc = impl_->builder->CreateSelect( - has_program_name, impl_->builder->CreateSub(argc_value, one), zero, - "ny.argc"); - auto *argv_after_program_name = impl_->builder->CreateGEP( - opaque_pointer_type, argv_value, one, "ny.argv.after_program_name"); - auto *program_argv = impl_->builder->CreateSelect( - has_program_name, argv_after_program_name, null_argv, "ny.argv"); + llvm::Value *argc_value = zero; + llvm::Value *argv_value = null_argv; + if (!freestanding) { + auto argument = platform_main->arg_begin(); + argc_value = &*argument++; + argv_value = &*argument; + argc_value->setName("argc"); + argv_value->setName("argv"); + } + + auto *entry = llvm::BasicBlock::Create(ctx, "entry", platform_main); + impl_->builder->SetInsertPoint(entry); + llvm::Value *program_argc = zero; + llvm::Value *program_argv = null_argv; + if (!freestanding) { + auto *has_program_name = impl_->builder->CreateAnd( + impl_->builder->CreateICmpSGT(argc_value, zero), + impl_->builder->CreateICmpNE(argv_value, null_argv)); + program_argc = impl_->builder->CreateSelect( + has_program_name, impl_->builder->CreateSub(argc_value, one), zero, + "ny.argc"); + auto *argv_after_program_name = impl_->builder->CreateGEP( + opaque_pointer_type, argv_value, one, "ny.argv.after_program_name"); + program_argv = impl_->builder->CreateSelect( + has_program_name, argv_after_program_name, null_argv, "ny.argv"); + } auto begin_context = impl_->module->getOrInsertFunction( "nyrt_context_begin", diff --git a/nilcompiler/src/llvm_backend.hpp b/nilcompiler/src/llvm_backend.hpp index e3fdc2ee..f6496aa9 100644 --- a/nilcompiler/src/llvm_backend.hpp +++ b/nilcompiler/src/llvm_backend.hpp @@ -48,6 +48,14 @@ class NativeCodegen { void setMemoryMode(MemoryMode mode); MemoryMode getMemoryMode() const; + // Emit the entry sequence under the documented freestanding symbol + // `__ny_entry`, with no arguments, instead of the hosted C `main(int, + // char **)`. A target without a C runtime then has one named entry to call + // rather than a wrapper it has to recognise and feed argc/argv. The + // sequence itself -- runtime ABI check, context begin, global + // initialisation, user main, context end -- is unchanged. + void setFreestandingEntry(bool enabled); + // Opt in to a retained, read-only context manifest on supported native // targets. Annotation contents are embedded verbatim; the default is off. void setEmbedContext(bool enabled); diff --git a/tests/tools/native_symbol_surface.py b/tests/tools/native_symbol_surface.py index dc4187f3..2dfccfb1 100644 --- a/tests/tools/native_symbol_surface.py +++ b/tests/tools/native_symbol_surface.py @@ -61,6 +61,7 @@ def text(table_offset: int, index: int) -> str: return data[table_offset + index:end].decode('utf-8', 'replace') undefined: set[str] = set() + exported: set[str] = set() for index in range(section_count): header = section(index) if text(names['offset'], header['name']) != '.symtab': @@ -70,20 +71,28 @@ def text(table_offset: int, index: int) -> str: 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('> 4 == 1: # STB_GLOBAL and defined here + exported.add(name) + return undefined, exported -def emit(compiler: Path, assembler: Path, root: Path, name: str, source: str) -> set[str]: +def emit(compiler: Path, assembler: Path, root: Path, name: str, source: str, + freestanding: bool = False): path = root / f'{name}.ny' path.write_text(source, newline='\n') nil = root / f'{name}.nil' obj = root / f'{name}.o' + assemble = [assembler, '--unmanaged'] + if freestanding: + assemble.append('--freestanding') for command in ([compiler, '--no-stdlib', '--no-bundle', '--unmanaged', '-o', nil, path], - [assembler, '--unmanaged', '-o', obj, nil]): + assemble + ['-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) @@ -102,8 +111,8 @@ def main() -> int: 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') + trivial = 'fn main() -> i64 {\n let total: i64 = 0;\n return total;\n}\n' + plain, plain_exports = emit(args.compiler, args.assembler, root, 'plain', trivial) assert plain <= runtime_abi, ( 'an object that uses no hosted facility imports only the native runtime ABI; ' f'unexpected: {sorted(plain - runtime_abi)}') @@ -115,7 +124,7 @@ def main() -> int: # 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', + 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') @@ -128,6 +137,24 @@ def main() -> int: f'unexpected: {sorted(concat - runtime_abi - 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 + # should not have to recognise a wrapper by its shape. + assert 'main' in plain_exports and '__ny_entry' not in plain_exports, ( + f'a hosted object is entered through main; exports: {sorted(plain_exports)}') + checks += 1 + free, free_exports = emit(args.compiler, args.assembler, root, 'free', + trivial, freestanding=True) + assert '__ny_entry' in free_exports and 'main' not in free_exports, ( + 'a freestanding object is entered through __ny_entry and defines no C main; ' + f'exports: {sorted(free_exports)}') + checks += 1 + assert free <= runtime_abi, ( + 'the freestanding entry must not widen the import surface; ' + f'unexpected: {sorted(free - runtime_abi)}') + checks += 1 + print(f'Native symbol surface: {checks} checks passed') return 0