Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ if(APPLE)
enable_language(OBJCXX)
endif()

# The native runtime ABI for targets with no operating system. Built for
# every host because the sources are portable; only its link test is ELF.
add_library(nilruntime_freestanding STATIC
nilruntime-freestanding/freestanding_runtime.cpp)
target_compile_features(nilruntime_freestanding PRIVATE cxx_std_17)
set_target_properties(nilruntime_freestanding PROPERTIES
CXX_EXTENSIONS OFF
POSITION_INDEPENDENT_CODE ON)
if(NOT MSVC)
# No hosted assumptions, no unwinder, no type information: a kernel or
# loader links this archive without providing any of them.
target_compile_options(nilruntime_freestanding PRIVATE
-ffreestanding -fno-exceptions -fno-rtti)
endif()

add_subdirectory(nilcompiler)
add_subdirectory(nilinterpreter)
add_subdirectory(nillsp)
Expand Down Expand Up @@ -695,6 +710,17 @@ if(BUILD_TESTING)
set_tests_properties(nil.native-symbol-surface PROPERTIES
LABELS "native;abi;rc" SKIP_RETURN_CODE 77 TIMEOUT 180)
endif()
# Prove the freestanding boundary closes: object plus runtime, linked
# with no C library and its own entry, actually runs.
if(NIL_ENABLE_LLVM AND NOT MSVC)
add_test(NAME nil.freestanding-runtime
COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/tools/freestanding_runtime_contract.py"
--compiler $<TARGET_FILE:nilcompiler> --assembler $<TARGET_FILE:nilassembler>
--archive $<TARGET_FILE:nilruntime_freestanding>
--cxx "${CMAKE_CXX_COMPILER}")
set_tests_properties(nil.freestanding-runtime PROPERTIES
LABELS "native;abi;runtime;rc" SKIP_RETURN_CODE 77 TIMEOUT 300)
endif()
add_test(NAME nil.ui-models
COMMAND $<TARGET_FILE:niltest> run
--compiler $<TARGET_FILE:nilcompiler> --interpreter $<TARGET_FILE:nilinterpreter>
Expand Down
42 changes: 40 additions & 2 deletions nilassembler/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,22 @@ struct command_line {
bool version = false;
bool unmanaged = false;
bool freestanding = false;
bool no_red_zone = false;
std::string emit_llvm;
bool embed_context = false;
};

void print_usage(std::ostream &stream) {
stream
<< "Usage: nilassembler [-o <output.o>] [--unmanaged] [--freestanding]"
" [--embed-context] <input.nil>\n"
" [--no-red-zone] [--emit-llvm <ir.ll>] [--embed-context] <input.nil>\n"
<< "\n"
<< "Options:\n"
<< " -o, --output <path> Write the host relocatable object to <path>\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"
<< " --emit-llvm <path> 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"
<< " -h, --help Show this help\n";
Expand All @@ -65,6 +69,8 @@ bool parse_command_line(int argc, char **argv, command_line &result,
bool output_seen = false;
bool unmanaged_seen = false;
bool freestanding_seen = false;
bool no_red_zone_seen = false;
bool emit_llvm_seen = false;
bool embed_context_seen = false;
for (int index = 1; index < argc; ++index) {
const std::string argument = argv[index];
Expand Down Expand Up @@ -106,6 +112,32 @@ bool parse_command_line(int argc, char **argv, command_line &result,
result.freestanding = true;
continue;
}
if (options && argument == "--no-red-zone") {
if (no_red_zone_seen) {
error = "the no-red-zone option was provided more than once";
return false;
}
no_red_zone_seen = true;
result.no_red_zone = true;
continue;
}
if (options && argument == "--emit-llvm") {
if (emit_llvm_seen) {
error = "the emit-llvm option was provided more than once";
return false;
}
if (++index >= argc) {
error = "missing IR path after " + argument;
return false;
}
result.emit_llvm = argv[index];
if (result.emit_llvm.empty()) {
error = "the IR path must not be empty";
return false;
}
emit_llvm_seen = true;
continue;
}
if (options && argument == "--embed-context") {
if (embed_context_seen) {
error = "the embed-context option was provided more than once";
Expand Down Expand Up @@ -145,7 +177,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 || embed_context_seen ||
freestanding_seen || no_red_zone_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;
Expand Down Expand Up @@ -415,6 +448,7 @@ int run_assembler(const command_line &arguments) {
native.setMemoryMode(arguments.unmanaged ? ny::MemoryMode::UNSAFE_MANUAL
: ny::MemoryMode::SAFE_GC);
native.setFreestandingEntry(arguments.freestanding);
native.setDisableRedZone(arguments.no_red_zone);
native.setEmbedContext(arguments.embed_context);
if (!native.initialize()) {
std::cerr << "nilassembler: failed to initialize the LLVM target\n";
Expand All @@ -424,6 +458,10 @@ int run_assembler(const command_line &arguments) {
std::cerr << "nilassembler: native lowering failed\n";
return 1;
}
if (!arguments.emit_llvm.empty() && !native.emitLlvmIr(arguments.emit_llvm)) {
std::cerr << "nilassembler: could not write LLVM IR\n";
return 1;
}
if (!native.emitObjectFile(workspace->object().string())) {
std::cerr << "nilassembler: object emission failed\n";
return 1;
Expand Down
29 changes: 29 additions & 0 deletions nilcompiler/src/llvm_backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1196,6 +1196,7 @@ struct NativeCodegen::Impl {
MemoryMode memory_mode = MemoryMode::UNSAFE_MANUAL;
bool embed_context = false;
bool freestanding_entry = false;
bool disable_red_zone = false;
llvm::Function *current_function = nullptr;

// State matching generateModule usage
Expand Down Expand Up @@ -1373,6 +1374,27 @@ void NativeCodegen::setFreestandingEntry(bool enabled) {
impl_->freestanding_entry = enabled;
}

void NativeCodegen::setDisableRedZone(bool enabled) {
impl_->disable_red_zone = enabled;
}

bool NativeCodegen::emitLlvmIr(const std::string &path) {
if (!impl_->module) {
std::cerr << "[NativeCodegen] no module to write\n";
return false;
}
std::error_code code;
llvm::raw_fd_ostream out(path, code, llvm::sys::fs::OF_Text);
if (code) {
std::cerr << "[NativeCodegen] could not write LLVM IR: " << code.message()
<< '\n';
return false;
}
impl_->module->print(out, nullptr);
out.flush();
return !out.has_error();
}

bool NativeCodegen::initialize() {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
Expand Down Expand Up @@ -9007,6 +9029,13 @@ bool NativeCodegen::generateModule(const nil_module &mod) {
llvm::appendToUsed(*impl_->module, {manifest});
}

if (impl_->disable_red_zone) {
for (auto &function : *impl_->module) {
if (function.isDeclaration()) continue;
function.addFnAttr(llvm::Attribute::NoRedZone);
}
}

std::string err;
llvm::raw_string_ostream err_s(err);
if (llvm::verifyModule(*impl_->module, &err_s)) {
Expand Down
11 changes: 11 additions & 0 deletions nilcompiler/src/llvm_backend.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,17 @@ class NativeCodegen {
// initialisation, user main, context end -- is unchanged.
void setFreestandingEntry(bool enabled);

// Mark every generated definition `noredzone`, so no leaf function uses
// the 128 bytes below the stack pointer. A kernel or interrupt-reentrant
// target needs that; a user-space target whose interrupt entry switches
// stacks does not, so this stays independent of the freestanding entry
// rather than being implied by it.
void setDisableRedZone(bool enabled);

// Write the generated LLVM IR, so what the backend produced can be
// inspected and asserted rather than inferred from an object.
bool emitLlvmIr(const std::string &path);

// 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);
Expand Down
78 changes: 78 additions & 0 deletions nilruntime-freestanding/freestanding_runtime.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright (C) 2008 - 2026 Execute Software. All rights reserved.
* SPDX-License-Identifier: MIT
*/
// 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.
//
// 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.
//
// pinned: this file must not gain an #include of a hosted header. The
// freestanding link test asserts the resulting archive imports nothing.
#include <cstdint>

namespace {

// Recorded for a host that wants them; nothing here interprets them.
int entry_argc = 0;
const char *const *entry_argv = nullptr;
bool context_active = false;

} // 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;

// Must equal the version the generated entry checks for; a mismatch makes the
// entry call nyrt_fail before running any user code.
std::uint32_t nyrt_abi_version() noexcept { return 1; }

void nyrt_context_begin(int argc, const char *const *argv) noexcept {
entry_argc = argc;
entry_argv = argv;
context_active = true;
}

void nyrt_context_end() noexcept {
context_active = false;
entry_argc = 0;
entry_argv = nullptr;
}

// Profiling attribution is a hosted capture facility. Accepting and ignoring
// the call keeps generated code identical across hosted and freestanding
// builds, which is the point of the boundary.
void nyrt_profile_site(const char *file, const char *function,
std::uint64_t line) noexcept {
(void)file;
(void)function;
(void)line;
}

[[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.
for (;;) {
}
}

// 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; }

} // extern "C"
Loading
Loading