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
33 changes: 29 additions & 4 deletions docs/advanced/freestanding-targets.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,26 @@ 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.

One more, **only if the program compares text**:

```c
int32_t nyrt_str_compare(const char *left, const char *right);
```

This replaces `strcmp`. Only the sign of the result is defined: generated code
compares it against zero and reads nothing else into it. The order is
unsigned-byte lexicographic, which is what a text comparison in Ny means by
it, and native text is NUL-free so the order matches the interpreter's.

A null is not a text value. Rather than read through one, the shipped runtime
orders a null before any non-null and calls two nulls equal, which keeps the
comparison total for inputs generated code should never produce.

Comparison needs no allocation, so a program may import this without the three
names above. Each of the four conditional hooks is required only by the
construct that uses it, so the import surface states what the program does
rather than what the language can do.

## Reaching a symbol the host supplies

A freestanding consumer's own call boundary — its system calls, its trap or
Expand Down Expand Up @@ -247,16 +267,21 @@ and the toolchain disagree.
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.
that a comparing one adds exactly `nyrt_str_compare` where a hosted object
reaches `strcmp`, 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.
through `nyrt_fail` with a message instead of continuing. For comparison it
checks the answers rather than the link: a comparison that collapsed
everything to equal would link and satisfy any symbol check, so the program
distinguishes unequal from equal and requires `"beta"` to order after
`"alpha"`.

## What this does not provide

Expand Down
50 changes: 33 additions & 17 deletions nilcompiler/src/llvm_backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,17 @@ static std::string compact_nil_type(std::string type) {
return type;
}

// The symbol a text comparison must call on this target. Generated code
// compares text by ordering bytes, which libc spells strcmp; a freestanding
// object has no libc, so on that target the comparison reaches the native
// runtime instead. This is the same division the concatenation helper already
// makes for length and copy, and it is the whole reason an object emitted with
// --freestanding could not compare text until now: it emitted a call to a
// symbol its own import surface forbids.
static const char *text_compare_symbol(bool freestanding) {
return freestanding ? "nyrt_str_compare" : "strcmp";
}

static std::string normalize_nil_type(std::string type) {
type = compact_nil_type(std::move(type));
std::transform(type.begin(), type.end(), type.begin(), [](unsigned char ch) {
Expand Down Expand Up @@ -6553,19 +6564,20 @@ bool NativeCodegen::generateModule(const nil_module &mod) {
llvm::Value *actual_str = impl_->builder->CreateLoad(
llvm::PointerType::getUnqual(ctx), tag_ptr);

// Compare strings (pointer comparison might work if constants are
// unique, but better use strcmp) For now, use strcmp
auto strcmp_type =
// Compared by bytes rather than by pointer: equal constants are not
// required to be the same object, and only the sign of the result is
// read below.
auto text_compare_type =
llvm::FunctionType::get(llvm::Type::getInt32Ty(ctx),
{llvm::PointerType::getUnqual(ctx),
llvm::PointerType::getUnqual(ctx)},
false);
auto strcmp_fn =
impl_->module->getOrInsertFunction("strcmp", strcmp_type);
auto text_compare_fn = impl_->module->getOrInsertFunction(
text_compare_symbol(impl_->freestanding_entry), text_compare_type);

std::vector<llvm::Value *> strcmp_args = {actual_str, expected_str};
std::vector<llvm::Value *> text_compare_args = {actual_str, expected_str};
auto res = impl_->builder->CreateCall(
strcmp_type, strcmp_fn.getCallee(), strcmp_args);
text_compare_type, text_compare_fn.getCallee(), text_compare_args);
auto is_eq = impl_->builder->CreateICmpEQ(
res, llvm::ConstantInt::get(llvm::Type::getInt32Ty(ctx), 0));

Expand Down Expand Up @@ -6689,15 +6701,15 @@ bool NativeCodegen::generateModule(const nil_module &mod) {
impl_->builder->CreateICmpEQ(
last_colon, llvm::ConstantPointerNull::get(pointer_type)),
actual_tag, after_colon);
auto *strcmp_type = llvm::FunctionType::get(
auto *text_compare_type = llvm::FunctionType::get(
llvm::Type::getInt32Ty(ctx), {pointer_type, pointer_type}, false);
auto strcmp_function =
impl_->module->getOrInsertFunction("strcmp", strcmp_type);
auto text_compare_fn = impl_->module->getOrInsertFunction(
text_compare_symbol(impl_->freestanding_entry), text_compare_type);
llvm::Value *matching_tag =
llvm::ConstantInt::getFalse(ctx);
for (const auto &variant : allowed_variants) {
auto *comparison = impl_->builder->CreateCall(
strcmp_type, strcmp_function.getCallee(),
text_compare_type, text_compare_fn.getCallee(),
{variant_tag, impl_->builder->CreateGlobalString(variant)});
matching_tag = impl_->builder->CreateOr(
matching_tag, impl_->builder->CreateICmpEQ(
Expand Down Expand Up @@ -8074,17 +8086,20 @@ bool NativeCodegen::generateModule(const nil_module &mod) {
<< fn.name << "'\n";
return false;
}
// Native text is NUL-free. strcmp therefore matches the VM's
// unsigned-byte lexicographic string order. Only its sign matters;
// Native text is NUL-free, so an unsigned-byte comparison matches
// the VM's lexicographic string order. Only its sign matters;
// neither pointer addresses nor a presumed -1/+1 result define it.
auto *strcmp_type = llvm::FunctionType::get(
// The symbol differs by target: a freestanding object reaches the
// native runtime, because it has no libc and its import surface
// admits no libc name.
auto *text_compare_type = llvm::FunctionType::get(
llvm::Type::getInt32Ty(ctx),
{llvm::PointerType::getUnqual(ctx),
llvm::PointerType::getUnqual(ctx)}, false);
auto strcmp_fn =
impl_->module->getOrInsertFunction("strcmp", strcmp_type);
auto text_compare_fn = impl_->module->getOrInsertFunction(
text_compare_symbol(impl_->freestanding_entry), text_compare_type);
lhs = impl_->builder->CreateCall(
strcmp_type, strcmp_fn.getCallee(), {lhs, rhs});
text_compare_type, text_compare_fn.getCallee(), {lhs, rhs});
rhs = llvm::ConstantInt::get(ctx, llvm::APInt(32, 0));
} else {
raw_pointer_comparison =
Expand Down Expand Up @@ -9356,6 +9371,7 @@ int NativeCodegen::executeJIT(const std::vector<std::string> &program_args) {
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_str_compare", &nyrt_str_compare);
expose_runtime_symbol("nyrt_arg_count", &nyrt_arg_count);
expose_runtime_symbol("nyrt_arg", &nyrt_arg);
expose_runtime_symbol("nyrt_exit", &nyrt_exit);
Expand Down
14 changes: 14 additions & 0 deletions nilcompiler/src/native_runtime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1043,6 +1043,20 @@ std::uint64_t nyrt_str_length(const char *text) noexcept {
return static_cast<std::uint64_t>(std::strlen(text));
}

std::int32_t nyrt_str_compare(const char *left, const char *right) noexcept {
if (left == nullptr || right == nullptr) {
if (left == right)
return 0;
return left != nullptr ? 1 : -1;
}
const int ordering = std::strcmp(left, right);
// Only the sign is part of the contract, so it is normalized here rather
// than passing libc's magnitude through as if it meant something.
if (ordering == 0)
return 0;
return ordering < 0 ? -1 : 1;
}

std::int32_t nyrt_free(void *pointer) noexcept {
if (pointer == nullptr)
return 1;
Expand Down
1 change: 1 addition & 0 deletions nilcompiler/src/native_runtime.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ std::int32_t nyrt_free(void *pointer) noexcept;
void *nyrt_mem_copy(void *destination, const void *source,
std::uint64_t size) noexcept;
std::uint64_t nyrt_str_length(const char *text) noexcept;
std::int32_t nyrt_str_compare(const char *left, const char *right) noexcept;

// Each address names an initialized, live eight-byte word. Frames are LIFO
// and remain registered until the generated function returns. This internal
Expand Down
28 changes: 26 additions & 2 deletions nilruntime-freestanding/freestanding_runtime.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
// 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
// nyrt_mem_copy and nyrt_str_length, and nyrt_str_compare only if it compares
// text. 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.
//
Expand Down Expand Up @@ -172,6 +172,30 @@ std::uint64_t nyrt_str_length(const char *text) noexcept {
return length;
}

// Unsigned-byte lexicographic order, which is what a text comparison in
// generated code means by it, and only the sign is defined -- the caller
// compares the result against zero and nothing else. Supplied here for the
// same reason as the two above: a freestanding object has no strcmp to call,
// and until it had this it could not compare text at all.
//
// A null is not a text value, so rather than read through one this orders a
// null before any non-null and calls two nulls equal, leaving the comparison
// total for inputs generated code should never produce.
std::int32_t nyrt_str_compare(const char *left, const char *right) noexcept {
const auto *first = reinterpret_cast<const unsigned char *>(left);
const auto *second = reinterpret_cast<const unsigned char *>(right);
if (!first || !second) {
if (first == second) return 0;
return first ? 1 : -1;
}
while (*first != '\0' && *first == *second) {
++first;
++second;
}
if (*first == *second) return 0;
return *first < *second ? -1 : 1;
}

// 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; }
Expand Down
73 changes: 68 additions & 5 deletions notebook/2026-11-09-anomalous-abi.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,73 @@ real drift.
reason they needed a reverse-engineered shim, trap stubs for libc imports
they never wanted, and an allocator they would have had to implement.

## Text comparison had the same defect as concatenation (second pass)

Found from the consumer side, which is the only place it could have been
found: Anomalous wanted a vessel to recognise a word in a line the kernel
delivered, and `==` on text turned out to be unusable in a freestanding
object. The object emitted a call to `strcmp`.

That is exactly the defect the concatenation helper had before this branch --
it imported `strlen`, `memcpy` and `calloc` unconditionally -- in a different
operation. The allocation path was routed through the runtime and the
comparison path was not, so a freestanding object could allocate but could not
compare, and the failure was not a diagnostic: it was a libc import that a
consumer's own symbol check rejects at link time, which is a long way from
where the mistake is.

Three sites in `llvm_backend.cpp` emitted `strcmp` -- the text comparison
operators, a variant tag against one expected string, and a variant tag
against an allowed set. All three now go through one function that names the
symbol per target, which is the same shape the concatenation helper already
used for length and copy. A fourth site would have been missed by any fix that
patched the operators alone, which is why the name is chosen in one place
rather than at each call.

The hook is `nyrt_str_compare`, and the contract is narrower than `strcmp`'s:
only the sign is defined, because that is all generated code reads. Native
text is NUL-free, so unsigned-byte order matches the interpreter's. A null is
not a text value, and the shipped runtime orders a null before any non-null
rather than reading through one -- total for inputs generated code should
never produce. It is defined in the hosted runtime too, for the same reason
the other two were: otherwise an object emitted with `--freestanding` could
only ever link against the freestanding archive.

Comparison allocates nothing, so this is a fourth *conditional* hook rather
than a fourth allocation hook: five always, three if the program allocates,
one if it compares text. Each is required only by the construct that uses it,
so the import surface still states what a program does rather than what the
language can do.

Measured, not asserted. The same source, emitted both ways:

hosted: nyrt_abi_version nyrt_context_begin nyrt_context_end
nyrt_fail nyrt_profile_site probe_mode strcmp
freestanding: nyrt_abi_version nyrt_context_begin nyrt_context_end
nyrt_fail nyrt_profile_site nyrt_str_compare probe_mode

And linked against the archive and run, because an import list cannot show
that the answers are right -- a comparison that said "equal" to everything
would link and pass any symbol check. A program comparing `"alpha"`,
`"beta"` and a second `"alpha"` returns 7, so equality, inequality and
ordering all hold.

`nil.native-symbol-surface` is now 23 checks and `nil.freestanding-runtime`
is 14. The new ones pin which symbol each target reaches for, that no libc
name survives a freestanding comparison, and the three answers above.

**What this does not do:** Anomalous cannot use it until a generation carrying
it is built and that repository re-pins. Its vessel selects its failing run
through a cell the host writes, which is a workaround for this defect, and it
can be simplified once the pin moves. Re-pinning is a deliberate act there --
the pin is the evidence for a qualification -- so it is not done here.

## Branch state

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
`macos-ui-acceptance-record` redundant.
The first pass was `anomalous-abi-symbol-surface`, merged as pull request #36.
It also carried `72c9547`, the macOS desktop acceptance record, because the
branch was cut from `macos-ui-acceptance-record` before that merged, which
made `macos-ui-acceptance-record` redundant.

The comparison fix above is on `freestanding-text-compare`, cut from `master`
after that merge.
49 changes: 49 additions & 0 deletions tests/tools/freestanding_runtime_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@
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.

Comparison is checked by its answers rather than by its link. A freestanding
object has no strcmp, so a text comparison reaches the runtime instead; a
version of that which collapsed every comparison to "equal" would link and
pass any symbol check, so the program here distinguishes unequal from equal
and checks that "beta" orders after "alpha".
"""
from __future__ import annotations

Expand Down Expand Up @@ -85,6 +91,28 @@
'}\n'
)

# Distinct from every other exit, so a wrong ordering names itself.
unequal_text_exit = 81
equal_text_exit = 82
reversed_order_exit = 83

# Comparing text, which orders bytes. Before the comparison was routed through
# the runtime this program could not be linked freestanding at all: it emitted
# a call to strcmp, which a freestanding object has no libc to resolve and
# whose presence its own import surface forbids. The answers are checked, not
# just the link -- a comparison that always said "equal" would link too.
compare_program = (
'fn main() -> i64 {\n'
' let a: text = "alpha";\n'
' let b: text = "beta";\n'
' let same: text = "alpha";\n'
f' if a == b then\n return {unequal_text_exit};\n end if\n'
f' if a != same then\n return {equal_text_exit};\n end if\n'
f' if b < a then\n return {reversed_order_exit};\n end if\n'
f' return {expected_exit};\n'
'}\n'
)

driver_source = """
extern "C" int __ny_entry();

Expand Down Expand Up @@ -368,6 +396,27 @@ def main() -> int:
f'got {result.returncode}, stderr: {result.stderr!r}')
checks += 1

# Comparing text, with no libc to compare it with. The program has to
# link at all -- which it could not before -- and then has to get the
# answers right, because an ordering that collapsed everything to
# equal would link just as well.
comparing = build(args.compiler, args.assembler, args.archive, args.cxx,
root, 'compare', driver_source,
program_source=compare_program)
checks += 1
result = run([comparing], timeout=60)
assert result.returncode != unequal_text_exit, (
'two different texts must not compare equal')
assert result.returncode != equal_text_exit, (
'two identical texts must compare equal')
assert result.returncode != reversed_order_exit, (
'text must order by unsigned bytes, so "beta" follows "alpha"')
assert result.returncode == expected_exit, (
'a freestanding program that compares text must run and return '
f'what Ny returned; got {result.returncode}, stderr: '
f'{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
Expand Down
Loading
Loading