packages: Pin dependency metadata

679002bbe45b8c0b5d4b23a546bcb9a8cc6f7740209fe3f6d6a3b7857c888a5f
Hash canonical exported RIL contracts, RID declarations, and dependency
metadata for client cache keys and image pins. Keep full image
identities for exact artifacts. Write package.lock for exported graphs
and validate source-free selections against an available lockfile.

Retain exact provider references at publication. Select matching
metadata in publication order and reuse native code only for the same
image and resolved providers. Use the same selection policy in boot
image builds.

Resolve the dependencies of a verified load only among packages behind
the caller's Image handles with execute rights. A provider's name and
metadata come from its own binary, so selection across the whole
registry would let any domain with allocation authority impersonate a
provider for later clients. A domain holds Image handles to at most one
package per name and metadata, so its handles select each provider
unambiguously; loads, grants, and transfers that would add a second fail
with InvalidArg. Boot catalog admission still sees every resident
package, because the trusted image builder selected it.

Generate each module interface from its roots and the private
declarations that retained declarations refer to, transitively. The
metadata pin hashes the RID text, so an edit to an unused private
declaration otherwise changed the pin and invalidated every client.
References come from the nodes that the formatted interface presents,
which replaces the resolver's interface-use flag for functions.

Compile each client against parsed provider RID declarations. Use the
package pipeline in every storage mode, reclaim frontend storage between
packages, and generate native code from the completed images. Keep
artifacts and export names in persistent storage.

Document that verified linking is structural: a verified client can
build any value of a provider's opaque record, so providers must not
trust opaque invariants, and verified clients link only against
verified providers.

Keep canonical hashing in the compiler. Hash exports through a temporary
export table whose function indices refer to the retained declarations,
and check function bounds and names as for data exports. Reserve
resolver symbols for the combined std and kernel test graph within the
existing memory budget.

Compute request keys, image identities, and text metadata only for cache
publication or artifact export.

Pass fresh function IL directly to native generation through the package
sink. Encode images for cache storage and artifact export. Keep retained
symbols and data in persistent storage across package frontend resets.

Assisted-by: Codex:gpt-6
Assisted-by: Claude:opus-5.5
Change-Id: I387c154c91488342c5385bf6f0f2b6e4c9860ee9
Alexis Sellier committed ago 1 parent 1ccd7e0c
Makefile +1 -1
26 26
# Compiler build
27 27
28 28
SEED         := seed/radiance.rv64
29 29
COMPILER_SRC := compiler/radiance.rad compiler/radiance/codegen.rad \
30 30
    compiler/radiance/testgen.rad compiler/radiance/link.rad \
31 -
    compiler/radiance/artifact.rad \
31 +
    compiler/radiance/artifact.rad compiler/radiance/metadata.rad \
32 32
    compiler/radiance/build.rad compiler/radiance/cache.rad compiler/radiance/locations.rad
33 33
COMPILER_MANIFEST := $(STD_MANIFEST) compiler/radiance.manifest
34 34
SEED_OPTS    := $(STD) -pkg radiance $(patsubst %,-mod %,$(COMPILER_SRC)) \
35 35
    -entry radiance
36 36
compiler/radiance.rad +6 -6
1 1
//! Radiance compiler front-end.
2 2
mod codegen;
3 3
mod testgen;
4 4
mod link;
5 5
mod artifact;
6 +
mod metadata;
6 7
mod build;
7 8
mod cache;
8 9
mod locations;
9 10
10 11
use std::arch::rv64;
44 45
/// room for it to grow.
45 46
constant MAX_SOURCES_SIZE: u32 = 6291456;
46 47
/// Maximum number of assembly source paths we can load per package.
47 48
constant MAX_ASM_MODULES: u32 = 64;
48 49
49 -
/// Shared syntax, semantic metadata, and global IL storage (268 MB).
50 -
/// These allocations remain live until the compilation ends.
50 +
/// Package frontend storage and decoded native data (268 MB).
51 51
constant FRONTEND_ARENA_SIZE: u32 = 281018368;
52 52
/// Function IL arena size (16 MB). Every lowering pass resets it after each
53 53
/// function. It must fit the largest function of the standard library,
54 54
/// compiler and kernel test builds.
55 55
constant FN_ARENA_SIZE: u32 = 16777216;
149 149
    inputs: [PackageInput; package::MAX_PACKAGES],
150 150
    /// Number of packages.
151 151
    packageCount: u32,
152 152
    /// Index of entry package.
153 153
    entryPkgIdx: ?u32,
154 -
    /// Parser that owns the node arena and string pool for the whole compilation.
154 +
    /// Parser and string pool for the current frontend pass or artifact read.
155 155
    parser: parser::Parser,
156 156
    /// Resolver configuration.
157 157
    config: resolver::Config,
158 158
    /// What to dump during compilation.
159 159
    dump: Dump,
182 182
/// table is valid after the entry runs: the entry sets each slice in the region to
183 183
/// the empty slice, a hash table entry has an empty key, and a module entry is
184 184
/// vacant with no parent, AST, or source. So no table needs run-time initialization
185 185
/// in [`main`].
186 186
record Storage {
187 -
    /// Shared lifetime storage for syntax, resolution, and program data.
187 +
    /// Storage for package frontends and decoded native program data.
188 188
    frontend: [u8; FRONTEND_ARENA_SIZE],
189 189
    /// Function IL arena, reset after each lowered function.
190 190
    fnIl: [u8; FN_ARENA_SIZE],
191 191
    /// Printed functions of an IL dump or the current binary function spool.
192 192
    ilText: [u8; IL_TEXT_SIZE],
197 197
    emitter: [u8; EMITTER_SIZE],
198 198
    /// Driver tables that live for the whole compilation.
199 199
    driver: [u8; DRIVER_ARENA_SIZE],
200 200
    /// Source text of the modules.
201 201
    moduleSources: [u8; MAX_SOURCES_SIZE],
202 -
    /// Slots of the string pool, empty at entry. The process builds one pool.
202 +
    /// Reusable string pool slots, empty at entry.
203 203
    poolTable: [*[u8]; strings::TABLE_SIZE],
204 -
    /// Entries of the module graph. The process builds one module graph.
204 +
    /// Reusable module graph entries.
205 205
    moduleEntries: [module::ModuleEntry; MAX_TOTAL_MODULES],
206 206
    /// Data symbols of the program. The process generates one program.
207 207
    dataSyms: [data::DataSym; data::MAX_DATA_SYMS],
208 208
    /// Hash table of the data symbol map, with no occupied entry at entry.
209 209
    dataSymTable: [dict::Entry; data::DATA_SYM_TABLE_SIZE],
compiler/radiance/artifact.rad +166 -33
6 6
use std::hash::blake3;
7 7
use std::lang::alloc;
8 8
use std::lang::ast;
9 9
use std::lang::il::binary;
10 10
use std::lang::il::binary::linkage;
11 +
use std::lang::il::binary::program;
12 +
use std::lang::il::binary::reader;
11 13
use std::lang::layout;
12 14
use std::lang::parser;
13 15
use std::lang::pretty;
14 16
use std::lang::scanner;
15 17
use std::lang::sexpr;
21 23
constant VERSION: u32 = 1;
22 24
/// Largest artifact metadata, including module and dependency descriptors.
23 25
constant MAX_METADATA: u32 = 1048576;
24 26
25 27
/// Content validation required when loading a package artifact set.
26 -
export union Validation {
28 +
export union Validation: Copy {
27 29
    /// Trust content identities recorded in a compiler cache entry.
28 30
    Trusted,
29 31
    /// Compare every recorded content identity with its file bytes.
30 32
    Full,
31 33
}
38 40
    text: *[u8],
39 41
    /// Digest of the complete text snapshot.
40 42
    hash: binary::Id,
41 43
}
42 44
43 -
/// Exact compiler and runtime inputs selected for a dependency.
45 +
/// Compiler metadata required from a dependency.
44 46
export record Dependency: Copy {
45 47
    /// Provider package name.
46 48
    name: *[u8],
47 -
    /// Hash of its complete RIL image.
48 -
    image: binary::Id,
49 -
    /// Hash of its complete artifact metadata.
49 +
    /// Hash of its compiler declarations and exported runtime contracts.
50 50
    declarations: binary::Id,
51 51
}
52 52
53 53
/// Additional native-link input retained with a package image.
54 54
export union FileRole: Copy {
70 70
    bytes: *[u8],
71 71
    /// Use of these bytes during native linking.
72 72
    role: FileRole,
73 73
}
74 74
75 +
/// Content identities and text for a stored package artifact.
76 +
export record Publication: Copy {
77 +
    /// Complete binary RIL image.
78 +
    image: *[u8],
79 +
    /// Complete source compilation request key.
80 +
    inputs: binary::Id,
81 +
    /// Identity of the complete binary RIL image.
82 +
    identity: binary::Id,
83 +
    /// Encoded metadata which binds the complete set.
84 +
    metadata: *[u8],
85 +
}
86 +
75 87
/// Package artifact retained in immutable compiler storage.
76 88
export record Package: Copy {
77 89
    /// Package name and root module identity.
78 90
    name: *[u8],
79 -
    /// Complete binary RIL image.
80 -
    image: *[u8],
81 -
    /// Identity of `image`.
82 -
    identity: binary::Id,
83 91
    /// Text modules in parent-before-child order.
84 92
    modules: *[Module],
85 93
    /// Assembly and source locations used by native output.
86 94
    files: *[File],
87 -
    /// Exact dependency selections.
95 +
    /// Dependency names and required compiler metadata.
88 96
    dependencies: *[Dependency],
89 -
    /// Complete source compilation request key.
90 -
    inputs: binary::Id,
91 -
    /// Digest of compiler declarations and exact dependency selections.
97 +
    /// Canonical hash of exported runtime contracts.
98 +
    exports: binary::Id,
99 +
    /// Digest of compiler declarations and dependency metadata.
92 100
    declarations: binary::Id,
93 -
    /// Encoded metadata which binds the complete set.
94 -
    metadata: *[u8],
101 +
    /// Storage identities and text for cache or artifact publication.
102 +
    publication: ?Publication,
95 103
}
96 104
97 105
/// Join path components or report exhausted permanent storage.
98 106
export fn join(arena: &heap::Heap, parts: &[*[u8]]) -> *[u8] throws (sys::Error) {
99 107
    let bytes = try alloc::concatBytes(arena, parts) catch {
113 121
    mem::store32Le(&mut size[..], 0, bytes.len);
114 122
    blake3::update(state, &size[..]);
115 123
    blake3::update(state, bytes);
116 124
}
117 125
118 -
/// Hash declaration contents and their selected dependency closure.
126 +
/// Hash exported contracts, RID declarations, and dependency metadata.
119 127
/// Build provenance, source locations, and implementation-only files are separate inputs.
120 128
export fn declarations(package: &Package) -> binary::Id {
121 129
    let mut state = blake3::new();
122 130
    field(&mut state, package.name);
131 +
    field(&mut state, &package.exports.bytes[..]);
123 132
    let mut counts: [u8; 12] = [0; 12];
124 133
    mem::store32Le(&mut counts[..], 0, VERSION);
125 134
    mem::store32Le(&mut counts[..], 4, package.modules.len);
126 135
    mem::store32Le(&mut counts[..], 8, package.dependencies.len);
127 136
    field(&mut state, &counts[..]);
129 138
        field(&mut state, module.path);
130 139
        field(&mut state, &module.hash.bytes[..]);
131 140
    }
132 141
    for dependency in package.dependencies {
133 142
        field(&mut state, dependency.name);
134 -
        field(&mut state, &dependency.image.bytes[..]);
135 143
        field(&mut state, &dependency.declarations.bytes[..]);
136 144
    }
137 145
    let hash = blake3::finish(state);
138 146
    return binary::Id { bytes: hash.bytes };
139 147
}
268 276
    return id;
269 277
}
270 278
271 279
/// Format package metadata as a record literal.
272 280
/// The arena holds temporary AST nodes, literal text, and layout data.
273 -
export fn metadata(package: &Package, buffer: *mut [u8], arena: *heap::Heap) -> *[u8]
281 +
export fn metadata(
282 +
    package: &Package,
283 +
    inputs: binary::Id,
284 +
    identity: binary::Id,
285 +
    imageSize: u32,
286 +
    buffer: *mut [u8],
287 +
    arena: *heap::Heap
288 +
) -> *[u8]
274 289
    throws (alloc::AllocError, binary::Error)
275 290
{
276 291
    let mut nodes = ast::NodeArena { heap: arena, nextId: 0 };
277 292
    let mut modules: *mut [*ast::Node] = &mut [];
278 293
    let mut files: *mut [*ast::Node] = &mut [];
307 322
        let node = try ast::synthRecord(
308 323
            &mut nodes,
309 324
            "Dependency",
310 325
            &[
311 326
                ast::field("name", ast::stringValue(dependency.name)),
312 -
                ast::field("image", try ast::hexStringValue(&dependency.image.bytes[..], arena)),
313 327
                ast::field(
314 328
                    "declarations",
315 329
                    try ast::hexStringValue(&dependency.declarations.bytes[..], arena)
316 330
                ),
317 331
            ]
322 336
        &mut nodes,
323 337
        "Package",
324 338
        &[
325 339
            ast::field("version", try ast::numberValue(VERSION as u64, arena)),
326 340
            ast::field("name", ast::stringValue(package.name)),
327 -
            ast::field("inputs", try ast::hexStringValue(&package.inputs.bytes[..], arena)),
328 -
            ast::field("image",  try ast::hexStringValue(&package.identity.bytes[..], arena)),
329 -
            ast::field("size",   try ast::numberValue(package.image.len as u64, arena)),
341 +
            ast::field("exports", try ast::hexStringValue(&package.exports.bytes[..], arena)),
342 +
            ast::field("inputs",  try ast::hexStringValue(&inputs.bytes[..], arena)),
343 +
            ast::field("image",   try ast::hexStringValue(&identity.bytes[..], arena)),
344 +
            ast::field("size",    try ast::numberValue(imageSize as u64, arena)),
330 345
            ast::field("modules", ast::arrayValue(&modules[..])),
331 346
            ast::field("files", ast::arrayValue(&files[..])),
332 347
            ast::field("dependencies", ast::arrayValue(&dependencies[..])),
333 348
        ]
334 349
    );
358 373
    if info.size > MAX_METADATA as u64 {
359 374
        throw sys::Error::Invalid;
360 375
    }
361 376
    // Interned names point into metadata source for the life of the parser.
362 377
    let encoded = try readFile(path, syntax.arena.heap);
363 -
    return try decode(
378 +
    return try locked(
364 379
        root, tree, name, encoded, validation, syntax, arena
365 380
    ) catch err as binary::Error {
366 381
        if err == binary::Error::Storage {
367 382
            throw sys::Error::TooLarge;
368 383
        }
389 404
            throw binary::Error::Storage;
390 405
        }
391 406
        throw binary::Error::Invalid;
392 407
    };
393 408
    let literal = try readRecord(value, "Package", &[
394 -
        "version", "name", "inputs", "image", "size", "modules", "files", "dependencies"
409 +
        "version", "name", "exports", "inputs", "image", "size", "modules", "files", "dependencies"
395 410
    ]);
396 411
    if try readNumber(try fieldNode(&literal, "version")) <> VERSION
397 412
        or not mem::eq(try readString(try fieldNode(&literal, "name")), name)
398 413
    {
399 414
        throw binary::Error::Invalid;
400 415
    }
416 +
    let exports = try readId(try fieldNode(&literal, "exports"));
401 417
    let inputs = try readId(try fieldNode(&literal, "inputs"));
402 418
    let identity = try readId(try fieldNode(&literal, "image"));
403 419
    let length = try readNumber(try fieldNode(&literal, "size"));
404 420
    let image = try readFile(try join(arena, &[root, "/", name, ".ril"]), arena);
405 421
    if image.len <> length
483 499
        };
484 500
    }
485 501
    let dependencyNodes = try readArray(try fieldNode(&literal, "dependencies"));
486 502
    let mut dependencies: *mut [Dependency] = &mut [];
487 503
    for node in dependencyNodes {
488 -
        let descriptor = try readRecord(node, "Dependency", &["name", "image", "declarations"]);
504 +
        let descriptor = try readRecord(node, "Dependency", &["name", "declarations"]);
489 505
        let name = try readString(try fieldNode(&descriptor, "name"));
490 506
        if not validPath(name) {
491 507
            throw binary::Error::Invalid;
492 508
        }
493 509
        for i in 0 .. dependencies.len {
498 514
        for byte in name {
499 515
            if byte == '/' or byte == '.' {
500 516
                throw binary::Error::Invalid;
501 517
            }
502 518
        }
503 -
        let image = try readId(try fieldNode(&descriptor, "image"));
504 519
        let declarations = try readId(try fieldNode(&descriptor, "declarations"));
505 -
        try dependencies.append(Dependency { name, image, declarations }, arena) catch {
520 +
        try dependencies.append(Dependency { name, declarations }, arena) catch {
506 521
            throw binary::Error::Storage;
507 522
        };
508 523
    }
509 524
    let mut package = Package {
510 525
        name,
511 -
        image,
512 -
        identity,
513 526
        modules: &modules[..],
514 527
        files: &files[..],
515 528
        dependencies: &dependencies[..],
516 -
        inputs,
529 +
        exports,
517 530
        declarations: binary::Id { bytes: [0; 32] },
518 -
        metadata: encoded,
531 +
        publication: Publication { image, inputs, identity, metadata: encoded },
519 532
    };
520 533
    set package.declarations = declarations(&package);
534 +
    let mut input = reader::new(image);
535 +
    let header = try program::header(&mut input, arena);
536 +
    if header.links.metadata <> package.declarations {
537 +
        throw binary::Error::Invalid;
538 +
    }
521 539
    return package;
522 540
}
523 541
524 542
/// Write the complete set inside a private artifact root. The caller publishes that root.
525 543
export fn write(package: &Package, root: *[u8], arena: &heap::Heap) throws (sys::Error) {
544 +
    let publication = package.publication else panic "write: missing publication";
526 545
    let tree = try join(arena, &[root, "/", package.name, ".interface/"]);
527 546
    for module in package.modules {
528 547
        let path = try join(arena, &[tree, module.path]);
529 548
        try directories(path);
530 549
        try fs::writeFile(path, module.text);
534 553
        try directories(path);
535 554
        try fs::writeFile(path, file.bytes);
536 555
    }
537 556
    let image = try join(arena, &[root, "/", package.name, ".ril"]);
538 557
    try directories(image);
539 -
    try fs::writeFile(image, package.image);
540 -
    try fs::writeFile(try join(arena, &[tree, "package.metadata"]), package.metadata);
558 +
    try fs::writeFile(image, publication.image);
559 +
    try fs::writeFile(try join(arena, &[tree, "package.metadata"]), publication.metadata);
560 +
}
561 +
562 +
/// Read an artifact and check its exact selection when a lockfile is present.
563 +
fn locked(
564 +
    root: *[u8],
565 +
    tree: *[u8],
566 +
    name: *[u8],
567 +
    encoded: *[u8],
568 +
    validation: Validation,
569 +
    syntax: &mut parser::Parser,
570 +
    arena: &heap::Heap
571 +
) -> Package throws (binary::Error, sys::Error) {
572 +
    let package = try decode(root, tree, name, encoded, validation, syntax, arena);
573 +
    let publication = package.publication else panic "locked: missing publication";
574 +
    if validation == Validation::Trusted {
575 +
        return package;
576 +
    }
577 +
    let path = try join(arena, &[root, "/package.lock"]);
578 +
    let info = try fs::stat(path) else return package;
579 +
    if info.size > MAX_METADATA as u64 {
580 +
        throw binary::Error::Invalid;
581 +
    }
582 +
    let encoded = try readFile(path, syntax.arena.heap);
583 +
    let node = try parser::parseValue(syntax, scanner::SourceLoc::String, encoded) catch error {
584 +
        if error == parser::ParseError::AllocationFailed {
585 +
            throw binary::Error::Storage;
586 +
        }
587 +
        throw binary::Error::Invalid;
588 +
    };
589 +
    let lock = try readRecord(node, "Lock", &["version", "packages"]);
590 +
    if try readNumber(try fieldNode(&lock, "version")) <> 1 {
591 +
        throw binary::Error::Invalid;
592 +
    }
593 +
    let packages = try readArray(try fieldNode(&lock, "packages"));
594 +
    let mut names: *mut [*[u8]] = &mut [];
595 +
    let mut found = false;
596 +
    for node in packages {
597 +
        let entry = try readRecord(node, "LockedPackage", &["name", "image", "metadata"]);
598 +
        let selected = try readString(try fieldNode(&entry, "name"));
599 +
        let image = try readId(try fieldNode(&entry, "image"));
600 +
        let metadata = try readId(try fieldNode(&entry, "metadata"));
601 +
        for i in 0 .. names.len {
602 +
            if mem::eq(names[i], selected) {
603 +
                throw binary::Error::Invalid;
604 +
            }
605 +
        }
606 +
        try names.append(selected, arena) catch {
607 +
            throw binary::Error::Storage;
608 +
        };
609 +
        if mem::eq(selected, name) {
610 +
            if image <> publication.identity or metadata <> package.declarations {
611 +
                throw binary::Error::Invalid;
612 +
            }
613 +
            set found = true;
614 +
        }
615 +
    }
616 +
    if not found {
617 +
        throw binary::Error::Invalid;
618 +
    }
619 +
    return package;
620 +
}
621 +
622 +
/// Write the exact images and metadata selected for an exported package graph.
623 +
export fn writeLock(packages: &[Package], root: *[u8], arena: *heap::Heap)
624 +
    throws (sys::Error, alloc::AllocError)
625 +
{
626 +
    let mut nodes = ast::NodeArena { heap: arena, nextId: 0 };
627 +
    let mut entries: *mut [*ast::Node] = &mut [];
628 +
    for package in packages {
629 +
        let publication = package.publication else panic "writeLock: missing publication";
630 +
        let identity = publication.identity;
631 +
        let node = try ast::synthRecord(
632 +
            &mut nodes,
633 +
            "LockedPackage",
634 +
            &[
635 +
                ast::field("name", ast::stringValue(package.name)),
636 +
                ast::field("image", try ast::hexStringValue(&identity.bytes[..], arena)),
637 +
                ast::field(
638 +
                    "metadata", try ast::hexStringValue(&package.declarations.bytes[..], arena)
639 +
                ),
640 +
            ]
641 +
        ) catch {
642 +
            throw sys::Error::TooLarge;
643 +
        };
644 +
        try entries.append(node, arena) catch {
645 +
            throw sys::Error::TooLarge;
646 +
        };
647 +
    }
648 +
    let rootNode = try ast::synthRecord(
649 +
        &mut nodes,
650 +
        "Lock",
651 +
        &[
652 +
            ast::field("version", try ast::numberValue(1, arena)),
653 +
            ast::field("packages", ast::arrayValue(&entries[..])),
654 +
        ]
655 +
    ) catch {
656 +
        throw sys::Error::TooLarge;
657 +
    };
658 +
    let tree = try pretty::expression(rootNode, arena) catch {
659 +
        throw sys::Error::TooLarge;
660 +
    };
661 +
    let mut buffer: *mut [u8] = &mut [];
662 +
    try buffer.resize(MAX_METADATA, 0, arena) catch {
663 +
        throw sys::Error::TooLarge;
664 +
    };
665 +
    let mut out = sexpr::Buffer { buf: buffer.take(), pos: 0 };
666 +
    {
667 +
        let sink: &mut opaque sexpr::Output = &mut out;
668 +
        layout::text::render(tree, layout::text::Options { width: 80, indent: 4 }, sink);
669 +
    }
670 +
    if out.pos >= out.buf.len {
671 +
        throw sys::Error::TooLarge;
672 +
    }
673 +
    try fs::writeFile(try join(arena, &[root, "/package.lock"]), &out.buf[.. out.pos]);
541 674
}
compiler/radiance/build.rad +410 -302
8 8
use std::fs;
9 9
use std::hash::blake3;
10 10
use std::io;
11 11
use std::lang::alloc;
12 12
use std::lang::ast;
13 +
use std::lang::gen::bitset;
13 14
use std::lang::gen::data;
14 15
use std::lang::gen::labels;
15 16
use std::lang::il;
16 17
use std::lang::il::binary;
17 18
use std::lang::il::binary::linkage;
30 31
use std::lang::strings;
31 32
use std::mem;
32 33
use std::mem::heap;
33 34
use std::sys;
34 35
use super::artifact;
36 +
use super::metadata;
35 37
use super::cache;
36 38
use super::codegen;
37 39
use super::link;
38 40
use super::locations;
39 41
41 43
export constant ARTIFACT_BYTES: u32 = 16777216;
42 44
/// Reusable package header storage in the emitter arena.
43 45
constant HEADER_BYTES: u32 = 4194304;
44 46
/// Largest textual interface module.
45 47
constant INTERFACE_BYTES: u32 = 2097152;
48 +
/// Source location table storage for one package.
49 +
constant DEBUG_BYTES: u32 = 8388608;
46 50
47 51
/// Disjoint storage of the package pipeline and final native generator.
48 52
export record Workspace {
49 -
    /// Persistent syntax, semantic state, and global IL storage.
53 +
    /// Reusable syntax, semantic state, and decoded native data storage.
50 54
    main: *heap::Heap,
51 55
    /// Function IL storage, reclaimed after each function, and final
52 56
    /// assembly storage.
53 57
    functions: *heap::Heap,
54 58
    /// Native data records, encoding tables, and final code generation storage.
101 105
record Request['providers]: Copy {
102 106
    /// Declared provider indices in the selected graph.
103 107
    declared: *[u16],
104 108
    /// Completed provider contracts used to select imports.
105 109
    providers: &'providers [link::Provider],
106 -
    /// Content key for this source request.
107 -
    key: binary::Id,
110 +
    /// Content key when cache or artifact publication is required.
111 +
    key: ?binary::Id,
108 112
    /// Captured assembly inputs.
109 113
    files: *[artifact::File],
110 -
    /// Whether this package supplies the program entry.
111 -
    entry: bool,
112 114
}
113 115
114 -
/// Outputs and retained semantic state of one source compilation.
116 +
/// Artifacts of one source compilation.
115 117
record Compilation {
116 118
    /// Complete cache and export artifacts.
117 119
    package: artifact::Package,
118 120
    /// Public definitions retained for later package imports.
119 121
    exports: *[binary::Export],
120 -
    /// Resolver with all declarations and checked bodies retained.
121 -
    resolver: resolver::Resolver,
122 -
    /// Native generator after consuming the fresh lowered functions.
122 +
    /// Native generator after the package's functions.
123 123
    native: locations::Native,
124 -
    /// Global data used by the native program.
124 +
    /// Data retained for final native linking.
125 125
    data: *[il::Data],
126 -
    /// Reusable source location encoding buffer.
127 -
    debug: *mut [u8],
128 126
}
129 127
130 -
/// Native startup state and assembly storage for one output program.
131 -
record NativeOutput {
132 -
    /// Native generator when executable output is selected.
128 +
/// Initial native generator and startup assembly data.
129 +
record NativeSetup {
130 +
    /// Native generator selected for the invocation.
133 131
    native: locations::Native,
134 -
    /// Data supplied by startup assembly.
135 -
    assembly: *mut [u8],
132 +
    /// Read-only data from startup assembly.
133 +
    asmData: *mut [u8],
136 134
}
137 135
138 -
/// Completed package graph and its generated native output.
136 +
/// Package artifacts and native state of one compilation invocation.
139 137
record BuiltPackages {
140 -
    /// Artifacts in dependency order.
138 +
    /// Completed compiler declarations and stored package images.
141 139
    packages: *[artifact::Package],
142 -
    /// Native generator after all package functions are consumed.
140 +
    /// Native generator after all packages.
143 141
    native: locations::Native,
144 -
    /// Program-wide native data records.
142 +
    /// Persistent data records for final native linking.
145 143
    data: *mut [il::Data],
146 -
    /// Source paths used by the native debug map.
144 +
    /// Source paths in native debug module order.
147 145
    sourcePaths: *mut [*[u8]],
146 +
    /// Assembly data emitted before the source functions.
147 +
    asmData: *mut [u8],
148 148
}
149 149
150 150
/// Reserve output storage whose encoded prefix is initialized before it is read.
151 151
fn buffer(arena: &heap::Heap, size: u32) -> *mut [u8] throws (super::Error) {
152 152
    let mut bytes: *mut [u8] = &mut [];
467 467
        throw super::Error::Other;
468 468
    };
469 469
    return module::ModuleTable { entries: &entries[..] };
470 470
}
471 471
472 -
/// Hash immutable source inputs and complete selected compiler dependencies.
472 +
/// Hash source inputs, compiler options, and selected dependency metadata.
473 473
fn key(
474 474
    ctx: &super::CompileContext,
475 475
    name: *[u8],
476 476
    input: &Source,
477 477
    providers: &[artifact::Package],
506 506
        artifact::field(&mut state, file.bytes);
507 507
    }
508 508
    for id in declared {
509 509
        let provider = providers[id as u32];
510 510
        artifact::field(&mut state, provider.name);
511 -
        artifact::field(&mut state, &provider.identity.bytes[..]);
512 511
        artifact::field(&mut state, &provider.declarations.bytes[..]);
513 512
    }
514 513
    let hash = blake3::finish(state);
515 514
    return binary::Id { bytes: hash.bytes };
516 515
}
517 516
518 -
/// Check exact dependency image and declaration references against the selected graph.
517 +
/// Check dependency metadata against the selected package graph.
519 518
fn validate(package: &artifact::Package, providers: &[artifact::Package])
520 519
    throws (super::Error)
521 520
{
522 521
    for dependency in package.dependencies {
523 522
        let mut found = false;
524 523
        for provider in providers {
525 524
            if mem::eq(dependency.name, provider.name) {
526 -
                if dependency.image <> provider.identity
527 -
                    or dependency.declarations <> provider.declarations
528 -
                {
525 +
                if dependency.declarations <> provider.declarations {
529 526
                    throw super::error(&["package dependency artifact mismatch", dependency.name]);
530 527
                }
531 528
                set found = true;
532 529
                break;
533 530
            }
534 531
        }
535 532
        if not found {
536 -
            throw super::error(&["missing exact package dependency", dependency.name]);
533 +
            throw super::error(&["missing package dependency", dependency.name]);
537 534
        }
538 535
    }
539 536
}
540 537
541 538
/// Compile selected packages and produce the requested final output.
545 542
    work: &mut Workspace,
546 543
    sourceArena: &heap::Heap,
547 544
    driverArena: &heap::Heap,
548 545
    compiler: binary::Id
549 546
) throws (super::Error) {
547 +
    set ctx.parser.arena.heap = work.artifacts;
550 548
    let selected = try inputs(ctx, sourceArena, work.artifacts) catch {
551 549
        throw super::error(&["cannot read package inputs or dependency manifests"]);
552 550
    };
553 551
    let entryIndex = ctx.entryPkgIdx else panic "run: missing entry package";
554 552
    let entryName = ctx.inputs[entryIndex].name;
555 -
    let case NativeOutput { native, assembly: asmData } = try beginNative(
556 -
        ctx, selected, entryName, work
557 -
    ) else panic "run: missing native output state";
558 -
559 -
    let mut sourceOnly = true;
560 -
    for input in selected {
561 -
        if let case Contents::Compiled(_) = input.contents {
562 -
            set sourceOnly = false;
563 -
        }
564 -
    }
565 -
    if sourceOnly
566 -
        and ctx.outputPath <> nil
567 -
        and ctx.cacheDirectory == nil
568 -
        and ctx.rilDirectory == nil
569 -
    {
570 -
        let case locations::Native::Program(generator) = native
571 -
            else panic "run: missing direct native output";
572 -
        try direct(ctx, selected, entryName, graph, work, driverArena, generator, asmData);
573 -
        return;
574 -
    }
575 -
    let case BuiltPackages {
576 -
        packages: compiled, native: generated, data: allData, sourcePaths
577 -
    } = try buildPackages(ctx, graph, work, selected, entryName, driverArena, compiler, native)
578 -
        else panic "run: missing package output state";
553 +
    let built = try buildPackages(
554 +
        ctx, graph, work, selected, entryName, driverArena, compiler
555 +
    );
556 +
    let case BuiltPackages { packages, native, data, sourcePaths, asmData } = built
557 +
        else panic "run: expected package results";
579 558
    if let directory = ctx.rilDirectory {
580 -
        try writePackages(compiled, directory, driverArena);
559 +
        try writePackages(packages, directory, driverArena, work.functions);
581 560
    }
582 561
    if let output = ctx.outputPath {
583 -
        let case locations::Native::Program(generator) = generated
562 +
        resetFrontend(ctx, graph, work.main);
563 +
        let case locations::Native::Program(native) = native
584 564
            else panic "run: missing native generator";
585 -
        try finish(ctx, selected, generator, allData, asmData, sourcePaths, output, work);
586 -
    }
587 -
}
588 -
589 -
/// Prepare native entry code and assembly storage for the requested output.
590 -
fn beginNative(
591 -
    ctx: &mut super::CompileContext, selected: &[Input], entryName: *[u8], work: &mut Workspace
592 -
) -> NativeOutput throws (super::Error) {
593 -
    let mut native = locations::Native::None;
594 -
    let mut asmData: *mut [u8] = &mut [];
595 -
    if ctx.outputPath <> nil {
596 -
        let mut startup: ?artifact::File = nil;
597 -
        for input in selected {
598 -
            if not mem::eq(input.options.name, entryName) {
599 -
                continue;
600 -
            }
601 -
            let mut files: *[artifact::File] = &[];
602 -
            match input.contents {
603 -
                case Contents::Source(source)    => set files = source.files,
604 -
                case Contents::Compiled(package) => set files = package.files,
605 -
            }
606 -
            for file in files {
607 -
                if file.role == artifact::FileRole::Startup {
608 -
                    set startup = file;
609 -
                }
610 -
            }
611 -
        }
612 -
        let mut generator = try rv64::beginProgram(rv64::ProgramOptions {
613 -
            stack: rv64::StackCheck::TpLimit if ctx.stackCheck else rv64::StackCheck::Off,
614 -
            entryPatch: rv64::EntryPatch::None
615 -
                if startup <> nil
616 -
                else rv64::EntryPatch::Reserved(nil),
617 -
            debug: ctx.debug,
618 -
            placement: rv64::image::Placement::Hosted,
619 -
        }, work.emitter, labels::fresh(
620 -
            work.native.blockOffsets.take(), work.native.funcTable.take()
621 -
        )) catch {
622 -
            throw super::Error::Other;
623 -
        };
624 -
        if let file = startup {
625 -
            try assembly(&mut generator, &file, &mut asmData, work.main, &mut ctx.parser.pool);
626 -
        }
627 -
        set native = locations::Native::Program(generator);
565 +
        let case codegen::Context { generator } = native else panic "run: expected native context";
566 +
        try finish(
567 +
            ctx, selected, generator, data, asmData, sourcePaths, output, work
568 +
        );
628 569
    }
629 -
    return NativeOutput { native, assembly: asmData };
630 570
}
631 571
632 572
/// Compile source packages or reuse artifacts in dependency order.
633 573
fn buildPackages(
634 574
    ctx: &mut super::CompileContext,
635 575
    graph: &mut module::ModuleGraph,
636 576
    work: &mut Workspace,
637 577
    selected: *[Input],
638 578
    entryName: *[u8],
639 579
    driverArena: &heap::Heap,
640 -
    compiler: binary::Id,
641 -
    target: locations::Native
580 +
    compiler: binary::Id
642 581
) -> BuiltPackages throws (super::Error) {
643 -
    let mut native = target;
582 +
    let entry = find(selected, entryName) else panic "buildPackages: missing entry package";
583 +
    let initial = try nativeOutput(ctx, selected[entry], work);
584 +
    let case NativeSetup { native: initialNative, asmData } = initial
585 +
        else panic "buildPackages: expected native setup";
586 +
    let mut native = initialNative;
644 587
    let mut allData: *mut [il::Data] = &mut [];
645 588
    let mut sourcePaths: *mut [*[u8]] = &mut [];
646 -
    let mut debug: *mut [u8] = &mut [];
647 -
    if ctx.debug {
648 -
        set debug = try buffer(work.main, 8388608);
649 -
    }
650 -
    let mut retained: ?resolver::Resolver = nil;
651 589
    let mut compiled: *mut [artifact::Package] = &mut [];
652 590
    let mut published: *mut [link::Provider] = &mut [];
653 591
    for input, index in selected {
654 592
        set ctx.inputs[index] = input.options;
655 593
        set ctx.packageCount = index + 1;
660 598
        let mut built: artifact::Package = undefined;
661 599
        let mut fresh = false;
662 600
        match input.contents {
663 601
            case Contents::Compiled(package) => set built = package,
664 602
            case Contents::Source(source) => {
665 -
                let request = key(
603 +
                let request: ?binary::Id = key(
666 604
                    ctx,
667 605
                    input.options.name,
668 606
                    &source,
669 607
                    &compiled[..],
670 608
                    providerIds,
671 609
                    ctx.config.buildTest and mem::eq(input.options.name, entryName),
672 610
                    compiler
673 -
                );
611 +
                )
612 +
                    if ctx.cacheDirectory <> nil or ctx.rilDirectory <> nil
613 +
                    else nil;
674 614
                let mut cached: ?artifact::Package = nil;
675 615
                if let root = ctx.cacheDirectory {
616 +
                    let cacheKey = request else panic "buildPackages: missing cache key";
676 617
                    set cached = try cache::lookup(
677 -
                        root, input.options.name, request, &mut ctx.parser, work.artifacts
618 +
                        root, input.options.name, cacheKey, &mut ctx.parser, work.artifacts
678 619
                    ) catch {
679 620
                        throw super::error(&["cannot read package cache"]);
680 621
                    };
681 622
                }
682 623
                if let package = cached {
684 625
                    io::printError(package.name);
685 626
                    io::printError("\n");
686 627
                    set built = package;
687 628
                } else {
688 629
                    for i in published.len .. compiled.len {
689 -
                        let provider = compiled[i];
690 -
                        let checkpoint = heap::mark(work.functions);
691 -
                        let mut input = reader::new(provider.image);
692 -
                        let head = try program::header(&mut input, work.functions) catch {
693 -
                            throw super::error(&[
694 -
                                "package encoding storage exhausted", provider.name
695 -
                            ]);
696 -
                        };
697 -
                        let mut exports: *mut [binary::Export] = &mut [];
698 -
                        for item in head.exports {
699 -
                            let name = try keep(work.emitter, item.name) catch {
700 -
                                throw super::Error::Other;
701 -
                            };
702 -
                            let mut item = item;
703 -
                            set item.name = name;
704 -
                            try exports.append(item, work.emitter) catch {
705 -
                                throw super::error(&[
706 -
                                    "package encoding storage exhausted", provider.name
707 -
                                ]);
708 -
                            };
709 -
                        }
710 -
                        try published.append(
711 -
                            link::Provider {
712 -
                                name: provider.name, image: provider.identity, exports: &exports[..]
713 -
                            },
714 -
                            work.emitter
715 -
                        ) catch {
630 +
                        let provider = try readExports(&compiled[i], work);
631 +
                        try published.append(provider, work.emitter) catch {
716 632
                            throw super::Error::Other;
717 633
                        };
718 -
                        // Only the copied export descriptors survive header decoding.
719 -
                        unsafe {
720 -
                            heap::rewind(work.functions, checkpoint);
721 -
                        }
722 634
                    }
635 +
                    resetFrontend(ctx, graph, work.main);
723 636
                    try loadInterfaces(ctx, graph, selected, &compiled[..], driverArena);
724 637
                    try load(ctx, graph, index, source.modules, module::Role::Source, providerIds);
725 638
                    if ctx.config.buildTest and mem::eq(input.options.name, entryName) {
726 639
                        try super::generateTestRunner(ctx, graph, driverArena);
727 640
                    }
728 641
                    let modules = try table(graph, ctx.parser.arena.heap);
729 -
                    let mut res: resolver::Resolver = undefined;
730 -
                    if let previous = retained {
731 -
                        set res = previous;
732 -
                        try super::resolvePackages(ctx, modules, &mut res, driverArena);
733 -
                    } else {
734 -
                        set res = try super::runResolver(
735 -
                            ctx, modules, ctx.parser.arena.nextId, work.main, driverArena
736 -
                        );
737 -
                    }
642 +
                    let res = try super::runResolver(
643 +
                        ctx, modules, ctx.parser.arena.nextId, work.main, driverArena
644 +
                    );
738 645
                    if ctx.debug and ctx.outputPath <> nil {
739 646
                        let root = ctx.packages[index].rootModuleId
740 647
                            else panic "buildPackages: missing source root";
741 648
                        assert sourcePaths.len == root as u32, "buildPackages: source module order";
742 -
                        for entry in &modules.entries[root as u32 ..] {
743 -
                            try sourcePaths.append(entry.filePath, work.main) catch {
744 -
                                throw super::Error::Other;
745 -
                            };
649 +
                        for module in modules.entries {
650 +
                            if module.packageId as u32 == index {
651 +
                                try sourcePaths.append(module.filePath, work.emitter) catch {
652 +
                                    throw super::Error::Other;
653 +
                                };
654 +
                            }
746 655
                        }
747 656
                    }
748 657
                    let result = try compile(
749 658
                        ctx,
750 659
                        modules,
754 663
                        Request {
755 664
                            declared: providerIds,
756 665
                            providers: &published[..],
757 666
                            key: request,
758 667
                            files: source.files,
759 -
                            entry: mem::eq(input.options.name, entryName),
760 668
                        },
761 669
                        native,
762 -
                        debug.take()
670 +
                        entryName
763 671
                    );
764 -
                    let case Compilation {
765 -
                        package,
766 -
                        exports,
767 -
                        resolver: resolved,
768 -
                        native: generated,
769 -
                        data,
770 -
                        debug: debugBuffer,
771 -
                    } =
772 -
                        result else panic "buildPackages: expected compilation";
672 +
                    let case Compilation { package, exports, native: generated, data } = result
673 +
                        else panic "buildPackages: expected compilation";
773 674
                    set built = package;
675 +
                    set native = generated;
676 +
                    set fresh = true;
677 +
                    try allData.extend(data, work.emitter) catch {
678 +
                        throw super::Error::Other;
679 +
                    };
774 680
                    try published.append(
775 681
                        link::Provider {
776 -
                            name: built.name, image: built.identity, exports
682 +
                            name: built.name, metadata: built.declarations, exports
777 683
                        },
778 684
                        work.emitter
779 685
                    ) catch {
780 686
                        throw super::Error::Other;
781 687
                    };
782 -
                    set retained = resolved;
783 -
                    set native = generated;
784 -
                    try allData.extend(data, work.emitter) catch {
785 -
                        throw super::error(&["native data storage exhausted"]);
786 -
                    };
787 -
                    set fresh = true;
688 +
                    set ctx.parser.arena.heap = work.artifacts;
788 689
                    if let root = ctx.cacheDirectory {
789 690
                        // Function storage has no live IL after its sink consumed each function.
790 691
                        try cache::publish(root, &built, &mut ctx.parser, work.functions) catch {
791 692
                            throw super::error(&["cannot publish package cache", built.name]);
792 693
                        };
793 694
                        unsafe {
794 695
                            heap::reset(work.functions);
795 696
                        }
796 697
                    }
797 -
                    // The reusable buffer is permanent; each package owns a copied prefix.
798 -
                    set debug = debugBuffer;
799 698
                }
800 699
            }
801 700
        }
802 701
        try validate(&built, &compiled[..]);
803 702
        if not fresh {
804 -
            if let case locations::Native::Program(generator) = &mut native {
805 -
                try decode(ctx, &built, entryName, generator, &mut allData, &mut sourcePaths, work);
703 +
            if let case locations::Native::Program(target) = &mut native {
704 +
                try decode(
705 +
                    ctx,
706 +
                    &built,
707 +
                    entryName,
708 +
                    &mut target.generator,
709 +
                    &mut allData,
710 +
                    &mut sourcePaths,
711 +
                    work
712 +
                );
806 713
            }
807 714
        }
808 715
        try compiled.append(built, work.artifacts) catch {
809 716
            throw super::error(&["package artifact storage exhausted"]);
810 717
        };
811 718
    }
812 -
    return BuiltPackages { packages: &compiled[..], native, data: allData, sourcePaths };
719 +
    return BuiltPackages {
720 +
        packages: &compiled[..], native, data: allData, sourcePaths, asmData
721 +
    };
813 722
}
814 723
815 -
/// Register interfaces of providers that have no source resolver state.
724 +
/// Copy a completed provider's exports into persistent emitter storage.
725 +
fn readExports(provider: &artifact::Package, work: &mut Workspace) -> link::Provider
726 +
    throws (super::Error)
727 +
{
728 +
    let checkpoint = heap::mark(work.functions);
729 +
    let publication = provider.publication else panic "readExports: missing package image";
730 +
    let mut input = reader::new(publication.image);
731 +
    let head = try program::header(&mut input, work.functions) catch {
732 +
        throw super::error(&[
733 +
            "package encoding storage exhausted", provider.name
734 +
        ]);
735 +
    };
736 +
    let mut exports: *mut [binary::Export] = &mut [];
737 +
    for item in head.exports {
738 +
        let name = try keep(work.emitter, item.name) catch {
739 +
            throw super::Error::Other;
740 +
        };
741 +
        let mut item = item;
742 +
        set item.name = name;
743 +
        try exports.append(item, work.emitter) catch {
744 +
            throw super::error(&[
745 +
                "package encoding storage exhausted", provider.name
746 +
            ]);
747 +
        };
748 +
    }
749 +
    let result = link::Provider {
750 +
        name: provider.name, metadata: provider.declarations, exports: &exports[..]
751 +
    };
752 +
    // Only the copied export descriptors survive header decoding.
753 +
    unsafe {
754 +
        heap::rewind(work.functions, checkpoint);
755 +
    }
756 +
    return result;
757 +
}
758 +
759 +
/// Register the interfaces and embedded files of completed providers.
816 760
fn loadInterfaces(
817 761
    ctx: &mut super::CompileContext,
818 762
    graph: &mut module::ModuleGraph,
819 763
    selected: &[Input],
820 764
    compiled: &[artifact::Package],
821 765
    driverArena: &heap::Heap
822 766
) throws (super::Error) {
823 767
    for i in 0 .. compiled.len {
824 -
        if ctx.packages[i].rootModuleId <> nil {
825 -
            continue;
826 -
        }
827 768
        let deps = try providers(&selected[i], &selected[.. i], driverArena) catch {
828 769
            throw super::Error::Other;
829 770
        };
830 771
        let mut modules: *mut [Snapshot] = &mut [];
831 772
        for item in compiled[i].modules {
837 778
        }
838 779
        try load(ctx, graph, i, &modules[..], module::Role::Interface, deps);
839 780
    }
840 781
}
841 782
842 -
/// Write the completed package artifact trees.
783 +
/// Write package artifact trees and the exact graph lockfile.
843 784
fn writePackages(
844 -
    compiled: &[artifact::Package], directory: *[u8], driverArena: &heap::Heap
785 +
    compiled: &[artifact::Package],
786 +
    directory: *[u8],
787 +
    driverArena: &heap::Heap,
788 +
    functions: *heap::Heap
845 789
) throws (super::Error) {
846 790
    for i in 0 .. compiled.len {
847 791
        let package = compiled[i];
848 792
        try artifact::write(&package, directory, driverArena) catch {
849 793
            throw super::error(&["cannot write package artifacts", package.name]);
850 794
        };
851 795
    }
796 +
    try artifact::writeLock(&compiled[..], directory, functions) catch {
797 +
        throw super::error(&["cannot write package lockfile"]);
798 +
    };
852 799
}
853 800
854 -
/// Generate an uncached source program with one frontend and one streaming native pass.
855 -
fn direct(
801 +
/// Begin native generation and assemble the selected startup input.
802 +
fn nativeOutput(
856 803
    ctx: &mut super::CompileContext,
857 -
    selected: &[Input],
858 -
    entry: *[u8],
859 -
    graph: &mut module::ModuleGraph,
860 -
    work: &mut Workspace,
861 -
    arena: &heap::Heap,
862 -
    generator: rv64::Generator,
863 -
    asmData: *mut [u8]
864 -
) throws (super::Error) {
865 -
    for input, i in selected {
866 -
        set ctx.inputs[i] = input.options;
867 -
        if mem::eq(input.options.name, entry) {
868 -
            set ctx.entryPkgIdx = i;
804 +
    entry: Input,
805 +
    work: &mut Workspace
806 +
) -> NativeSetup throws (super::Error) {
807 +
    let mut asmData: *mut [u8] = &mut [];
808 +
    let mut native = locations::Native::None;
809 +
    if ctx.outputPath <> nil {
810 +
        let mut startup: ?artifact::File = nil;
811 +
        let mut files: *[artifact::File] = &[];
812 +
        match entry.contents {
813 +
            case Contents::Source(source)    => set files = source.files,
814 +
            case Contents::Compiled(package) => set files = package.files,
869 815
        }
870 -
        let case Contents::Source(source) = input.contents
871 -
            else panic "direct: expected source input";
872 -
        let deps = try providers(&input, &selected[.. i], arena) catch {
816 +
        for file in files {
817 +
            if file.role == artifact::FileRole::Startup {
818 +
                set startup = file;
819 +
            }
820 +
        }
821 +
        let mut generator = try rv64::beginProgram(rv64::ProgramOptions {
822 +
            stack: rv64::StackCheck::TpLimit if ctx.stackCheck else rv64::StackCheck::Off,
823 +
            entryPatch: rv64::EntryPatch::None
824 +
                if startup <> nil
825 +
                else rv64::EntryPatch::Reserved(nil),
826 +
            debug: ctx.debug,
827 +
            placement: rv64::image::Placement::Hosted,
828 +
        }, work.emitter, labels::fresh(
829 +
            work.native.blockOffsets.take(), work.native.funcTable.take()
830 +
        )) catch {
873 831
            throw super::Error::Other;
874 832
        };
875 -
        try load(ctx, graph, i, source.modules, module::Role::Source, deps);
833 +
        if let file = startup {
834 +
            try assembly(&mut generator, &file, &mut asmData, work.emitter, &mut ctx.parser.pool);
835 +
        }
836 +
        set native = locations::Native::Program(codegen::Context { generator });
876 837
    }
877 -
    set ctx.packageCount = selected.len;
878 -
    if ctx.config.buildTest {
879 -
        try super::generateTestRunner(ctx, graph, arena);
838 +
    return NativeSetup { native, asmData };
839 +
}
840 +
841 +
/// Reclaim package syntax and semantic storage before a new frontend pass.
842 +
fn resetFrontend(
843 +
    ctx: &mut super::CompileContext, graph: &mut module::ModuleGraph, arena: *heap::Heap
844 +
) {
845 +
    let pool = strings::pool(ctx.parser.pool.table.take());
846 +
    set graph.entriesLen = 0;
847 +
    // Package artifacts and export names use separate persistent storage.
848 +
    unsafe {
849 +
        heap::reset(arena);
880 850
    }
881 -
    let modules = try table(graph, ctx.parser.arena.heap);
882 -
    let res = try super::runResolver(ctx, modules, ctx.parser.arena.nextId, work.main, arena);
883 -
    let mut low = lower::lowerer(res, modules, entry, work.functions, lower::LowerOptions {
884 -
        debug: ctx.debug, buildTest: ctx.config.buildTest, tableScope: lower::TableScope::Program
885 -
    });
886 -
    let mut sink = codegen::Context { generator };
887 -
    for package in &ctx.packages[.. ctx.packageCount] {
888 -
        try super::lowerPackage(
889 -
            ctx, modules, &mut low, &package, mem::eq(package.name, entry), &mut sink
890 -
        );
851 +
    set ctx.parser = parser::newParser(ast::NodeArena { heap: arena, nextId: 0 }, pool);
852 +
}
853 +
854 +
/// Whether a module statement belongs to the interface on its own: declarations
855 +
/// visible outside the module, test and compiler entry points, and statements
856 +
/// such as imports and instances, which are always kept. Other private
857 +
/// declarations belong to it only when a retained declaration refers to them.
858 +
fn interfaceRoot(node: *ast::Node) -> bool {
859 +
    let mut attrs: ?ast::Attributes = nil;
860 +
    match node.value {
861 +
        case ast::NodeValue::FnDecl(decl)                => set attrs = decl.attrs,
862 +
        case ast::NodeValue::ConstDecl(decl)             => set attrs = decl.attrs,
863 +
        case ast::NodeValue::StaticDecl(decl)            => set attrs = decl.attrs,
864 +
        case ast::NodeValue::RecordDecl(decl)            => set attrs = decl.attrs,
865 +
        case ast::NodeValue::UnionDecl(decl)             => set attrs = decl.attrs,
866 +
        case ast::NodeValue::TraitDecl { attrs: a, .. }  => set attrs = a,
867 +
        case ast::NodeValue::MethodDecl { attrs: a, .. } => set attrs = a,
868 +
        else                                             => return true,
891 869
    }
892 -
    let mut sourcePaths: *mut [*[u8]] = &mut [];
893 -
    if ctx.debug {
894 -
        for module in modules.entries {
895 -
            try sourcePaths.append(module.filePath, work.main) catch {
896 -
                throw super::Error::Other;
897 -
            };
870 +
    let list = attrs else return false;
871 +
    return ast::attributesContains(&list, ast::Attribute::Export)
872 +
        or ast::attributesContains(&list, ast::Attribute::Test)
873 +
        or ast::attributesContains(&list, ast::Attribute::Intrinsic)
874 +
        or ast::attributesContains(&list, ast::Attribute::Language);
875 +
}
876 +
877 +
/// Mark the symbols of the nodes that a statement layout presents. Every alternative
878 +
/// of a choice presents the same nodes, so only the first is visited.
879 +
fn markReferences(out: *layout::Layout, res: &resolver::Resolver, marks: &mut bitset::Bitset) {
880 +
    if let source = out.source {
881 +
        if let symbol = resolver::symbolFor(res, source) {
882 +
            bitset::put(marks, *symbol);
898 883
        }
899 884
    }
900 -
    let case codegen::Context { generator: generated } = sink
901 -
        else panic "direct: expected native sink";
902 -
    let case lower::Lowerer { data, .. } = low else panic "direct: expected lowerer";
903 -
    let output = ctx.outputPath else panic "direct: missing output path";
904 -
    try finish(ctx, selected, generated, data, asmData, sourcePaths, output, work);
885 +
    match out.item {
886 +
        case layout::Item::Box(children) => {
887 +
            for child in children {
888 +
                markReferences(child.layout, res, marks);
889 +
            }
890 +
        }
891 +
        case layout::Item::Choice(alternatives) => markReferences(alternatives[0], res, marks),
892 +
        case layout::Item::Broken(inner)        => markReferences(inner, res, marks),
893 +
        else                                    => {}
894 +
    }
905 895
}
906 896
907 -
/// Format callable provider declarations and functions used by retained declarations.
897 +
/// Format the interface of a module: its roots and the private declarations that
898 +
/// retained declarations refer to, transitively. Private symbols are visible only in
899 +
/// their module, so the closure stays within it. A private declaration that nothing
900 +
/// retained refers to is omitted, so editing it leaves the interface unchanged.
908 901
fn interface(
909 902
    root: *ast::Node, res: &resolver::Resolver, arena: *heap::Heap
910 903
) -> *layout::Layout throws (alloc::AllocError) {
911 904
    let case ast::NodeValue::Module(block) = root.value
912 905
        else panic "interface: expected module root";
913 -
    let mut declarations: *mut [*ast::Node] = &mut [];
914 -
    for node in block.statements {
915 -
        if let case ast::NodeValue::FnDecl(decl) = node.value {
916 -
            let symbol = resolver::symbolFor(res, node) else continue;
917 -
            let attrs = res.symbols[*symbol].attrs;
918 -
            if not (ast::hasAttribute(attrs, ast::Attribute::Export)
919 -
                or ast::hasAttribute(attrs, ast::Attribute::Test)
920 -
                or ast::hasAttribute(attrs, ast::Attribute::Intrinsic)
921 -
                or ast::hasAttribute(attrs, ast::Attribute::Language)
922 -
                or res.symbols[*symbol].interfaceUse)
923 -
            {
906 +
    let mut retained: *mut [bool] = &mut [];
907 +
    let mut formatted: *mut [?*layout::Layout] = &mut [];
908 +
    let mut added: *mut [u32] = &mut [];
909 +
    let mut marks = try bitset::allocate(arena, res.symbols.len);
910 +
    try formatted.resize(block.statements.len, nil, arena);
911 +
    for node, i in block.statements {
912 +
        let keep = interfaceRoot(node);
913 +
        try retained.append(keep, arena);
914 +
        if keep {
915 +
            try added.append(i, arena);
916 +
        }
917 +
    }
918 +
    // Each retained statement is formatted once; its layout is both walked for the
919 +
    // symbols it refers to and placed in the module layout.
920 +
    while added.len > 0 {
921 +
        for i in added {
922 +
            if let statement = try pretty::interfaceStatement(
923 +
                block.statements[i], arena
924 +
            ) {
925 +
                markReferences(statement, res, &mut marks);
926 +
                set formatted[i] = statement;
927 +
            }
928 +
        }
929 +
        set added = &mut [];
930 +
        for node, i in block.statements {
931 +
            if retained[i] {
924 932
                continue;
925 933
            }
934 +
            let symbol = resolver::symbolFor(res, node) else continue;
935 +
            if bitset::contains(&marks, *symbol) {
936 +
                set retained[i] = true;
937 +
                try added.append(i, arena);
938 +
            }
926 939
        }
927 -
        try declarations.append(node, arena);
928 940
    }
929 -
    let mut nodes = ast::NodeArena { heap: arena, nextId: 0 };
930 -
    let module = try ast::synthNode(&mut nodes, ast::NodeValue::Module(ast::Module {
931 -
        statements: &declarations[..]
932 -
    }));
933 -
    return try pretty::interface(module, arena);
941 +
    let mut statements: *mut [*layout::Layout] = &mut [];
942 +
    for entry in formatted {
943 +
        if let statement = entry {
944 +
            try statements.append(statement, arena);
945 +
        }
946 +
    }
947 +
    return try pretty::interfaceModule(root, &statements[..], arena);
934 948
}
935 949
936 950
/// Produce an immutable package image and compiler declaration set.
937 951
fn compile(
938 952
    ctx: &mut super::CompileContext,
939 953
    modules: module::ModuleTable,
940 954
    res: resolver::Resolver,
941 955
    providers: &[artifact::Package],
942 956
    work: &mut Workspace,
943 957
    selection: Request['providers],
944 -
    target: locations::Native,
945 -
    debug: *mut [u8]
958 +
    native: locations::Native,
959 +
    entryName: *[u8]
946 960
) -> Compilation throws (super::Error) {
947 961
    let index = ctx.entryPkgIdx else panic "compile: missing package";
948 962
    let pkg = ctx.packages[index];
949 963
    let mut declarations: *mut [artifact::Module] = &mut [];
950 964
    {
991 1005
        }
992 1006
    }
993 1007
    unsafe {
994 1008
        heap::reset(work.functions);
995 1009
    }
996 -
    let initial = try codegen::ril(work.emitter, work.spool.take(), pkg.name) catch {
1010 +
    let bytes: ?*mut [u8] = work.spool.take() if selection.key <> nil else nil;
1011 +
    let initial = try codegen::ril(work.emitter, bytes, pkg.name) catch {
997 1012
        throw super::error(&["package encoding storage exhausted", pkg.name]);
998 1013
    };
999 1014
    let mut low = lower::lowerer(res, modules, pkg.name, work.functions, lower::LowerOptions {
1000 1015
        debug: ctx.debug, buildTest: ctx.config.buildTest, tableScope: lower::TableScope::Package
1001 1016
    });
1017 +
    let mut debug: *mut [u8] = &mut [];
1018 +
    if ctx.debug and selection.key <> nil {
1019 +
        set debug = try buffer(work.main, DEBUG_BYTES);
1020 +
    }
1002 1021
    let mut locationWriter = writer::new(debug);
1003 1022
    let root = pkg.rootModuleId else panic "compile: missing root";
1004 -
    if ctx.debug {
1023 +
    if locationWriter.bytes.len > 0 {
1005 1024
        let count = modules.entries.len - root as u32;
1006 1025
        try writer::word(&mut locationWriter, count as u64) catch {
1007 1026
            throw super::Error::Other;
1008 1027
        };
1009 1028
        for i in root as u32 .. modules.entries.len {
1014 1033
    }
1015 1034
    let mut sink = locations::Sink {
1016 1035
        ril: initial,
1017 1036
        locations: locationWriter,
1018 1037
        firstModule: root,
1019 -
        native: target,
1020 -
        entry: selection.entry,
1038 +
        native,
1039 +
        entry: mem::eq(pkg.name, entryName),
1021 1040
    };
1022 1041
    try super::lowerPackage(ctx, modules, &mut low, &pkg, true, &mut sink);
1023 1042
    return try finishPackage(
1024 1043
        ctx, low, sink, &declarations[..], providers, work, selection
1025 1044
    );
1026 1045
}
1027 1046
1028 -
/// Encode the tables, exact pins, and metadata after a package's functions are consumed.
1047 +
/// Encode the tables, metadata pins, and artifact descriptors after a package's functions are consumed.
1029 1048
fn finishPackage(
1030 1049
    ctx: &super::CompileContext,
1031 1050
    low: lower::Lowerer,
1032 1051
    sink: locations::Sink,
1033 1052
    declarations: *[artifact::Module],
1042 1061
        else panic "finishPackage: expected source request";
1043 1062
    let mut packageFiles: *mut [artifact::File] = &mut [];
1044 1063
    try packageFiles.extend(files, work.artifacts) catch {
1045 1064
        throw super::Error::Other;
1046 1065
    };
1047 -
    if ctx.debug {
1066 +
    if sink.locations.bytes.len > 0 {
1048 1067
        let bytes = try keep(
1049 1068
            work.artifacts, &sink.locations.bytes[.. sink.locations.offset]
1050 1069
        ) catch {
1051 1070
            throw super::Error::Other;
1052 1071
        };
1057 1076
            work.artifacts
1058 1077
        ) catch {
1059 1078
            throw super::Error::Other;
1060 1079
        };
1061 1080
    }
1062 -
    let case locations::Sink { ril: encoded, native, locations: locationOutput, .. } = sink
1081 +
    let case locations::Sink { ril: encoded, native, .. } = sink
1063 1082
        else panic "compile: expected function sink";
1064 1083
    let mut spool = encoded;
1065 1084
    let dataOrigins = lowering.dataOrigins.take();
1066 1085
    let references = lowering.tables.references.take();
1067 -
    let case lower::Lowerer { resolver: resolved, data, tables, .. } = lowering
1068 -
        else panic "compile: expected lowerer";
1086 +
    let case lower::Lowerer { data, tables, .. } = lowering else panic "compile: expected lowerer";
1069 1087
    let whole = il::Program {
1070 1088
        data,
1071 1089
        fns: &[],
1072 1090
        layouts: &tables.layouts[..],
1073 1091
        signatures: &tables.signatures[..],
1074 1092
        traits: &tables.traits[..],
1075 1093
    };
1076 -
    let plan = try link::prepare(
1094 +
    let checkpoint = heap::mark(work.functions);
1095 +
    // Function exports follow the retained signatures until the export table
1096 +
    // is sorted.
1097 +
    let mut declaredIndices: *mut [?u32] = &mut [];
1098 +
    try declaredIndices.resize(spool.count, nil, work.functions) catch {
1099 +
        throw super::error(&["package encoding storage exhausted", pkg.name]);
1100 +
    };
1101 +
    {
1102 +
        let borrowed = &spool;
1103 +
        for item, i in &borrowed.exports[..] {
1104 +
            let case binary::ExportKind::Function(source) = item.kind
1105 +
                else panic "finishPackage: expected function export";
1106 +
            set declaredIndices[source] = i;
1107 +
        }
1108 +
    }
1109 +
    let mut plan = try link::prepare(
1077 1110
        &mut spool, &whole, &dataOrigins[..], selection.providers, &references[..], index as u16
1078 1111
    ) catch {
1079 1112
        throw super::error(&["cannot resolve package imports"]);
1080 1113
    };
1081 1114
    super::pkgLog(&pkg, &["encoding package tables"]);
1082 -
    let mut head = try buffer(work.functions, HEADER_BYTES);
1083 1115
    let functionCount = spool.count;
1084 -
    let length = try program::encodeHead(
1085 -
        &mut head, &plan.image, &mut spool.names.index, functionCount
1086 -
    ) catch {
1087 -
        throw super::error(&["cannot encode package image"]);
1088 -
    };
1089 -
    try artifact::alignBuffer(work.artifacts) catch {
1090 -
        throw super::Error::Other;
1091 -
    };
1092 -
    let mut image: *mut [u8] = &mut [];
1093 -
    let end = spool.used;
1094 -
    try image.reserve(length + end, work.artifacts) catch {
1095 -
        throw super::error(&["package image storage exhausted", pkg.name]);
1096 -
    };
1097 -
    try image.extend(&head[.. length], work.artifacts) catch {
1098 -
        throw super::error(&["package encoding storage exhausted", pkg.name]);
1099 -
    };
1100 -
    try image.extend(&spool.bytes[.. end], work.artifacts) catch {
1101 -
        throw super::error(&["package encoding storage exhausted", pkg.name]);
1116 +
    // The spool kept the exported signatures, so the contract is hashed from the tables
1117 +
    // in memory, before the head that records its metadata is encoded.
1118 +
    let declaredFunctions = spool.declared.take();
1119 +
    let signatures: *[il::Fn] = &declaredFunctions[..];
1120 +
    let mut fns: *mut [*il::Fn] = &mut [];
1121 +
    for i in 0 .. signatures.len {
1122 +
        try fns.append(&signatures[i], work.functions) catch {
1123 +
            throw super::error(&["package encoding storage exhausted", pkg.name]);
1124 +
        };
1125 +
    }
1126 +
    let mut contractExports: *mut [binary::Export] = &mut [];
1127 +
    for item in plan.image.exports {
1128 +
        let mut definition = item;
1129 +
        if let case binary::ExportKind::Function(source) = item.kind {
1130 +
            let target = declaredIndices[source]
1131 +
                else panic "finishPackage: missing function declaration";
1132 +
            set definition.kind = binary::ExportKind::Function(target);
1133 +
        }
1134 +
        try contractExports.append(definition, work.functions) catch {
1135 +
            throw super::error(&["package encoding storage exhausted", pkg.name]);
1136 +
        };
1137 +
    }
1138 +
    let mut contract = plan.image;
1139 +
    set contract.program.fns = &fns[..];
1140 +
    set contract.exports = &contractExports[..];
1141 +
    let exports = try metadata::exports(&contract, work.functions) catch {
1142 +
        throw super::error(&["cannot hash exported contracts", pkg.name]);
1102 1143
    };
1103 -
    let bytes: *[u8] = &image[..];
1104 -
    set work.spool = spool.bytes.take();
1144 +
    // Only the hash survives the temporary declaration graph.
1145 +
    unsafe {
1146 +
        heap::rewind(work.functions, checkpoint);
1147 +
    }
1105 1148
    let mut dependencies: *mut [artifact::Dependency] = &mut [];
1106 1149
    for provider, i in providers {
1107 1150
        let mut used = false;
1108 1151
        for id in declared {
1109 1152
            set used = used or id as u32 == i;
1113 1156
        }
1114 1157
        if used {
1115 1158
            try dependencies.append(
1116 1159
                artifact::Dependency {
1117 1160
                    name: provider.name,
1118 -
                    image: provider.identity,
1119 1161
                    declarations: provider.declarations,
1120 1162
                },
1121 1163
                work.artifacts
1122 1164
            ) catch {
1123 1165
                throw super::error(&["package encoding storage exhausted", pkg.name]);
1125 1167
        }
1126 1168
    }
1127 1169
    super::pkgLog(&pkg, &["encoding interface metadata"]);
1128 1170
    let mut result = artifact::Package {
1129 1171
        name: pkg.name,
1130 -
        image: bytes,
1131 -
        identity: linkage::imageId(bytes),
1132 1172
        modules: declarations,
1133 1173
        files: &packageFiles[..],
1134 1174
        dependencies: &dependencies[..],
1135 -
        inputs: request,
1175 +
        exports,
1136 1176
        declarations: binary::Id { bytes: [0; linkage::ID_BYTES] },
1137 -
        metadata: "",
1177 +
        publication: nil,
1138 1178
    };
1139 1179
    set result.declarations = artifact::declarations(&result);
1140 -
    let metadata = try artifact::metadata(&result, head.take(), work.functions) catch {
1141 -
        throw super::error(&["package encoding storage exhausted", pkg.name]);
1142 -
    };
1143 -
    set result.metadata = try keep(work.artifacts, metadata) catch {
1144 -
        throw super::error(&["package encoding storage exhausted", pkg.name]);
1145 -
    };
1180 +
    set plan.image.links.metadata = result.declarations;
1181 +
    let case codegen::RilSpool { encoding, names: collectedNames, .. } = spool
1182 +
        else panic "finishPackage: expected package spool";
1183 +
    let mut names = collectedNames;
1184 +
    if let case codegen::Encoding::Image { bytes, used } = encoding {
1185 +
        let inputs = request else panic "finishPackage: missing publication key";
1186 +
        let mut head = try buffer(work.functions, HEADER_BYTES);
1187 +
        let length = try program::encodeHead(
1188 +
            &mut head, &plan.image, &mut names.index, functionCount
1189 +
        ) catch {
1190 +
            throw super::error(&["cannot encode package image"]);
1191 +
        };
1192 +
        try artifact::alignBuffer(work.artifacts) catch {
1193 +
            throw super::Error::Other;
1194 +
        };
1195 +
        let mut finalImage: *mut [u8] = &mut [];
1196 +
        try finalImage.reserve(length + used, work.artifacts) catch {
1197 +
            throw super::error(&["package image storage exhausted", pkg.name]);
1198 +
        };
1199 +
        try finalImage.extend(&head[.. length], work.artifacts) catch {
1200 +
            throw super::error(&["package encoding storage exhausted", pkg.name]);
1201 +
        };
1202 +
        try finalImage.extend(&bytes[.. used], work.artifacts) catch {
1203 +
            throw super::error(&["package encoding storage exhausted", pkg.name]);
1204 +
        };
1205 +
        let image: *[u8] = &finalImage[..];
1206 +
        let identity = linkage::imageId(image);
1207 +
        let metadata = try artifact::metadata(
1208 +
            &result, inputs, identity, image.len, head.take(), work.functions
1209 +
        ) catch {
1210 +
            throw super::error(&["package encoding storage exhausted", pkg.name]);
1211 +
        };
1212 +
        let text = try keep(work.artifacts, metadata) catch {
1213 +
            throw super::error(&["package encoding storage exhausted", pkg.name]);
1214 +
        };
1215 +
        set result.publication = artifact::Publication { image, inputs, identity, metadata: text };
1216 +
        set work.spool = bytes;
1217 +
    }
1218 +
    let mut nativeData: *[il::Data] = &[];
1219 +
    if let case locations::Native::Program(_) = &native {
1220 +
        set nativeData = try retainData(whole.data, work.emitter) catch {
1221 +
            throw super::error(&["native data storage exhausted"]);
1222 +
        };
1223 +
    }
1146 1224
    unsafe {
1147 1225
        heap::reset(work.functions);
1148 1226
    }
1149 -
    let case writer::Writer { bytes: debugBuffer, .. } = locationOutput
1150 -
        else panic "finishPackage: expected location output";
1151 -
    return Compilation {
1152 -
        package: result,
1153 -
        exports: plan.image.exports,
1154 -
        resolver: resolved,
1155 -
        native,
1156 -
        data: whole.data,
1157 -
        debug: debugBuffer,
1158 -
    };
1227 +
    let mut definitions: *mut [binary::Export] = &mut [];
1228 +
    for item in plan.image.exports {
1229 +
        let mut item = item;
1230 +
        set item.name = try keep(work.emitter, item.name) catch {
1231 +
            throw super::Error::Other;
1232 +
        };
1233 +
        try definitions.append(item, work.emitter) catch {
1234 +
            throw super::Error::Other;
1235 +
        };
1236 +
    }
1237 +
    return Compilation { package: result, exports: &definitions[..], native, data: nativeData };
1238 +
}
1239 +
1240 +
/// Retain native data names and values across package frontend resets.
1241 +
fn retainData(items: &[il::Data], arena: &heap::Heap) -> *[il::Data]
1242 +
    throws (sys::Error, alloc::AllocError)
1243 +
{
1244 +
    let mut retained: *mut [il::Data] = &mut [];
1245 +
    for item in items {
1246 +
        let mut stored = item;
1247 +
        set stored.name = try keep(arena, item.name);
1248 +
        let mut values: *mut [il::DataValue] = &mut [];
1249 +
        for value in item.values {
1250 +
            let mut storedValue = value;
1251 +
            match value.item {
1252 +
                case il::DataItem::Sym(name) =>
1253 +
                    set storedValue.item = il::DataItem::Sym(try keep(arena, name)),
1254 +
                case il::DataItem::Fn(name) =>
1255 +
                    set storedValue.item = il::DataItem::Fn(try keep(arena, name)),
1256 +
                case il::DataItem::Str(bytes) =>
1257 +
                    set storedValue.item = il::DataItem::Str(try keep(arena, bytes)),
1258 +
                else => {}
1259 +
            }
1260 +
            try values.append(storedValue, arena);
1261 +
        }
1262 +
        set stored.values = &values[..];
1263 +
        try retained.append(stored, arena);
1264 +
    }
1265 +
    return &retained[..];
1159 1266
}
1160 1267
1161 1268
/// Assemble a captured native input and register its code and immutable data.
1162 1269
fn assembly(
1163 1270
    generator: &mut rv64::Generator,
1216 1323
        };
1217 1324
        if sourceCount <> package.modules.len {
1218 1325
            throw super::error(&["package debug module count mismatch", package.name]);
1219 1326
        }
1220 1327
        for _ in 0 .. sourceCount {
1221 -
            let path = try debug.bytes(work.main) catch {
1328 +
            let path = try debug.bytes(work.emitter) catch {
1222 1329
                throw super::Error::Other;
1223 1330
            };
1224 -
            try sourcePaths.append(path, work.main) catch {
1331 +
            try sourcePaths.append(path, work.emitter) catch {
1225 1332
                throw super::Error::Other;
1226 1333
            };
1227 1334
        }
1228 1335
    }
1229 1336
    if ctx.debug and debugBytes.len == 0 {
1230 1337
        for module in package.modules {
1231 -
            try sourcePaths.append(module.path, work.main) catch {
1338 +
            try sourcePaths.append(module.path, work.emitter) catch {
1232 1339
                throw super::Error::Other;
1233 1340
            };
1234 1341
        }
1235 1342
    }
1236 -
    let mut input = reader::new(package.image);
1237 -
    let head = try program::header(&mut input, work.main) catch {
1343 +
    let publication = package.publication else panic "decode: missing package image";
1344 +
    let mut input = reader::new(publication.image);
1345 +
    let head = try program::header(&mut input, work.emitter) catch {
1238 1346
        throw super::error(&["invalid native package image", package.name]);
1239 1347
    };
1240 1348
    if not mem::eq(head.name, package.name) {
1241 1349
        throw super::error(&["package image name mismatch", package.name]);
1242 1350
    }
compiler/radiance/cache.rad +6 -3
44 44
        if error == sys::Error::NotFound or error == sys::Error::Invalid {
45 45
            return nil;
46 46
        }
47 47
        throw error;
48 48
    };
49 -
    if result.inputs <> key {
49 +
    let publication = result.publication else panic "lookup: missing publication";
50 +
    if publication.inputs <> key {
50 51
        unsafe {
51 52
            heap::rewind(arena, saved);
52 53
        }
53 54
        return nil;
54 55
    }
82 83
export fn publish(
83 84
    root: *[u8], package: &artifact::Package, syntax: &mut parser::Parser, arena: &heap::Heap
84 85
)
85 86
    throws (sys::Error)
86 87
{
87 -
    let path = try entry(root, package.inputs, arena);
88 +
    let publication = package.publication else panic "publish: missing publication";
89 +
    let path = try entry(root, publication.inputs, arena);
88 90
    try artifact::directories(try artifact::join(arena, &[root, "/"]));
89 91
    let stage = try temporary(path, arena);
90 92
    try artifact::write(package, stage, arena) catch error {
91 93
        try fs::removeTree(stage, arena) catch {};
92 94
        throw error;
104 106
    stage: *[u8],
105 107
    package: &artifact::Package,
106 108
    syntax: &mut parser::Parser,
107 109
    arena: &heap::Heap
108 110
) throws (sys::Error) {
111 +
    let publication = package.publication else panic "install: missing publication";
109 112
    for _ in 0 .. TEMPORARY_SLOTS {
110 113
        try fs::rename(stage, path) catch error {
111 114
            if error <> sys::Error::NotEmpty
112 115
                and error <> sys::Error::Exists
113 116
                and error <> sys::Error::Invalid
116 119
            }
117 120
            if try fs::stat(path) == nil {
118 121
                continue;
119 122
            }
120 123
            let existing = try lookup(
121 -
                root, package.name, package.inputs, syntax, arena
124 +
                root, package.name, publication.inputs, syntax, arena
122 125
            );
123 126
            if existing <> nil {
124 127
                try fs::removeTree(stage, arena);
125 128
                return;
126 129
            }
compiler/radiance/codegen.rad +91 -20
3 3
4 4
use std::arch::rv64;
5 5
use std::collections::dict;
6 6
use std::io;
7 7
use std::lang::gen::data;
8 +
use std::lang::alloc;
8 9
use std::lang::il;
9 10
use std::lang::il::binary;
11 +
use std::lang::il::binary::cfg;
10 12
use std::lang::il::binary::collect;
11 13
use std::lang::il::binary::program;
12 14
use std::lang::lower;
13 15
use std::lang::sexpr;
14 16
use std::mem;
99 101
            throw lower::LowerError::OutputFailed;
100 102
        }
101 103
    }
102 104
}
103 105
104 -
/// Sink that encodes one package's functions and reclaims their IL arena.
105 -
/// Only encoded bytes and name tables remain after each function.
106 +
/// Optional serialized function storage for a package.
107 +
export union Encoding {
108 +
    /// Keep declarations without serialized function bodies.
109 +
    None,
110 +
    /// Retain encoded functions for cache storage or artifact export.
111 +
    Image {
112 +
        /// Encoded functions in lowering order.
113 +
        bytes: *mut [u8],
114 +
        /// Number of initialized function bytes.
115 +
        used: u32,
116 +
    },
117 +
}
118 +
119 +
/// Sink that collects package declarations and reclaims each function's IL.
120 +
/// Encoded output is retained when package storage is selected.
106 121
export record RilSpool {
107 122
    /// Storage of the name tables. It lives until the package is written.
108 123
    arena: *heap::Heap,
109 124
    /// Package name.
110 125
    name: *[u8],
111 126
    /// Interned names shared by functions and package tables.
112 127
    names: collect::Names,
113 -
    /// Encoded functions in lowering order.
114 -
    bytes: *mut [u8],
115 -
    /// Number of initialized function bytes.
116 -
    used: u32,
117 -
    /// Number of encoded functions.
128 +
    /// Serialized function output when package storage is selected.
129 +
    encoding: Encoding,
130 +
    /// Number of lowered functions.
118 131
    count: u32,
119 132
    /// Exported functions, followed by exported data after lowering.
120 133
    exports: *mut [binary::Export],
134 +
    /// Signatures of the exported functions in export order, copied out of each
135 +
    /// function's storage, for the metadata hash of the package.
136 +
    declared: *mut [il::Fn],
121 137
    /// Default function's stored name, including its storage wrapper if present.
122 138
    entry: ?*[u8],
123 139
}
124 140
125 141
/// Create a function spool for one package.
126 -
export fn ril(arena: *heap::Heap, bytes: *mut [u8], name: *[u8]) -> RilSpool
142 +
export fn ril(arena: *heap::Heap, bytes: ?*mut [u8], name: *[u8]) -> RilSpool
127 143
    throws (binary::Error)
128 144
{
129 145
    let mut names = try collect::new(collect::INDEX_SLOTS, arena);
130 146
    try collect::start(&mut names, name, arena);
147 +
    let mut encoding = Encoding::None;
148 +
    if let bytes = bytes {
149 +
        set encoding = Encoding::Image { bytes, used: 0 };
150 +
    }
131 151
    return RilSpool {
132 -
        arena, name, names, bytes, used: 0, count: 0, exports: &mut [], entry: nil
152 +
        arena,
153 +
        name,
154 +
        names,
155 +
        encoding,
156 +
        count: 0,
157 +
        exports: &mut [],
158 +
        declared: &mut [],
159 +
        entry: nil,
133 160
    };
134 161
}
135 162
136 163
instance lower::FnSink for RilSpool {
137 -
    /// Encode one function into its package and reclaim its IL arena.
164 +
    /// Retain one function's declarations and selected encoding, then reclaim its IL arena.
138 165
    fn (spool: &mut RilSpool) emit(
139 166
        func: *il::Fn,
140 167
        role: lower::FnRole,
141 168
        origin: lower::Origin,
142 169
        layouts: &[il::Layout],
159 186
        };
160 187
        resetFnArena(fnArena);
161 188
    }
162 189
}
163 190
164 -
/// Collect the names of `func` and append its encoding to the package spool.
191 +
/// Collect the declarations of `func` and write its selected package encoding.
165 192
/// A function with the default role becomes the entry of its package. An exported function
166 193
/// is also an export.
167 194
fn encodeFunction(spool: &mut RilSpool, func: *il::Fn, role: lower::FnRole, origin: lower::Origin)
168 195
    throws (binary::Error)
169 196
{
171 198
        &mut spool.names, spool.name, func.name, spool.arena
172 199
    );
173 200
    if let case lower::Linkage::Exported = origin.linkage {
174 201
        let definition = binary::Export {
175 202
            name: stored,
176 -
            kind: binary::ExportKind::Function,
203 +
            kind: binary::ExportKind::Function(spool.count),
177 204
            startable: false,
178 205
        };
179 206
        try spool.exports.append(definition, spool.arena) catch {
180 207
            throw binary::Error::Storage;
181 208
        };
209 +
        let mut params: *mut [il::Param] = &mut [];
210 +
        let mut borrows: *mut [il::Borrow] = &mut [];
211 +
        try params.extend(func.params, spool.arena) catch {
212 +
            throw binary::Error::Storage;
213 +
        };
214 +
        try borrows.extend(func.borrows, spool.arena) catch {
215 +
            throw binary::Error::Storage;
216 +
        };
217 +
        try spool.declared.append(
218 +
            il::Fn {
219 +
                name: stored,
220 +
                params: &params[..],
221 +
                returnType: func.returnType,
222 +
                isExtern: false,
223 +
                isLeaf: func.isLeaf,
224 +
                blocks: &[],
225 +
                vals: &[],
226 +
                cases: &[],
227 +
                borrows: &borrows[..],
228 +
            },
229 +
            spool.arena
230 +
        ) catch {
231 +
            throw binary::Error::Storage;
232 +
        };
182 233
    }
183 234
    if let case lower::FnRole::Default = role {
184 235
        set spool.entry = stored;
185 236
    }
186 -
    let end = try program::appendCollected(
187 -
        &mut spool.bytes, spool.used, &mut spool.names, func, spool.arena
188 -
    );
237 +
    if let case Encoding::Image { bytes, used } = &mut spool.encoding {
238 +
        let end = try program::appendCollected(
239 +
            bytes, *used, &mut spool.names, func, spool.arena
240 +
        );
241 +
        set *used = end;
242 +
    }
189 243
    set spool.count += 1;
190 -
    set spool.used = end;
191 244
}
192 245
193 246
/// Reset the function arena after a function has been generated.
194 247
///
195 248
/// This is the audited unsafe site of the streaming pass. Invariant: the
200 253
    unsafe {
201 254
        heap::reset(fnArena);
202 255
    }
203 256
}
204 257
205 -
/// Generate a function and register its entry symbol when required.
206 -
fn generateFunction(
258 +
/// Rebuild control-flow metadata, generate a function, and register its entry symbol.
259 +
export fn generateFunction(
207 260
    ctx: &mut Context,
208 261
    func: *il::Fn,
209 262
    role: lower::FnRole,
210 263
    layouts: &[il::Layout],
211 264
    fnArena: &heap::Heap
213 266
    match role {
214 267
        case lower::FnRole::Default => {
215 268
            try rv64::recordFunctionAlias(&mut ctx.generator, super::DEFAULT_ENTRY_SYMBOL);
216 269
            match ctx.generator.entryPatch {
217 270
                case rv64::EntryPatch::Reserved(_) => {
218 -
                    set ctx.generator.entryPatch = rv64::EntryPatch::Reserved(func.name);
271 +
                    let name = try alloc::copyBytes(ctx.generator.e.arena, func.name) catch {
272 +
                        throw rv64::Error::Allocation;
273 +
                    };
274 +
                    set ctx.generator.entryPatch = rv64::EntryPatch::Reserved(&name[..]);
219 275
                }
220 276
                // Startup assembly calls the default function through its
221 277
                // default entry symbol when no entry jump is reserved.
222 278
                case rv64::EntryPatch::None => {}
223 279
            }
224 280
        }
225 281
        else => {}
226 282
    }
227 -
    try rv64::generateFunction(&mut ctx.generator, func, layouts, fnArena);
283 +
    let mut blocks: *mut [il::Block] = &mut [];
284 +
    try blocks.extend(func.blocks, fnArena) catch {
285 +
        throw rv64::Error::Allocation;
286 +
    };
287 +
    try cfg::link(&mut blocks[..], func.cases, fnArena) catch error {
288 +
        throw rv64::Error::Allocation
289 +
            if error == binary::Error::Storage
290 +
            else rv64::Error::Invalid;
291 +
    };
292 +
    let mut linked = *func;
293 +
    set linked.blocks = &blocks[..];
294 +
    let mut functions: *mut [il::Fn] = &mut [];
295 +
    try functions.append(linked, fnArena) catch {
296 +
        throw rv64::Error::Allocation;
297 +
    };
298 +
    try rv64::generateFunction(&mut ctx.generator, &functions[0], layouts, fnArena);
228 299
}
229 300
230 301
/// Describe the limit that code generation exceeded.
231 302
fn limitName(limit: rv64::Limit) -> *[u8] {
232 303
    match limit {
compiler/radiance/link.rad +46 -19
3 3
use std::lang::il;
4 4
use std::lang::il::binary;
5 5
use std::lang::il::binary::collect;
6 6
use std::lang::lower;
7 7
use std::mem;
8 +
use std::mem::heap;
8 9
use super::codegen;
9 10
10 -
/// Test whether a resolved foreign reference names a public provider definition.
11 -
fn exported(provider: &Provider, name: *[u8]) -> bool {
12 -
    for item in provider.exports {
13 -
        if mem::eq(item.name, name) {
14 -
            return true;
15 -
        }
16 -
    }
17 -
    return false;
18 -
}
19 -
20 -
/// Completed provider used to select exact imports.
11 +
/// Completed provider used to select typed imports.
21 12
export record Provider: Copy {
22 13
    /// Package name.
23 14
    name: *[u8],
24 -
    /// Identity of the complete RIL image.
25 -
    image: binary::Id,
26 -
    /// Public function and data definitions.
15 +
    /// Compiler metadata hash of the provider.
16 +
    metadata: binary::Id,
17 +
    /// Public function and data definitions, sorted by name.
27 18
    exports: *[binary::Export],
28 19
}
29 20
30 21
/// Package head and resolved provider indices for one compilation step.
31 22
export record Plan {
33 24
    image: binary::Package,
34 25
    /// Provider indices in the image's dependency order.
35 26
    dependencies: *[u32],
36 27
}
37 28
38 -
/// Construct one package head with typed aliases and exact dependency labels.
29 +
/// Construct one package head with typed aliases and dependency metadata hashes.
39 30
/// Function records remain in the spool.
40 31
export fn prepare(
41 32
    spool: &mut codegen::RilSpool,
42 33
    whole: &il::Program,
43 34
    origins: &[lower::Origin],
51 42
            throw binary::Error::Invalid;
52 43
        }
53 44
        if let case lower::Linkage::Exported = origins[i].linkage {
54 45
            try spool.exports.append(
55 46
                binary::Export {
56 -
                    name: item.name, kind: binary::ExportKind::Data, startable: false
47 +
                    name: item.name, kind: binary::ExportKind::Data(i), startable: false
57 48
                },
58 49
                arena
59 50
            ) catch {
60 51
                throw binary::Error::Storage;
61 52
            };
72 63
        let owner = reference.provider as u32;
73 64
        if owner >= providers.len {
74 65
            throw binary::Error::Symbol;
75 66
        }
76 67
        let provider = &providers[owner];
77 -
        if not exported(provider, reference.name) {
68 +
        if binary::find(provider.exports, reference.name) == nil {
78 69
            throw binary::Error::Symbol;
79 70
        }
80 71
        let mut dependency: ?u32 = nil;
81 72
        for k in 0 .. indices.len {
82 73
            if indices[k] == owner {
87 78
        if dependency == nil {
88 79
            set dependency = dependencies.len;
89 80
            try dependencies.append(provider.name, arena) catch {
90 81
                throw binary::Error::Storage;
91 82
            };
92 -
            try pins.append(provider.image, arena) catch {
83 +
            try pins.append(provider.metadata, arena) catch {
93 84
                throw binary::Error::Storage;
94 85
            };
95 86
            try indices.append(owner, arena) catch {
96 87
                throw binary::Error::Storage;
97 88
            };
107 98
            arena
108 99
        ) catch {
109 100
            throw binary::Error::Storage;
110 101
        };
111 102
    }
112 -
    let exports = spool.exports.take();
103 +
    let mut exports = spool.exports.take();
104 +
    try sort(&mut exports[..], arena);
113 105
    let mut image = try collect::finish(
114 106
        &mut spool.names,
115 107
        spool.name,
116 108
        &dependencies[..],
117 109
        *whole,
121 113
    );
122 114
    set image.links.pins = &pins[..];
123 115
    set image.links.imports = &imports[..];
124 116
    return Plan { image, dependencies: &indices[..] };
125 117
}
118 +
119 +
/// Sort exports by name, with a bottom-up merge sort.
120 +
fn sort(exports: &mut [binary::Export], arena: *heap::Heap) throws (binary::Error) {
121 +
    let count = exports.len;
122 +
    let mut merged: *mut [binary::Export] = &mut [];
123 +
    try merged.extend(exports, arena) catch {
124 +
        throw binary::Error::Storage;
125 +
    };
126 +
    let mut width: u32 = 1;
127 +
    while width < count {
128 +
        let mut start: u32 = 0;
129 +
        while start < count {
130 +
            let middle = count if width > count - start else start + width;
131 +
            let end = count if width > count - middle else middle + width;
132 +
            let mut left = start;
133 +
            let mut right = middle;
134 +
            for k in start .. end {
135 +
                if left < middle
136 +
                    and (right == end
137 +
                        or mem::cmp(exports[left].name, exports[right].name) <= 0)
138 +
                {
139 +
                    set merged[k] = exports[left];
140 +
                    set left += 1;
141 +
                } else {
142 +
                    set merged[k] = exports[right];
143 +
                    set right += 1;
144 +
                }
145 +
            }
146 +
            set start = end;
147 +
        }
148 +
        let values: &[binary::Export] = &merged[..];
149 +
        set exports[..] = values;
150 +
        set width *= 2;
151 +
    }
152 +
}
compiler/radiance/locations.rad +8 -20
1 1
//! Source location sidecars for independently compiled native package images.
2 2
3 -
use std::arch::rv64;
4 3
use std::fs;
5 4
use std::lang::alloc;
6 -
use std::io;
7 5
use std::lang::gen::types;
8 6
use std::lang::il;
9 7
use std::lang::il::binary;
10 8
use std::lang::il::binary::reader;
11 9
use std::lang::il::binary::writer;
22 20
    registers: 1048576, blocks: 65536
23 21
};
24 22
/// Bytes in a source location pair in the sidecar.
25 23
constant LOCATION_WIRE_BYTES: u32 = 8;
26 24
27 -
/// Native generation from the same functions that populate a package image.
25 +
/// Native function output for the invocation.
28 26
export union Native {
29 -
    /// Produce package artifacts only.
27 +
    /// Check or export packages without native generation.
30 28
    None,
31 -
    /// Retain the invocation's native generator between packages.
32 -
    Program(rv64::Generator),
29 +
    /// Generate native code from each function's IL.
30 +
    Program(codegen::Context),
33 31
}
34 32
35 33
/// Package RIL sink with native generation and source location output.
36 34
export record Sink {
37 35
    /// Encoded functions and their symbol tables.
38 36
    ril: codegen::RilSpool,
39 37
    /// Source table followed by one location record for each function.
40 38
    locations: writer::Writer,
41 39
    /// First module identifier of the package in its source compilation.
42 40
    firstModule: u16,
43 -
    /// Native output selected for this invocation.
41 +
    /// Native function output for the invocation.
44 42
    native: Native,
45 43
    /// Whether this package supplies the program entry.
46 44
    entry: bool,
47 45
}
48 46
60 58
        if sink.locations.bytes.len > 0 {
61 59
            try encode(&mut sink.locations, sink.firstModule, func) catch {
62 60
                throw lower::LowerError::OutputFailed;
63 61
            };
64 62
        }
65 -
        if let case Native::Program(generator) = &mut sink.native {
66 -
            if sink.entry and role == lower::FnRole::Default {
67 -
                try rv64::recordFunctionAlias(generator, super::DEFAULT_ENTRY_SYMBOL) catch {
68 -
                    throw lower::LowerError::OutputFailed;
69 -
                };
70 -
                if let case rv64::EntryPatch::Reserved(_) = generator.entryPatch {
71 -
                    set generator.entryPatch = rv64::EntryPatch::Reserved(func.name);
72 -
                }
73 -
            }
74 -
            try rv64::generateFunction(generator, func, layouts, arena) catch error {
63 +
        if let case Native::Program(ctx) = &mut sink.native {
64 +
            let nativeRole = role if sink.entry else lower::FnRole::Normal;
65 +
            try codegen::generateFunction(ctx, func, nativeRole, layouts, arena) catch error {
75 66
                codegen::printError(error);
76 -
                io::printError("radiance: while generating function ");
77 -
                io::printError(func.name);
78 -
                io::printError("\n");
79 67
                throw lower::LowerError::OutputFailed;
80 68
            };
81 69
        }
82 70
        let target: &mut opaque lower::FnSink = &mut sink.ril;
83 71
        try target.emit(func, role, origin, layouts, arena);
compiler/radiance/metadata.rad added +329 -0
1 +
//! Canonical exported RIL contracts for compiler metadata hashes.
2 +
3 +
use std::hash::blake3;
4 +
use std::lang::il;
5 +
use std::lang::il::binary;
6 +
use std::mem;
7 +
use std::mem::heap;
8 +
9 +
/// Bytes of the contract encoding collected before each hash update, so that the hash
10 +
/// sees long runs instead of one call per field.
11 +
constant PENDING: u32 = 4096;
12 +
13 +
/// Descriptor table of a canonical graph edge.
14 +
union Kind: Copy {
15 +
    /// Memory layout.
16 +
    Layout,
17 +
    /// Callable signature.
18 +
    Signature,
19 +
    /// Dynamic trait contract.
20 +
    Trait,
21 +
}
22 +
23 +
/// Descriptor reached in canonical traversal order.
24 +
record Edge: Copy {
25 +
    /// Descriptor table.
26 +
    kind: Kind,
27 +
    /// Provider-local descriptor index.
28 +
    index: u32,
29 +
}
30 +
31 +
/// Hash state and canonical graph indices.
32 +
record State {
33 +
    /// Incremental hash of the contract encoding.
34 +
    hash: blake3::State,
35 +
    /// Encoded bytes not yet passed to `hash`.
36 +
    pending: [u8; PENDING],
37 +
    /// Number of initialized bytes in `pending`.
38 +
    used: u32,
39 +
    /// Descriptors in first-use order.
40 +
    edges: *mut [Edge],
41 +
    /// Position in `edges` of each descriptor seen, indexed by layout, then signature,
42 +
    /// then trait index.
43 +
    positions: *mut [?u32],
44 +
    /// Number of layouts, where signature positions start.
45 +
    layouts: u32,
46 +
    /// Number of layouts and signatures, where trait positions start.
47 +
    signatures: u32,
48 +
    /// Storage for graph edges.
49 +
    arena: *heap::Heap,
50 +
}
51 +
52 +
/// Pass the pending bytes to the hash.
53 +
fn flush(state: &mut State) {
54 +
    blake3::update(&mut state.hash, &state.pending[.. state.used]);
55 +
    set state.used = 0;
56 +
}
57 +
58 +
/// Hash a fixed-width unsigned field.
59 +
fn number(state: &mut State, value: u64) {
60 +
    if state.used > PENDING - 8 {
61 +
        flush(state);
62 +
    }
63 +
    mem::store64Le(&mut state.pending[..], state.used, value);
64 +
    set state.used += 8;
65 +
}
66 +
67 +
/// Hash a length-delimited byte field.
68 +
fn bytes(state: &mut State, value: &[u8]) {
69 +
    number(state, value.len as u64);
70 +
    if value.len > PENDING - state.used {
71 +
        flush(state);
72 +
        blake3::update(&mut state.hash, value);
73 +
        return;
74 +
    }
75 +
    set state.pending[state.used .. state.used + value.len] = value;
76 +
    set state.used += value.len;
77 +
}
78 +
79 +
/// Hash an edge through its canonical index and retain unseen descriptors.
80 +
fn edge(state: &mut State, kind: Kind, index: u32) throws (binary::Error) {
81 +
    let mut slot = index;
82 +
    let mut end = state.layouts;
83 +
    match kind {
84 +
        case Kind::Layout => {}
85 +
        case Kind::Signature => {
86 +
            set slot += state.layouts;
87 +
            set end = state.signatures;
88 +
        }
89 +
        case Kind::Trait => {
90 +
            set slot += state.signatures;
91 +
            set end = state.positions.len;
92 +
        }
93 +
    }
94 +
    if slot >= end {
95 +
        throw binary::Error::Invalid;
96 +
    }
97 +
    if let position = state.positions[slot] {
98 +
        number(state, position as u64);
99 +
        return;
100 +
    }
101 +
    let count = state.edges.len;
102 +
    number(state, count as u64);
103 +
    set state.positions[slot] = count;
104 +
    try state.edges.append(Edge { kind, index }, state.arena) catch {
105 +
        throw binary::Error::Storage;
106 +
    };
107 +
}
108 +
109 +
/// Hash pointer rights and its pointee edge.
110 +
fn pointer(state: &mut State, ptr: il::PtrType) throws (binary::Error) {
111 +
    number(state, 1 if ptr.own else 0);
112 +
    number(state, 1 if ptr.mutable else 0);
113 +
    number(state, 1 if ptr.nullable else 0);
114 +
    try edge(state, Kind::Layout, ptr.layout);
115 +
}
116 +
117 +
/// Hash a value type with a distinct tag for each type category.
118 +
fn value(state: &mut State, typ: il::ValType) throws (binary::Error) {
119 +
    match typ {
120 +
        case il::ValType::Void => number(state, 0),
121 +
        case il::ValType::Data(t) => {
122 +
            number(state, 1);
123 +
            number(state, il::typeSize(t) as u64);
124 +
        }
125 +
        case il::ValType::Ptr(p) => {
126 +
            number(state, 2);
127 +
            try pointer(state, p);
128 +
        }
129 +
        case il::ValType::Fn(s) => {
130 +
            number(state, 3);
131 +
            try edge(state, Kind::Signature, s);
132 +
        }
133 +
        case il::ValType::Heap(h) => {
134 +
            number(state, 4);
135 +
            number(state, h as u64);
136 +
        }
137 +
    }
138 +
}
139 +
140 +
/// Hash a counted list of region positions.
141 +
fn regions(state: &mut State, items: &[u32]) {
142 +
    number(state, items.len as u64);
143 +
    for item in items {
144 +
        number(state, item as u64);
145 +
    }
146 +
}
147 +
148 +
/// Hash a presence tag and an optional region position.
149 +
fn optional(state: &mut State, item: ?u32) {
150 +
    number(state, 1 if item <> nil else 0);
151 +
    if let index = item {
152 +
        number(state, index as u64);
153 +
    }
154 +
}
155 +
156 +
/// Hash ordered borrow relations.
157 +
fn borrows(state: &mut State, items: &[il::Borrow]) {
158 +
    number(state, items.len as u64);
159 +
    for item in items {
160 +
        optional(state, item.target);
161 +
        number(state, item.result as u64);
162 +
        number(state, item.param as u64);
163 +
        optional(state, item.source);
164 +
    }
165 +
}
166 +
167 +
/// Hash a protected slot and queue its descriptor edges.
168 +
fn slot(state: &mut State, item: il::SlotKind) throws (binary::Error) {
169 +
    match item {
170 +
        case il::SlotKind::Ptr(p) => {
171 +
            number(state, 0);
172 +
            try pointer(state, p);
173 +
        }
174 +
        case il::SlotKind::Slice(p) => {
175 +
            number(state, 1);
176 +
            try pointer(state, p);
177 +
        }
178 +
        case il::SlotKind::Fn(s) => {
179 +
            number(state, 2);
180 +
            try edge(state, Kind::Signature, s);
181 +
        }
182 +
        case il::SlotKind::Heap(h) => {
183 +
            number(state, 3);
184 +
            number(state, h as u64);
185 +
        }
186 +
        case il::SlotKind::Trait(t) => {
187 +
            number(state, 4);
188 +
            number(state, 1 if t.own else 0);
189 +
            number(state, 1 if t.mutable else 0);
190 +
            try edge(state, Kind::Trait, t.iface);
191 +
        }
192 +
        case il::SlotKind::Sub(s) => {
193 +
            number(state, 5);
194 +
            try edge(state, Kind::Layout, s);
195 +
        }
196 +
        case il::SlotKind::Array { layout, count } => {
197 +
            number(state, 6);
198 +
            number(state, count as u64);
199 +
            try edge(state, Kind::Layout, layout);
200 +
        }
201 +
        case il::SlotKind::Union { offset, size, variants } => {
202 +
            number(state, 7);
203 +
            number(state, offset as u64);
204 +
            number(state, size as u64);
205 +
            number(state, variants.len as u64);
206 +
            for variant in variants {
207 +
                number(state, variant.tag as u64);
208 +
                number(state, 1 if variant.layout <> nil else 0);
209 +
                if let layout = variant.layout {
210 +
                    try edge(state, Kind::Layout, layout);
211 +
                }
212 +
                regions(state, variant.regions);
213 +
            }
214 +
        }
215 +
    }
216 +
}
217 +
218 +
/// Hash all descriptors reachable from the exported roots. Every queued index is in
219 +
/// range, because [`edge`] rejects the others.
220 +
fn graph(state: &mut State, program: &il::Program) throws (binary::Error) {
221 +
    let mut cursor: u32 = 0;
222 +
    while cursor < state.edges.len {
223 +
        let item = state.edges[cursor];
224 +
        set cursor += 1;
225 +
        number(state, item.kind as u64);
226 +
        match item.kind {
227 +
            case Kind::Layout => {
228 +
                let layout = program.layouts[item.index];
229 +
                number(state, layout.size as u64);
230 +
                number(state, layout.alignment as u64);
231 +
                number(state, layout.regions as u64);
232 +
                number(state, layout.slots.len as u64);
233 +
                for item in layout.slots {
234 +
                    number(state, item.offset as u64);
235 +
                    try slot(state, item.kind);
236 +
                    regions(state, item.regions);
237 +
                }
238 +
            }
239 +
            case Kind::Signature => {
240 +
                let signature = program.signatures[item.index];
241 +
                number(state, signature.params.len as u64);
242 +
                for param in signature.params {
243 +
                    try value(state, param);
244 +
                }
245 +
                try value(state, signature.ret);
246 +
                borrows(state, signature.borrows);
247 +
            }
248 +
            case Kind::Trait => {
249 +
                let contract = program.traits[item.index];
250 +
                number(state, contract.methods.len as u64);
251 +
                for method in contract.methods {
252 +
                    number(state, method.receiver as u64);
253 +
                    number(state, 1 if method.own else 0);
254 +
                    number(state, 1 if method.mutable else 0);
255 +
                    try edge(state, Kind::Signature, method.sig);
256 +
                }
257 +
            }
258 +
        }
259 +
    }
260 +
}
261 +
262 +
/// Hash exported names and their reachable contracts, independent of private table indices.
263 +
/// Function bodies, data initializers, and dependency image selections are separate inputs.
264 +
/// Exports must be sorted by name. Each export must index a definition of
265 +
/// the same name.
266 +
export fn exports(package: &binary::Package, arena: *heap::Heap) -> binary::Id
267 +
    throws (binary::Error)
268 +
{
269 +
    let program = package.program;
270 +
    let mut positions: *mut [?u32] = &mut [];
271 +
    let descriptors = program.layouts.len + program.signatures.len + program.traits.len;
272 +
    try positions.resize(descriptors, nil, arena) catch {
273 +
        throw binary::Error::Storage;
274 +
    };
275 +
    let mut state = State {
276 +
        hash: blake3::new(),
277 +
        pending: [0; PENDING],
278 +
        used: 0,
279 +
        edges: &mut [],
280 +
        positions,
281 +
        layouts: program.layouts.len,
282 +
        signatures: program.layouts.len + program.signatures.len,
283 +
        arena,
284 +
    };
285 +
    bytes(&mut state, "Radiance exported metadata 1");
286 +
    number(&mut state, binary::ABI_VERSION as u64);
287 +
    number(&mut state, package.exports.len as u64);
288 +
    for item, i in package.exports {
289 +
        if i > 0 and mem::cmp(package.exports[i - 1].name, item.name) >= 0 {
290 +
            throw binary::Error::Invalid;
291 +
        }
292 +
        bytes(&mut state, item.name);
293 +
        match item.kind {
294 +
            case binary::ExportKind::Function(found) => {
295 +
                number(&mut state, 0);
296 +
                if found >= program.fns.len or not mem::eq(program.fns[found].name, item.name) {
297 +
                    throw binary::Error::Invalid;
298 +
                }
299 +
                let func = program.fns[found];
300 +
                number(&mut state, func.params.len as u64);
301 +
                for param in func.params {
302 +
                    try value(&mut state, param.type);
303 +
                }
304 +
                try value(&mut state, func.returnType);
305 +
                borrows(&mut state, func.borrows);
306 +
            }
307 +
            case binary::ExportKind::Data(found) => {
308 +
                number(&mut state, 1);
309 +
                if found >= program.data.len or not mem::eq(program.data[found].name, item.name) {
310 +
                    throw binary::Error::Invalid;
311 +
                }
312 +
                let definition = program.data[found];
313 +
                number(&mut state, definition.size as u64);
314 +
                number(&mut state, definition.alignment as u64);
315 +
                number(&mut state, 1 if definition.readOnly else 0);
316 +
                number(&mut state, 1 if definition.heap <> nil else 0);
317 +
                if let rights = definition.heap {
318 +
                    number(&mut state, rights as u64);
319 +
                }
320 +
                try edge(&mut state, Kind::Layout, definition.layout);
321 +
            }
322 +
        }
323 +
    }
324 +
    try graph(&mut state, &package.program);
325 +
    flush(&mut state);
326 +
    let case State { hash, .. } = state else panic "exports: hash state";
327 +
    let result = blake3::finish(hash);
328 +
    return binary::Id { bytes: result.bytes };
329 +
}
kernel/kernel/abi.rad +2 -1
271 271
    EventTimeout = 40,
272 272
    /// Wait for an event.
273 273
    EventWait = 41,
274 274
    /// Deliver a wake token.
275 275
    EventWakeup = 42,
276 -
    /// Load a binary RIL package, which the kernel verifies.
276 +
    /// Load a binary RIL package, which the kernel verifies. It links only against
277 +
    /// packages behind the caller's Image handles with execute rights.
277 278
    ImageLoad = 50,
278 279
    /// Create an additional execution context.
279 280
    ContextCreate = 60,
280 281
    /// Destroy an additional execution context.
281 282
    ContextDestroy = 61,
kernel/kernel/calls.rad +3 -0
236 236
        return try interrupts::transfer(
237 237
            &mut shared.interrupts, source, destination, handle, rights
238 238
        );
239 239
    }
240 240
    try resident(&*shared, entry);
241 +
    if entry.kind == abi::Kind::Image {
242 +
        try registry::unique(&shared.registry, &*destination, entry.object);
243 +
    }
241 244
    let pending = try transactions::reserve(
242 245
        destination, source.owner, handle, entry, rights, moving
243 246
    );
244 247
    if moving {
245 248
        return transactions::transfer(source, destination, pending);
kernel/kernel/lifecycle.rad +2 -0
434 434
                    match access {
435 435
                        case LoadAccess::Input(input) =>
436 436
                            return try loader::finish(
437 437
                                state,
438 438
                                memory,
439 +
                                &*packages,
439 440
                                table,
440 441
                                loader::Reservation::Held(loading.input, input),
441 442
                                existing
442 443
                            ),
443 444
                        case LoadAccess::Output(
463 464
                                compiled
464 465
                            );
465 466
                            return try loader::finish(
466 467
                                state,
467 468
                                memory,
469 +
                                &*packages,
468 470
                                table,
469 471
                                loader::Reservation::Held(loading.input, input),
470 472
                                object
471 473
                            );
472 474
                        }
kernel/kernel/loader.rad +16 -7
131 131
    base: u64,
132 132
    /// Validated physical source address.
133 133
    address: u64,
134 134
    /// Number of source bytes to snapshot.
135 135
    length: u32,
136 +
    /// Packages behind the caller's Image handles when the load began, which are the
137 +
    /// only providers it may link against.
138 +
    visible: registry::Visible,
136 139
}
137 140
138 141
/// Proof that the input's workspace and source ranges are allocated. The holder is
139 142
/// the only user of the workspace until the load is cancelled or finished.
140 143
export union InputAccess {
397 400
            // SAFETY: see `Input`.
398 401
            unsafe {
399 402
                let work = view(address);
400 403
                try physical::readAt(source, 0, &mut work.input[.. input.length]);
401 404
                let image = linkage::imageId(&work.input[.. input.length]);
402 -
                if let resident = registry::findImage(
403 -
                    packages, image, shared::Verification::Verified
404 -
                ) {
405 -
                    return Prepared::Resident(resident);
406 -
                }
407 405
                let decoder = heap::over(&mut work.decoded[..]);
408 406
                let mut package = try program::parse(
409 407
                    &work.input[.. input.length],
410 408
                    decoder,
411 409
                    binary::Limits {
419 417
                };
420 418
                set package.links.image = image;
421 419
                let scratch = heap::over(&mut work.scratch[..]);
422 420
                set work.dependencies = try registry::resolve(
423 421
                    packages,
422 +
                    &input.visible,
424 423
                    package.dependencies,
425 424
                    package.links.pins,
426 425
                    shared::Verification::Verified
427 426
                );
427 +
                if let resident = registry::findLinked(packages, image, &work.dependencies) {
428 +
                    return Prepared::Resident(resident);
429 +
                }
428 430
                let providers = try registry::providers(packages, &work.dependencies, decoder);
429 431
                try verify::verifyLinkedPackage(
430 432
                    &mut package,
431 433
                    &providers[..],
432 434
                    shared::verifierConfig(@sizeOf(abi::Env) as u32),
636 638
                    handle,
637 639
                    frames: run,
638 640
                    base: extent.start,
639 641
                    address,
640 642
                    length: request.length as u32,
643 +
                    visible: registry::held(table),
641 644
                }, InputAccess::Held(
642 645
                    work, sourceAccess
643 646
                ));
644 647
            }
645 648
        },
691 694
    releaseUsing(state, &mut store.backings.pool, Lease::Held(input.frames), release);
692 695
    try! slots::cancel(&mut table.slots[..], slots::Reservation::Held(input.handle));
693 696
}
694 697
695 698
/// Install a resident package handle and return the workspace under serialization.
699 +
/// A caller that holds another implementation of the package's contract gets none.
696 700
export fn finish(
697 701
    state: &mut State,
698 702
    store: &mut pages::Store,
703 +
    packages: &registry::Store,
699 704
    table: &mut capability::Table,
700 705
    reservation: Reservation,
701 706
    object: abi::Ref
702 707
) -> abi::Handle throws (abi::Error) {
703 708
    match reservation {
706 711
            require(state, table, &input);
707 712
            if not backing::domainLive(&store.backings, input.owner) {
708 713
                cancelUsing(state, store, table, input, frames::release);
709 714
                throw abi::Error::BadHandle;
710 715
            }
716 +
            try registry::unique(packages, &*table, object) catch err {
717 +
                cancelUsing(state, store, table, input, frames::release);
718 +
                throw err;
719 +
            };
711 720
            let result = capability::publish(
712 721
                table,
713 722
                slots::Reservation::Held(input.handle),
714 723
                capability::Entry {
715 724
                    kind: abi::Kind::Image, object, rights: abi::Rights(registry::IMAGE_RIGHTS)
737 746
        cancel(state, store, table, pending);
738 747
        throw err;
739 748
    };
740 749
    let case Prepared::New(package) = input else {
741 750
        let case Prepared::Resident(object) = input else panic "load: invalid prepared input";
742 -
        return try finish(state, store, table, pending, object);
751 +
        return try finish(state, store, &*packages, table, pending, object);
743 752
    };
744 753
    let output = try reserveOutput(&mut store.backings.pool, packages) catch err {
745 754
        cancel(state, store, table, pending);
746 755
        throw err;
747 756
    };
749 758
        cancelOutput(&mut store.backings.pool, packages, output);
750 759
        cancel(state, store, table, pending);
751 760
        throw err;
752 761
    };
753 762
    let object = publishOutput(state, &mut store.backings.pool, packages, output, sizes);
754 -
    return try finish(state, store, table, pending, object);
763 +
    return try finish(state, store, &*packages, table, pending, object);
755 764
}
kernel/kernel/registry.rad +168 -12
22 22
use super::limits;
23 23
use super::slots;
24 24
25 25
/// Rights installed on a new Image capability.
26 26
export constant IMAGE_RIGHTS: u16 = abi::READ | abi::EXECUTE | abi::GRANT | abi::TRANSFER;
27 +
/// Number of package visibility bits in one word.
28 +
constant VISIBLE_WORD_BITS: u32 = 64;
27 29
28 30
/// Fixed package registry. Callers serialize admission and handle publication.
29 31
export record Store: Copy {
30 32
    /// Package generations; published slots remain live until shutdown.
31 33
    slots: [slots::Slot; limits::PACKAGES],
33 35
    entries: [catalog::Entry; limits::PACKAGES],
34 36
    /// Resolved dependencies in each package's declared order.
35 37
    dependencies: [[abi::Ref; limits::PACKAGES]; limits::PACKAGES],
36 38
    /// Number of valid resolved dependencies per live package.
37 39
    counts: [u32; limits::PACKAGES],
40 +
    /// Publication order of each live slot.
41 +
    order: [u32; limits::PACKAGES],
42 +
    /// Number of published packages. Live slots remain resident until shutdown.
43 +
    published: u32,
38 44
}
39 45
40 46
/// Initialize an empty registry before loading any native package.
41 47
export fn initialize(store: &mut Store) {
42 48
    slots::initialize(&mut store.slots[..]);
49 +
    set store.published = 0;
43 50
}
44 51
45 52
/// Read-only view of the packages that were published when it was captured.
46 53
/// Opaque, so only `capture` can build one: holding a view proves it was
47 54
/// captured from a real registry. It holds no lock: it stays valid because published packages never
50 57
export opaque record Published: Copy {
51 58
    /// Slot generations and states at capture. Only live slots are readable.
52 59
    slots: [slots::Slot; limits::PACKAGES],
53 60
    /// The registry's descriptor array, read only at slots that were live.
54 61
    entries: *unsafe [catalog::Entry],
62 +
    /// Exact dependency references for live slots.
63 +
    dependencies: *unsafe [[abi::Ref; limits::PACKAGES]],
64 +
    /// Initialized dependency counts for live slots.
65 +
    counts: *unsafe [u32],
66 +
    /// Immutable publication order for live slots.
67 +
    order: *unsafe [u32],
55 68
}
56 69
57 70
/// Capture the published packages. The caller holds the metadata lock, which
58 71
/// orders every earlier publication before reads through the view.
59 72
export fn capture(store: &Store) -> Published {
60 73
    let mut entries: *unsafe [catalog::Entry] = undefined;
61 74
    // The pointer only designates the descriptor array, which `describe` reads at published slots.
62 75
    unsafe {
63 76
        set entries = &store.entries[..] as *unsafe [catalog::Entry];
64 77
    }
65 -
    return Published { slots: store.slots, entries };
78 +
    let mut dependencies: *unsafe [[abi::Ref; limits::PACKAGES]] = undefined;
79 +
    let mut counts: *unsafe [u32] = undefined;
80 +
    let mut order: *unsafe [u32] = undefined;
81 +
    // Published dependency rows are complete and immutable.
82 +
    unsafe {
83 +
        set dependencies = &store.dependencies[..] as *unsafe [[abi::Ref; limits::PACKAGES]];
84 +
        set counts = &store.counts[..] as *unsafe [u32];
85 +
        set order = &store.order[..] as *unsafe [u32];
86 +
    }
87 +
    return Published { slots: store.slots, entries, dependencies, counts, order };
66 88
}
67 89
68 90
/// Read the descriptor of a package that was live at capture.
69 91
export fn describe(view: &Published, object: abi::Ref) -> catalog::Entry throws (abi::Error) {
70 92
    if not slots::matches(&view.slots[..], object, slots::State::Live) {
116 138
        }
117 139
    }
118 140
    return nil;
119 141
}
120 142
143 +
/// Find native code with the same exact image and resolved provider set.
144 +
export fn findLinked(
145 +
    view: &Published, image: binary::Id, dependencies: &Dependencies
146 +
) -> ?abi::Ref {
147 +
    for slot, i in &view.slots[..] {
148 +
        if slot.state <> slots::State::Live {
149 +
            continue;
150 +
        }
151 +
        let object = abi::Ref { index: i, generation: slot.generation };
152 +
        let package = try! lookup(view, object);
153 +
        if package.contract.verification <> shared::Verification::Verified
154 +
            or package.contract.image <> image
155 +
        {
156 +
            continue;
157 +
        }
158 +
        let mut matches = true;
159 +
        // Only rows of slots that were live at capture can be read.
160 +
        unsafe {
161 +
            set matches = view.counts[i] == dependencies.count;
162 +
            for target, j in &dependencies.objects[.. dependencies.count] {
163 +
                set matches = matches and view.dependencies[i][j] == target;
164 +
            }
165 +
        }
166 +
        if matches {
167 +
            return object;
168 +
        }
169 +
    }
170 +
    return nil;
171 +
}
172 +
121 173
/// Reserve the stable package-state slot before compiling its native code.
122 174
export fn reserve(store: &mut Store) -> slots::Reservation throws (abi::Error) {
123 175
    return try slots::reserve(&mut store.slots[..]);
124 176
}
125 177
154 206
    objects: [abi::Ref; limits::PACKAGES],
155 207
    /// Number of initialized references.
156 208
    count: u32,
157 209
}
158 210
159 -
/// Resolve exact pins, or diagnostic labels for trusted native packages.
211 +
/// Resident packages that a load may select as providers, by package slot.
212 +
/// A published slot stays live with one generation, so its index names one package.
213 +
/// Opaque, so only `held` and `all` build one.
214 +
export opaque record Visible: Copy {
215 +
    /// Bit `i % VISIBLE_WORD_BITS` of word `i / VISIBLE_WORD_BITS` is set when the package in slot `i` is visible.
216 +
    bits: [u64; limits::PACKAGES / VISIBLE_WORD_BITS],
217 +
}
218 +
219 +
/// Collect the packages behind a table's Image handles with execute rights.
220 +
/// A load links only against code that its caller can already run.
221 +
export fn held(table: &capability::Table) -> Visible {
222 +
    let mut result = Visible { bits: [0; limits::PACKAGES / VISIBLE_WORD_BITS] };
223 +
    for slot, i in &table.slots[..] {
224 +
        if slot.state <> slots::State::Live {
225 +
            continue;
226 +
        }
227 +
        let entry = table.entries[i];
228 +
        if entry.kind == abi::Kind::Image
229 +
            and abi::permits(entry.rights, abi::Rights(abi::EXECUTE))
230 +
        {
231 +
            let index = entry.object.index;
232 +
            set result.bits[index / VISIBLE_WORD_BITS] |= 1 << (index % VISIBLE_WORD_BITS) as u64;
233 +
        }
234 +
    }
235 +
    return result;
236 +
}
237 +
238 +
/// Make every package that was live at capture visible.
239 +
/// Only boot uses it, for a catalog that the trusted image builder selected.
240 +
export fn all(view: &Published) -> Visible {
241 +
    let mut result = Visible { bits: [0; limits::PACKAGES / VISIBLE_WORD_BITS] };
242 +
    for slot, i in &view.slots[..] {
243 +
        if slot.state == slots::State::Live {
244 +
            set result.bits[i / VISIBLE_WORD_BITS] |= 1 << (i % VISIBLE_WORD_BITS) as u64;
245 +
        }
246 +
    }
247 +
    return result;
248 +
}
249 +
250 +
/// Select the most recently published visible package with matching metadata for
251 +
/// each dependency, or the first visible package with its name when there are no pins.
252 +
/// Packages held by one table never share a name and metadata, so only boot, which
253 +
/// sees every package, chooses among several matches.
254 +
/// Admission retains the selected exact references until shutdown.
160 255
export fn resolve(
161 -
    view: &Published, names: &[*[u8]], pins: &[binary::Id], verification: shared::Verification
256 +
    view: &Published,
257 +
    visible: &Visible,
258 +
    names: &[*[u8]],
259 +
    pins: &[binary::Id],
260 +
    verification: shared::Verification
162 261
) -> Dependencies throws (abi::Error) {
163 262
    if names.len > limits::PACKAGES
164 263
        or (verification == shared::Verification::Verified and pins.len <> names.len)
165 264
    {
166 265
        throw abi::Error::VerifyFailed;
167 266
    }
168 267
    let mut result = Dependencies { objects: undefined, count: names.len };
169 268
    for name, i in names {
170 269
        let mut selected: ?abi::Ref = nil;
171 -
        if pins.len == names.len {
172 -
            set selected = findImage(view, pins[i], verification);
173 -
        } else {
174 -
            set selected = find(view, name);
270 +
        let mut latest: u32 = 0;
271 +
        for slot, j in &view.slots[..] {
272 +
            if slot.state <> slots::State::Live
273 +
                or ((visible.bits[j / VISIBLE_WORD_BITS] >> (j % VISIBLE_WORD_BITS) as u64) & 1) == 0
274 +
            {
275 +
                continue;
276 +
            }
277 +
            let object = abi::Ref { index: j, generation: slot.generation };
278 +
            let package = try! lookup(view, object);
279 +
            if not mem::eq(package.name, name) {
280 +
                continue;
281 +
            }
282 +
            if pins.len <> names.len {
283 +
                set selected = object;
284 +
                break;
285 +
            }
286 +
            if package.contract.verification == verification
287 +
                and package.contract.metadata == pins[i]
288 +
            {
289 +
                let mut order: u32 = 0;
290 +
                // This slot was live at capture, so its order is immutable.
291 +
                unsafe {
292 +
                    set order = view.order[j];
293 +
                }
294 +
                if order > latest {
295 +
                    set latest = order;
296 +
                    set selected = object;
297 +
                }
298 +
            }
175 299
        }
176 300
        let target = selected else throw abi::Error::VerifyFailed;
177 301
        for prior in &result.objects[.. i] {
178 302
            if prior == target {
179 303
                throw abi::Error::VerifyFailed;
225 349
        assert slots::matches(&store.slots[..], target, slots::State::Live);
226 350
        set store.dependencies[object.index][i] = target;
227 351
    }
228 352
    set store.counts[object.index] = admission.count;
229 353
    set store.entries[object.index] = admission.entry;
354 +
    set store.published += 1;
355 +
    set store.order[object.index] = store.published;
230 356
    return try! slots::commit(&mut store.slots[..], reservation);
231 357
}
232 358
233 359
/// Read resident metadata through a generation-bearing package reference.
234 360
export fn get(store: &Store, object: abi::Ref) -> shared::Package throws (abi::Error) {
248 374
    };
249 375
    return target;
250 376
}
251 377
252 378
/// Decode immutable verified provider declarations into the load's retained workspace.
379 +
/// Every provider must be verified: a verified client can forge values of a provider's
380 +
/// opaque types, which only verified provider code is safe against.
253 381
export fn providers(
254 382
    view: &Published, dependencies: &Dependencies, arena: &heap::Heap
255 383
) -> *[linking::Provider] throws (abi::Error) {
256 384
    let mut result: *mut [linking::Provider] = &mut [];
257 385
    for object in &dependencies.objects[.. dependencies.count] {
315 443
/// Register a persistent boot catalog in dependency order through normal admission.
316 444
export fn boot(store: &mut Store, catalog: &[catalog::Entry]) throws (abi::Error) {
317 445
    for entry in catalog {
318 446
        let image = identity(entry.source, &entry.package);
319 447
        let view = capture(&*store);
320 -
        let existing = findImage(&view, image, entry.package.contract.verification);
321 -
        if existing <> nil {
322 -
            continue;
323 -
        }
324 448
        let dependencies = try resolve(
325 449
            &view,
450 +
            &all(&view),
326 451
            entry.package.dependencies,
327 452
            entry.package.contract.pins,
328 453
            entry.package.contract.verification
329 454
        );
455 +
        let existing = findLinked(&view, image, &dependencies)
456 +
            if entry.package.contract.verification == shared::Verification::Verified
457 +
            else findImage(&view, image, entry.package.contract.verification);
458 +
        if existing <> nil {
459 +
            continue;
460 +
        }
330 461
        let reservation = try reserve(store);
331 462
        let mut package = entry.package;
332 463
        set package.contract.image = image;
333 464
        let admission = try admit(
334 465
            &capture(&*store), slots::reference(&reservation), entry.source, package, &dependencies
338 469
        };
339 470
        let object = commit(store, reservation, admission);
340 471
    }
341 472
}
342 473
474 +
/// Reject a handle to `object` when the table holds one to another package with the
475 +
/// same name, verification policy and metadata. A domain holds at most one
476 +
/// implementation of a contract, so its handles select each provider unambiguously.
477 +
export fn unique(store: &Store, table: &capability::Table, object: abi::Ref)
478 +
    throws (abi::Error)
479 +
{
480 +
    let package = try get(store, object);
481 +
    for slot, i in &table.slots[..] {
482 +
        if slot.state <> slots::State::Live {
483 +
            continue;
484 +
        }
485 +
        let entry = table.entries[i];
486 +
        if entry.kind <> abi::Kind::Image or entry.object == object {
487 +
            continue;
488 +
        }
489 +
        let held = try! get(store, entry.object);
490 +
        if mem::eq(held.name, package.name)
491 +
            and held.contract.verification == package.contract.verification
492 +
            and held.contract.metadata == package.contract.metadata
493 +
        {
494 +
            throw abi::Error::InvalidArg;
495 +
        }
496 +
    }
497 +
}
498 +
343 499
/// Install an Image handle for a resident package without duplicating its code.
344 500
export fn install(store: &Store, table: &mut capability::Table, object: abi::Ref) -> abi::Handle
345 501
    throws (abi::Error)
346 502
{
347 -
    let package = try get(store, object);
503 +
    try unique(store, &*table, object);
348 504
    return try capability::install(table, capability::Entry {
349 505
        kind: abi::Kind::Image, object, rights: abi::Rights(IMAGE_RIGHTS)
350 506
    });
351 507
}
352 508
kernel/kernel/sys.rad +8 -2
53 53
        case -(abi::Error::Exhausted as i64)  => throw abi::Error::Exhausted,
54 54
        else                                  => panic "result: invalid kernel error",
55 55
    }
56 56
}
57 57
58 -
/// Copy authority to a domain with optional rights narrowing.
58 +
/// Copy authority to a domain with optional rights narrowing. An Image handle fails
59 +
/// with InvalidArg when the target holds another package with the same name and metadata.
59 60
export fn capabilityGrant(handle: abi::Handle, target: abi::Handle, rights: u64) -> abi::Handle
60 61
    throws (abi::Error)
61 62
{
62 63
    return abi::Handle(try result(ecall(
63 64
        abi::Operation::CapabilityGrant as u32, *handle as i64, *target as i64, rights as i64, 0
68 69
export fn domainReparent(domain: abi::Handle, parent: abi::Handle) throws (abi::Error) {
69 70
    try result(ecall(abi::Operation::DomainReparent as u32, *domain as i64, *parent as i64, 0, 0));
70 71
}
71 72
72 73
/// Load a binary package from a readable Page range. The kernel verifies it.
74 +
/// Each dependency resolves to the package with the pinned name and metadata
75 +
/// among those behind the caller's Image handles with execute rights. A domain
76 +
/// holds Image handles to at most one package per name and metadata, so the load
77 +
/// fails with InvalidArg when the caller holds another implementation of its contract.
73 78
export fn imageLoad(
74 79
    authority: abi::Handle, source: abi::Handle, offset: u64, length: u64
75 80
) -> abi::Handle throws (abi::Error) {
76 81
    return abi::Handle(try result(ecall(
77 82
        abi::Operation::ImageLoad as u32,
127 132
    return abi::Handle(try result(ecall(
128 133
        abi::Operation::BudgetBind as u32, *handle as i64, *domain as i64, context as i64, 0
129 134
    )));
130 135
}
131 136
132 -
/// Move authority to another domain with optional rights narrowing.
137 +
/// Move authority to another domain with optional rights narrowing. An Image handle fails
138 +
/// with InvalidArg when the target holds another package with the same name and metadata.
133 139
export fn capabilityTransfer(handle: abi::Handle, target: abi::Handle, rights: u64) -> abi::Handle
134 140
    throws (abi::Error)
135 141
{
136 142
    return abi::Handle(try result(ecall(
137 143
        abi::Operation::CapabilityTransfer as u32, *handle as i64, *target as i64, rights as i64, 0
kernel/kernel/tests/loader.rad +101 -13
120 120
    }
121 121
    let mut exports: *mut [binary::Export] = &mut [];
122 122
    try! exports.append(
123 123
        binary::Export {
124 124
            name,
125 -
            kind: binary::ExportKind::Function,
125 +
            kind: binary::ExportKind::Function(0),
126 126
            startable: false,
127 127
        },
128 128
        arena
129 129
    );
130 130
    let package = binary::Package {
361 361
    let object = try! registry::image(&PACKAGES, &TABLE, handle, abi::Rights(0));
362 362
    let before = free();
363 363
    let pending = try! loader::reserve(&mut LOADER, &mut PAGES, &mut TABLE, request);
364 364
    try! backing::endDomain(&mut PAGES.backings, TABLE.owner);
365 365
    let mut dead = false;
366 -
    try loader::finish(&mut LOADER, &mut PAGES, &mut TABLE, pending, object) catch error {
366 +
    try loader::finish(
367 +
        &mut LOADER, &mut PAGES, &PACKAGES, &mut TABLE, pending, object
368 +
    ) catch error {
367 369
        assert error == abi::Error::BadHandle;
368 370
        set dead = true;
369 371
    };
370 372
    assert dead and LOADER.owner == nil and free() == before;
371 373
    assert TABLE.slots[3].state == slots::State::Free;
590 592
    if let supplied = provider {
591 593
        set name = "unit::main";
592 594
        set entry = name;
593 595
        set leaf = false;
594 596
        set dependencies = &["unit"];
595 -
        let image = supplied.contract.image else panic "linkedInput: provider identity";
597 +
        let image = supplied.contract.metadata;
596 598
        let mut pin = image;
597 599
        if change == LinkCase::Image {
598 600
            set pin.bytes[0] ^= 1;
599 601
        }
600 602
        try! pins.append(pin, arena);
698 700
            },
699 701
            arena
700 702
        );
701 703
        try! exports.append(
702 704
            binary::Export {
703 -
                name: "unit::counter", kind: binary::ExportKind::Data, startable: false
705 +
                name: "unit::counter", kind: binary::ExportKind::Data(0), startable: false
704 706
            },
705 707
            arena
706 708
        );
707 709
        try! data.append(
708 710
            il::Data {
723 725
            },
724 726
            arena
725 727
        );
726 728
    }
727 729
    try! exports.append(
728 -
        binary::Export { name, kind: binary::ExportKind::Function, startable: false }, arena
730 +
        binary::Export { name, kind: binary::ExportKind::Function(0), startable: false }, arena
729 731
    );
730 732
    let mut blocks: *mut [il::Block] = &mut [];
731 733
    try! blocks.append(
732 734
        il::Block {
733 735
            label: il::BlockLabel { base: "entry", suffix: nil },
779 781
            layouts: &layouts[..],
780 782
            signatures: &signatures[..],
781 783
            traits: &[],
782 784
        },
783 785
        links: binary::Links {
784 -
            pins: &pins[..], imports: &imports[..], image: nil, verified: false
786 +
            metadata: binary::Id { bytes: [0; linkage::ID_BYTES] },
787 +
            pins: &pins[..],
788 +
            imports: &imports[..],
789 +
            image: nil,
790 +
            verified: false,
785 791
        },
786 792
    };
787 793
    if change == LinkCase::Unbound {
788 794
        set package.links.imports = &[];
789 795
    }
796 +
    set package.links.metadata = linkage::imageId(
797 +
        "unit provider metadata" if provider == nil else "unit client metadata"
798 +
    );
790 799
    let bytes = @sliceOf(&mut RAM[0] as *mut u8, @sizeOf([u64; 19398656]));
791 800
    let mut output = &mut bytes[OFFSET .. OFFSET + 4096] as *mut [u8];
792 801
    let length = try! program::encode(&mut output, &package);
793 802
    return loader::Request {
794 803
        authority: abi::Handle(0), source: SOURCE, offset: 0, length: length as u64
865 874
        assert rejected and free() == before and LOADER.owner == nil;
866 875
        assert PACKAGES.slots[1].state == slots::State::Free;
867 876
    }
868 877
}
869 878
870 -
/// Body versions and clients with different exact pins coexist under the same names.
879 +
/// Body versions with the same metadata share client image bytes.
871 880
@test unsafe fn linkedVersions() throws (testing::TestError) {
872 881
    initialize();
873 882
    let firstRequest = linkedInput(nil, LinkCase::Valid);
874 883
    let firstHandle = try! loader::load(
875 884
        &mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, firstRequest
876 885
    );
877 886
    let firstRef = (try! capability::get(&TABLE, firstHandle)).object;
878 887
    let first = try! registry::get(&PACKAGES, firstRef);
888 +
    let firstClientRequest = linkedInput(first, LinkCase::Valid);
889 +
    let firstClientHandle = try! loader::load(
890 +
        &mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, firstClientRequest
891 +
    );
892 +
    let firstClient = (try! capability::get(&TABLE, firstClientHandle)).object;
893 +
    assert PACKAGES.dependencies[firstClient.index][0] == firstRef;
894 +
    try! capability::invalidate(&mut TABLE, firstHandle);
879 895
    let secondRequest = linkedInput(nil, LinkCase::Version);
880 896
    let secondHandle = try! loader::load(
881 897
        &mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, secondRequest
882 898
    );
883 899
    let secondRef = (try! capability::get(&TABLE, secondHandle)).object;
887 903
    let oldRequest = linkedInput(first, LinkCase::Valid);
888 904
    let bytes = @sliceOf(&RAM[0] as *u8, @sizeOf([u64; 19398656]));
889 905
    let oldImage = linkage::imageId(&bytes[OFFSET .. OFFSET + oldRequest.length as u32]);
890 906
    let request = linkedInput(second, LinkCase::Valid);
891 907
    let newImage = linkage::imageId(&bytes[OFFSET .. OFFSET + request.length as u32]);
892 -
    assert oldImage <> newImage;
893 -
    let clientHandle = try! loader::load(
894 -
        &mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, request
908 +
    assert oldImage == newImage;
909 +
    let before = free();
910 +
    let pending = try! loader::reserve(&mut LOADER, &mut PAGES, &mut TABLE, request);
911 +
    let prepared = try! loader::decode(&registry::capture(&PACKAGES), &pending);
912 +
    let case loader::Prepared::New(package) = prepared
913 +
        else panic "linkedVersions: changed providers require native linking";
914 +
    assert package.links.verified and package.links.image == newImage;
915 +
    loader::cancel(&mut LOADER, &mut PAGES, &mut TABLE, pending);
916 +
    assert free() == before;
917 +
}
918 +
919 +
/// Load a client of `provider` and return its package, or the load error.
920 +
unsafe fn loadClient(provider: shared::Package) -> abi::Ref throws (abi::Error) {
921 +
    let request = linkedInput(provider, LinkCase::Valid);
922 +
    let handle = try loader::load(&mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, request);
923 +
    return (try! capability::get(&TABLE, handle)).object;
924 +
}
925 +
926 +
/// Providers resolve only through the loader's own Image handles with execute rights,
927 +
/// so a later package that claims the same name and metadata is not selected.
928 +
@test unsafe fn linkedAuthority() throws (testing::TestError) {
929 +
    initialize();
930 +
    let firstHandle = try! loader::load(
931 +
        &mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, linkedInput(nil, LinkCase::Valid)
932 +
    );
933 +
    let firstRef = (try! capability::invalidate(&mut TABLE, firstHandle)).object;
934 +
    let first = try! registry::get(&PACKAGES, firstRef);
935 +
    let impostorHandle = try! loader::load(
936 +
        &mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, linkedInput(nil, LinkCase::Version)
937 +
    );
938 +
    let impostorRef = (try! capability::invalidate(&mut TABLE, impostorHandle)).object;
939 +
    let impostor = try! registry::get(&PACKAGES, impostorRef);
940 +
    assert impostor.contract.metadata == first.contract.metadata;
941 +
    let mut rejected = false;
942 +
    try loadClient(first) catch error {
943 +
        assert error == abi::Error::VerifyFailed;
944 +
        set rejected = true;
945 +
    };
946 +
    assert rejected;
947 +
    let readable = try! capability::install(&mut TABLE, capability::Entry {
948 +
        kind: abi::Kind::Image, object: firstRef, rights: abi::Rights(abi::READ)
949 +
    });
950 +
    set rejected = false;
951 +
    try loadClient(first) catch error {
952 +
        assert error == abi::Error::VerifyFailed;
953 +
        set rejected = true;
954 +
    };
955 +
    assert rejected;
956 +
    let executable = try! capability::install(&mut TABLE, capability::Entry {
957 +
        kind: abi::Kind::Image, object: firstRef, rights: abi::Rights(abi::EXECUTE)
958 +
    });
959 +
    let client = try! loadClient(first);
960 +
    assert PACKAGES.dependencies[client.index][0] == firstRef;
961 +
}
962 +
963 +
/// A load that would give its caller a second implementation of a held contract fails
964 +
/// without installing a handle, and succeeds once the caller drops the first.
965 +
@test unsafe fn linkedExclusive() throws (testing::TestError) {
966 +
    initialize();
967 +
    let firstHandle = try! loader::load(
968 +
        &mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, linkedInput(nil, LinkCase::Valid)
895 969
    );
896 -
    let client = (try! capability::get(&TABLE, clientHandle)).object;
897 -
    assert client.index == 2;
898 -
    assert PACKAGES.dependencies[client.index][0] == secondRef;
970 +
    let mut rejected = false;
971 +
    for _ in 0 .. 2 {
972 +
        set rejected = false;
973 +
        try loader::load(&mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, linkedInput(
974 +
            nil, LinkCase::Version
975 +
        )) catch error {
976 +
            assert error == abi::Error::InvalidArg;
977 +
            set rejected = true;
978 +
        };
979 +
        assert rejected and LOADER.owner == nil and TABLE.slots[3].state == slots::State::Free;
980 +
    }
981 +
    let firstRef = (try! capability::invalidate(&mut TABLE, firstHandle)).object;
982 +
    let secondHandle = try! loader::load(
983 +
        &mut LOADER, &mut PAGES, &mut PACKAGES, &mut TABLE, linkedInput(nil, LinkCase::Version)
984 +
    );
985 +
    let secondRef = (try! capability::get(&TABLE, secondHandle)).object;
986 +
    assert secondRef <> firstRef and secondRef.index == 1;
899 987
}
kernel/kernel/tests/registry.rad +88 -4
1 1
//! Resident package identity, dependency admission, and image capabilities.
2 2
3 3
use std::arch::rv64::shared;
4 4
use std::arch::rv64::shared::catalog;
5 +
use std::lang::il::binary;
5 6
use std::lang::il::binary::linkage;
6 7
use std::testing;
7 8
use super::support;
8 9
use kernel::abi;
9 10
use kernel::capability;
42 43
    return try support::publish(&mut STORE, pending, bytes, package(
43 44
        name, dependencies, slot.index
44 45
    ));
45 46
}
46 47
48 +
/// Resolve dependencies against every package published in the test registry.
49 +
unsafe fn resolveAll(
50 +
    names: &[*[u8]], pins: &[binary::Id], verification: shared::Verification
51 +
) -> registry::Dependencies throws (abi::Error) {
52 +
    let view = registry::capture(&STORE);
53 +
    return try registry::resolve(&view, &registry::all(&view), names, pins, verification);
54 +
}
55 +
47 56
/// Admission resolves dependencies before its reserved package becomes visible.
48 57
@test unsafe fn stagedAdmission() throws (testing::TestError) {
49 58
    registry::initialize(&mut STORE);
50 59
    let base = try! register("base", &[], "base bytes");
51 60
    let pending = try! registry::reserve(&mut STORE);
52 61
    let object = slots::reference(&pending);
53 -
    let dependencies = try! registry::resolve(
54 -
        &registry::capture(&STORE), &["base"], &[], shared::Verification::Unverified
62 +
    let dependencies = try! resolveAll(
63 +
        &["base"], &[], shared::Verification::Unverified
55 64
    );
56 65
    let admitted = try! registry::admit(
57 66
        &registry::capture(&STORE),
58 67
        object,
59 68
        "child bytes",
69 78
    assert published == object and STORE.counts[object.index] == 1;
70 79
    assert STORE.dependencies[object.index][0] == base;
71 80
    let rejected = try! registry::reserve(&mut STORE);
72 81
    let slot = slots::reference(&rejected);
73 82
    let mut duplicate = false;
74 -
    try registry::resolve(
75 -
        &registry::capture(&STORE), &["base", "base"], &[], shared::Verification::Unverified
83 +
    try resolveAll(
84 +
        &["base", "base"], &[], shared::Verification::Unverified
76 85
    ) catch error {
77 86
        assert error == abi::Error::VerifyFailed;
78 87
        set duplicate = true;
79 88
    };
80 89
    assert duplicate and STORE.slots[slot.index].state == slots::State::Reserved;
139 148
        set stale = true;
140 149
    };
141 150
    try testing::expect(stale);
142 151
}
143 152
153 +
/// Publish a verified package that claims `name` and the metadata hash of `contract`.
154 +
unsafe fn implementation(name: *[u8], contract: *[u8], bytes: *[u8]) -> abi::Ref {
155 +
    let pending = try! registry::reserve(&mut STORE);
156 +
    let slot = slots::reference(&pending);
157 +
    let mut checked = package(name, &[], slot.index);
158 +
    set checked.contract.verification = shared::Verification::Verified;
159 +
    set checked.contract.metadata = linkage::imageId(contract);
160 +
    return try! support::publish(&mut STORE, pending, bytes, checked);
161 +
}
162 +
163 +
/// A table holds Image handles to at most one package per name and metadata.
164 +
@test unsafe fn uniqueContracts() throws (testing::TestError) {
165 +
    registry::initialize(&mut STORE);
166 +
    let first = implementation("unit", "contract", "first");
167 +
    let second = implementation("unit", "contract", "second");
168 +
    let other = implementation("unit", "other contract", "third");
169 +
    let renamed = implementation("renamed", "contract", "fourth");
170 +
    let mut table: capability::Table = undefined;
171 +
    capability::initialize(&mut table, abi::Ref { index: 0, generation: 1 });
172 +
    let handle = try! registry::install(&STORE, &mut table, first);
173 +
    let again = try! registry::install(&STORE, &mut table, first);
174 +
    let mut rejected = false;
175 +
    try registry::install(&STORE, &mut table, second) catch err {
176 +
        assert err == abi::Error::InvalidArg;
177 +
        set rejected = true;
178 +
    };
179 +
    assert rejected;
180 +
    try! registry::install(&STORE, &mut table, other);
181 +
    try! registry::install(&STORE, &mut table, renamed);
182 +
    try! capability::invalidate(&mut table, handle);
183 +
    set rejected = false;
184 +
    try registry::install(&STORE, &mut table, second) catch err {
185 +
        assert err == abi::Error::InvalidArg;
186 +
        set rejected = true;
187 +
    };
188 +
    assert rejected;
189 +
    try! capability::invalidate(&mut table, again);
190 +
    try! registry::install(&STORE, &mut table, second);
191 +
}
192 +
144 193
/// Boot admission uses the same identity and dependency records as runtime publication.
145 194
@test unsafe fn bootCatalog() throws (testing::TestError) {
146 195
    registry::initialize(&mut STORE);
147 196
    let catalog = [
148 197
        catalog::Entry { source: "base", package: package("base", &[], 0) },
254 303
    ) == privileged;
255 304
    assert registry::findImage(
256 305
        &registry::capture(&STORE), image, shared::Verification::Verified
257 306
    ) == verified;
258 307
}
308 +
309 +
/// Metadata selection follows publication order across out-of-order reservations.
310 +
@test unsafe fn metadataSelection() throws (testing::TestError) {
311 +
    registry::initialize(&mut STORE);
312 +
    let first = try! registry::reserve(&mut STORE);
313 +
    let second = try! registry::reserve(&mut STORE);
314 +
    let firstRef = slots::reference(&first);
315 +
    let secondRef = slots::reference(&second);
316 +
    let mut early = package("version", &[], secondRef.index);
317 +
    set early.contract.verification = shared::Verification::Verified;
318 +
    let empty = try! resolveAll(
319 +
        &[], &[], shared::Verification::Verified
320 +
    );
321 +
    let earlyAdmission = try! registry::admit(
322 +
        &registry::capture(&STORE), secondRef, "early", early, &empty
323 +
    );
324 +
    let earlyRef = registry::commit(&mut STORE, second, earlyAdmission);
325 +
    let mut late = package("version", &[], firstRef.index);
326 +
    set late.contract.verification = shared::Verification::Verified;
327 +
    let lateAdmission = try! registry::admit(
328 +
        &registry::capture(&STORE), firstRef, "late", late, &empty
329 +
    );
330 +
    let lateRef = registry::commit(&mut STORE, first, lateAdmission);
331 +
    let dependencies = try! resolveAll(
332 +
        &["version"], &[late.contract.metadata], shared::Verification::Verified
333 +
    );
334 +
    let pending = try! registry::reserve(&mut STORE);
335 +
    let target = slots::reference(&pending);
336 +
    let client = package("client", &["version"], target.index);
337 +
    let admitted = try! registry::admit(
338 +
        &registry::capture(&STORE), target, "client", client, &dependencies
339 +
    );
340 +
    assert admitted.count == 1 and admitted.dependencies[0] == firstRef;
341 +
    registry::cancel(&mut STORE, pending);
342 +
}
kernel/kernel/tests/support.rad +5 -1
25 25
    if let object = existing {
26 26
        registry::cancel(store, reservation);
27 27
        return object;
28 28
    }
29 29
    let dependencies = try registry::resolve(
30 -
        &view, package.dependencies, package.contract.pins, package.contract.verification
30 +
        &view,
31 +
        &registry::all(&view),
32 +
        package.dependencies,
33 +
        package.contract.pins,
34 +
        package.contract.verification
31 35
    ) catch err {
32 36
        registry::cancel(store, reservation);
33 37
        throw err;
34 38
    };
35 39
    let object = slots::reference(&reservation);
kernel/tools/build.rad +15 -12
178 178
    for word, i in &e.code[..] {
179 179
        set NATIVE[i] = word;
180 180
    }
181 181
}
182 182
183 -
/// Select one exact verified provider from earlier immutable boot entries.
184 -
fn dependency(entries: &[catalog::Entry], pin: binary::Id) -> catalog::Entry
183 +
/// Select one verified provider with matching metadata from boot entries.
184 +
fn dependency(entries: &[catalog::Entry], name: *[u8], pin: binary::Id) -> catalog::Entry
185 185
    throws (shared::Error)
186 186
{
187 +
    let mut selected: ?catalog::Entry = nil;
187 188
    for entry in entries {
188 189
        let package = entry.package;
189 -
        if package.contract.verification <> shared::Verification::Verified {
190 +
        if package.contract.verification <> shared::Verification::Verified
191 +
            or not mem::eq(package.name, name)
192 +
        {
190 193
            continue;
191 194
        }
192 -
        let image = package.contract.image else continue;
193 -
        if not mem::eq(&image.bytes[..], &pin.bytes[..]) {
195 +
        let metadata = package.contract.metadata;
196 +
        if not mem::eq(&metadata.bytes[..], &pin.bytes[..]) {
194 197
            continue;
195 198
        }
196 -
        return entry;
199 +
        set selected = entry;
197 200
    }
198 -
    throw shared::Error::Symbol;
201 +
    let entry = selected else throw shared::Error::Symbol;
202 +
    return entry;
199 203
}
200 204
201 205
/// Build typed provider declarations and the same native aliases for a user boot package.
202 206
fn userImports(
203 207
    input: &binary::Package,
211 215
    if input.links.imports.len > output.len {
212 216
        throw shared::Error::Capacity;
213 217
    }
214 218
    let mut providers: *mut [linking::Provider] = &mut [];
215 219
    let mut exports: *mut [*[shared::Symbol]] = &mut [];
216 -
    for pin in input.links.pins {
217 -
        let selected = try dependency(entries, pin);
220 +
    for pin, i in input.links.pins {
221 +
        let selected = try dependency(entries, input.dependencies[i], pin);
218 222
        let declarations = try program::declarations(selected.source, arena) catch error {
219 223
            if error == binary::Error::Storage {
220 224
                throw shared::Error::Capacity;
221 225
            }
222 226
            throw shared::Error::Symbol;
223 227
        };
224 228
        try exports.append(selected.package.exports, arena) catch {
225 229
            throw shared::Error::Capacity;
226 230
        };
231 +
        let image = selected.package.contract.image else throw shared::Error::Symbol;
227 232
        try providers.append(
228 -
            linking::Provider {
229 -
                image: pin, contract: declarations
230 -
            },
233 +
            linking::Provider { image, contract: declarations },
231 234
            arena
232 235
        ) catch {
233 236
            throw shared::Error::Capacity;
234 237
        };
235 238
    }
lib/std/arch/rv64/emit.rad +24 -6
304 304
/// Record a function's code offset at `index` for call resolution.
305 305
export fn recordFuncOffsetAt(e: &mut Emitter, name: *[u8], index: u32) throws (super::Error) {
306 306
    if index > MAX_CODE_LEN {
307 307
        throw super::Error::Relocation;
308 308
    }
309 -
    try dict::insert(&mut e.labels.funcs, name, index as i32 * super::INSTR_SIZE) catch {
309 +
    let stored = try alloc::copyBytes(e.arena, name) catch {
310 +
        throw super::Error::Allocation;
311 +
    };
312 +
    try dict::insert(&mut e.labels.funcs, &stored[..], index as i32 * super::INSTR_SIZE) catch {
310 313
        throw super::Error::Capacity(super::Limit::FunctionTable);
311 314
    };
312 315
}
313 316
314 317
/// Record a function's start position for printing.
317 320
    try recordFuncAt(e, name, codeLen);
318 321
}
319 322
320 323
/// Record a function's start position at `index` for printing.
321 324
export fn recordFuncAt(e: &mut Emitter, name: *[u8], index: u32) throws (super::Error) {
322 -
    try e.funcs.append(types::FuncAddr { name, index }, e.arena) catch {
325 +
    let stored = try alloc::copyBytes(e.arena, name) catch {
326 +
        throw super::Error::Allocation;
327 +
    };
328 +
    try e.funcs.append(types::FuncAddr { name: &stored[..], index }, e.arena) catch {
323 329
        throw super::Error::Allocation;
324 330
    };
325 331
}
326 332
327 333
/// Record a local branch needing later patching.
362 368
363 369
/// Record a call whose two instruction words start at `index` and need whole-program patching.
364 370
export fn recordCallAt(
365 371
    e: &mut Emitter, target: *[u8], link: gen::Reg, scratch: gen::Reg, index: u32
366 372
) throws (super::Error) {
373 +
    let stored = try alloc::copyBytes(e.arena, target) catch {
374 +
        throw super::Error::Allocation;
375 +
    };
367 376
    try e.pendingCalls.append(
368 377
        PendingCall {
369 378
            index,
370 -
            target,
379 +
            target: &stored[..],
371 380
            link,
372 381
            scratch,
373 382
        },
374 383
        e.arena
375 384
    ) catch {
379 388
380 389
/// Record a jump emitted by assembly that needs whole-program patching.
381 390
export fn recordJumpAt(e: &mut Emitter, target: *[u8], rd: gen::Reg, index: u32)
382 391
    throws (super::Error)
383 392
{
393 +
    let stored = try alloc::copyBytes(e.arena, target) catch {
394 +
        throw super::Error::Allocation;
395 +
    };
384 396
    try e.pendingJumps.append(
385 397
        PendingJump {
386 398
            index,
387 -
            target,
399 +
            target: &stored[..],
388 400
            rd,
389 401
        },
390 402
        e.arena
391 403
    ) catch {
392 404
        throw super::Error::Allocation;
406 418
407 419
/// Record a function address load already reserved by assembly.
408 420
export fn recordAddrLoadAt(e: &mut Emitter, target: *[u8], rd: gen::Reg, index: u32)
409 421
    throws (super::Error)
410 422
{
423 +
    let stored = try alloc::copyBytes(e.arena, target) catch {
424 +
        throw super::Error::Allocation;
425 +
    };
411 426
    try e.pendingAddrLoads.append(
412 427
        PendingAddrLoad {
413 428
            index,
414 -
            target,
429 +
            target: &stored[..],
415 430
            rd: rd,
416 431
            isData: false,
417 432
        },
418 433
        e.arena
419 434
    ) catch {
422 437
}
423 438
424 439
/// Record a data address load needing later patching.
425 440
/// Reserves two instructions for a PC-relative address load.
426 441
export fn recordDataAddrLoad(e: &mut Emitter, target: *[u8], rd: gen::Reg) throws (super::Error) {
442 +
    let stored = try alloc::copyBytes(e.arena, target) catch {
443 +
        throw super::Error::Allocation;
444 +
    };
427 445
    try e.pendingAddrLoads.append(
428 446
        PendingAddrLoad {
429 447
            index: e.code.len,
430 -
            target,
448 +
            target: &stored[..],
431 449
            rd: rd,
432 450
            isData: true,
433 451
        },
434 452
        e.arena
435 453
    ) catch {
lib/std/arch/rv64/shared.rad +10 -5
8 8
use std::lang::gen::data;
9 9
use std::lang::gen::labels;
10 10
use std::lang::gen::regalloc::liveness;
11 11
use std::lang::il;
12 12
use std::lang::il::binary;
13 +
use std::lang::il::binary::linkage;
13 14
use std::lang::il::verify;
14 15
use std::mem;
15 16
use std::mem::heap;
16 17
use super::asm;
17 18
use super::emit;
102 103
    Unverified,
103 104
    /// Checked RIL with a protected stack and no assembly prefix.
104 105
    Verified,
105 106
}
106 107
107 -
/// Persistent evidence and exact dependencies of a native package.
108 +
/// Persistent source identity and dependency metadata of a native package.
108 109
export record Contract: Copy {
109 -
    /// Exact dependency identities in the declared order.
110 +
    /// Dependency metadata hashes in the declared order.
110 111
    pins: *[binary::Id],
111 112
    /// Exact source identity, present for decoded binary packages.
112 113
    image: ?binary::Id,
113 114
    /// Eligibility for user-package imports and native-cache reuse.
114 115
    verification: Verification,
116 +
    /// Compiler metadata hash of the retained package.
117 +
    metadata: binary::Id,
115 118
}
116 119
117 120
/// Native metadata without a user-package verification result.
118 121
export constant UNVERIFIED: Contract = Contract {
119 122
    pins: &[],
120 123
    image: nil,
121 124
    verification: Verification::Unverified,
125 +
    metadata: binary::Id { bytes: [0; linkage::ID_BYTES] },
122 126
};
123 127
124 128
/// A resident package entry used by boot catalogs and runtime loading.
125 129
export record Package: Copy {
126 130
    /// Diagnostic label of the package.
127 131
    name: *[u8],
128 -
    /// Diagnostic dependency labels, in exact pin order.
132 +
    /// Dependency labels in metadata pin order.
129 133
    dependencies: *[*[u8]],
130 134
    /// Stable slot in each domain's package-state table.
131 135
    slot: u32,
132 136
    /// Address at which the shared instructions execute.
133 137
    codeAddress: u64,
528 532
        throw Error::Capacity;
529 533
    }
530 534
    for exported, i in input.exports {
531 535
        let target = try resolve(local, &[], exported.name);
532 536
        match exported.kind {
533 -
            case binary::ExportKind::Function => {
537 +
            case binary::ExportKind::Function(_) => {
534 538
                try function(local, &[], exported.name);
535 539
            }
536 -
            case binary::ExportKind::Data => {
540 +
            case binary::ExportKind::Data(_) => {
537 541
                try dataRef(target);
538 542
            }
539 543
        }
540 544
        if lookup(&exportStorage[.. i], exported.name) <> nil {
541 545
            throw Error::Symbol;
575 579
            verification: Verification::Verified
576 580
                if input.links.verified
577 581
                    and stack == super::StackCheck::TpLimit
578 582
                    and assembly.text.len == 0
579 583
                else Verification::Unverified,
584 +
            metadata: input.links.metadata,
580 585
        },
581 586
    };
582 587
}
583 588
584 589
/// Validate a package's private-state bases and fixups without touching memory.
lib/std/arch/rv64/shared/catalog.rad +7 -1
26 26
export constant SLICE_LEN: u32 = 8;
27 27
/// Offset of the capacity in a native slice.
28 28
export constant SLICE_CAP: u32 = 12;
29 29
30 30
/// Size of a native [`Entry`].
31 -
export constant ENTRY_SIZE: u32 = 208;
31 +
export constant ENTRY_SIZE: u32 = 240;
32 32
/// Alignment of a native [`Entry`].
33 33
export constant ENTRY_ALIGN: u32 = 8;
34 34
/// Offset of `Entry.source`.
35 35
export constant ENTRY_SOURCE: u32 = 0;
36 36
/// Offset of `Entry.package.name`.
78 78
export constant ENTRY_VERIFICATION: u32 = 201;
79 79
/// Offset of the optional exact image identity tag.
80 80
export constant ENTRY_IMAGE_TAG: u32 = 168;
81 81
/// Offset of the 32 identity bytes when the identity is present.
82 82
export constant ENTRY_IMAGE_VALUE: u32 = 169;
83 +
/// Offset of the package compiler metadata hash.
84 +
export constant ENTRY_METADATA: u32 = 202;
83 85
/// Size in bytes of one 256-bit dependency identity.
84 86
export constant PIN_SIZE: u32 = 32;
85 87
86 88
/// Size of a native [`shared::Relocation`].
87 89
export constant RELOCATION_SIZE: u32 = 16;
264 266
            try! mem::copy(
265 267
                &mut output[at + ENTRY_IMAGE_VALUE .. at + ENTRY_IMAGE_VALUE + 32],
266 268
                &identity.bytes[..]
267 269
            );
268 270
        }
271 +
        try! mem::copy(
272 +
            &mut output[at + ENTRY_METADATA .. at + ENTRY_METADATA + PIN_SIZE],
273 +
            &package.contract.metadata.bytes[..]
274 +
        );
269 275
        integer(
270 276
            output,
271 277
            at + ENTRY_VERIFICATION,
272 278
            1 if package.contract.verification == shared::Verification::Verified else 0,
273 279
            1
lib/std/arch/rv64/shared/tests.rad +5 -2
37 37
        name: "p",
38 38
        dependencies: &[],
39 39
        exports: &[
40 40
            binary::Export {
41 41
                name: "p::entry",
42 -
                kind: binary::ExportKind::Function,
42 +
                kind: binary::ExportKind::Function(0),
43 43
                startable: false,
44 44
            },
45 45
        ],
46 46
        entry: "p::entry",
47 47
        program: il::Program {
99 99
        pins: &[
100 100
            binary::Id { bytes: [1; 32] }
101 101
        ],
102 102
        image: binary::Id { bytes: [3; 32] },
103 103
        verification: super::Verification::Verified,
104 +
        metadata: binary::Id { bytes: [7; linkage::ID_BYTES] },
104 105
    };
105 106
    let output = @sliceOf(&mut CATALOG[0] as *mut u8, @sizeOf([u64; 512]));
106 107
    let base = output.ptr as u64;
107 108
    let used = try catalog::pack(
108 109
        &[catalog::Entry { source: "binary package", package }], base, output
149 150
    );
150 151
    for fixup, i in package.relocations {
151 152
        try testing::expect(entry.package.relocations[i] == fixup);
152 153
    }
153 154
    assert entry.package.contract.pins[0] == package.contract.pins[0];
155 +
    assert entry.package.contract.metadata == package.contract.metadata;
154 156
    assert entry.package.contract.image == package.contract.image;
155 157
    assert entry.package.contract.verification == super::Verification::Verified;
156 158
    try testing::expect(mem::eq(entry.package.template, package.template));
157 159
    set TEMPLATE[0] = 91;
158 160
    set EXPORTS[0].name = "changed";
242 244
    try testing::expect(offsetOf(&entry, &entry.package.alignment) == catalog::ENTRY_ALIGNMENT);
243 245
    try testing::expect(offsetOf(&entry, &entry.package.relocations) == catalog::ENTRY_RELOCATIONS);
244 246
    assert offsetOf(&entry, &entry.package.contract.pins) == catalog::ENTRY_PINS;
245 247
    assert offsetOf(&entry, &entry.package.contract.image) == catalog::ENTRY_IMAGE_TAG;
246 248
    assert offsetOf(&entry, &entry.package.contract.verification) == catalog::ENTRY_VERIFICATION;
249 +
    assert offsetOf(&entry, &entry.package.contract.metadata) == catalog::ENTRY_METADATA;
247 250
    assert @sizeOf(binary::Id) == catalog::PIN_SIZE;
248 251
    // A slice is an address, a length, and a capacity.
249 252
    let slice = catalog::ENTRY_SOURCE;
250 253
    try testing::expect(word(&entry, slice, 8) == entry.source.ptr as u64);
251 254
    try testing::expect(
373 376
        name: "p",
374 377
        dependencies: &["dep"],
375 378
        exports: &[
376 379
            binary::Export {
377 380
                name: "p::refs",
378 -
                kind: binary::ExportKind::Data,
381 +
                kind: binary::ExportKind::Data(0),
379 382
                startable: false,
380 383
            },
381 384
        ],
382 385
        entry: nil,
383 386
        program: il::Program {
lib/std/arch/rv64/shared/tests/run.rad +3 -3
444 444
        name: "p",
445 445
        dependencies: &[],
446 446
        exports: &[
447 447
            binary::Export {
448 448
                name: "p::f",
449 -
                kind: binary::ExportKind::Function,
449 +
                kind: binary::ExportKind::Function(0),
450 450
                startable: false,
451 451
            },
452 452
            binary::Export {
453 453
                name: FIRST,
454 -
                kind: binary::ExportKind::Data,
454 +
                kind: binary::ExportKind::Data(0),
455 455
                startable: false,
456 456
            },
457 457
            binary::Export {
458 458
                name: SECOND,
459 -
                kind: binary::ExportKind::Data,
459 +
                kind: binary::ExportKind::Data(1),
460 460
                startable: false,
461 461
            },
462 462
        ],
463 463
        entry: nil,
464 464
        program: il::Program {
lib/std/arch/rv64/tests.rad +27 -0
22 22
use super::encode;
23 23
use super::isel;
24 24
25 25
/// Reusable emitter storage.
26 26
static ASSEMBLY_ARENA_STORAGE: [u8; 16777216] = [0; 16777216];
27 +
/// Reusable source name storage for emitter lifetime checks.
28 +
static SYMBOL_ARENA_STORAGE: [u8; 64] = [0; 64];
27 29
static ASSEMBLY_TEXT_STORAGE: [u32; 2] = [0; 2];
28 30
29 31
/// Number of entries in the dictionaries of the tests. It is a power of two.
30 32
constant TEST_DICT_SIZE: u32 = 4;
31 33
1573 1575
    try testing::expect(spilledOf(26, (1 << 7) | (1 << 5)) == ((1 << 7) | (1 << 5) | 0b11));
1574 1576
    // Cheap values fewer than the excess are all spilled.
1575 1577
    try testing::expect(spilledOf(26, 1 << 25) == ((1 << 25) | 0b111));
1576 1578
}
1577 1579
1580 +
/// Emitted symbol records own their names after the input storage changes.
1581 +
@test unsafe fn testEmitterOwnsSymbols() throws (testing::TestError) {
1582 +
    let arena = heap::over(&mut ASSEMBLY_ARENA_STORAGE[..]);
1583 +
    let tables = try! testLabels(arena);
1584 +
    let mut e = try! rv64::emit::emitter(arena, false, tables);
1585 +
    let source = heap::over(&mut SYMBOL_ARENA_STORAGE[..]);
1586 +
    let bytes = try! alloc::copyBytes(source, "foo");
1587 +
    let name: *[u8] = &bytes[..];
1588 +
    try! rv64::emit::recordFuncOffsetAt(&mut e, name, 0);
1589 +
    try! rv64::emit::recordFuncAt(&mut e, name, 0);
1590 +
    try! rv64::emit::recordCallAt(&mut e, name, rv64::RA, rv64::T1, 0);
1591 +
    try! rv64::emit::recordJumpAt(&mut e, name, rv64::ZERO, 0);
1592 +
    try! rv64::emit::recordAddrLoadAt(&mut e, name, rv64::T1, 0);
1593 +
    try! rv64::emit::recordDataAddrLoad(&mut e, name, rv64::T1);
1594 +
    heap::reset(source);
1595 +
    let replaced = try! alloc::copyBytes(source, "bar");
1596 +
    assert replaced.ptr == name.ptr;
1597 +
    assert dict::get(&e.labels.funcs, "foo") == 0;
1598 +
    assert e.funcs[0].name[0] == 'f';
1599 +
    assert e.pendingCalls[0].target[0] == 'f';
1600 +
    assert e.pendingJumps[0].target[0] == 'f';
1601 +
    assert e.pendingAddrLoads[0].target[0] == 'f';
1602 +
    assert e.pendingAddrLoads[1].target[0] == 'f';
1603 +
}
1604 +
1578 1605
/// Unresolved calls preserve their placeholder instructions and report a symbol error.
1579 1606
@test unsafe fn testMissingCallSymbol() throws (testing::TestError) {
1580 1607
    let arena = heap::over(&mut ASSEMBLY_ARENA_STORAGE[..]);
1581 1608
    let tables = try! testLabels(arena);
1582 1609
    let mut e = try! rv64::emit::emitter(arena, false, tables);
lib/std/arch/rv64/tests/bounds.rad +10 -11
35 35
/// An emitter whose arena is full reports the allocation failure and keeps its earlier output.
36 36
@test unsafe fn emissionCapacity() throws (testing::TestError) {
37 37
    let arena = heap::over(&mut MEMORY[..]);
38 38
    let labelTables = try! tables(arena);
39 39
    let mut e = try! emit::emitter(arena, false, labelTables);
40 -
    // Take the rest of the arena, so that only the reserved lists can hold entries.
40 +
    let reserved = e.pendingCalls.cap;
41 +
    for _ in 0 .. reserved {
42 +
        try! emit::recordCall(&mut e, "p::call");
43 +
    }
44 +
    // Take the rest of the arena after the reserved calls own their names.
41 45
    let mut rest: *mut [u8] = &mut [];
42 46
    try! rest.resize(heap::remaining(e.arena), 0, e.arena);
43 -
    let reserved = e.pendingCalls.cap;
44 47
    let mut failed = false;
45 -
    let mut count: u32 = 0;
46 -
    while not failed and count <= reserved {
47 -
        try emit::recordCall(&mut e, "p::call") catch err {
48 -
            try testing::expect(err == rv64::Error::Allocation);
49 -
            set failed = true;
50 -
        };
51 -
        set count += 1;
52 -
    }
53 -
    try testing::expect(failed and count == reserved + 1);
48 +
    try emit::recordCall(&mut e, "p::call") catch err {
49 +
        try testing::expect(err == rv64::Error::Allocation);
50 +
        set failed = true;
51 +
    };
52 +
    try testing::expect(failed);
54 53
    try testing::expect(e.pendingCalls.len == reserved);
55 54
}
56 55
57 56
/// A full function table rejects a new function without changing earlier entries.
58 57
@test unsafe fn functionTableCapacity() throws (testing::TestError) {
lib/std/lang/il.rad +2 -0
975 975
}
976 976
977 977
/// Description of the objects of a type: their size and alignment, and the
978 978
/// byte ranges that are not plain data. Slots are sorted by offset, do not
979 979
/// overlap, and lie within the size. A layout without slots is plain data.
980 +
/// A layout is structural and names no owning type, so verified code can build any
981 +
/// value that fits it, whatever the source visibility of its type.
980 982
export record Layout: Copy {
981 983
    /// Size in bytes.
982 984
    size: u32,
983 985
    /// Alignment in bytes, a power of two.
984 986
    alignment: u32,
lib/std/lang/il/binary.rad +36 -13
10 10
export mod linkage;
11 11
@test export mod tests;
12 12
13 13
use std::hash::blake3;
14 14
use std::lang::il;
15 +
use std::mem;
15 16
16 17
/// Minimum wire bytes in a register and value-type parameter.
17 18
export constant MIN_PARAM_BYTES: u32 = 5;
18 19
/// Minimum wire bytes in a layout slot.
19 20
export constant MIN_SLOT_BYTES: u32 = 13;
28 29
/// Minimum wire bytes in a function record.
29 30
export constant MIN_FUNCTION_BYTES: u32 = 22;
30 31
/// Minimum wire bytes in a block record.
31 32
export constant MIN_BLOCK_BYTES: u32 = 13;
32 33
/// Minimum wire bytes in an exported symbol.
33 -
export constant MIN_EXPORT_BYTES: u32 = 5;
34 +
export constant MIN_EXPORT_BYTES: u32 = 9;
34 35
/// Minimum wire bytes in a layout record.
35 36
export constant MIN_LAYOUT_BYTES: u32 = 16;
36 37
/// Minimum wire bytes in a function signature.
37 38
export constant MIN_SIGNATURE_BYTES: u32 = 9;
38 39
/// Minimum wire bytes in a borrowed result source.
278 279
/// Wire tag for comparison Slt.
279 280
export constant CMP_SLT: u8 = 2;
280 281
/// Wire tag for comparison Ult.
281 282
export constant CMP_ULT: u8 = 3;
282 283
283 -
/// The kind of an exported package symbol.
284 +
/// The kind and definition of an exported package symbol.
284 285
export union ExportKind: Copy {
285 -
    /// A callable function entry.
286 -
    Function,
287 -
    /// A global data definition.
288 -
    Data,
286 +
    /// A callable function entry, by index in the package's function table.
287 +
    Function(u32),
288 +
    /// A global data definition, by index in the package's data table.
289 +
    Data(u32),
289 290
}
290 291
291 -
/// A public symbol supplied by a package.
292 +
/// A public symbol supplied by a package. A package lists its exports in
293 +
/// strictly increasing byte order of their names, so names are unique.
292 294
export record Export: Copy {
293 -
    /// Qualified symbol name.
295 +
    /// Qualified symbol name, equal to the name of its definition.
294 296
    name: *[u8],
295 -
    /// Definition kind.
297 +
    /// Definition kind and table index.
296 298
    kind: ExportKind,
297 299
    /// Context-entry eligibility, derived by package verification.
298 300
    startable: bool,
299 301
}
300 302
331 333
    kind: ImportKind,
332 334
}
333 335
334 336
/// Link declarations and a derived verification classification.
335 337
export record Links: Copy {
336 -
    /// Exact identities in dependency order. Loadable dependencies require pins.
338 +
    /// Compiler metadata hash for exported contracts and RID declarations.
339 +
    metadata: Id,
340 +
    /// Metadata hashes in dependency order. Loadable dependencies require pins.
337 341
    pins: *[Id],
338 342
    /// Explicit local aliases for imported definitions.
339 343
    imports: *[Import],
340 344
    /// Exact payload identity, computed after complete binary decoding.
341 345
    /// Constructed IL has no identity until it has an encoded payload.
342 346
    image: ?Id,
343 -
    /// Whether package verification checked all local bodies and exact import bindings.
347 +
    /// Whether package verification checked all local bodies and structural import bindings.
344 348
    /// This field is derived and is never decoded from the wire.
345 349
    verified: bool,
346 350
}
347 351
348 352
/// Link metadata of a package with no dependencies.
349 353
export constant EMPTY_LINKS: Links = Links {
350 -
    pins: &[], imports: &[], image: nil, verified: false
354 +
    metadata: Id { bytes: [0; blake3::DIGEST_BYTES] }, pins: &[], imports: &[], image: nil, verified: false
351 355
};
352 356
353 357
/// Supported RIL package semantics and envelope encoding.
354 358
export constant FORMAT_VERSION: u32 = 1;
355 359
/// RV64 call, layout, and domain-state ABI of loadable packages.
362 366
    symbols: *[*[u8]],
363 367
    /// Immutable package name.
364 368
    name: *[u8],
365 369
    /// Names of required packages.
366 370
    dependencies: *[*[u8]],
367 -
    /// Public definitions.
371 +
    /// Public definitions, sorted by name.
368 372
    exports: *[Export],
369 373
    /// Default exported entry, if the package has one.
370 374
    entry: ?*[u8],
371 375
    /// Package-local functions and global data.
372 376
    program: il::Program,
379 383
    /// Exclusive upper bound for SSA register numbers.
380 384
    registers: u32,
381 385
    /// Maximum number of blocks in one function.
382 386
    blocks: u32,
383 387
}
388 +
389 +
/// Find an export by name in a sorted export table.
390 +
export fn find(exports: &[Export], name: &[u8]) -> ?Export {
391 +
    let mut low: u32 = 0;
392 +
    let mut high = exports.len;
393 +
    while low < high {
394 +
        let middle = low + (high - low) / 2;
395 +
        let order = mem::cmp(exports[middle].name, name);
396 +
        if order == 0 {
397 +
            return exports[middle];
398 +
        }
399 +
        if order < 0 {
400 +
            set low = middle + 1;
401 +
        } else {
402 +
            set high = middle;
403 +
        }
404 +
    }
405 +
    return nil;
406 +
}
lib/std/lang/il/binary/linkage.rad +4 -5
1 -
//! Exact dependency pins and typed import bindings in binary RIL envelopes.
1 +
//! Metadata dependency pins and typed import bindings in binary RIL envelopes.
2 2
3 3
use std::hash::blake3;
4 4
use std::lang::il;
5 5
use std::lang::il::binary;
6 6
use std::lang::il::binary::reader;
47 47
48 48
/// Encode persistent declarations. Verification state has no wire representation.
49 49
export fn write(
50 50
    out: &mut writer::Writer, links: &binary::Links, symbols: &mut opaque writer::SymbolTable
51 51
) throws (binary::Error) {
52 +
    try writeId(out, &links.metadata);
52 53
    try writer::word(out, links.pins.len as u64);
53 54
    for pin in links.pins {
54 55
        try writeId(out, &pin);
55 56
    }
56 57
    try writer::word(out, links.imports.len as u64);
79 80
80 81
/// Decode link declarations before reading the program's descriptor tables.
81 82
export fn read(input: &mut reader::Reader['wire], arena: &heap::Heap) -> binary::Links
82 83
    throws (binary::Error)
83 84
{
85 +
    let metadata = try readId(input);
84 86
    let pinCount = try input.count(32);
85 87
    let mut pins: *mut [binary::Id] = &mut [];
86 88
    try pins.reserve(pinCount, arena) catch {
87 89
        throw binary::Error::Storage;
88 90
    };
120 122
        try imports.append(binary::Import { name, dependency, exported, kind }, arena) catch {
121 123
            throw binary::Error::Storage;
122 124
        };
123 125
    }
124 126
    return binary::Links {
125 -
        pins: &pins[..],
126 -
        imports: &imports[..],
127 -
        image: nil,
128 -
        verified: false,
127 +
        metadata, pins: &pins[..], imports: &imports[..], image: nil, verified: false
129 128
    };
130 129
}
131 130
132 131
/// Check import indices against the decoded package table sizes.
133 132
export fn check(links: &binary::Links, dependencies: u32, layouts: u32, signatures: u32)
lib/std/lang/il/binary/program.rad +13 -5
58 58
    }
59 59
    try writer::word(out, package.exports.len as u64);
60 60
    for item in package.exports {
61 61
        try writer::symbol(out, item.name, symbols);
62 62
        match item.kind {
63 -
            case binary::ExportKind::Function => try writer::byte(out, 0),
64 -
            case binary::ExportKind::Data     => try writer::byte(out, 1),
63 +
            case binary::ExportKind::Function(index) => {
64 +
                try writer::byte(out, binary::SYMBOL_FUNCTION);
65 +
                try writer::word(out, index as u64);
66 +
            }
67 +
            case binary::ExportKind::Data(index) => {
68 +
                try writer::byte(out, binary::SYMBOL_DATA);
69 +
                try writer::word(out, index as u64);
70 +
            }
65 71
        }
66 72
    }
67 73
    if let entry = package.entry {
68 74
        try writer::byte(out, 1);
69 75
        try writer::symbol(out, entry, symbols);
688 694
    try exports.reserve(exportCount, a) catch {
689 695
        throw binary::Error::Storage;
690 696
    };
691 697
    for _ in 0 .. exportCount {
692 698
        let symbol = try input.symbol();
693 -
        let kind = binary::ExportKind::Data
694 -
            if try input.flag()
695 -
            else binary::ExportKind::Function;
699 +
        let isData = try input.flag();
700 +
        let index = try input.word() as u32;
701 +
        let kind = binary::ExportKind::Data(index)
702 +
            if isData
703 +
            else binary::ExportKind::Function(index);
696 704
        try exports.append(
697 705
            binary::Export {
698 706
                name: symbol,
699 707
                kind,
700 708
                startable: false,
lib/std/lang/il/binary/tests.rad +20 -0
839 839
            2, 0, 0, 0, 0, 0, 0, 0, 0,
840 840
            0, 0, 0, 0,
841 841
        ]
842 842
    );
843 843
}
844 +
845 +
/// Export lookup finds every name of a sorted table and nothing between them.
846 +
@test fn exportLookup() throws (testing::TestError) {
847 +
    let exports: *[binary::Export] = &[
848 +
        binary::Export { name: "p::a", kind: binary::ExportKind::Data(1), startable: false },
849 +
        binary::Export { name: "p::c", kind: binary::ExportKind::Function(0), startable: false },
850 +
        binary::Export { name: "p::e", kind: binary::ExportKind::Data(0), startable: false },
851 +
    ];
852 +
    for item in exports {
853 +
        let found = binary::find(exports, item.name) else {
854 +
            throw testing::TestError::Failed;
855 +
        };
856 +
        try testing::expect(found.kind == item.kind);
857 +
    }
858 +
    try testing::expect(binary::find(exports, "p::") == nil);
859 +
    try testing::expect(binary::find(exports, "p::b") == nil);
860 +
    try testing::expect(binary::find(exports, "p::d") == nil);
861 +
    try testing::expect(binary::find(exports, "p::f") == nil);
862 +
    try testing::expect(binary::find(&[], "p::a") == nil);
863 +
}
lib/std/lang/il/binary/tests/decode.rad +11 -8
106 106
        &[
107 107
            82, 73, 76, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0,
108 108
            1, 0, 0, 0, 112, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
109 109
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
110 110
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
111 +
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
112 +
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
111 113
        ]
112 114
    );
113 115
}
114 116
115 117
/// Check functions, dependencies, exports, initializers, and block metadata.
204 206
        name: "p",
205 207
        dependencies: &["dep"],
206 208
        exports: &[
207 209
            binary::Export {
208 210
                name: "p::main",
209 -
                kind: binary::ExportKind::Function,
211 +
                kind: binary::ExportKind::Function(0),
210 212
                startable: false,
211 213
            },
212 214
            binary::Export {
213 215
                name: "p::data",
214 -
                kind: binary::ExportKind::Data,
216 +
                kind: binary::ExportKind::Data(0),
215 217
                startable: false,
216 218
            },
217 219
        ],
218 220
        entry: "p::main",
219 221
        program: il::Program {
520 522
}
521 523
522 524
/// Indexed headers and streaming functions match a complete package encoding.
523 525
/// Encoding errors return buffer and symbol storage to their owners.
524 526
@test unsafe fn streamingEncoding() throws (testing::TestError) {
525 -
    static whole: [u8; 128] = [0; 128];
526 -
    static split: [u8; 128] = [0; 128];
527 +
    static whole: [u8; 160] = [0; 160];
528 +
    static split: [u8; 160] = [0; 160];
527 529
    unsafe static slots: [dict::Entry; 8] = [dict::Entry { key: "", value: 0 }; 8];
528 530
    static fixture: [u8; 2048] = [0; 2048];
529 531
    let arena = heap::over(&mut fixture[..]);
530 532
    let func = retainFn(
531 533
        il::Fn {
567 569
    let mut index = dict::init(&mut slots[..] as *mut [dict::Entry]);
568 570
    try! dict::insert(&mut index, "p", 0);
569 571
    try! dict::insert(&mut index, "p::f", 1);
570 572
    let mut bytes = &mut split[..] as *mut [u8];
571 573
    let head = try! program::encodeHead(&mut bytes, &package, &mut index, 1);
572 -
    assert bytes.len == 128 and index.count == 2 and dict::get(&index, "p::f") == 1;
574 +
    assert bytes.len == 160 and index.count == 2 and dict::get(&index, "p::f") == 1;
573 575
574 576
    // Streaming collection assigns first-use indices while encoding the same bytes.
575 577
    let mut names = try! collect::new(8, arena);
576 578
    try! collect::start(&mut names, "p", arena);
577 579
    let end = try! program::appendCollected(&mut bytes, head, &mut names, func, arena);
578 580
    assert names.symbols.len == 2 and mem::eq(names.symbols[1], "p::f");
579 -
    assert names.index.count == 2 and bytes.len == 128;
581 +
    assert names.index.count == 2 and bytes.len == 160;
580 582
    try testing::expectBytesEq(&whole[.. length], &bytes[.. end]);
581 583
    let mut limited = &mut split[.. head + 8] as *mut [u8];
582 584
    let mut failed = false;
583 585
    try program::appendCollected(&mut limited, head, &mut names, func, arena) catch error {
584 586
        assert error == binary::Error::Capacity;
598 600
    set failed = false;
599 601
    try program::encodeHead(&mut bytes, &package, &mut missing, 1) catch error {
600 602
        assert error == binary::Error::Symbol;
601 603
        set failed = true;
602 604
    };
603 -
    assert failed and bytes.len == 128 and missing.count == 0;
605 +
    assert failed and bytes.len == 160 and missing.count == 0;
604 606
}
605 607
606 608
/// Reject unknown initializer tags and widths before reading their payloads.
607 609
@test unsafe fn malformedInitializers() throws (testing::TestError) {
608 610
    let arena = heap::withCapacity(&mut MEMORY[..], 8);
1457 1459
                il::Signature { params: &[], ret: il::ValType::Void, borrows: &[] }
1458 1460
            ],
1459 1461
            traits: &[],
1460 1462
        },
1461 1463
        links: binary::Links {
1464 +
            metadata: binary::Id { bytes: [9; linkage::ID_BYTES] },
1462 1465
            pins: &[
1463 1466
                binary::Id { bytes: [1; 32] }
1464 1467
            ],
1465 1468
            imports: &[
1466 1469
                binary::Import {
1507 1510
        symbols: &["p", "p::f"],
1508 1511
        name: "p",
1509 1512
        dependencies: &[],
1510 1513
        exports: &[
1511 1514
            binary::Export {
1512 -
                name: "p::f", kind: binary::ExportKind::Function, startable: false
1515 +
                name: "p::f", kind: binary::ExportKind::Function(0), startable: false
1513 1516
            },
1514 1517
        ],
1515 1518
        entry: nil,
1516 1519
        program: il::Program {
1517 1520
            data: &[], fns: &functions[..], layouts: &[], signatures: &[], traits: &[]
lib/std/lang/il/verify.rad +21 -19
2621 2621
            {
2622 2622
                throw failFn(index as u32, Rule::Package);
2623 2623
            }
2624 2624
        }
2625 2625
    }
2626 -
    for item in package.exports {
2626 +
    for item, i in package.exports {
2627 +
        if i > 0 and mem::cmp(package.exports[i - 1].name, item.name) >= 0 {
2628 +
            throw bad;
2629 +
        }
2627 2630
        match item.kind {
2628 -
            case binary::ExportKind::Function => {
2629 -
                let index = dict::get(&c.fnNames, item.name) else throw bad;
2630 -
                if index as u32 >= c.localFunctions {
2631 +
            case binary::ExportKind::Function(index) => {
2632 +
                if index >= c.localFunctions
2633 +
                    or not mem::eq(package.program.fns[index].name, item.name)
2634 +
                {
2631 2635
                    throw bad;
2632 2636
                }
2633 2637
            }
2634 -
            case binary::ExportKind::Data => {
2635 -
                let index = dict::get(&c.dataNames, item.name) else throw bad;
2636 -
                if index as u32 >= c.localData {
2638 +
            case binary::ExportKind::Data(index) => {
2639 +
                if index >= c.localData
2640 +
                    or not mem::eq(package.program.data[index].name, item.name)
2641 +
                {
2637 2642
                    throw bad;
2638 2643
                }
2639 2644
            }
2640 2645
        }
2641 2646
    }
2646 2651
/// be read from above the fresh stack.
2647 2652
constant START_ARGS: u32 = 2;
2648 2653
2649 2654
/// Whether an exported function accepts the plain arguments of a fresh context.
2650 2655
/// The domain entry uses its separate Env contract.
2651 -
fn startable(package: &binary::Package, c: &Context, name: *[u8]) -> bool {
2656 +
fn startable(package: &binary::Package, index: u32) -> bool {
2657 +
    let func = package.program.fns[index];
2652 2658
    if let entry = package.entry {
2653 -
        if mem::eq(entry, name) {
2659 +
        if mem::eq(entry, func.name) {
2654 2660
            return false;
2655 2661
        }
2656 2662
    }
2657 -
    let index = dict::get(&c.fnNames, name) else {
2658 -
        return false;
2659 -
    };
2660 -
    let func = package.program.fns[index as u32];
2661 2663
    if func.params.len > START_ARGS or not isData(func.returnType) {
2662 2664
        return false;
2663 2665
    }
2664 2666
    for param in func.params {
2665 2667
        if not isData(param.type) {
2669 2671
    return true;
2670 2672
}
2671 2673
2672 2674
/// Classify public functions for checked library calls and fresh context creation.
2673 2675
/// The retained export metadata is allocated from keep and must outlive the package.
2674 -
fn classifyExports(package: &mut binary::Package, c: &Context, keep: &heap::Heap)
2675 -
    throws (Error)
2676 -
{
2676 +
fn classifyExports(package: &mut binary::Package, keep: &heap::Heap) throws (Error) {
2677 2677
    let mut kept: *mut [binary::Export] = &mut [];
2678 2678
    try kept.reserve(package.exports.len, keep) catch {
2679 2679
        throw STORAGE;
2680 2680
    };
2681 2681
    for item in package.exports {
2682 -
        let eligible =
2683 -
            item.kind == binary::ExportKind::Function and startable(package, c, item.name);
2682 +
        let mut eligible = false;
2683 +
        if let case binary::ExportKind::Function(index) = item.kind {
2684 +
            set eligible = startable(package, index);
2685 +
        }
2684 2686
        try kept.append(
2685 2687
            binary::Export {
2686 2688
                name: item.name, kind: item.kind, startable: eligible
2687 2689
            },
2688 2690
            keep
2719 2721
    let resolved = try linking::bind(package, providers, scratch);
2720 2722
    let mut c = try prepare(&resolved, config, scratch);
2721 2723
    set c.localFunctions = package.program.fns.len;
2722 2724
    set c.localData = package.program.data.len;
2723 2725
    try checkPackage(package, &c);
2724 -
    try classifyExports(package, &c, keep);
2726 +
    try classifyExports(package, keep);
2725 2727
    try finish(c, scratch);
2726 2728
    set package.links.verified = true;
2727 2729
}
lib/std/lang/il/verify/linking.rad +22 -34
1 -
//! Typed import environments for exact verified provider images.
1 +
//! Typed import environments for verified provider metadata.
2 +
//!
3 +
//! Imports match their providers by structure: layouts, signatures and traits
4 +
//! carry no owner. Verification guarantees memory safety, not encapsulation.
5 +
//! A verified client can build any value whose layout fits, including a value of
6 +
//! a provider's opaque record, so `opaque` hides a representation only from source
7 +
//! code. Provider code must treat every value it receives as untrusted, and an
8 +
//! opaque record cannot serve as authority across a verified boundary; kernel
9 +
//! handles, or keys that the provider checks against state it holds, can.
10 +
//! Memory safety holds because every provider is itself verified against any
11 +
//! input of its types. A verified client therefore never links against an
12 +
//! unverified provider, whose unsafe code might rely on opaque invariants.
2 13
3 14
use std::lang::il;
4 15
use std::lang::il::binary;
5 16
use std::lang::il::link;
6 17
use std::lang::il::verify;
7 18
use std::mem;
8 19
use std::mem::heap;
9 20
10 -
/// Maximum distinct descriptor pairs in one import comparison.
11 -
constant PAIRS: u32 = 4096;
12 -
13 21
/// Declarations of code which the caller has already verified.
14 22
/// Kernel callers obtain these only from verified resident image descriptors.
23 +
/// An unverified provider must never be supplied: see the module documentation.
15 24
export record Provider: Copy {
16 25
    /// Identity of the resident image's complete immutable source payload.
17 26
    image: binary::Id,
18 27
    /// Decoded declarations from that verified image, retained for this check.
19 28
    contract: binary::Package,
76 85
    if package.dependencies.len <> providers.len or package.links.pins.len <> providers.len {
77 86
        throw BAD;
78 87
    }
79 88
    for provider, i in providers {
80 89
        let pin = package.links.pins[i];
81 -
        if not mem::eq(&pin.bytes[..], &provider.image.bytes[..]) {
90 +
        if not mem::eq(&pin.bytes[..], &provider.contract.links.metadata.bytes[..]) {
82 91
            throw BAD;
83 92
        }
84 93
        for earlier in &providers[.. i] {
85 94
            if mem::eq(&earlier.image.bytes[..], &provider.image.bytes[..]) {
86 95
                throw BAD;
102 111
        }
103 112
    }
104 113
    let product = leftCount * rightCount;
105 114
    let mut capacity: u32 = 1;
106 115
    if product > 0 {
107 -
        set capacity = PAIRS if product > PAIRS as u64 else product as u32;
116 +
        set capacity = link::MAX_PAIRS if product > link::MAX_PAIRS as u64 else product as u32;
108 117
    }
109 118
    let mut work = try link::workspace(capacity, arena) catch error {
110 119
        throw graphError(error);
111 120
    };
112 121
    let mut fns: *mut [*il::Fn] = &mut [];
120 129
    for imported in package.links.imports {
121 130
        if imported.dependency >= providers.len {
122 131
            throw BAD;
123 132
        }
124 133
        let provider = providers[imported.dependency].contract;
125 -
        let mut exported: ?binary::ExportKind = nil;
126 -
        for entry in provider.exports {
127 -
            if mem::eq(entry.name, imported.exported) {
128 -
                if exported <> nil {
129 -
                    throw BAD;
130 -
                }
131 -
                set exported = entry.kind;
132 -
            }
133 -
        }
134 -
        let exportKind = exported else throw BAD;
134 +
        let exported = binary::find(provider.exports, imported.exported) else throw BAD;
135 135
        match imported.kind {
136 136
            case binary::ImportKind::Function(index) => {
137 -
                if exportKind <> binary::ExportKind::Function
138 -
                    or index >= package.program.signatures.len
139 -
                {
137 +
                let case binary::ExportKind::Function(target) = exported.kind else throw BAD;
138 +
                if index >= package.program.signatures.len {
140 139
                    throw BAD;
141 140
                }
142 -
                let mut target: ?*il::Fn = nil;
143 -
                for func in provider.program.fns {
144 -
                    if mem::eq(func.name, imported.exported) {
145 -
                        set target = func;
146 -
                    }
147 -
                }
148 -
                let definition = target else throw BAD;
141 +
                let definition = provider.program.fns[target];
149 142
                let sig = package.program.signatures[index];
150 143
                let matches = try link::sameCallable(
151 144
                    &mut work, &package.program, &sig, &provider.program, definition
152 145
                ) catch error {
153 146
                    throw graphError(error);
156 149
                    throw BAD;
157 150
                }
158 151
                try function(&mut fns, imported.name, sig, arena);
159 152
            }
160 153
            case binary::ImportKind::Data { layout, readOnly, heap } => {
161 -
                if exportKind <> binary::ExportKind::Data or layout >= package.program.layouts.len {
154 +
                let case binary::ExportKind::Data(target) = exported.kind else throw BAD;
155 +
                if layout >= package.program.layouts.len {
162 156
                    throw BAD;
163 157
                }
164 -
                let mut target: ?il::Data = nil;
165 -
                for item in provider.program.data {
166 -
                    if mem::eq(item.name, imported.exported) {
167 -
                        set target = item;
168 -
                    }
169 -
                }
170 -
                let definition = target else throw BAD;
158 +
                let definition = provider.program.data[target];
171 159
                let info = package.program.layouts[layout];
172 160
                let declaration = il::Data {
173 161
                    name: imported.name,
174 162
                    size: info.size,
175 163
                    alignment: info.alignment,
lib/std/lang/il/verify/tests.rad +121 -5
3184 3184
        throw testing::TestError::Failed;
3185 3185
    };
3186 3186
    try testing::expect(err.rule == verify::Rule::Package);
3187 3187
}
3188 3188
3189 +
/// Exports are sorted by name, and each one indexes a definition of the same name.
3190 +
@test unsafe fn packageExportTable() throws (testing::TestError) {
3191 +
    let a = binary::Export { name: "a", kind: binary::ExportKind::Function(0), startable: false };
3192 +
    let b = binary::Export { name: "b", kind: binary::ExportKind::Function(1), startable: false };
3193 +
    let d = binary::Export { name: "d", kind: binary::ExportKind::Data(0), startable: false };
3194 +
    let mut ok = newBuilder();
3195 +
    addFn(&mut ok, "a", &[], il::ValType::Void, &[retVoid()]);
3196 +
    addFn(&mut ok, "b", &[], il::ValType::Void, &[retVoid()]);
3197 +
    addData(&mut ok, "d", P4, true, &[]);
3198 +
    try testing::expect(packageVerdict(&mut ok, &[], nil, &[a, b, d]) == nil);
3199 +
    try packageRejected(&mut ok, &[], nil, &[b, a, d]);
3200 +
    try packageRejected(&mut ok, &[], nil, &[a, a, d]);
3201 +
    let mut renamed = b;
3202 +
    set renamed.kind = binary::ExportKind::Function(0);
3203 +
    try packageRejected(&mut ok, &[], nil, &[a, renamed]);
3204 +
    let mut beyond = d;
3205 +
    set beyond.kind = binary::ExportKind::Data(1);
3206 +
    try packageRejected(&mut ok, &[], nil, &[a, beyond]);
3207 +
    let mut kind = d;
3208 +
    set kind.kind = binary::ExportKind::Function(0);
3209 +
    try packageRejected(&mut ok, &[], nil, &[kind]);
3210 +
}
3211 +
3189 3212
/// A package has no dependencies, and no extern functions.
3190 3213
@test unsafe fn packageIsSelfContained() throws (testing::TestError) {
3191 3214
    let mut ok = newBuilder();
3192 3215
    addFn(&mut ok, "f", &[], il::ValType::Void, &[retVoid()]);
3193 3216
    try testing::expect(packageVerdict(&mut ok, &[], nil, &[]) == nil);
3245 3268
3246 3269
/// Public functions retain their call contracts; only data-argument entries can start contexts.
3247 3270
@test unsafe fn packageExports() throws (testing::TestError) {
3248 3271
    let function = binary::Export {
3249 3272
        name: "f",
3250 -
        kind: binary::ExportKind::Function,
3273 +
        kind: binary::ExportKind::Function(0),
3251 3274
        startable: false,
3252 3275
    };
3253 3276
    let mut ok = newBuilder();
3254 3277
    addFn(&mut ok, "f", &[oneData()], dataType(), &[ret(reg(0))]);
3255 3278
    try testing::expect(packageVerdict(&mut ok, &[], nil, &[function]) == nil);
3295 3318
    let mut missing = newBuilder();
3296 3319
    try packageRejected(&mut missing, &[], nil, &[function]);
3297 3320
    let env = param(0, ptrType(P16, true, false, false));
3298 3321
    let entry = binary::Export {
3299 3322
        name: "entry",
3300 -
        kind: binary::ExportKind::Function,
3323 +
        kind: binary::ExportKind::Function(0),
3301 3324
        startable: false,
3302 3325
    };
3303 3326
    let mut exportedEntry = newBuilder();
3304 3327
    addFn(&mut exportedEntry, "entry", &[env], il::ValType::Void, &[retVoid()]);
3305 3328
    try testing::expect(packageVerdict(&mut exportedEntry, &[], "entry", &[entry]) == nil);
3307 3330
    let mut data = newBuilder();
3308 3331
    addData(&mut data, "d", P4, true, &[]);
3309 3332
3310 3333
    let item = binary::Export {
3311 3334
        name: "d",
3312 -
        kind: binary::ExportKind::Data,
3335 +
        kind: binary::ExportKind::Data(0),
3313 3336
        startable: false,
3314 3337
    };
3315 3338
    try testing::expect(packageVerdict(&mut data, &[], nil, &[item]) == nil);
3316 3339
    let mut absent = newBuilder();
3317 3340
    try packageRejected(&mut absent, &[], nil, &[item]);
5548 5571
    let mut declarations: *mut [il::Fn] = &mut [];
5549 5572
    try! declarations.append(IMPORT_TARGET, providerArena);
5550 5573
    let frozen: *[il::Fn] = &declarations[..];
5551 5574
    let mut functions: *mut [*il::Fn] = &mut [];
5552 5575
    try! functions.append(&frozen[0], providerArena);
5553 -
    let provider = binary::Package {
5576 +
    let mut provider = binary::Package {
5554 5577
        symbols: &["dep", "dep::id"],
5555 5578
        name: "dep",
5556 5579
        dependencies: &[],
5557 5580
        exports: &[
5558 -
            binary::Export { name: "dep::id", kind: binary::ExportKind::Function, startable: false }
5581 +
            binary::Export {
5582 +
                name: "dep::id", kind: binary::ExportKind::Function(0), startable: false
5583 +
            },
5559 5584
        ],
5560 5585
        entry: nil,
5561 5586
        program: il::Program {
5562 5587
            data: &[], fns: &functions[..], layouts: &[], signatures: &[], traits: &[]
5563 5588
        },
5569 5594
    let arguments = args(&mut b, &[imm(42)]);
5570 5595
    addFn(&mut b, "caller", &[], dataType(), &[
5571 5596
        call(0, dataType(), il::Val::FnAddr("alias"), arguments), ret(reg(0))
5572 5597
    ]);
5573 5598
    let identity = linkage::imageId("provider image");
5599 +
    set provider.links.metadata = identity;
5574 5600
    let mut pins: *mut [binary::Id] = &mut [];
5575 5601
    try! pins.append(
5576 5602
        identity, b.arena
5577 5603
    );
5578 5604
    let mut package = binary::Package {
5581 5607
        dependencies: &["dep"],
5582 5608
        exports: &[],
5583 5609
        entry: nil,
5584 5610
        program: program(&mut b),
5585 5611
        links: binary::Links {
5612 +
            metadata: binary::Id { bytes: [0; linkage::ID_BYTES] },
5586 5613
            pins: &pins[..],
5587 5614
            imports: &[
5588 5615
                binary::Import {
5589 5616
                    name: "alias",
5590 5617
                    dependency: 0,
5602 5629
    );
5603 5630
    let work = heap::over(&mut SCRATCH[..]);
5604 5631
    let keep = heap::over(&mut KEEP[..]);
5605 5632
    try! verify::verifyLinkedPackage(&mut package, &supplied[..], CONFIG, work, keep);
5606 5633
}
5634 +
5635 +
/// Layouts in a pointer chain, more than the 4096 descriptor pairs of a small workspace.
5636 +
constant CHAIN: u32 = 4100;
5637 +
5638 +
/// Storage for the layout chain, which the provider and the client share.
5639 +
static CHAIN_MEMORY: [u8; 524288] = [0; 524288];
5640 +
/// Working storage for the comparison of the chain.
5641 +
static CHAIN_SCRATCH: [u8; 2097152] = [0; 2097152];
5642 +
5643 +
/// An imported data contract binds when its layout graph has more pairs than a small
5644 +
/// fixed workspace holds.
5645 +
@test unsafe fn longImportedLayoutChain() throws (testing::TestError) {
5646 +
    let arena = heap::over(&mut CHAIN_MEMORY[..]);
5647 +
    let mut layouts: *mut [il::Layout] = &mut [];
5648 +
    try! layouts.reserve(CHAIN, arena);
5649 +
    try! layouts.append(il::Layout { size: 8, alignment: 8, slots: &[], regions: 0 }, arena);
5650 +
    for i in 1 .. CHAIN {
5651 +
        let mut slots: *mut [il::Slot] = &mut [];
5652 +
        try! slots.append(ptrSlot(0, i - 1, false, false), arena);
5653 +
        try! layouts.append(
5654 +
            il::Layout { size: 8, alignment: 8, slots: &slots[..], regions: 0 }, arena
5655 +
        );
5656 +
    }
5657 +
    let mut data: *mut [il::Data] = &mut [];
5658 +
    try! data.append(
5659 +
        il::Data {
5660 +
            name: "dep::d",
5661 +
            size: 8,
5662 +
            alignment: 8,
5663 +
            layout: CHAIN - 1,
5664 +
            readOnly: true,
5665 +
            heap: nil,
5666 +
            isZeroInit: true,
5667 +
            values: &[],
5668 +
        },
5669 +
        arena
5670 +
    );
5671 +
    let identity = linkage::imageId("chain image");
5672 +
    let mut provider = binary::Package {
5673 +
        symbols: &["dep", "dep::d"],
5674 +
        name: "dep",
5675 +
        dependencies: &[],
5676 +
        exports: &[
5677 +
            binary::Export { name: "dep::d", kind: binary::ExportKind::Data(0), startable: false }
5678 +
        ],
5679 +
        entry: nil,
5680 +
        program: il::Program {
5681 +
            data: &data[..], fns: &[], layouts: &layouts[..], signatures: &[], traits: &[]
5682 +
        },
5683 +
        links: binary::EMPTY_LINKS,
5684 +
    };
5685 +
    set provider.links.metadata = identity;
5686 +
    let mut pins: *mut [binary::Id] = &mut [];
5687 +
    try! pins.append(identity, arena);
5688 +
    let mut imports: *mut [binary::Import] = &mut [];
5689 +
    try! imports.append(
5690 +
        binary::Import {
5691 +
            name: "alias",
5692 +
            dependency: 0,
5693 +
            exported: "dep::d",
5694 +
            kind: binary::ImportKind::Data { layout: CHAIN - 1, readOnly: true, heap: nil },
5695 +
        },
5696 +
        arena
5697 +
    );
5698 +
    let package = binary::Package {
5699 +
        symbols: &[],
5700 +
        name: "p",
5701 +
        dependencies: &["dep"],
5702 +
        exports: &[],
5703 +
        entry: nil,
5704 +
        program: il::Program {
5705 +
            data: &[], fns: &[], layouts: &layouts[..], signatures: &[], traits: &[]
5706 +
        },
5707 +
        links: binary::Links {
5708 +
            metadata: binary::Id { bytes: [0; linkage::ID_BYTES] },
5709 +
            pins: &pins[..],
5710 +
            imports: &imports[..],
5711 +
            image: nil,
5712 +
            verified: false,
5713 +
        },
5714 +
    };
5715 +
    let mut supplied: *mut [linking::Provider] = &mut [];
5716 +
    try! supplied.append(linking::Provider { image: identity, contract: provider }, arena);
5717 +
    let scratch = heap::over(&mut CHAIN_SCRATCH[..]);
5718 +
    let resolved = try linking::bind(&package, &supplied[..], scratch) catch {
5719 +
        throw testing::TestError::Failed;
5720 +
    };
5721 +
    try testing::expect(resolved.data.len == 1);
5722 +
}
lib/std/lang/pretty.rad +43 -16
168 168
        role: Role::Source, trivia: &[], used: 0, fnDepth: 0, marks: 0, tableRecord: nil
169 169
    };
170 170
    return try expr(a, &mut p, node, Ctx::Normal);
171 171
}
172 172
173 -
/// Format provider declarations without runtime bodies or compiler entry helpers.
174 -
/// Supporting declarations keep their source visibility and nominal ownership.
175 -
export fn interface(root: *ast::Node, a: &heap::Heap) -> *layout::Layout
176 -
    throws (alloc::AllocError)
177 -
{
178 -
    return try withRole(root, &[], Role::Interface, a);
173 +
/// Format one top-level statement of a provider interface without its runtime body.
174 +
/// A compiler entry helper formats as nothing. Declarations keep their source
175 +
/// visibility and nominal ownership.
176 +
export fn interfaceStatement(
177 +
    node: *ast::Node, a: &heap::Heap
178 +
) -> ?*layout::Layout throws (alloc::AllocError) {
179 +
    if isEntry(node) {
180 +
        return nil;
181 +
    }
182 +
    let mut p = Printer {
183 +
        role: Role::Interface,
184 +
        trivia: &[],
185 +
        used: 0,
186 +
        fnDepth: 0,
187 +
        marks: 0,
188 +
        tableRecord: nil,
189 +
    };
190 +
    return try stmt(a, &mut p, node);
191 +
}
192 +
193 +
/// Place the layouts of interface statements one per line, as the layout of the
194 +
/// module `root`. This is the layout of a module of those statements without trivia.
195 +
export fn interfaceModule(
196 +
    root: *ast::Node, statements: *[*layout::Layout], a: &heap::Heap
197 +
) -> *layout::Layout throws (alloc::AllocError) {
198 +
    let mut kids: *mut [layout::Child] = &mut [];
199 +
    for statement in statements {
200 +
        try add(a, &mut kids, layout::Placement::Line, statement);
201 +
    }
202 +
    return try group(a, root, kids);
179 203
}
180 204
181 205
/// Build the layout of one module in its input role.
182 206
export fn withRole(
183 207
    root: *ast::Node, trivia: *[ast::Trivia], role: Role, a: &heap::Heap
587 611
) throws (alloc::AllocError) {
588 612
    let mut flow = Flow { started: false, blank: false, afterBlock: false };
589 613
    let mut row = Row { kids: &mut [], at: 0, comment: nil };
590 614
    let spaced = p.role == Role::Source and spacesFunctions(p, container);
591 615
    for item, i in items {
592 -
        if p.role == Role::Interface {
593 -
            // Compiler entry declarations have reserved names outside source syntax.
594 -
            if let case ast::NodeValue::FnDecl(decl) = item.value {
595 -
                if let case ast::NodeValue::Ident(name) =
596 -
                    decl.name.value;
597 -
                    name.len > 0 and name[0] == '#'
598 -
                {
599 -
                    continue;
600 -
                }
601 -
            }
616 +
        if p.role == Role::Interface and isEntry(item) {
617 +
            continue;
602 618
        }
603 619
        if i > 0 {
604 620
            // Functions are one blank line apart. A block in a function body
605 621
            // has no blank line after it.
606 622
            if spaced and hasBody(items[i - 1]) and hasBody(item) {
645 661
        set flow.afterBlock = p.fnDepth > 0 and endsWithBlock(last);
646 662
    }
647 663
    try comments(a, kids, closing, level, &mut flow);
648 664
}
649 665
666 +
/// Whether a declaration is a compiler entry helper, which has a reserved name
667 +
/// outside source syntax and is left out of interfaces.
668 +
fn isEntry(node: *ast::Node) -> bool {
669 +
    if let case ast::NodeValue::FnDecl(decl) = node.value {
670 +
        if let case ast::NodeValue::Ident(name) = decl.name.value {
671 +
            return name.len > 0 and name[0] == '#';
672 +
        }
673 +
    }
674 +
    return false;
675 +
}
676 +
650 677
/// Whether a list with the container `container` puts one blank line between
651 678
/// functions: the top level of a module, and the methods of an instance.
652 679
fn spacesFunctions(p: &Printer, container: *ast::Node) -> bool {
653 680
    match container.value {
654 681
        case ast::NodeValue::Module(_)           => return true,
lib/std/lang/resolver.rad +3 -15
41 41
/// Maximum number of symbols stored within a module scope.
42 42
export constant MAX_MODULE_SYMBOLS: u32 = 512;
43 43
44 44
/// Initial capacity of `Resolver.symbols`. The slice grows past it when a
45 45
/// package has more symbols, but each growth copies every symbol, so the
46 -
/// capacity covers the standard library with its tests, which has 33000 symbols. A growth copy
46 +
/// capacity covers the standard library and kernel test declarations. A growth copy
47 47
/// keeps the old table in the arena, so a smaller capacity costs more memory than this one.
48 -
export constant INITIAL_SYMBOL_CAPACITY: u32 = 36864;
48 +
export constant INITIAL_SYMBOL_CAPACITY: u32 = 49152;
49 49
/// Maximum number of symbols stored within a local scope.
50 50
export constant MAX_LOCAL_SYMBOLS: u32 = 32;
51 51
/// Maximum declared parameters of a function or method. The receiver of a
52 52
/// method is not declared, so it does not count.
53 53
export constant MAX_FN_PARAMS: u32 = 8;
555 555
    name: *[u8],
556 556
    /// Data associated with the symbol.
557 557
    data: SymbolData,
558 558
    /// Bitset of attributes applied to the declaration.
559 559
    attrs: u32,
560 -
    /// Whether a source declaration references this function.
561 -
    interfaceUse: bool,
562 560
    /// AST node that introduced the symbol.
563 561
    node: *ast::Node,
564 562
    /// Module ID this symbol belongs to. Only for module-level symbols.
565 563
    moduleId: ?u16,
566 564
}
1678 1676
fn setNodeSymbol(self: &mut Resolver, node: *ast::Node, symbol: SymbolId) {
1679 1677
    if self.nodeData.get(node.id).sym <> nil {
1680 1678
        panic "setNodeSymbol: a symbol is already associated with this node";
1681 1679
    }
1682 1680
    set self.nodeData.getMut(node.id).sym = symbol;
1683 -
    if (self.phase == Phase::Declaration or self.constantInitializer <> nil)
1684 -
        and node <> self.symbols[*symbol].node
1685 -
    {
1686 -
        if let case ast::NodeValue::FnDecl(decl) =
1687 -
            self.symbols[*symbol].node.value;
1688 -
            node <> decl.name
1689 -
        {
1690 -
            set self.symbols[*symbol].interfaceUse = true;
1691 -
        }
1692 -
    }
1693 1681
}
1694 1682
1695 1683
/// Associate a resolved type with an AST node and return it.
1696 1684
fn setNodeType(self: &mut Resolver, node: *ast::Node, ty: Type) -> Type {
1697 1685
    if ty == Type::Unknown {
1937 1925
fn allocSymbol(
1938 1926
    self: &mut Resolver, data: SymbolData, name: *[u8], node: *ast::Node, attrs: u32
1939 1927
) -> SymbolId {
1940 1928
    let id = SymbolId(self.symbols.len);
1941 1929
    try! self.symbols.append(
1942 -
        Symbol { name, data, attrs, interfaceUse: false, node, moduleId: nil }, self.arena
1930 +
        Symbol { name, data, attrs, node, moduleId: nil }, self.arena
1943 1931
    );
1944 1932
1945 1933
    return id;
1946 1934
}
1947 1935
lib/std/lang/resolver/tests/core.rad +0 -18
50 50
    assert resolver::success(&extended);
51 51
    assert res.symbols.len > symbols;
52 52
    assert res.scopes.len > scopes;
53 53
}
54 54
55 -
/// Interface uses retain private callbacks even when their array has no runtime elements.
56 -
@test unsafe fn interfaceFunctionUses() throws (testing::TestError) {
57 -
    let mut res = testResolver();
58 -
    let result = try resolveProgramStr(
59 -
        &mut res,
60 -
        "fn unused() {} fn callback() {} constant HANDLERS: [fn(); 0] = [callback; 0]; fn body() { unused(); }"
61 -
    );
62 -
    try expectNoErrors(&result);
63 -
    let case ast::NodeValue::Module(block) = result.root.value
64 -
        else panic "interfaceFunctionUses: expected root";
65 -
    let unused = resolver::symbolFor(&res, block.statements[0])
66 -
        else panic "interfaceFunctionUses: missing private function";
67 -
    let callback = resolver::symbolFor(&res, block.statements[1])
68 -
        else panic "interfaceFunctionUses: missing callback";
69 -
    assert not res.symbols[*unused].interfaceUse;
70 -
    assert res.symbols[*callback].interfaceUse;
71 -
}
72 -
73 55
// Tests ///////////////////////////////////////////////////////////////////////
74 56
75 57
/// Function signatures and constants resolve their declaration dependencies.
76 58
@test unsafe fn testSignatureConstantDependencies() throws (testing::TestError) {
77 59
    for program in [
test/Makefile +9 -2
62 62
	@$(call integration,host)
63 63
64 64
package-test: $(INTEGRATION)
65 65
	@$(call integration,packages)
66 66
67 -
module-test: $(RAD_BIN) test/compiler/discovery.rv64
67 +
module-test: $(RAD_BIN) test/compiler/discovery.rv64 test/compiler/metadata.rv64
68 68
	@$(HOSTED) test/compiler/discovery.rv64
69 +
	@$(HOSTED) test/compiler/metadata.rv64
69 70
70 71
# Standard Library Tests
71 72
72 73
STD_LIB_TEST := lib/std.test.rv64
73 74
132 133
test/tests/%.rv64: test/tests/%.ras test/runner.rv64 test/Makefile
133 134
	@$(HOSTED) test/runner.rv64 assemble $< $@
134 135
135 136
clean-bin-test:
136 137
	@rm -f $(TEST_TOOLS) $(INTEGRATION) $(BIN_TEST_BIN) \
137 -
	    test/compiler/discovery.rv64 \
138 +
	    test/compiler/discovery.rv64 test/compiler/metadata.rv64 \
138 139
	    $(wildcard test/tests/*.rv64.debug test/tests/*.rv64.s) \
139 140
	    $(TEST_TOOLS:.rv64=.rv64.debug) $(TEST_TOOLS:.rv64=.rv64.s) \
140 141
	    $(TEST_TOOLS:.rv64=.rv64.o)
141 142
142 143
# Integer trap contexts and nested machine interrupts.
221 222
    compiler/radiance/testgen.rad compiler/radiance/testgen.manifest \
222 223
    test/compiler/checks.manifest $(STD_LIB) $(STD_MANIFEST) test/std.manifest $(RAD_BIN) test/Makefile
223 224
	@$(RADIANCE) $(STD) -pkg testgen -mod compiler/radiance/testgen.rad \
224 225
	    -pkg checks -mod test/compiler/discovery.rad -entry checks -o $@
225 226
227 +
# Check canonical exported metadata through the production compiler module.
228 +
test/compiler/metadata.rv64: test/compiler/metadata.rad compiler/radiance/metadata.rad \
229 +
    test/compiler/metachecks.manifest $(STD_LIB) $(STD_MANIFEST) test/std.manifest $(RAD_BIN) test/Makefile
230 +
	@$(RADIANCE) $(STD) -pkg metadata -manifest test/std.manifest -mod compiler/radiance/metadata.rad \
231 +
	    -pkg metachecks -mod test/compiler/metadata.rad -entry metachecks -o $@
232 +
226 233
.PHONY: test $(TESTS) $(SMP_TESTS) $(CYCLES_TESTS) clean-std-test clean-bin-test
test/compiler/metachecks.manifest added +2 -0
1 +
std
2 +
metadata
test/compiler/metadata.rad added +62 -0
1 +
//! Canonical compiler metadata hash checks.
2 +
3 +
use std::lang::il;
4 +
use std::lang::il::binary;
5 +
use std::mem::heap;
6 +
use metadata;
7 +
8 +
/// Export hashes exclude private descriptor indices and runtime initializer values.
9 +
@default unsafe fn main() -> u32 {
10 +
    static storage: [u8; 32768] = [0; 32768];
11 +
    let arena = heap::over(&mut storage[..]);
12 +
    let plain = il::Layout { size: 8, alignment: 8, slots: &[], regions: 0 };
13 +
    let private = il::Layout { size: 4, alignment: 4, slots: &[], regions: 0 };
14 +
    let mut original: ?binary::Id = nil;
15 +
    for version in 0 .. 4 {
16 +
        let mut layouts: *mut [il::Layout] = &mut [];
17 +
        if version > 0 {
18 +
            try! layouts.append(private, arena);
19 +
        }
20 +
        try! layouts.append(plain, arena);
21 +
        let mut declarations: *mut [il::Data] = &mut [];
22 +
        try! declarations.append(
23 +
            il::Data {
24 +
                name: "p::value",
25 +
                size: 8,
26 +
                alignment: 8,
27 +
                layout: 0 if version == 0 else 1,
28 +
                readOnly: version == 2,
29 +
                heap: nil,
30 +
                isZeroInit: version == 0,
31 +
                values: &[],
32 +
            },
33 +
            arena
34 +
        );
35 +
        let package = binary::Package {
36 +
            symbols: &[],
37 +
            name: "p",
38 +
            dependencies: &[],
39 +
            exports: &[
40 +
                binary::Export {
41 +
                    name: "p::value", kind: binary::ExportKind::Data(0), startable: false
42 +
                },
43 +
            ],
44 +
            entry: nil,
45 +
            program: il::Program {
46 +
                data: &declarations[..],
47 +
                fns: &[],
48 +
                layouts: &layouts[..],
49 +
                signatures: &[],
50 +
                traits: &[],
51 +
            },
52 +
            links: binary::EMPTY_LINKS,
53 +
        };
54 +
        let hash = try! metadata::exports(&package, arena);
55 +
        if let expected = original {
56 +
            assert hash <> expected if version == 2 else hash == expected;
57 +
        } else {
58 +
            set original = hash;
59 +
        }
60 +
    }
61 +
    return 0;
62 +
}
test/integration/packages.rad +118 -14
67 67
}
68 68
69 69
/// Compile a large std test artifact, then use its complete interfaces in a test client.
70 70
fn large(h: &mut Harness) throws (sys::Error) {
71 71
    let root = h.path(&["large"]);
72 -
    h.add(&["-test"]);
72 +
    h.add(&["-no-cache", "-test"]);
73 73
    try h.addStd();
74 74
    for path in try h.manifest("std.lib.test") {
75 75
        h.add(&["-mod", path]);
76 76
    }
77 +
    let provider = h.path(&["large-provider.rad"]);
78 +
    let client = h.path(&["large-client.rad"]);
79 +
    try fs::writeFile(provider, "export fn value() -> u32 { return 42; }\n");
80 +
    try fs::writeFile(
81 +
        client, "use provider; export fn value() -> u32 { return provider::value(); }\n"
82 +
    );
83 +
    try fs::writeFile(h.path(&["provider.manifest"]), "std\n");
84 +
    try fs::writeFile(h.path(&["client.manifest"]), "provider\n");
85 +
    h.add(&["-pkg", "provider", "-mod", provider, "-pkg", "client", "-mod", client]);
77 86
    h.add(&["-entry", "std", "-ril", root]);
78 87
    if not h.compile("export the std test artifact", h.out(&["large-export.log"])) {
79 88
        return;
80 89
    }
81 90
    let source = h.path(&["checks.rad"]);
224 233
    h.add(&["-no-cache", "-pkg", "dep", "-artifact", root]);
225 234
    h.compile("load reordered metadata fields", h.out(&["reordered-metadata.log"]));
226 235
    try fs::writeFile(path, original);
227 236
}
228 237
238 +
/// Implementation edits preserve client images across a transitive dependency graph.
239 +
fn metadataReuse(h: &mut Harness) throws (sys::Error) {
240 +
    let provider = h.path(&["reuse.rad"]);
241 +
    let facade = h.path(&["forward.rad"]);
242 +
    let client = h.path(&["consumer.rad"]);
243 +
    try fs::writeFile(h.path(&["forward.manifest"]), "reuse\n");
244 +
    try fs::writeFile(h.path(&["consumer.manifest"]), "forward\n");
245 +
    try fs::writeFile(
246 +
        facade, "use reuse; export fn value() -> u32 { return reuse::value(); }\n"
247 +
    );
248 +
    try fs::writeFile(
249 +
        client,
250 +
        "use forward; @default fn main() -> u32 { assert forward::value() == 43; return 0; }\n"
251 +
    );
252 +
    for version in 0 .. 2 {
253 +
        try fs::writeFile(
254 +
            provider,
255 +
            "export fn value() -> u32 { return 42; }\n"
256 +
                if version == 0
257 +
                else "export fn value() -> u32 { return 43; }\n"
258 +
        );
259 +
        let output = h.path(&["reuse-first"]) if version == 0 else h.path(&["reuse-second"]);
260 +
        let report =
261 +
            h.path(&["reuse-first.log"]) if version == 0 else h.path(&["reuse-second.log"]);
262 +
        h.add(
263 +
            &[
264 +
                "-cache", h.path(&["reuse-cache"]),
265 +
                "-pkg", "reuse", "-mod", provider,
266 +
                "-pkg", "forward", "-mod", facade,
267 +
                "-pkg", "consumer", "-mod", client, "-entry", "consumer", "-ril", output,
268 +
            ]
269 +
        );
270 +
        if not h.compile("compile metadata reuse graph", process::Output::File(report)) {
271 +
            return;
272 +
        }
273 +
        if version == 1 {
274 +
            h.expect("implementation edit retains facade", report, harness::Expect::Contains(
275 +
                "cache hit forward"
276 +
            ));
277 +
            h.expect("implementation edit retains client", report, harness::Expect::Contains(
278 +
                "cache hit consumer"
279 +
            ));
280 +
            for name in &["forward.ril", "consumer.ril"] {
281 +
                h.expect(
282 +
                    "implementation edit preserves client bytes",
283 +
                    h.join(&[output, "/", name]),
284 +
                    harness::Expect::Same(h.join(&[h.path(&["reuse-first"]), "/", name]))
285 +
                );
286 +
            }
287 +
        }
288 +
    }
289 +
    let root = h.path(&["reuse-second"]);
290 +
    let lock = h.join(&[root, "/package.lock"]);
291 +
    let original = try h.load(lock);
292 +
    h.expect("export exact package selections", lock, harness::Expect::Contains("LockedPackage"));
293 +
    let start = mem::find(original, "image: \"") else panic "metadataReuse: locked image";
294 +
    let digit = start + "image: \"".len;
295 +
    let changed = "0" if original[digit] <> '0' else "1";
296 +
    try fs::writeFileParts(lock, &[&original[.. digit], changed, &original[digit + 1 ..]]);
297 +
    h.add(&["-no-cache", "-pkg", "consumer", "-artifact", root]);
298 +
    let rejected = h.cc(h.take(), h.out(&["lock-mismatch.log"]));
299 +
    h.run("reject an image outside its lockfile", rejected, process::Outcome::Exited(1), &[]);
300 +
    try fs::writeFile(lock, original);
301 +
    h.add(&["-no-cache", "-pkg", "consumer", "-artifact", root, "-o", h.path(&["reuse.rv64"])]);
302 +
    if h.compile("link an unchanged client to the selected provider", h.out(&["reuse-link.log"])) {
303 +
        execute(h, h.path(&["reuse.rv64"]));
304 +
    }
305 +
}
306 +
229 307
/// A different compiler image uses its own cache entries and reads compatible artifacts.
230 308
fn compilerImage(h: &mut Harness, exported: *[u8]) throws (sys::Error) {
231 309
    let original = h.compiler;
232 310
    let bytes = try h.load(original);
233 311
    assert bytes.len >= 48 and mem::eq(&bytes[.. 8], "RADIANCE");
291 369
    }
292 370
    h.add(
293 371
        &[
294 372
            "-cache", h.path(&["disabled-cache"]), "-no-cache",
295 373
            "-pkg", "dep", "-mod", dep, "-pkg", "app", "-mod", app,
296 -
            "-entry", "app", "-o", h.path(&["direct.rv64"]),
374 +
            "-entry", "app", "-o", h.path(&["uncached.rv64"]),
297 375
        ]
298 376
    );
299 -
    if not h.compile("generate an uncached source program directly", h.out(&["direct.log"])) {
377 +
    if not h.compile("compile an uncached source graph", h.out(&["uncached.log"])) {
300 378
        return;
301 379
    }
302 380
    h.expect("cache bypass creates no cache", h.path(&["disabled-cache"]), harness::Expect::Absent);
303 381
    h.expect(
304 -
        "cache bypass skips package encoding",
305 -
        h.path(&["direct.log"]),
306 -
        harness::Expect::Matching {
307 -
            text: "encoding package tables", count: 0
308 -
        }
382 +
        "uncached graph uses package interfaces",
383 +
        h.path(&["uncached.log"]),
384 +
        harness::Expect::Contains("encoding interface metadata")
309 385
    );
310 -
    execute(h, h.path(&["direct.rv64"]));
386 +
    execute(h, h.path(&["uncached.rv64"]));
311 387
    source(h, image, "-o");
312 388
    if not h.compile("compile source package graph", h.out(&["cold.log"])) {
313 389
        return;
314 390
    }
315 391
    execute(h, image);
392 +
    h.expect("uncached executable parity", h.path(&["uncached.rv64"]), harness::Expect::Same(
393 +
        image
394 +
    ));
316 395
    source(h, h.path(&["warm.rv64"]), "-o");
317 396
    if not h.compile("reuse unchanged packages", h.out(&["warm.log"])) {
318 397
        return;
319 398
    }
320 399
    h.expect("dependency cache hit", h.path(&["warm.log"]), harness::Expect::Contains(
344 423
        declarations,
345 424
        harness::Expect::Contains(
346 425
            "fn emptyCallback("
347 426
        )
348 427
    );
428 +
    h.expect("interface omits unused private types", declarations, harness::Expect::Matching {
429 +
        text: "record Unused", count: 0
430 +
    });
431 +
    h.expect("interface omits private statics", declarations, harness::Expect::Matching {
432 +
        text: "static counter", count: 0
433 +
    });
434 +
    h.expect(
435 +
        "interface retains private opaque field types",
436 +
        declarations,
437 +
        harness::Expect::Contains("record Inner")
438 +
    );
439 +
    h.expect(
440 +
        "interface retains private constant operands",
441 +
        declarations,
442 +
        harness::Expect::Contains("constant BASE")
443 +
    );
349 444
    unsafe {
350 445
        try verified(h, exported);
351 446
    }
352 447
    h.add(
353 448
        &[
386 481
    h.expect(
387 482
        "equivalent provider retains client",
388 483
        h.path(&["equivalent.log"]),
389 484
        harness::Expect::Contains("cache hit app")
390 485
    );
486 +
    try fs::writeFileParts(dep, &[
487 +
        provider, "\nconstant PRIVATE: u32 = 1;\nrecord Private: Copy { value: u32 }\n"
488 +
    ]);
489 +
    source(h, h.path(&["private.rv64"]), "-o");
490 +
    h.compile("rebuild a provider with private additions", h.out(&["private.log"]));
491 +
    h.expect(
492 +
        "unused private additions retain client",
493 +
        h.path(&["private.log"]),
494 +
        harness::Expect::Contains("cache hit app")
495 +
    );
391 496
    try fs::writeFileParts(dep, &[provider, "\nexport record Added: Copy { value: u32 }\n"]);
392 497
    let changed = h.path(&["changed"]);
393 498
    source(h, changed, "-ril");
394 499
    h.compile("rebuild a changed compiler interface", h.out(&["interface.log"]));
395 500
    h.expect(
397 502
        h.path(&["interface.log"]),
398 503
        harness::Expect::Matching {
399 504
            text: "cache hit app", count: 0
400 505
        }
401 506
    );
402 -
    h.expect(
403 -
        "interface-only edit keeps the same RIL",
404 -
        h.join(&[changed, "/dep.ril"]),
405 -
        harness::Expect::Same(h.join(&[exported, "/dep.ril"]))
406 -
    );
507 +
    let originalImage = try h.load(h.join(&[exported, "/dep.ril"]));
508 +
    let changedImage = try h.load(h.join(&[changed, "/dep.ril"]));
509 +
    assert not mem::eq(originalImage, changedImage);
407 510
    try fs::writeFile(
408 511
        app, "use dep; @default fn main() { let value = dep::hidden(); let bad = value.value; }\n"
409 512
    );
410 513
    source(h, h.path(&["opaque.rv64"]), "-o");
411 514
    let inaccessible = h.cc(h.take(), h.out(&["opaque.log"]));
423 526
        "reject a same-length mismatched explicit interface",
424 527
        rejected,
425 528
        process::Outcome::Exited(1),
426 529
        &[]
427 530
    );
531 +
    try metadataReuse(h);
428 532
    try reexports(h);
429 533
    try paths(h);
430 534
    try large(h);
431 535
    h.done(mark, "packages: source-free linking, cache reuse, and integrity checks passed");
432 536
}
test/loader/hostile.rad +1 -1
165 165
        name: "hostile",
166 166
        dependencies,
167 167
        exports: &[
168 168
            binary::Export {
169 169
                name: ENTRY,
170 -
                kind: binary::ExportKind::Function,
170 +
                kind: binary::ExportKind::Function(0),
171 171
                startable: false,
172 172
            },
173 173
        ],
174 174
        entry: ENTRY,
175 175
        program: il::Program {
test/packages/cache/dep.rad +10 -0
5 5
export constant EMPTY: [fn() -> u32; 0] = [emptyCallback; 0];
6 6
export constant CALLBACKS: [fn() -> u32; 1] = [callback];
7 7
8 8
unsafe static counter: u32 = 0;
9 9
10 +
record Unused: Copy { value: u32 }
11 +
12 +
record Inner: Copy { value: u32 }
13 +
14 +
export opaque record Sealed { inner: Inner }
15 +
10 16
export record Item: Copy { value: u32 }
11 17
12 18
export opaque record Hidden { value: Item }
13 19
14 20
export trait Read {
25 31
    fn (item: &Item) get() -> u32 {
26 32
        return item.value;
27 33
    }
28 34
}
29 35
36 +
export fn seal() -> Sealed {
37 +
    return Sealed { inner: Inner { value: 5 } };
38 +
}
39 +
30 40
fn helper() -> u32 {
31 41
    return 41;
32 42
}
33 43
34 44
export fn make() -> Item {
test/shared/build.rad +1 -1
187 187
        if let case verify::Place::Data(i) = err.place {
188 188
            io::printLn(appInput.program.data[i].name);
189 189
        }
190 190
        return 1;
191 191
    };
192 -
    assert appInput.links.pins[0] == identity;
192 +
    assert appInput.links.pins[0] == supportInput.links.metadata;
193 193
    let support = try! compile(&supportInput, 0, &[]);
194 194
    let mut far: [shared::Symbol; EXPORTS_CAPACITY] = undefined;
195 195
    for symbol, i in support.exports {
196 196
        set far[i] = symbol;
197 197
        match symbol.target {