lang: Fix heap validation and data metadata

91a41994a72ceba25efd3feb023a7956e41016b4bc34778fd47af46f7d973bdd
Reject safe statics that reach heap handles through pointer targets,
including recursive records and unions. Trap on null heap handles when
zero-sized slices need more capacity.

Use physical data definitions for heap headers and pools so their sizes
and alignments do not carry unrelated IL layout indices. Cache the heap
allocation throw list, report invalid pageHeap output types correctly,
and simplify allocation argument validation. Document the pool suffix.

Add resolver and lowering regressions and cover zero-sized null-handle
traps in generated RV64 execution. The full make test suite passes.

Assisted-by: Codex:gpt-6
Alexis Sellier committed ago 1 parent f0b7d201
lib/std/arch/rv64.rad +4 -7
466 466
    storage: Storage,
467 467
    roDataPrefix: *[u8],
468 468
    roDataBuf: &mut [u8],
469 469
    rwDataBuf: &mut [u8]
470 470
) -> Program throws (Error) {
471 -
    let expanded = try data::expandHeaps(globalData, generator.e.arena) catch error {
471 +
    let items = try data::prepare(globalData, generator.e.arena) catch error {
472 472
        throw Error::Data(error);
473 473
    };
474 -
    if let items = expanded {
475 -
        return try finishData(generator, items, storage, roDataPrefix, roDataBuf, rwDataBuf);
476 -
    }
477 -
    return try finishData(generator, globalData, storage, roDataPrefix, roDataBuf, rwDataBuf);
474 +
    return try finishData(generator, items, storage, roDataPrefix, roDataBuf, rwDataBuf);
478 475
}
479 476
480 -
/// Lay out `globalData`, whose heaps are expanded, and finish the program.
477 +
/// Lay out physical data definitions and finish the program.
481 478
fn finishData(
482 479
    generator: &mut Generator,
483 -
    globalData: &[il::Data],
480 +
    globalData: &[data::Data],
484 481
    storage: Storage,
485 482
    roDataPrefix: *[u8],
486 483
    roDataBuf: &mut [u8],
487 484
    rwDataBuf: &mut [u8]
488 485
) -> Program throws (Error) {
lib/std/arch/rv64/image/tests.rad +7 -9
216 216
    try testing::expect(result.code[3] == encode::addi(rv64::A1, rv64::A1, 0));
217 217
}
218 218
219 219
/// Check bounded data-layout failure without wrapped addresses or symbol writes.
220 220
@test unsafe fn dataLayout() throws (testing::TestError) {
221 -
    let item = il::Data {
221 +
    let item = data::Data {
222 222
        name: "p::data",
223 223
        size: 16,
224 224
        alignment: 8,
225 -
        layout: 0,
226 225
        readOnly: false,
227 -
        heap: nil,
228 226
        isZeroInit: true,
229 227
        values: &[],
230 228
    };
231 229
    unsafe static syms: [data::DataSym; 1] = undefined;
232 230
    let mut count: u32 = 0;
407 405
        readOnly: true,
408 406
        heap: nil,
409 407
        isZeroInit: false,
410 408
        values: &[],
411 409
    };
412 -
    try testing::expect(try! data::expandHeaps(&[plain], arena) == nil);
410 +
    let unchanged = try! data::prepare(&[plain], arena);
411 +
    assert unchanged.len == 1;
412 +
    assert unchanged[0].name == plain.name and unchanged[0].size == plain.size;
413 413
414 414
    let region = il::Data {
415 415
        name: "p::pool",
416 416
        size: 4096,
417 417
        alignment: 1,
419 419
        readOnly: false,
420 420
        heap: il::HeapType::Typed,
421 421
        isZeroInit: true,
422 422
        values: &[],
423 423
    };
424 -
    let expanded = try! data::expandHeaps(&[plain, region], arena) else {
425 -
        throw testing::TestError::Failed;
426 -
    };
424 +
    let expanded = try! data::prepare(&[plain, region], arena);
427 425
    try testing::expect(expanded.len == 3);
428 426
    try testing::expect(expanded[0].name == "p::plain");
429 427
    let header = expanded[1];
430 428
    try testing::expect(header.name == "p::pool" and header.size == heap::HEADER_SIZE);
431 -
    try testing::expect(header.heap == nil and not header.isZeroInit and not header.readOnly);
429 +
    try testing::expect(header.alignment == 8 and not header.isZeroInit and not header.readOnly);
432 430
    try testing::expect(header.values.len == 4);
433 431
    try testing::expect(
434 432
        header.values[0] == il::DataValue {
435 433
            item: il::DataItem::Val { typ: il::Type::W64, val: 0 }, count: 1
436 434
        }
440 438
            item: il::DataItem::Val { typ: il::Type::W64, val: 4096 }, count: 1
441 439
        }
442 440
    );
443 441
    let pool = expanded[2];
444 442
    try testing::expect(pool.size == 4096 and pool.alignment == heap::POOL_ALIGNMENT);
445 -
    try testing::expect(pool.isZeroInit and pool.values.len == 0 and pool.heap == nil);
443 +
    try testing::expect(pool.isZeroInit and pool.values.len == 0);
446 444
    let case il::DataItem::Sym(target) = header.values[2].item else {
447 445
        throw testing::TestError::Failed;
448 446
    };
449 447
    try testing::expect(target == pool.name and pool.name <> header.name);
450 448
    // The fourth word is zero.
lib/std/arch/rv64/isel.rad +6 -5
1155 1155
    try emit::emitLoad(e, a, rs, SLICE_CAP_OFFSET, il::Type::W32);
1156 1156
    let enough = try emitBranchHole(e, encode::bgeu(a, t1, 0));
1157 1157
    try emit::loadImm(e, t3, limit as i64);
1158 1158
    try emitTrapUnlessLeu(e, t1, t3);
1159 1159
1160 +
    let h = try resolveVal(s, e, t2, heap);
1161 +
    // A null handle traps.
1162 +
    try emitTrapUnlessLtu(e, super::ZERO, h);
1160 1163
    let mut exhausted: ?u32 = nil;
1161 1164
    if size == 0 {
1162 1165
        // No bytes are needed. The pointer of the slice is its alignment.
1163 1166
        try emit::loadImm(e, t3, alignment as i64);
1164 -
        try emit::emitSd(e, t3, rs, SLICE_PTR_OFFSET);
1165 -
        try emit::emitSw(e, t1, rs, SLICE_CAP_OFFSET);
1167 +
        let slot = try getSrcReg(s, e, slice, t2);
1168 +
        try emit::emitSd(e, t3, slot, SLICE_PTR_OFFSET);
1169 +
        try emit::emitSw(e, t1, slot, SLICE_CAP_OFFSET);
1166 1170
    } else {
1167 -
        let h = try resolveVal(s, e, t2, heap);
1168 -
        // A null handle traps.
1169 -
        try emitTrapUnlessLtu(e, super::ZERO, h);
1170 1171
        let retry = e.code.len;
1171 1172
        try loadU32(s, e, t1, t1, capacity);
1172 1173
        try emitScale(e, t1, t1, size, a);
1173 1174
        // Several harts can allocate from one heap, so the carve is a load-reserved and
1174 1175
        // store-conditional pair that retries when another hart took memory first.
lib/std/arch/rv64/shared.rad +2 -6
255 255
    relocations: u32,
256 256
}
257 257
258 258
/// Build initialized bytes and compact private pointer fixups.
259 259
fn template(
260 -
    items: *[il::Data],
260 +
    items: *[data::Data],
261 261
    local: &[Symbol],
262 262
    imports: &[Symbol],
263 263
    bytes: &mut [u8],
264 264
    relocs: &mut [Relocation]
265 265
) -> TemplateSize throws (Error) {
451 451
        let func = generator.e.funcs[i];
452 452
        try define(&mut symbolStorage[..], &mut symbols, func.name, Target::Function(
453 453
            codeAddress + func.index as u64 * 4
454 454
        ));
455 455
    }
456 -
    let mut items: *[il::Data] = input.program.data;
457 -
    let expanded = try data::expandHeaps(input.program.data, generator.e.arena) catch {
456 +
    let items = try data::prepare(input.program.data, generator.e.arena) catch {
458 457
        throw Error::Range;
459 458
    };
460 -
    if let heaps = expanded {
461 -
        set items = heaps;
462 -
    }
463 459
    let mut dataCount: u32 = 0;
464 460
    let roSize = try data::layoutSection(
465 461
        items, &mut dataStorage[..], &mut dataCount, 0, true
466 462
    ) catch {
467 463
        throw Error::Range;
lib/std/arch/rv64/shared/tests/run.rad +4 -2
883 883
    try testing::expect(returned(exact.outcome, 1) and exact.used == 32);
884 884
    let over = try sliceGrow(0, 0, 0, 4, 0, 31, HEAP);
885 885
    try testing::expect(returned(over.outcome, 0) and over.used == 0);
886 886
}
887 887
888 -
/// Elements without bytes take nothing from the heap, which can be null.
888 +
/// Elements without bytes take nothing from a valid heap.
889 889
@test unsafe fn sliceGrowZeroSized() throws (testing::TestError) {
890 -
    let grown = try sliceGrow(3, 2, 2, 5, 7, 0, 0);
890 +
    let grown = try sliceGrow(3, 2, 2, 5, 7, 0, HEAP);
891 891
    try testing::expect(returned(grown.outcome, 1));
892 892
    try testing::expect(grown.ptr == 8 and grown.len == 2 and grown.cap == 5 and grown.used == 7);
893 893
    let enough = try sliceGrow(3, 2, 5, 4, 7, 0, 0);
894 894
    try testing::expect(returned(enough.outcome, 1) and enough.cap == 5);
895 895
}
898 898
@test unsafe fn sliceGrowTraps() throws (testing::TestError) {
899 899
    let over = try sliceGrow(0, 0, 0, 0x20000000, 0, 256, HEAP);
900 900
    try testing::expect(trapped(over.outcome));
901 901
    let limit = try sliceGrow(0, 0, 0, 0x1fffffff, 0, 256, HEAP);
902 902
    try testing::expect(returned(limit.outcome, 0));
903 +
    let zeroNull = try sliceGrow(3, 2, 2, 5, 7, 0, 0);
904 +
    try testing::expect(trapped(zeroNull.outcome));
903 905
    let null = try sliceGrow(0, 0, 0, 4, 0, 256, 0);
904 906
    try testing::expect(trapped(null.outcome));
905 907
    // Only the 32 low bits of the capacity count.
906 908
    let wrapped = try sliceGrow(0, 0, 0, 0x100000002, 0, 256, HEAP);
907 909
    try testing::expect(returned(wrapped.outcome, 1) and wrapped.cap == 2);
lib/std/arch/rv64/tests.rad +2 -6
1708 1708
    let tables = try! testLabels(arena);
1709 1709
    let table = try! testDict(arena);
1710 1710
    let e = try! rv64::emit::emitter(arena, false, tables);
1711 1711
    let map = try! data::buildMap(&[], table);
1712 1712
    let items = [
1713 -
        il::Data {
1713 +
        data::Data {
1714 1714
            name: "symbol",
1715 1715
            size: 8,
1716 1716
            alignment: 8,
1717 -
            layout: 0,
1718 1717
            readOnly: true,
1719 -
            heap: nil,
1720 1718
            isZeroInit: false,
1721 1719
            values: &[il::DataValue { item: il::DataItem::Sym("missing"), count: 1 }],
1722 1720
        },
1723 1721
    ];
1724 1722
    let mut bytes = [0xaa as u8; 8];
1733 1731
1734 1732
/// Initialized and zero-filled data start at the requested alignment.
1735 1733
@test unsafe fn testDataAlignment() throws (testing::TestError) {
1736 1734
    for zeroInit in [false, true] {
1737 1735
        let items = [
1738 -
            il::Data {
1736 +
            data::Data {
1739 1737
                name: "aligned",
1740 1738
                size: 8,
1741 1739
                alignment: 8,
1742 -
                layout: 0,
1743 1740
                readOnly: true,
1744 -
                heap: nil,
1745 1741
                isZeroInit: zeroInit,
1746 1742
                values: &[],
1747 1743
            },
1748 1744
        ];
1749 1745
        let mut symbols: [data::DataSym; 1] = undefined;
lib/std/arch/rv64/tests/bounds.rad +2 -6
84 84
            name: "p::other", addr: 0x80002008
85 85
        },
86 86
    ];
87 87
    let map = try! data::buildMap(syms, try! table(arena, 4));
88 88
    let items = &[
89 -
        il::Data {
89 +
        data::Data {
90 90
            name: "p::data",
91 91
            size: 8,
92 92
            alignment: 8,
93 -
            layout: 0,
94 93
            readOnly: false,
95 -
            heap: nil,
96 94
            isZeroInit: false,
97 95
            values: &[
98 96
                il::DataValue {
99 97
                    item: il::DataItem::Val { typ: il::Type::W64, val: 1 }, count: 1
100 98
                },
124 122
    ) catch err {
125 123
        try testing::expect(err == data::Error::Symbol);
126 124
        set failed += 1;
127 125
    };
128 126
    let repeated = &[
129 -
        il::Data {
127 +
        data::Data {
130 128
            name: "p::data",
131 129
            size: 8,
132 130
            alignment: 8,
133 -
            layout: 0,
134 131
            readOnly: false,
135 -
            heap: nil,
136 132
            isZeroInit: false,
137 133
            values: &[
138 134
                il::DataValue {
139 135
                    item: il::DataItem::Val { typ: il::Type::W64, val: 1 }, count: 2
140 136
                },
lib/std/lang/gen/data.rad +37 -18
44 44
    dict: dict::Dict,
45 45
    /// Fallback linear array for edge cases.
46 46
    syms: *[DataSym],
47 47
}
48 48
49 +
/// Physical data definition for binary section layout and emission.
50 +
export record Data: Copy {
51 +
    /// Symbol name.
52 +
    name: *[u8],
53 +
    /// Size in bytes.
54 +
    size: u32,
55 +
    /// Alignment in bytes.
56 +
    alignment: u32,
57 +
    /// Whether the section is read-only.
58 +
    readOnly: bool,
59 +
    /// Whether the data needs only zero-filled memory.
60 +
    isZeroInit: bool,
61 +
    /// Initializer values.
62 +
    values: *[il::DataValue],
63 +
}
64 +
49 65
/// Offset in the header of a heap of the bytes that it has handed out.
50 66
export constant HEAP_USED_OFFSET: i32 = 0;
51 67
/// Offset in the header of a heap of the size of its pool in bytes.
52 68
export constant HEAP_SIZE_OFFSET: i32 = 8;
53 69
/// Offset in the header of a heap of the address of its pool.
54 70
export constant HEAP_BASE_OFFSET: i32 = 16;
71 +
/// Suffix that identifies the backing pool of a heap symbol.
55 72
constant HEAP_POOL_SUFFIX: *[u8] = ".heap";
56 73
57 74
/// A data value of one 64-bit word.
58 75
fn word(val: i64) -> il::DataValue {
59 76
    return il::DataValue { item: il::DataItem::Val { typ: il::Type::W64, val }, count: 1 };
60 77
}
61 78
62 -
/// Replace each heap region by the two data items that implement it, and return the items.
79 +
/// Prepare physical data definitions, with each heap as a header and a backing pool.
63 80
/// The symbol of the heap names its header, which holds zero used bytes, the size of the
64 81
/// pool, the address of the pool, and a zero word. The pool is zero-filled data aligned for any element.
65 -
/// Returns nil for a program without a heap, which needs no change.
66 -
export fn expandHeaps(items: &[il::Data], a: &heap::Heap) -> ?*[il::Data] throws (Error) {
82 +
export fn prepare(items: &[il::Data], a: &heap::Heap) -> *[Data] throws (Error) {
67 83
    let mut heaps: u32 = 0;
68 84
    for item in items {
69 85
        if item.heap <> nil {
70 86
            set heaps += 1;
71 87
        }
72 88
    }
73 -
    if heaps == 0 {
74 -
        return nil;
75 -
    }
76 -
    let mut out: *mut [il::Data] = &mut [];
89 +
    let mut out: *mut [Data] = &mut [];
77 90
    try out.reserve(items.len + heaps, a) catch {
78 91
        throw Error::Capacity;
79 92
    };
80 93
    // The reserved capacity holds every item, so the appends below cannot fail.
81 94
    for item in items {
82 95
        if item.heap == nil {
83 -
            try! out.append(item, a);
96 +
            try! out.append(
97 +
                Data {
98 +
                    name: item.name,
99 +
                    size: item.size,
100 +
                    alignment: item.alignment,
101 +
                    readOnly: item.readOnly,
102 +
                    isZeroInit: item.isZeroInit,
103 +
                    values: item.values,
104 +
                },
105 +
                a
106 +
            );
84 107
            continue;
85 108
        }
86 109
        let pool = try alloc::concatBytes(a, &[item.name, HEAP_POOL_SUFFIX]) catch {
87 110
            throw Error::Capacity;
88 111
        };
98 121
            a
99 122
        ) catch {
100 123
            throw Error::Capacity;
101 124
        };
102 125
        try! out.append(
103 -
            il::Data {
126 +
            Data {
104 127
                name: item.name,
105 128
                size: heap::HEADER_SIZE,
106 129
                alignment: 8,
107 -
                layout: item.layout,
108 130
                readOnly: false,
109 -
                heap: nil,
110 131
                isZeroInit: false,
111 132
                values: &values[..],
112 133
            },
113 134
            a
114 135
        );
115 136
        try! out.append(
116 -
            il::Data {
137 +
            Data {
117 138
                name: poolName,
118 139
                size: item.size,
119 140
                alignment: heap::POOL_ALIGNMENT,
120 -
                layout: item.layout,
121 141
                readOnly: false,
122 -
                heap: nil,
123 142
                isZeroInit: true,
124 143
                values: &[],
125 144
            },
126 145
            a
127 146
        );
132 151
/// Lay out data symbols for a single section.
133 152
/// Data with sidecar image bytes is placed first, then zero-initialized data,
134 153
/// so that only meaningful bytes need to be written to the output file.
135 154
/// Returns the updated offset past all placed symbols.
136 155
export fn layoutSection(
137 -
    items: &[il::Data],
156 +
    items: &[Data],
138 157
    syms: &mut [DataSym],
139 158
    count: &mut u32,
140 159
    base: u64,
141 160
    readOnly: bool
142 161
) -> u32 throws (Error) {
143 162
    return try layoutSectionAtOffset(items, syms, count, base, 0, readOnly);
144 163
}
145 164
146 165
/// Lay out data symbols for a single section starting at [`startOffset`].
147 166
export fn layoutSectionAtOffset(
148 -
    items: &[il::Data],
167 +
    items: &[Data],
149 168
    syms: &mut [DataSym],
150 169
    count: &mut u32,
151 170
    base: u64,
152 171
    startOffset: u32,
153 172
    readOnly: bool
192 211
193 212
/// Emit data bytes for a single section (read-only or read-write) into `buf`.
194 213
/// Iterates data requiring sidecar image bytes, serializing each data item.
195 214
/// Returns the total number of bytes written.
196 215
export fn emitSection(
197 -
    items: &[il::Data],
216 +
    items: &[Data],
198 217
    dataSymMap: &DataSymMap,
199 218
    fnLabels: &labels::Labels,
200 219
    codeBase: u64,
201 220
    buf: &mut [u8],
202 221
    readOnly: bool
204 223
    return try emitSectionAtOffset(items, dataSymMap, fnLabels, codeBase, buf, readOnly, 0);
205 224
}
206 225
207 226
/// Emit data bytes for a single section starting at `startOffset`.
208 227
export fn emitSectionAtOffset(
209 -
    items: &[il::Data],
228 +
    items: &[Data],
210 229
    dataSymMap: &DataSymMap,
211 230
    fnLabels: &labels::Labels,
212 231
    codeBase: u64,
213 232
    buf: &mut [u8],
214 233
    readOnly: bool,
lib/std/lang/lower.rad +5 -4
10727 10727
fn lowerPageHeap(self: &mut Lowerer, call: ast::Call) -> il::Val throws (LowerError) {
10728 10728
    if call.args.len <> 2 {
10729 10729
        throw LowerError::InvalidArgCount;
10730 10730
    }
10731 10731
    // The slot holds a heap, so the argument points to a heap or an optional one.
10732 -
    let case resolver::Type::Pointer { target, .. } = try effectiveType(self, call.args[1])
10733 -
        else throw LowerError::InvalidArgCount;
10732 +
    let outType = try effectiveType(self, call.args[1]);
10733 +
    let case resolver::Type::Pointer { target, .. } = outType
10734 +
        else throw LowerError::UnexpectedType(outType);
10734 10735
    // The memory of a Page holds elements of any type, so it cannot be a scratch heap.
10735 10736
    let rights = heapRights(self, *target) else {
10736 -
        throw LowerError::InvalidArgCount;
10737 +
        throw LowerError::UnexpectedType(outType);
10737 10738
    };
10738 10739
    if rights == il::HeapType::Reset {
10739 -
        throw LowerError::InvalidArgCount;
10740 +
        throw LowerError::UnexpectedType(outType);
10740 10741
    }
10741 10742
    let handle = try lowerExpr(self, call.args[0]);
10742 10743
    let slot = try emitValToReg(self, try lowerExpr(self, call.args[1]));
10743 10744
    let err = nextReg(self);
10744 10745
lib/std/lang/lower/tests.rad +26 -0
2 2
3 3
use std::mem;
4 4
use std::testing;
5 5
use std::mem::heap;
6 6
use std::lang::ast;
7 +
use std::lang::alloc;
7 8
use std::lang::il;
8 9
use std::lang::module;
9 10
use std::lang::resolver;
10 11
use std::lang::resolver::tests;
11 12
186 187
        }
187 188
    }
188 189
    assert reads == 1;
189 190
    assert copies == 0;
190 191
}
192 +
193 +
/// A page heap output must point to a heap with typed or plain rights.
194 +
@test unsafe fn testPageHeapOutputType() throws (testing::TestError) {
195 +
    for out in ["u32", "&mut u32", "&mut ?*Scratch"] {
196 +
        let mut res = tests::testResolver();
197 +
        let source = try! alloc::concatBytes(
198 +
            res.arena,
199 +
            &[
200 +
                "@language record Scratch {} @intrinsic fn pageHeap(h: u64, out: ",
201 +
                out, ") -> i64; fn f(out: ", out, ") -> i64 { return pageHeap(0, out); }",
202 +
            ]
203 +
        );
204 +
        let result = try tests::resolveProgramStr(&mut res, source);
205 +
        try tests::expectNoErrors(&result);
206 +
        let arena = heap::over(&mut FN_STORAGE[..]);
207 +
        let mut failed = false;
208 +
        try super::lower(res, result.root, "test", arena) catch err {
209 +
            let case super::LowerError::UnexpectedType(_) = err else {
210 +
                throw testing::TestError::Failed;
211 +
            };
212 +
            set failed = true;
213 +
        };
214 +
        assert failed;
215 +
    }
216 +
}
lib/std/lang/resolver.rad +34 -12
1181 1181
    instances: *mut [InstanceEntry],
1182 1182
    /// Standalone method registry, indexed by `MethodId`. Storage comes from `arena`.
1183 1183
    methods: *mut [MethodEntry],
1184 1184
    /// The allocation error, declared with `@language`. Every declaration of it is this type.
1185 1185
    allocError: ?NominalId,
1186 +
    /// Cached throw list for heap allocation calls.
1187 +
    heapThrows: ?*[*Type],
1186 1188
    /// The heap types declared with `@language`, indexed by `HeapKind`. Every declaration of
1187 1189
    /// one of them is this type.
1188 1190
    heaps: [?NominalId; HEAP_KINDS],
1189 1191
    /// Whether values of each nominal type have slots, by `NominalId`. Nil until first needed.
1190 1192
    slotMemo: *mut [?bool],
1375 1377
        moduleTable: module::ModuleTable { entries: &[] },
1376 1378
        moduleScopes,
1377 1379
        instances,
1378 1380
        methods,
1379 1381
        allocError: nil,
1382 +
        heapThrows: nil,
1380 1383
        heaps: [nil; HEAP_KINDS],
1381 1384
        slotMemo: &mut [],
1382 1385
    };
1383 1386
}
1384 1387
4193 4196
    try ensureStorableType(self, decl.type, bindingTy);
4194 4197
    let isUnsafe = ast::hasAttribute(self.symbols[*sym].attrs, ast::Attribute::Unsafe);
4195 4198
    // An unsafe static is reached only by unsafe code, which is not verified and may keep any
4196 4199
    // handle that it made.
4197 4200
    if not isUnsafe {
4198 -
        if holdsHeapHandle(self, bindingTy) {
4201 +
        let mut seen: *mut [NominalId] = &mut [];
4202 +
        if try holdsHeapHandle(self, bindingTy, decl.type, &mut seen) {
4199 4203
            throw emitError(self, decl.type, ErrorKind::HeapStatic);
4200 4204
        }
4201 4205
        try ensureMutableDataType(self, decl.type, bindingTy);
4202 4206
    }
4203 4207
    let wasUnsafe = self.inUnsafeContext;
7335 7339
        case Type::Optional(inner)    => return holdsHeapValue(self, *inner),
7336 7340
        else                          => return isHeapNominal(self, ty),
7337 7341
    }
7338 7342
}
7339 7343
7340 -
/// Whether a value of `ty` holds a heap handle: a pointer to a heap, or an array, slice, optional
7341 -
/// or resolved record or union that holds one.
7342 -
fn holdsHeapHandle(self: &Resolver, ty: Type) -> bool {
7344 +
/// Whether `ty` reaches a heap handle through pointers or aggregate fields.
7345 +
/// `seen` holds visited nominal types to stop at recursive records and unions.
7346 +
fn holdsHeapHandle(
7347 +
    self: &mut Resolver, ty: Type, site: *ast::Node, seen: &mut *mut [NominalId]
7348 +
) -> bool throws (ResolveError) {
7343 7349
    match ty {
7344 -
        case Type::Pointer { target, .. } => return isHeapNominal(self, *target),
7345 -
        case Type::Array(array)           => return holdsHeapHandle(self, *array.item),
7346 -
        case Type::Slice { item, .. }     => return holdsHeapHandle(self, *item),
7347 -
        case Type::Optional(inner)        => return holdsHeapHandle(self, *inner),
7350 +
        case Type::Pointer { target, .. } => {
7351 +
            if isHeapNominal(self, *target) {
7352 +
                return true;
7353 +
            }
7354 +
            try ensureTypeResolved(self, *target, site);
7355 +
            return try holdsHeapHandle(self, *target, site, seen);
7356 +
        }
7357 +
        case Type::Array(array)       => return try holdsHeapHandle(self, *array.item, site, seen),
7358 +
        case Type::Slice { item, .. } => return try holdsHeapHandle(self, *item, site, seen),
7359 +
        case Type::Optional(inner)    => return try holdsHeapHandle(self, *inner, site, seen),
7348 7360
        case Type::Nominal(id) => {
7361 +
            for visited in &seen[..] {
7362 +
                if visited == id {
7363 +
                    return false;
7364 +
                }
7365 +
            }
7366 +
            try! seen.append(id, self.arena);
7349 7367
            match self.nominals[*id] {
7350 7368
                case NominalType::Record(recordType) => {
7351 7369
                    for field in recordType.fields {
7352 -
                        if holdsHeapHandle(self, field.fieldType) {
7370 +
                        if try holdsHeapHandle(self, field.fieldType, site, seen) {
7353 7371
                            return true;
7354 7372
                        }
7355 7373
                    }
7356 7374
                    return false;
7357 7375
                }
7358 7376
                case NominalType::Union(unionType) => {
7359 7377
                    for variant in unionType.variants {
7360 -
                        if holdsHeapHandle(self, variant.valueType) {
7378 +
                        if try holdsHeapHandle(self, variant.valueType, site, seen) {
7361 7379
                            return true;
7362 7380
                        }
7363 7381
                    }
7364 7382
                    return false;
7365 7383
                }
7441 7459
    return heapKindOfType(self, ty);
7442 7460
}
7443 7461
7444 7462
/// The errors that growth in a heap throws: `AllocError`, which the program must declare.
7445 7463
fn heapThrowList(self: &mut Resolver, site: *ast::Node) -> *[*Type] throws (ResolveError) {
7464 +
    if let list = self.heapThrows {
7465 +
        return list;
7466 +
    }
7446 7467
    let id = self.allocError else throw emitError(self, site, ErrorKind::MissingAllocError);
7447 7468
    let mut list: *mut [*Type] = &mut [];
7448 7469
    try! list.append(allocType(self, Type::Nominal(id)), self.arena);
7449 -
    return &list[..];
7470 +
    let errors: *[*Type] = &list[..];
7471 +
    set self.heapThrows = errors;
7472 +
    return errors;
7450 7473
}
7451 7474
7452 7475
/// Resolve a slice method whose arguments are `valueTypes` followed by an allocator.
7453 7476
///
7454 7477
/// Each value argument must be assignable to its type, in order. The allocator is a handle to
7538 7561
    }
7539 7562
    let throwList = try heapThrowList(self, access.parent);
7540 7563
    // Only a `Heap` provides elements that are not plain data.
7541 7564
    let valueTy = try infer(self, call.args[0]);
7542 7565
    try ensureTypeResolved(self, valueTy, call.args[0]);
7543 -
    try checkAssignable(self, call.args[0], valueTy);
7544 7566
    if kind <> HeapKind::Heap and not isPlainData(self, valueTy) {
7545 7567
        throw emitError(self, call.args[0], ErrorKind::AllocatorElementNotPlain);
7546 7568
    }
7547 7569
    let elemType = allocType(self, valueTy);
7548 7570
    let returnTy = Type::Pointer {
lib/std/lang/resolver/tests/core.rad +28 -0
534 534
    let mut a = testResolver();
535 535
    let bad = try resolveProgramStr(&mut a, "@language record Heap {} static P: Heap = 1;");
536 536
    try expectError(&bad);
537 537
}
538 538
539 +
/// Safe statics cannot reach heap handles through pointer targets.
540 +
@test unsafe fn testHeapStaticPointerTargets() throws (testing::TestError) {
541 +
    for body in [
542 +
        "record Box { h: *Heap } static P: ?*Box = nil;",
543 +
        "static P: ?**Box = nil; record Box { h: *Heap }",
544 +
        "record Box { h: *Allocator } static P: ?*Box = nil;",
545 +
        "record Box { h: *Scratch } static P: ?*Box = nil;",
546 +
        "record Box { next: ?*Box, h: *Heap } static P: ?*Box = nil;",
547 +
        "record A { b: ?*B } record B { a: ?*A, h: *Heap } static P: ?*A = nil;",
548 +
        "union Box { Empty, Handle(*Heap) } static P: ?*Box = nil;",
549 +
        "record Box { h: [*Heap; 1] } static P: ?*Box = nil;",
550 +
        "record Box { h: ?*Heap } fn f() { static P: ?*Box = nil; }",
551 +
    ] {
552 +
        let mut a = testResolver();
553 +
        let bad = try resolveScratch(&mut a, body);
554 +
        try expectErrorKind(&bad, resolver::ErrorKind::HeapStatic);
555 +
    }
556 +
    for body in [
557 +
        "record Box { h: *Heap } unsafe static P: ?*Box = nil;",
558 +
        "record Box { next: ?*Box, n: u32 } static P: ?*Box = nil;",
559 +
        "record A { b: ?*B } record B { a: ?*A } static P: ?*A = nil;",
560 +
    ] {
561 +
        let mut a = testResolver();
562 +
        let result = try resolveScratch(&mut a, body);
563 +
        try expectNoErrors(&result);
564 +
    }
565 +
}
566 +
539 567
/// Declarations for the tests of `Scratch`.
540 568
constant SCRATCH_DECLS: *[u8] =
541 569
    "@language union AllocError: Copy { OutOfMemory } @language record Heap {} @language record Allocator {} @language record Scratch {} @intrinsic constant fn new(size: u32) -> Scratch; ";
542 570
543 571
/// Resolve `body` after the declarations of the heap types.