lib/std/lang/il/verify/tests.rad 216.6 KiB raw
1
//! Tests for the RIL verifier.
2
//!
3
//! A test builds a small program with [`Builder`], and checks that the verifier accepts it
4
//! or rejects it with a given rule. Every program starts with the layouts and signatures
5
//! named by the constants below.
6
7
use std::lang::il;
8
use std::lang::il::binary;
9
use std::lang::il::binary::linkage;
10
use std::lang::il::verify;
11
use std::lang::il::verify::layout;
12
use std::lang::il::verify::linking;
13
use std::mem::heap;
14
use std::testing;
15
16
///////////////
17
// Constants //
18
///////////////
19
20
/// Plain layout of one byte.
21
constant P1: u32 = 0;
22
/// Plain layout of four bytes.
23
constant P4: u32 = 1;
24
/// Plain layout of eight bytes.
25
constant P8: u32 = 2;
26
/// Plain layout of sixteen bytes.
27
constant P16: u32 = 3;
28
/// Eight bytes: a pointer that owns a writable `P4` at offset 0.
29
constant CELL: u32 = 4;
30
/// Eight bytes: a pointer that owns a read-only `P4` at offset 0.
31
constant CELLC: u32 = 5;
32
/// Eight bytes: a pointer that borrows a writable `P4` at offset 0.
33
constant LOCAL: u32 = 6;
34
/// Sixteen bytes: a slice of owned writable bytes at offset 0.
35
constant SLICE: u32 = 7;
36
/// Sixteen bytes: a slice of owned read-only bytes at offset 0.
37
constant SLICEC: u32 = 8;
38
/// Eight bytes: a function value of signature 0 at offset 0.
39
constant FNCELL: u32 = 9;
40
/// Thirty-two bytes: a `CELL` at offset 8 and a `SLICE` at offset 16.
41
constant PAIR: u32 = 10;
42
/// Twenty-four bytes: an array of three `CELL` at offset 0.
43
constant CELLS: u32 = 11;
44
/// Sixteen bytes: a slice of borrowed writable bytes at offset 0.
45
constant BORROW: u32 = 12;
46
/// Eight bytes: a function value of signature 1 at offset 0.
47
constant FNCELL1: u32 = 13;
48
/// Plain layout of three bytes.
49
constant P3: u32 = 14;
50
/// Plain layout of eight bytes with the alignment of a byte.
51
constant B8: u32 = 15;
52
/// Sixteen bytes: a slice of owned writable `P4` at offset 0.
53
constant SLICE4: u32 = 16;
54
/// Sixteen bytes: a slice of owned read-only `P4` at offset 0.
55
constant SLICE4C: u32 = 17;
56
/// Sixteen bytes: a slice of owned writable `CELL` at offset 0.
57
constant SLICECELL: u32 = 18;
58
/// Plain layout without bytes.
59
constant P0: u32 = 19;
60
/// Sixteen bytes: a slice of owned writable `P0` at offset 0.
61
constant SLICE0: u32 = 20;
62
/// Eight bytes: a plain heap handle at offset 0.
63
constant HEAPCELL: u32 = 21;
64
/// Eight bytes: a typed heap handle at offset 0.
65
constant HEAPCELLT: u32 = 22;
66
/// Sixteen bytes: a slice of borrowed writable `LOCAL` at offset 0.
67
constant SLICELOCAL: u32 = 23;
68
/// Eight bytes: an owned writable pointer to a `SLICE` at offset 0.
69
constant PTRSLICE: u32 = 24;
70
/// Eight bytes: an owned writable pointer to a `PTRSLICE` at offset 0.
71
constant PTRPTRSLICE: u32 = 25;
72
/// Eight bytes: a heap handle with the reset right at offset 0.
73
constant HEAPCELLR: u32 = 26;
74
75
/// Signature of a function from data to data.
76
constant SIG_DATA: u32 = 0;
77
/// Signature of a function without parameters or result.
78
constant SIG_VOID: u32 = 1;
79
80
/// Limits of the tests.
81
constant CONFIG: verify::Config = verify::Config {
82
    registers: 64, blocks: 16, layoutSize: 4096, layoutDepth: 4, params: 8, envSize: 32
83
};
84
85
/// Storage for the program under test.
86
static BUILD: [u8; 65536] = [0; 65536];
87
/// Working storage of the verifier.
88
static SCRATCH: [u8; 65536] = [0; 65536];
89
/// Storage for derived export classifications.
90
static KEEP: [u8; 4096] = [0; 4096];
91
92
///////////////////
93
// Program Build //
94
///////////////////
95
96
/// A program under construction. All its slices live in `arena`.
97
record Builder {
98
    /// Storage of the program.
99
    arena: *heap::Heap,
100
    /// Layout table.
101
    layouts: *mut [il::Layout],
102
    /// Signature table.
103
    signatures: *mut [il::Signature],
104
    /// Trait table.
105
    traits: *mut [il::Trait],
106
    /// Data definitions.
107
    data: *mut [il::Data],
108
    /// Functions.
109
    fns: *mut [*il::Fn],
110
    /// Argument pool shared by the functions.
111
    vals: *mut [il::Val],
112
    /// Switch case pool shared by the functions.
113
    cases: *mut [il::SwitchCase],
114
}
115
116
/// Plain data of eight bytes.
117
fn dataType() -> il::ValType {
118
    return il::ValType::Data(il::Type::W64);
119
}
120
121
/// Type of a pointer to a layout.
122
fn ptrType(layout: u32, own: bool, mutable: bool, nullable: bool) -> il::ValType {
123
    return il::ValType::Ptr(il::PtrType { layout, own, mutable, nullable });
124
}
125
126
/// A parameter in register `n`.
127
fn param(n: u32, type: il::ValType) -> il::Param {
128
    return il::Param { value: il::Reg { n }, type };
129
}
130
131
/// Register `n` as a value.
132
fn reg(n: u32) -> il::Val {
133
    return il::Val::Reg(il::Reg { n });
134
}
135
136
/// An immediate value.
137
fn imm(n: i64) -> il::Val {
138
    return il::Val::Imm(n);
139
}
140
141
/// A pointer slot at `offset`.
142
fn ptrSlot(offset: u32, layout: u32, own: bool, mutable: bool) -> il::Slot {
143
    return il::Slot {
144
        offset,
145
        kind: il::SlotKind::Ptr(il::PtrType {
146
            layout, own, mutable, nullable: true
147
        }),
148
        regions: &[],
149
    };
150
}
151
152
/// A slice slot at `offset`.
153
fn sliceSlot(offset: u32, layout: u32, own: bool, mutable: bool) -> il::Slot {
154
    return il::Slot {
155
        offset,
156
        kind: il::SlotKind::Slice(il::PtrType {
157
            layout, own, mutable, nullable: true
158
        }),
159
        regions: &[],
160
    };
161
}
162
163
/// A nested object at `offset`.
164
fn subSlot(offset: u32, layout: u32) -> il::Slot {
165
    return il::Slot { offset, kind: il::SlotKind::Sub(layout), regions: &[] };
166
}
167
168
/// Add a layout, and return its index.
169
fn addLayout(b: &mut Builder, size: u32, alignment: u32, slots: &[il::Slot]) -> u32 {
170
    let index = b.layouts.len;
171
    let mut copy: *mut [il::Slot] = &mut [];
172
    let mut regions: u32 = 0;
173
    for slot in slots {
174
        let mut item = slot;
175
        if item.regions.len == 0 {
176
            set item.regions = nextRegions(b, &mut regions, positions(b, slot.kind));
177
        }
178
        if let case il::SlotKind::Union { offset, size, variants } = slot.kind {
179
            let mut labeled: *mut [il::UnionVariant] = &mut [];
180
            for variant in variants {
181
                let mut v = variant;
182
                if let l = variant.layout; v.regions.len == 0 {
183
                    set v.regions = nextRegions(b, &mut regions, pointeeRegions(b, l));
184
                }
185
                try! labeled.append(v, b.arena);
186
            }
187
            set item.kind = il::SlotKind::Union { offset, size, variants: &labeled[..] };
188
        }
189
        try! copy.append(item, b.arena);
190
    }
191
    try! b.layouts.append(il::Layout { size, alignment, slots: &copy[..], regions }, b.arena);
192
    return index;
193
}
194
195
/// Number of region positions of a slot. A layout that is not added yet has none.
196
fn positions(b: &Builder, kind: il::SlotKind) -> u32 {
197
    match kind {
198
        case il::SlotKind::Ptr(p) => return (0 if p.own else 1) + pointeeRegions(b, p.layout),
199
        case il::SlotKind::Slice(p) => return (0 if p.own else 1) + pointeeRegions(b, p.layout),
200
        case il::SlotKind::Trait(object) => return 0 if object.own else 1,
201
        case il::SlotKind::Sub(child) => return pointeeRegions(b, child),
202
        case il::SlotKind::Array { layout, .. } => return pointeeRegions(b, layout),
203
        else => return 0,
204
    }
205
}
206
207
/// Number of regions of a layout, or zero if it is not added yet.
208
fn pointeeRegions(b: &Builder, l: u32) -> u32 {
209
    return b.layouts[l].regions if l < b.layouts.len else 0;
210
}
211
212
/// Give `count` positions the regions that follow `next`, each its own.
213
fn nextRegions(b: &Builder, next: &mut u32, count: u32) -> *[u32] {
214
    let mut out: *mut [u32] = &mut [];
215
    for _ in 0 .. count {
216
        try! out.append(*next, b.arena);
217
        set *next += 1;
218
    }
219
    return &out[..];
220
}
221
222
/// Add a signature, and return its index.
223
fn addSignature(b: &mut Builder, params: &[il::ValType], ret: il::ValType) -> u32 {
224
    let index = b.signatures.len;
225
    let mut copy: *mut [il::ValType] = &mut [];
226
    try! copy.extend(params, b.arena);
227
    try! b.signatures.append(
228
        il::Signature { params: &copy[..], ret, borrows: &[] }, b.arena
229
    );
230
    return index;
231
}
232
233
/// Add the argument values of a branch or call, and return their range.
234
fn args(b: &mut Builder, values: &[il::Val]) -> il::ArgRange {
235
    let start = b.vals.len;
236
    try! b.vals.extend(values, b.arena);
237
    return il::ArgRange { start, len: values.len };
238
}
239
240
/// Add a switch case, and return the range that holds it.
241
fn addCase(b: &mut Builder, value: i64, target: u32, values: il::ArgRange) -> il::CaseRange {
242
    let start = b.cases.len;
243
    try! b.cases.append(il::SwitchCase { value, target, args: values }, b.arena);
244
    return il::CaseRange { start, len: 1 };
245
}
246
247
/// Create a builder whose tables start with the layouts and signatures named above.
248
unsafe fn newBuilder() -> Builder {
249
    let mut b = Builder {
250
        arena: heap::over(&mut BUILD[..]),
251
        layouts: &mut [],
252
        signatures: &mut [],
253
        traits: &mut [],
254
        data: &mut [],
255
        fns: &mut [],
256
        vals: &mut [],
257
        cases: &mut [],
258
    };
259
    addLayout(&mut b, 1, 1, &[]);
260
    addLayout(&mut b, 4, 4, &[]);
261
    addLayout(&mut b, 8, 8, &[]);
262
    addLayout(&mut b, 16, 8, &[]);
263
    addLayout(&mut b, 8, 8, &[ptrSlot(0, P4, true, true)]);
264
    addLayout(&mut b, 8, 8, &[ptrSlot(0, P4, true, false)]);
265
    addLayout(&mut b, 8, 8, &[ptrSlot(0, P4, false, true)]);
266
    addLayout(&mut b, 16, 8, &[sliceSlot(0, P1, true, true)]);
267
    addLayout(&mut b, 16, 8, &[sliceSlot(0, P1, true, false)]);
268
    addLayout(&mut b, 8, 8, &[
269
        il::Slot { offset: 0, kind: il::SlotKind::Fn(SIG_DATA), regions: &[] }
270
    ]);
271
    addLayout(&mut b, 32, 8, &[subSlot(8, CELL), subSlot(16, SLICE)]);
272
    addLayout(&mut b, 24, 8, &[
273
        il::Slot {
274
            offset: 0,
275
            kind: il::SlotKind::Array {
276
                layout: CELL, count: 3
277
            },
278
            regions: &[],
279
        },
280
    ]);
281
    addLayout(&mut b, 16, 8, &[sliceSlot(0, P1, false, true)]);
282
    addLayout(&mut b, 8, 8, &[
283
        il::Slot { offset: 0, kind: il::SlotKind::Fn(SIG_VOID), regions: &[] }
284
    ]);
285
    addLayout(&mut b, 3, 1, &[]);
286
    addLayout(&mut b, 8, 1, &[]);
287
    addLayout(&mut b, 16, 8, &[sliceSlot(0, P4, true, true)]);
288
    addLayout(&mut b, 16, 8, &[sliceSlot(0, P4, true, false)]);
289
    addLayout(&mut b, 16, 8, &[sliceSlot(0, CELL, true, true)]);
290
    addLayout(&mut b, 0, 1, &[]);
291
    addLayout(&mut b, 16, 8, &[sliceSlot(0, P0, true, true)]);
292
    addLayout(&mut b, 8, 8, &[
293
        il::Slot {
294
            offset: 0, kind: il::SlotKind::Heap(il::HeapType::Plain), regions: &[]
295
        },
296
    ]);
297
    addLayout(&mut b, 8, 8, &[
298
        il::Slot {
299
            offset: 0, kind: il::SlotKind::Heap(il::HeapType::Typed), regions: &[]
300
        },
301
    ]);
302
    addLayout(&mut b, 16, 8, &[sliceSlot(0, LOCAL, false, true)]);
303
    addLayout(&mut b, 8, 8, &[ptrSlot(0, SLICE, true, true)]);
304
    addLayout(&mut b, 8, 8, &[ptrSlot(0, PTRSLICE, true, true)]);
305
    addLayout(&mut b, 8, 8, &[
306
        il::Slot {
307
            offset: 0, kind: il::SlotKind::Heap(il::HeapType::Reset), regions: &[]
308
        },
309
    ]);
310
    addSignature(&mut b, &[dataType()], dataType());
311
    addSignature(&mut b, &[], il::ValType::Void);
312
    return b;
313
}
314
315
/// A block with the given parameters and instructions.
316
fn block(b: &mut Builder, params: &[il::Param], instrs: &[il::Instr]) -> il::Block {
317
    let mut ownParams: *mut [il::Param] = &mut [];
318
    try! ownParams.extend(params, b.arena);
319
    let mut ownInstrs: *mut [il::Instr] = &mut [];
320
    try! ownInstrs.extend(instrs, b.arena);
321
    return il::Block {
322
        label: il::BlockLabel { base: "b", suffix: nil },
323
        params: &ownParams[..],
324
        instrs: &ownInstrs[..],
325
        locs: &[],
326
        preds: &[],
327
        loopDepth: 0,
328
    };
329
}
330
331
/// Add a function of several blocks, and return its index.
332
fn addBlocks(
333
    b: &mut Builder, name: *[u8], params: &[il::Param], ret: il::ValType, blocks: &[il::Block]
334
) -> u32 {
335
    return addBorrowing(b, name, params, ret, blocks, nil);
336
}
337
338
/// Add a function whose result borrows storage of parameter `borrow`.
339
fn addBorrowing(
340
    b: &mut Builder,
341
    name: *[u8],
342
    params: &[il::Param],
343
    ret: il::ValType,
344
    blocks: &[il::Block],
345
    borrow: ?u32
346
) -> u32 {
347
    return addBorrowingContract(b, name, params, ret, blocks, borrow, false);
348
}
349
350
/// Add a function of several blocks whose result borrows from parameter `borrow`, and
351
/// return its index.
352
fn addBorrowingContract(
353
    b: &mut Builder,
354
    name: *[u8],
355
    params: &[il::Param],
356
    ret: il::ValType,
357
    blocks: &[il::Block],
358
    borrow: ?u32,
359
    borrowsFirstLeaf: bool
360
) -> u32 {
361
    let mut borrows: *mut [il::Borrow] = &mut [];
362
    if let param = borrow {
363
        let mut source: ?u32 = nil;
364
        if borrowsFirstLeaf {
365
            set source = 0;
366
        }
367
        try! borrows.append(il::Borrow { target: nil, result: 0, param, source }, b.arena);
368
    }
369
    return addSources(b, name, params, ret, blocks, &borrows[..]);
370
}
371
372
/// Add a function with a separate contract for each borrowed result leaf.
373
fn addSources(
374
    b: &mut Builder,
375
    name: *[u8],
376
    params: &[il::Param],
377
    ret: il::ValType,
378
    blocks: &[il::Block],
379
    borrows: &[il::Borrow]
380
) -> u32 {
381
    let mut sources: *mut [il::Borrow] = &mut [];
382
    try! sources.extend(borrows, b.arena);
383
    let index = b.fns.len;
384
    let mut copyParams: *mut [il::Param] = &mut [];
385
    try! copyParams.extend(params, b.arena);
386
    let mut copyBlocks: *mut [il::Block] = &mut [];
387
    try! copyBlocks.extend(blocks, b.arena);
388
    let mut pool: *mut [il::Val] = &mut [];
389
    try! pool.extend(&b.vals[..], b.arena);
390
    let mut caseList: *mut [il::SwitchCase] = &mut [];
391
    try! caseList.extend(&b.cases[..], b.arena);
392
    let mut copy: *mut [il::Fn] = &mut [];
393
    try! copy.append(
394
        il::Fn {
395
            name,
396
            params: &copyParams[..],
397
            returnType: ret,
398
            isExtern: false,
399
            isLeaf: false,
400
            blocks: &copyBlocks[..],
401
            vals: &pool[..],
402
            cases: &caseList[..],
403
            borrows: &sources[..],
404
        },
405
        b.arena
406
    );
407
    try! b.fns.append(&copy[0], b.arena);
408
    return index;
409
}
410
411
/// Add a function of one block, and return its index.
412
fn addFn(
413
    b: &mut Builder, name: *[u8], params: &[il::Param], ret: il::ValType, instrs: &[il::Instr]
414
) -> u32 {
415
    let one = block(b, &[], instrs);
416
    return addBlocks(b, name, params, ret, &[one]);
417
}
418
419
/// Add an extern function, and return its index.
420
fn addExtern(b: &mut Builder, name: *[u8], params: &[il::Param], ret: il::ValType) -> u32 {
421
    let index = b.fns.len;
422
    let mut ownParams: *mut [il::Param] = &mut [];
423
    try! ownParams.extend(params, b.arena);
424
    let mut copy: *mut [il::Fn] = &mut [];
425
    try! copy.append(
426
        il::Fn {
427
            name,
428
            params: &ownParams[..],
429
            returnType: ret,
430
            isExtern: true,
431
            isLeaf: true,
432
            blocks: &[],
433
            vals: &[],
434
            cases: &[],
435
            borrows: &[],
436
        },
437
        b.arena
438
    );
439
    try! b.fns.append(&copy[0], b.arena);
440
    return index;
441
}
442
443
/// Add a data definition of the layout, and return its index.
444
fn addData(
445
    b: &mut Builder, name: *[u8], layout: u32, readOnly: bool, values: &[il::DataValue]
446
) -> u32 {
447
    let index = b.data.len;
448
    let l = b.layouts[layout];
449
    let mut copy: *mut [il::DataValue] = &mut [];
450
    try! copy.extend(values, b.arena);
451
    try! b.data.append(
452
        il::Data {
453
            name,
454
            size: l.size,
455
            alignment: l.alignment,
456
            layout,
457
            readOnly,
458
            heap: nil,
459
            isZeroInit: false,
460
            values: &copy[..],
461
        },
462
        b.arena
463
    );
464
    return index;
465
}
466
467
/// The program built so far, which leaves the builder empty.
468
fn program(b: &mut Builder) -> il::Program {
469
    let data = b.data.take();
470
    let fns = b.fns.take();
471
    let layouts = b.layouts.take();
472
    let signatures = b.signatures.take();
473
    let traits = b.traits.take();
474
    return il::Program {
475
        data: &data[..],
476
        fns: &fns[..],
477
        layouts: &layouts[..],
478
        signatures: &signatures[..],
479
        traits: &traits[..],
480
    };
481
}
482
483
/////////////////
484
// Instruction //
485
/////////////////
486
487
fn reserve(dst: u32, layout: u32) -> il::Instr {
488
    return il::Instr::Reserve { dst: il::Reg { n: dst }, layout };
489
}
490
491
fn load(dst: u32, src: u32, offset: i32) -> il::Instr {
492
    return il::Instr::Load {
493
        typ: il::Type::W32, dst: il::Reg { n: dst }, src: il::Reg { n: src }, offset
494
    };
495
}
496
497
fn load64(dst: u32, src: u32, offset: i32) -> il::Instr {
498
    return il::Instr::Load {
499
        typ: il::Type::W64, dst: il::Reg { n: dst }, src: il::Reg { n: src }, offset
500
    };
501
}
502
503
fn store(src: il::Val, dst: u32, offset: i32) -> il::Instr {
504
    return il::Instr::Store { typ: il::Type::W32, src, dst: il::Reg { n: dst }, offset };
505
}
506
507
fn store64(src: il::Val, dst: u32, offset: i32) -> il::Instr {
508
    return il::Instr::Store { typ: il::Type::W64, src, dst: il::Reg { n: dst }, offset };
509
}
510
511
fn loadPtr(dst: u32, src: u32, offset: i32) -> il::Instr {
512
    return il::Instr::LoadPtr {
513
        dst: il::Reg { n: dst }, src: il::Reg { n: src }, offset, nullable: false
514
    };
515
}
516
517
fn storePtr(src: il::Val, dst: u32, offset: i32) -> il::Instr {
518
    return il::Instr::StorePtr { src, dst: il::Reg { n: dst }, offset };
519
}
520
521
/// Load a pointer or function value that can be zero.
522
fn loadNullablePtr(dst: u32, src: u32, offset: i32) -> il::Instr {
523
    return il::Instr::LoadPtr {
524
        dst: il::Reg { n: dst }, src: il::Reg { n: src }, offset, nullable: true
525
    };
526
}
527
528
fn field(dst: u32, src: u32, offset: u32) -> il::Instr {
529
    return il::Instr::Field { dst: il::Reg { n: dst }, src: il::Reg { n: src }, offset };
530
}
531
532
fn elem(dst: u32, base: u32, index: il::Val, layout: u32, count: u32) -> il::Instr {
533
    return il::Instr::Elem {
534
        dst: il::Reg { n: dst }, base: il::Reg { n: base }, index, layout, count
535
    };
536
}
537
538
fn sliceElem(dst: u32, slice: u32, index: il::Val, layout: u32) -> il::Instr {
539
    return il::Instr::SliceElem {
540
        dst: il::Reg { n: dst }, slice: il::Reg { n: slice }, index, layout
541
    };
542
}
543
544
fn sliceNew(dst: u32, base: il::Val, layout: u32, count: u32) -> il::Instr {
545
    return il::Instr::SliceNew {
546
        dst: il::Reg { n: dst }, base, layout, count, start: imm(0), end: imm(count as i64)
547
    };
548
}
549
550
fn sliceSub(dst: u32, src: u32, layout: u32) -> il::Instr {
551
    return il::Instr::SliceSub {
552
        dst: il::Reg { n: dst }, src: il::Reg { n: src }, layout, start: imm(0), end: imm(0)
553
    };
554
}
555
556
fn sliceLen(dst: u32, layout: u32, length: il::Val) -> il::Instr {
557
    return il::Instr::SliceLen { dst: il::Reg { n: dst }, layout, length };
558
}
559
560
fn sliceCopy(dst: u32, src: u32, layout: u32) -> il::Instr {
561
    return il::Instr::SliceCopy { dst: il::Reg { n: dst }, src: il::Reg { n: src }, layout };
562
}
563
564
fn blit(dst: u32, src: u32, layout: u32) -> il::Instr {
565
    return il::Instr::Blit { dst: il::Reg { n: dst }, src: il::Reg { n: src }, layout };
566
}
567
568
fn copy(dst: u32, val: il::Val) -> il::Instr {
569
    return il::Instr::Copy { dst: il::Reg { n: dst }, val };
570
}
571
572
fn ret(val: il::Val) -> il::Instr {
573
    return il::Instr::Ret { val };
574
}
575
576
fn retVoid() -> il::Instr {
577
    return il::Instr::Ret { val: nil };
578
}
579
580
fn call(dst: ?u32, retTy: il::ValType, callee: il::Val, values: il::ArgRange) -> il::Instr {
581
    let mut result: ?il::Reg = nil;
582
    if let n = dst {
583
        set result = il::Reg { n };
584
    }
585
    return il::Instr::Call { retTy, dst: result, func: callee, args: values };
586
}
587
588
fn add(dst: u32, a: il::Val, c: il::Val) -> il::Instr {
589
    return il::Instr::BinOp {
590
        op: il::BinOp::Add, typ: il::Type::W64, dst: il::Reg { n: dst }, a, b: c
591
    };
592
}
593
594
fn jmp(target: u32, values: il::ArgRange) -> il::Instr {
595
    return il::Instr::Jmp { target, args: values };
596
}
597
598
////////////
599
// Checks //
600
////////////
601
602
/// Verify the program, and return the error if there is one.
603
unsafe fn verdict(b: &mut Builder) -> ?verify::Error {
604
    let prog = program(b);
605
    let scratch = heap::over(&mut SCRATCH[..]);
606
    try verify::verifyProgram(&prog, CONFIG, scratch) catch err {
607
        return err;
608
    };
609
    return nil;
610
}
611
612
/// Check that the program is accepted.
613
unsafe fn accepted(b: &mut Builder) throws (testing::TestError) {
614
    if let _ = verdict(b) {
615
        throw testing::TestError::Failed;
616
    }
617
}
618
619
/// Check that the program is rejected for violating `rule`.
620
unsafe fn rejected(b: &mut Builder, rule: verify::Rule) throws (testing::TestError) {
621
    let err = verdict(b) else {
622
        throw testing::TestError::Failed;
623
    };
624
    try testing::expect(err.rule == rule);
625
}
626
627
/// Check that the program is accepted when `rule` is nil, or rejected for violating `rule`.
628
unsafe fn expect(b: &mut Builder, rule: ?verify::Rule) throws (testing::TestError) {
629
    if let want = rule {
630
        try rejected(b, want);
631
    } else {
632
        try accepted(b);
633
    }
634
}
635
636
/// Add `main`, a function of one block with parameters and instructions, to the program of
637
/// `b`, and check it as [`expect`] does.
638
unsafe fn checkIn(
639
    b: &mut Builder,
640
    params: &[il::Param],
641
    ret: il::ValType,
642
    instrs: &[il::Instr],
643
    rule: ?verify::Rule
644
) throws (testing::TestError) {
645
    addFn(b, "main", params, ret, instrs);
646
    try expect(b, rule);
647
}
648
649
/// Check the program that holds only `main`, as for [`checkIn`].
650
unsafe fn checkBody(
651
    params: &[il::Param], ret: il::ValType, instrs: &[il::Instr], rule: ?verify::Rule
652
) throws (testing::TestError) {
653
    let mut b = newBuilder();
654
    try checkIn(&mut b, params, ret, instrs, rule);
655
}
656
657
/// Check the program that holds only `main`, a function without result whose body is `instrs`
658
/// followed by a return, as for [`checkIn`].
659
unsafe fn check(params: &[il::Param], instrs: &[il::Instr], rule: ?verify::Rule)
660
    throws (testing::TestError)
661
{
662
    let mut b = newBuilder();
663
    let mut body: *mut [il::Instr] = &mut [];
664
    try! body.extend(instrs, b.arena);
665
    try! body.append(retVoid(), b.arena);
666
    try checkIn(&mut b, params, il::ValType::Void, &body[..], rule);
667
}
668
669
fn br(a: il::Val, thenTarget: u32, elseTarget: u32) -> il::Instr {
670
    return il::Instr::Br {
671
        op: il::CmpOp::Eq,
672
        typ: il::Type::W64,
673
        a,
674
        b: imm(0),
675
        thenTarget,
676
        thenArgs: il::ArgRange { start: 0, len: 0 },
677
        elseTarget,
678
        elseArgs: il::ArgRange { start: 0, len: 0 },
679
    };
680
}
681
682
/// An empty range of arguments.
683
fn none() -> il::ArgRange {
684
    return il::ArgRange { start: 0, len: 0 };
685
}
686
687
/// The data type, as a list of one parameter.
688
fn oneData() -> il::Param {
689
    return param(0, dataType());
690
}
691
692
////////////////////////
693
// Registers and flow //
694
////////////////////////
695
696
/// A trivial function is accepted.
697
@test unsafe fn trivial() throws (testing::TestError) {
698
    try checkBody(&[], il::ValType::Void, &[retVoid()], nil);
699
}
700
701
/// A register must be defined before its use.
702
@test unsafe fn useBeforeDefinition() throws (testing::TestError) {
703
    try check(&[], &[add(1, reg(2), imm(1)), copy(2, imm(0))], verify::Rule::Register);
704
    try check(&[], &[copy(2, imm(0)), add(1, reg(2), imm(1))], nil);
705
}
706
707
/// A register has one definition, also across a parameter and an instruction.
708
@test unsafe fn definedTwice() throws (testing::TestError) {
709
    try check(&[], &[copy(1, imm(0)), copy(1, imm(1))], verify::Rule::Register);
710
    try check(&[oneData()], &[copy(0, imm(1))], verify::Rule::Register);
711
    try checkBody(&[oneData(), oneData()], il::ValType::Void, &[retVoid()], verify::Rule::Register);
712
}
713
714
/// A register belongs to the function that defines it: another function can use the number
715
/// for its own register, but cannot read the definition.
716
@test unsafe fn registersAreLocal() throws (testing::TestError) {
717
    let mut ok = newBuilder();
718
    addFn(&mut ok, "f", &[], il::ValType::Void, &[copy(1, imm(0)), retVoid()]);
719
    try checkIn(&mut ok, &[], il::ValType::Void, &[copy(1, imm(0)), retVoid()], nil);
720
    let mut bad = newBuilder();
721
    addFn(&mut bad, "f", &[], il::ValType::Void, &[copy(1, imm(0)), retVoid()]);
722
    try checkIn(
723
        &mut bad,
724
        &[],
725
        il::ValType::Void,
726
        &[add(2, reg(1), imm(1)), retVoid()],
727
        verify::Rule::Register
728
    );
729
    let mut param = newBuilder();
730
    addFn(&mut param, "f", &[oneData()], il::ValType::Void, &[retVoid()]);
731
    try checkIn(
732
        &mut param,
733
        &[],
734
        il::ValType::Void,
735
        &[add(2, reg(0), imm(1)), retVoid()],
736
        verify::Rule::Register
737
    );
738
}
739
740
/// Register numbers stay below the limit.
741
@test unsafe fn registerLimit() throws (testing::TestError) {
742
    try check(&[], &[copy(64, imm(0))], verify::Rule::Limit);
743
    try check(&[], &[copy(63, imm(0))], nil);
744
}
745
746
/// A definition on one path does not dominate the merge.
747
@test unsafe fn definitionDoesNotDominate() throws (testing::TestError) {
748
    let mut b = newBuilder();
749
    let blocks = [
750
        block(&mut b, &[], &[br(reg(0), 1, 2)]),
751
        block(&mut b, &[], &[copy(1, imm(5)), jmp(3, none())]),
752
        block(&mut b, &[], &[jmp(3, none())]),
753
        block(&mut b, &[], &[add(2, reg(1), imm(0)), retVoid()]),
754
    ];
755
    addBlocks(&mut b, "main", &[oneData()], il::ValType::Void, &blocks[..]);
756
    try rejected(&mut b, verify::Rule::Register);
757
}
758
759
/// The merge of two paths receives the value as a block argument.
760
@test unsafe fn blockArgumentMerges() throws (testing::TestError) {
761
    let mut b = newBuilder();
762
    let five = args(&mut b, &[imm(5)]);
763
    let six = args(&mut b, &[imm(6)]);
764
    let blocks = [
765
        block(&mut b, &[], &[br(reg(0), 1, 2)]),
766
        block(&mut b, &[], &[jmp(3, five)]),
767
        block(&mut b, &[], &[jmp(3, six)]),
768
        block(&mut b, &[param(1, dataType())], &[add(2, reg(1), imm(0)), retVoid()]),
769
    ];
770
    addBlocks(&mut b, "main", &[oneData()], il::ValType::Void, &blocks[..]);
771
    try accepted(&mut b);
772
}
773
774
/// A loop carries a value around the back edge. A register defined in the body does
775
/// not reach the header.
776
@test unsafe fn loops() throws (testing::TestError) {
777
    let mut b = newBuilder();
778
    let zero = args(&mut b, &[imm(0)]);
779
    let next = args(&mut b, &[reg(2)]);
780
    let blocks = [
781
        block(&mut b, &[], &[jmp(1, zero)]),
782
        block(&mut b, &[param(1, dataType())], &[add(2, reg(1), imm(1)), br(reg(2), 2, 3)]),
783
        block(&mut b, &[], &[jmp(1, next)]),
784
        block(&mut b, &[], &[retVoid()]),
785
    ];
786
    addBlocks(&mut b, "main", &[], il::ValType::Void, &blocks[..]);
787
    try accepted(&mut b);
788
789
    let mut bad = newBuilder();
790
    let back = args(&mut bad, &[reg(2)]);
791
    let again = [
792
        block(&mut bad, &[], &[jmp(1, back)]),
793
        block(&mut bad, &[param(1, dataType())], &[add(2, reg(1), imm(1)), br(reg(2), 2, 3)]),
794
        block(&mut bad, &[], &[jmp(1, back)]),
795
        block(&mut bad, &[], &[retVoid()]),
796
    ];
797
    addBlocks(&mut bad, "main", &[], il::ValType::Void, &again[..]);
798
    try rejected(&mut bad, verify::Rule::Register);
799
}
800
801
/// A block that nothing reaches is checked, and may use only its own definitions.
802
@test unsafe fn unreachableBlock() throws (testing::TestError) {
803
    let mut b = newBuilder();
804
    let blocks = [
805
        block(&mut b, &[], &[copy(1, imm(0)), retVoid()]),
806
        block(&mut b, &[], &[copy(2, imm(0)), add(3, reg(2), imm(1)), retVoid()]),
807
    ];
808
    addBlocks(&mut b, "main", &[], il::ValType::Void, &blocks[..]);
809
    try accepted(&mut b);
810
811
    let mut bad = newBuilder();
812
    let again = [
813
        block(&mut bad, &[], &[copy(1, imm(0)), retVoid()]),
814
        block(&mut bad, &[], &[add(3, reg(1), imm(1)), retVoid()]),
815
    ];
816
    addBlocks(&mut bad, "main", &[], il::ValType::Void, &again[..]);
817
    try rejected(&mut bad, verify::Rule::Register);
818
}
819
820
/// Every block ends with exactly one terminator.
821
@test unsafe fn terminators() throws (testing::TestError) {
822
    try checkBody(&[], il::ValType::Void, &[copy(1, imm(0))], verify::Rule::Structure);
823
    try checkBody(&[], il::ValType::Void, &[], verify::Rule::Structure);
824
    try check(&[], &[retVoid()], verify::Rule::Structure);
825
    try checkBody(&[], il::ValType::Void, &[jmp(5, none())], verify::Rule::Structure);
826
}
827
828
/// The entry block takes no parameters, and a function has blocks within the limit.
829
@test unsafe fn entryBlock() throws (testing::TestError) {
830
    let mut b = newBuilder();
831
    let entry = block(&mut b, &[param(1, dataType())], &[retVoid()]);
832
    addBlocks(&mut b, "main", &[], il::ValType::Void, &[entry]);
833
    try rejected(&mut b, verify::Rule::Structure);
834
835
    let mut empty = newBuilder();
836
    addBlocks(&mut empty, "main", &[], il::ValType::Void, &[]);
837
    try rejected(&mut empty, verify::Rule::Structure);
838
839
    let mut many = newBuilder();
840
    let mut blocks: [il::Block; 17] = [block(&mut many, &[], &[retVoid()]); 17];
841
    addBlocks(&mut many, "main", &[], il::ValType::Void, &blocks[..]);
842
    try rejected(&mut many, verify::Rule::Limit);
843
}
844
845
/// A branch passes as many arguments as the block has parameters, of matching types.
846
@test unsafe fn branchArguments() throws (testing::TestError) {
847
    let mut count = newBuilder();
848
    let blocks = [
849
        block(&mut count, &[], &[jmp(1, none())]),
850
        block(&mut count, &[param(1, dataType())], &[retVoid()]),
851
    ];
852
    addBlocks(&mut count, "main", &[], il::ValType::Void, &blocks[..]);
853
    try rejected(&mut count, verify::Rule::Arity);
854
855
    let mut kind = newBuilder();
856
    let one = args(&mut kind, &[imm(1)]);
857
    let more = [
858
        block(&mut kind, &[], &[jmp(1, one)]),
859
        block(&mut kind, &[param(1, ptrType(P4, true, true, false))], &[retVoid()]),
860
    ];
861
    addBlocks(&mut kind, "main", &[], il::ValType::Void, &more[..]);
862
    try rejected(&mut kind, verify::Rule::Type);
863
}
864
865
/// Parameters and arguments are limited in number.
866
@test unsafe fn parameterLimit() throws (testing::TestError) {
867
    let mut b = newBuilder();
868
    let mut params: [il::Param; 9] = [oneData(); 9];
869
    for i in 0 .. 9 {
870
        set params[i] = param(i, dataType());
871
    }
872
    addFn(&mut b, "main", &params[..], il::ValType::Void, &[retVoid()]);
873
    try rejected(&mut b, verify::Rule::Limit);
874
    let mut ok = newBuilder();
875
    addFn(&mut ok, "main", &params[.. 8], il::ValType::Void, &[retVoid()]);
876
    try accepted(&mut ok);
877
}
878
879
///////////////////////
880
// Loads and stores  //
881
///////////////////////
882
883
/// An access stays inside the layout of the pointer.
884
@test unsafe fn accessBounds() throws (testing::TestError) {
885
    try check(&[], &[reserve(0, P8), store(imm(1), 0, 4), load(1, 0, 4)], nil);
886
    try check(&[], &[reserve(0, P4), load(1, 0, 4)], verify::Rule::Bounds);
887
    try check(&[], &[reserve(0, P4), load(1, 0, -4)], verify::Rule::Bounds);
888
    try check(&[], &[reserve(0, P4), load64(1, 0, 0)], verify::Rule::Bounds);
889
    try check(&[], &[reserve(0, P4), store(imm(1), 0, 1)], verify::Rule::Bounds);
890
}
891
892
/// Data never becomes a pointer.
893
@test unsafe fn forgedPointer() throws (testing::TestError) {
894
    try check(&[oneData()], &[load(1, 0, 0)], verify::Rule::Type);
895
    try check(&[], &[reserve(0, P8), load64(1, 0, 0), load(2, 1, 0)], verify::Rule::Type);
896
    try check(&[], &[copy(1, imm(8)), store(imm(1), 1, 0)], verify::Rule::Type);
897
    try check(
898
        &[oneData()], &[reserve(1, P8), add(2, reg(1), imm(0)), load(3, 2, 0)], verify::Rule::Type
899
    );
900
}
901
902
/// A pointer that can be null needs a proof before memory access.
903
@test unsafe fn nullablePointer() throws (testing::TestError) {
904
    let maybe = [param(0, ptrType(P4, true, false, true))];
905
    try check(&maybe[..], &[load(1,  0, 0)], verify::Rule::Null);
906
    try check(&maybe[..], &[field(1, 0, 0)], verify::Rule::Null);
907
}
908
909
/// Only the tested pointer on the nonzero edge of a full-width equality test is refined.
910
@test unsafe fn branchNonNull() throws (testing::TestError) {
911
    for typ in [il::Type::W8, il::Type::W32, il::Type::W64] {
912
        for op in [il::CmpOp::Eq, il::CmpOp::Ne, il::CmpOp::Ult] {
913
            for swapped in [false, true] {
914
                for thenNonNull in [false, true] {
915
                    for passed in [reg(0), reg(1)] {
916
                        let mut b = newBuilder();
917
                        let value = args(&mut b, &[passed]);
918
                        let blocks = [
919
                            block(&mut b, &[], &[
920
                                il::Instr::Br {
921
                                    op,
922
                                    typ,
923
                                    a: imm(0) if swapped else reg(0),
924
                                    b: reg(0) if swapped else imm(0),
925
                                    thenTarget: 1 if thenNonNull else 2,
926
                                    thenArgs: value if thenNonNull else none(),
927
                                    elseTarget: 2 if thenNonNull else 1,
928
                                    elseArgs: none() if thenNonNull else value,
929
                                },
930
                            ]),
931
                            block(&mut b, &[param(2, ptrType(P4, true, false, false))], &[
932
                                load(3, 2, 0), retVoid()
933
                            ]),
934
                            block(&mut b, &[], &[retVoid()]),
935
                        ];
936
                        let params = [
937
                            param(0, ptrType(P4, true, false, true)),
938
                            param(1, ptrType(P4, true, false, true)),
939
                        ];
940
                        addBlocks(&mut b, "main", &params[..], il::ValType::Void, &blocks[..]);
941
                        let proven = typ == il::Type::W64
942
                            and passed == reg(0)
943
                            and ((op == il::CmpOp::Ne and thenNonNull)
944
                                or (op == il::CmpOp::Eq and not thenNonNull));
945
                        if proven {
946
                            try accepted(&mut b);
947
                        } else {
948
                            try rejected(&mut b, verify::Rule::Null);
949
                        }
950
                    }
951
                }
952
            }
953
        }
954
    }
955
}
956
957
/// A null test preserves pointer rights and checks both edges when their target is shared.
958
@test unsafe fn branchNonNullRights() throws (testing::TestError) {
959
    for want in [
960
        ptrType(P4, true, true, false), ptrType(P4, false, true, false),
961
        ptrType(P8, false, false, false), ptrType(P4, false, false, false),
962
    ] {
963
        for shared in [false, true] {
964
            let mut b = newBuilder();
965
            let value = args(&mut b, &[reg(0)]);
966
            let blocks = [
967
                block(&mut b, &[], &[
968
                    il::Instr::Br {
969
                        op: il::CmpOp::Ne,
970
                        typ: il::Type::W64,
971
                        a: reg(0),
972
                        b: imm(0),
973
                        thenTarget: 1,
974
                        thenArgs: value,
975
                        elseTarget: 1 if shared else 2,
976
                        elseArgs: value if shared else none(),
977
                    },
978
                ]),
979
                block(&mut b, &[param(1, want)], &[retVoid()]),
980
                block(&mut b, &[], &[retVoid()]),
981
            ];
982
            let params = [param(0, ptrType(P4, false, false, true))];
983
            addBlocks(&mut b, "main", &params[..], il::ValType::Void, &blocks[..]);
984
            if shared and want == ptrType(P4, false, false, false) {
985
                try rejected(&mut b, verify::Rule::Null);
986
            } else if want == ptrType(P4, true, true, false) {
987
                try rejected(&mut b, verify::Rule::Class);
988
            } else if want == ptrType(P4, false, true, false) {
989
                try rejected(&mut b, verify::Rule::Mutability);
990
            } else if want == ptrType(P8, false, false, false) {
991
                try rejected(&mut b, verify::Rule::View);
992
            } else {
993
                try accepted(&mut b);
994
            }
995
        }
996
    }
997
    let mut data = newBuilder();
998
    let value = args(&mut data, &[reg(0)]);
999
    let blocks = [
1000
        block(&mut data, &[], &[
1001
            il::Instr::Br {
1002
                op: il::CmpOp::Ne,
1003
                typ: il::Type::W64,
1004
                a: reg(0),
1005
                b: imm(0),
1006
                thenTarget: 1,
1007
                thenArgs: value,
1008
                elseTarget: 2,
1009
                elseArgs: none(),
1010
            },
1011
        ]),
1012
        block(&mut data, &[param(1, ptrType(P4, false, false, false))], &[retVoid()]),
1013
        block(&mut data, &[], &[retVoid()]),
1014
    ];
1015
    addBlocks(&mut data, "main", &[oneData()], il::ValType::Void, &blocks[..]);
1016
    try rejected(&mut data, verify::Rule::Type);
1017
}
1018
1019
/// A write needs a pointer to writable memory.
1020
@test unsafe fn writeThroughConstant() throws (testing::TestError) {
1021
    let fixed = [param(0, ptrType(P4, true, false, false))];
1022
    try check(&fixed[..], &[store(imm(1), 0, 0)], verify::Rule::Mutability);
1023
    try check(&fixed[..], &[load(1,       0, 0)], nil);
1024
}
1025
1026
/// Pointers are loaded only from their slots.
1027
@test unsafe fn pointerLoad() throws (testing::TestError) {
1028
    try check(&[], &[reserve(0, P8), loadPtr(1, 0, 0)], verify::Rule::Slot);
1029
    try check(&[], &[reserve(0, CELL), loadPtr(2, 0, 0), store(imm(1), 2, 0)], nil);
1030
    try check(
1031
        &[], &[reserve(0, CELL), loadNullablePtr(1, 0, 0), store(imm(1), 1, 0)], verify::Rule::Null
1032
    );
1033
    try check(
1034
        &[], &[reserve(0, CELLC), loadPtr(2, 0, 0), store(imm(1), 2, 0)], verify::Rule::Mutability
1035
    );
1036
    try check(&[], &[reserve(0,          CELL), loadPtr(1, 0, 4)], verify::Rule::Slot);
1037
    try check(&[], &[reserve(0,          SLICE), loadPtr(1, 0, 0)], verify::Rule::Slot);
1038
    try check(&[oneData()], &[loadPtr(1, 0, 0)], verify::Rule::Type);
1039
}
1040
1041
/// A data store cannot overwrite a pointer, or the pointer, length or capacity of a slice.
1042
@test unsafe fn dataOverSlot() throws (testing::TestError) {
1043
    try check(&[], &[reserve(0, CELL), store64(imm(5), 0, 0)], verify::Rule::Slot);
1044
    try check(&[], &[reserve(0, CELL), store(imm(5), 0, 4)], verify::Rule::Slot);
1045
    try check(&[], &[reserve(0, SLICE), store64(imm(5), 0, 0)], verify::Rule::Slot);
1046
    try check(&[], &[reserve(0, SLICE), store(imm(5), 0, 8)], verify::Rule::Slot);
1047
    try check(&[], &[reserve(0, SLICE), store(imm(5), 0, 12)], verify::Rule::Slot);
1048
    try check(&[], &[reserve(0, PAIR), store64(imm(5), 0, 8)], verify::Rule::Slot);
1049
    try check(
1050
        &[], &[reserve(0, PAIR), store64(imm(5), 0, 0), store64(imm(5), 0, 24)], verify::Rule::Slot
1051
    );
1052
    try check(
1053
        &[], &[reserve(0, PAIR), store64(imm(5), 0, 0), store(imm(5), 0, 28)], verify::Rule::Slot
1054
    );
1055
    try check(&[], &[reserve(0, CELLS), store64(imm(5), 0, 8)], verify::Rule::Slot);
1056
}
1057
1058
/// A pointer is stored into a slot of its kind, with at most the rights of the slot.
1059
@test unsafe fn pointerStore() throws (testing::TestError) {
1060
    let own = param(1, ptrType(P4, true, true, false));
1061
    let cell = param(0, ptrType(CELL, false, true, false));
1062
    try check(&[cell, own], &[storePtr(reg(1), 0, 0)], nil);
1063
    try check(&[cell], &[reserve(1,            P4), storePtr(reg(1), 0, 0)], verify::Rule::Class);
1064
    try check(
1065
        &[cell, param(1, ptrType(P4, true, false, false))],
1066
        &[storePtr(reg(1), 0, 0)],
1067
        verify::Rule::Mutability
1068
    );
1069
    try check(&[cell, param(1, ptrType(P4, true, true, true))], &[storePtr(reg(1), 0, 0)], nil);
1070
    try check(
1071
        &[cell, param(1, ptrType(CELL, true, true, false))],
1072
        &[storePtr(reg(1), 0, 0)],
1073
        verify::Rule::View
1074
    );
1075
    try check(&[cell, param(1, ptrType(P8, true, true, false))], &[storePtr(reg(1), 0, 0)], nil);
1076
    try check(
1077
        &[param(0, ptrType(P8, false, true, false)), own],
1078
        &[storePtr(reg(1), 0, 0)],
1079
        verify::Rule::Slot
1080
    );
1081
    try check(
1082
        &[param(0, ptrType(CELL, false, false, false)), own],
1083
        &[storePtr(reg(1), 0, 0)],
1084
        verify::Rule::Mutability
1085
    );
1086
}
1087
1088
/// A reference stays in a container of the frame that it lives in, or in a target
1089
/// object of a parameter that permits its source.
1090
@test unsafe fn referenceStore() throws (testing::TestError) {
1091
    let borrowed = param(1, ptrType(P4, false, true, false));
1092
    let owned = param(1, ptrType(P4, true, true, false));
1093
    let outer = param(0, ptrType(LOCAL, false, true, false));
1094
    try check(&[outer, borrowed], &[storePtr(reg(1), 0, 0)], verify::Rule::Return);
1095
    try check(&[borrowed], &[reserve(0, LOCAL), storePtr(reg(1), 0, 0)], nil);
1096
    try check(&[outer], &[reserve(1, P4), storePtr(reg(1), 0, 0)], verify::Rule::Return);
1097
    try check(
1098
        &[borrowed],
1099
        &[reserve(0, PAIR), field(2, 0, 8), storePtr(reg(1), 2, 0)],
1100
        verify::Rule::Class
1101
    );
1102
    try check(&[outer, owned], &[storePtr(reg(1), 0, 0)], nil);
1103
    // A pointer read from a region of a target object can be written back to it.
1104
    try check(&[outer], &[loadPtr(2, 0, 0), storePtr(reg(2), 0, 0)], nil);
1105
}
1106
1107
/// Only zero is a pointer that is not a register.
1108
@test unsafe fn pointerStoreValues() throws (testing::TestError) {
1109
    let cell = param(0, ptrType(CELL, false, true, false));
1110
    try check(&[cell], &[storePtr(imm(0), 0, 0)], nil);
1111
    try check(&[cell], &[storePtr(imm(1), 0, 0)], verify::Rule::Type);
1112
    try check(&[cell], &[storePtr(il::Val::Undef, 0, 0)], verify::Rule::Type);
1113
    try check(&[cell, param(1, dataType())], &[storePtr(reg(1), 0, 0)], verify::Rule::Type);
1114
}
1115
1116
/// A field is a pointer into a layout at a constant offset.
1117
@test unsafe fn fieldOffsets() throws (testing::TestError) {
1118
    let own = param(9, ptrType(P4, true, true, false));
1119
    try check(&[own], &[reserve(0, PAIR), field(1, 0, 8), storePtr(reg(9), 1, 0)], nil);
1120
    try check(&[], &[reserve(0,    PAIR), field(1, 0, 32)], nil);
1121
    try check(&[], &[reserve(0,    PAIR), field(1, 0, 33)], verify::Rule::Bounds);
1122
    try check(&[], &[reserve(0,    PAIR), field(1, 0, 32), load(2, 1, 0)], verify::Rule::Bounds);
1123
    try check(&[], &[reserve(0,    PAIR), field(1, 0, 8), field(2, 1, 25)], verify::Rule::Bounds);
1124
    try check(&[], &[reserve(0,    PAIR), field(1, 0, 8), load(2, 1, -12)], verify::Rule::Bounds);
1125
    try check(
1126
        &[own], &[reserve(0, PAIR), field(1, 0, 4), storePtr(reg(9), 1, 0)], verify::Rule::Slot
1127
    );
1128
}
1129
1130
/// An element address needs an array of the element layout and count.
1131
@test unsafe fn elementAddress() throws (testing::TestError) {
1132
    try check(
1133
        &[oneData()], &[reserve(1, P16), elem(2, 1, reg(0), P4, 4), store(imm(1), 2, 0)], nil
1134
    );
1135
    try check(&[], &[reserve(0, P16), elem(1, 0, imm(0), P4, 5)], verify::Rule::Bounds);
1136
    try check(&[], &[reserve(0, CELLS), elem(1, 0, imm(1), CELL, 3), loadPtr(2, 1, 0)], nil);
1137
    try check(&[], &[reserve(0, CELLS), elem(1, 0, imm(1), CELL, 2)], nil);
1138
    try check(&[], &[reserve(0, CELLS), elem(1, 0, imm(1), CELL, 4)], verify::Rule::Bounds);
1139
    try check(&[], &[reserve(0, P16), elem(1, 0, imm(0), CELL, 2)], verify::Rule::View);
1140
    try checkBody(
1141
        &[],
1142
        il::ValType::Void,
1143
        &[
1144
            reserve(0, PAIR), field(1, 0, 8),
1145
            elem(2,    1, imm(0), CELL, 1), loadPtr(3, 2, 0), retVoid(),
1146
        ],
1147
        nil
1148
    );
1149
    try check(&[], &[reserve(0,       PAIR), elem(1, 0, imm(0), P8, 2)], verify::Rule::View);
1150
    try check(&[oneData()], &[elem(1, 0, imm(0), P4, 1)], verify::Rule::Type);
1151
}
1152
1153
/// Plain array elements must have the alignment of their layout.
1154
@test unsafe fn elementAlignment() throws (testing::TestError) {
1155
    try check(&[], &[reserve(0, P16), field(1, 0, 4), elem(2, 1, imm(0), P4, 2)], nil);
1156
    try check(
1157
        &[], &[reserve(0, P16), field(1, 0, 2), elem(2, 1, imm(0), P4, 2)], verify::Rule::View
1158
    );
1159
    try check(&[], &[reserve(0, B8), elem(1, 0, imm(0), P4, 2)], verify::Rule::View);
1160
}
1161
1162
////////////
1163
// Slices //
1164
////////////
1165
1166
/// A slice is built over an array that is large enough, with the rights of the slot.
1167
@test unsafe fn sliceNewBase() throws (testing::TestError) {
1168
    try check(
1169
        &[], &[reserve(0, P16), reserve(1, SLICE), sliceNew(1, reg(0), P1, 16)], verify::Rule::Class
1170
    );
1171
    let own = param(0, ptrType(P16, true, true, false));
1172
    try check(&[own], &[reserve(1, SLICE), sliceNew(1, reg(0), P1, 16)], nil);
1173
    try check(&[own], &[reserve(1, SLICE), sliceNew(1, reg(0), P1, 17)], verify::Rule::Bounds);
1174
    try check(&[own], &[reserve(1, SLICE), sliceNew(1, reg(0), P1, 8)], nil);
1175
    try check(&[own], &[reserve(1, SLICE), sliceNew(1, reg(0), P4, 4)], verify::Rule::View);
1176
    try check(
1177
        &[param(0, ptrType(P16, true, true, true))],
1178
        &[reserve(1, SLICE), sliceNew(1, reg(0), P1, 16)],
1179
        verify::Rule::Null
1180
    );
1181
    try check(&[oneData()], &[reserve(1, SLICE), sliceNew(1, reg(0), P1, 16)], verify::Rule::Type);
1182
    try check(
1183
        &[param(0, ptrType(CELLS, true, true, false))],
1184
        &[reserve(1, SLICE), sliceNew(1, reg(0), P1, 24)],
1185
        verify::Rule::View
1186
    );
1187
}
1188
1189
/// A slice of no elements needs no base.
1190
@test unsafe fn emptySlice() throws (testing::TestError) {
1191
    try check(&[], &[reserve(0, SLICE), sliceNew(0, imm(4), P1, 0)], nil);
1192
    try check(&[], &[reserve(0, SLICE), sliceNew(0, il::Val::Undef, P1, 0)], nil);
1193
}
1194
1195
/// A writable slice needs writable memory.
1196
@test unsafe fn sliceMutability() throws (testing::TestError) {
1197
    let fixed = [param(0, ptrType(P16, true, false, false))];
1198
    try check(
1199
        &fixed[..], &[reserve(1, SLICE), sliceNew(1, reg(0), P1, 16)], verify::Rule::Mutability
1200
    );
1201
    try check(&fixed[..], &[reserve(1, SLICEC), sliceNew(1, reg(0), P1, 16)], nil);
1202
    try check(
1203
        &[
1204
            param(0, ptrType(P16, true, true, false)),
1205
            param(1, ptrType(SLICEC, false, false, false)),
1206
        ],
1207
        &[sliceNew(1, reg(0), P1, 16)],
1208
        verify::Rule::Mutability
1209
    );
1210
}
1211
1212
/// A slice that does not own its elements is built in the frame of its base.
1213
@test unsafe fn sliceClasses() throws (testing::TestError) {
1214
    let borrowed = param(1, ptrType(BORROW, false, true, false));
1215
    let own = param(0, ptrType(P16, true, true, false));
1216
    try check(&[], &[reserve(0, P16), reserve(1, BORROW), sliceNew(1, reg(0), P1, 16)], nil);
1217
    try check(
1218
        &[param(0, ptrType(P16, false, true, false)), borrowed],
1219
        &[sliceNew(1, reg(0), P1, 16)],
1220
        verify::Rule::Return
1221
    );
1222
    try check(&[own, borrowed], &[sliceNew(1, reg(0), P1, 16)], nil);
1223
    try check(&[own], &[reserve(1, P16), sliceNew(1, reg(0), P1, 16)], verify::Rule::Slot);
1224
}
1225
1226
/// A slice element is checked at run time, and the result has the rights of the slice.
1227
@test unsafe fn sliceElement() throws (testing::TestError) {
1228
    try check(
1229
        &[oneData()],
1230
        &[reserve(1, SLICE), sliceElem(2, 1, reg(0), P1), load(3, 2, 0)],
1231
        verify::Rule::Bounds
1232
    );
1233
    try check(&[oneData()], &[reserve(1, SLICE), sliceElem(2, 1, reg(0), P1)], nil);
1234
    try check(&[oneData()], &[reserve(1, SLICE), sliceElem(2, 1, reg(0), P4)], verify::Rule::View);
1235
    try check(&[oneData()], &[reserve(1, P16), sliceElem(2, 1, reg(0), P1)], verify::Rule::Slot);
1236
    try check(
1237
        &[oneData()],
1238
        &[reserve(1, SLICEC), sliceElem(2, 1, reg(0), P1), store(imm(1), 2, 0)],
1239
        verify::Rule::Mutability
1240
    );
1241
}
1242
1243
/// Slice views preserve the alignment of their elements.
1244
@test unsafe fn sliceElementAlignment() throws (testing::TestError) {
1245
    let mut weakRead = newBuilder();
1246
    let weak = addLayout(&mut weakRead, 16, 8, &[sliceSlot(0, B8, true, true)]);
1247
    try checkIn(
1248
        &mut weakRead,
1249
        &[oneData()],
1250
        il::ValType::Void,
1251
        &[reserve(1, weak), sliceElem(2, 1, reg(0), P8), retVoid()],
1252
        verify::Rule::View
1253
    );
1254
1255
    let mut strongRead = newBuilder();
1256
    let strong = addLayout(&mut strongRead, 16, 8, &[sliceSlot(0, P8, true, true)]);
1257
    try checkIn(
1258
        &mut strongRead,
1259
        &[oneData()],
1260
        il::ValType::Void,
1261
        &[reserve(1, strong), sliceElem(2, 1, reg(0), B8), retVoid()],
1262
        nil
1263
    );
1264
}
1265
1266
/// A slice write cannot weaken the alignment promised by its destination slot.
1267
@test unsafe fn sliceDestinationAlignment() throws (testing::TestError) {
1268
    let mut strongWrite = newBuilder();
1269
    let dest = addLayout(&mut strongWrite, 16, 8, &[sliceSlot(0, P8, true, true)]);
1270
    try checkIn(
1271
        &mut strongWrite,
1272
        &[param(0, ptrType(B8, true, true, false))],
1273
        il::ValType::Void,
1274
        &[reserve(1, dest), sliceNew(1, reg(0), B8, 1), retVoid()],
1275
        verify::Rule::View
1276
    );
1277
1278
    let mut page = newBuilder();
1279
    let pageDest = addLayout(&mut page, 16, 8, &[sliceSlot(0, P8, true, true)]);
1280
    try checkIn(
1281
        &mut page,
1282
        &[oneData()],
1283
        il::ValType::Void,
1284
        &[reserve(1, pageDest), pageSlice(2, 1, true, B8), retVoid()],
1285
        verify::Rule::View
1286
    );
1287
1288
    let mut aligned = newBuilder();
1289
    let alignedDest = addLayout(&mut aligned, 16, 8, &[sliceSlot(0, P8, true, true)]);
1290
    try checkIn(
1291
        &mut aligned,
1292
        &[param(0, ptrType(P8, true, true, false))],
1293
        il::ValType::Void,
1294
        &[reserve(1, alignedDest), sliceNew(1, reg(0), P8, 1), retVoid()],
1295
        nil
1296
    );
1297
1298
    let mut strongSource = newBuilder();
1299
    let weakDest = addLayout(&mut strongSource, 16, 8, &[sliceSlot(0, B8, true, true)]);
1300
    try checkIn(
1301
        &mut strongSource,
1302
        &[param(0, ptrType(P8, true, true, false))],
1303
        il::ValType::Void,
1304
        &[reserve(1, weakDest), sliceNew(1, reg(0), P8, 1), retVoid()],
1305
        nil
1306
    );
1307
1308
    let mut weakSlice = newBuilder();
1309
    let weakSlot = addLayout(&mut weakSlice, 16, 8, &[sliceSlot(0, B8, true, true)]);
1310
    let strongSlot = addLayout(&mut weakSlice, 16, 8, &[sliceSlot(0, P8, true, true)]);
1311
    try checkIn(
1312
        &mut weakSlice,
1313
        &[],
1314
        il::ValType::Void,
1315
        &[reserve(0, weakSlot), reserve(1, strongSlot), sliceSub(1, 0, P8), retVoid()],
1316
        verify::Rule::View
1317
    );
1318
}
1319
1320
/// A sub-slice has the rights of the slice that it is taken from.
1321
@test unsafe fn subSlice() throws (testing::TestError) {
1322
    try check(&[], &[reserve(0, SLICE), reserve(1, SLICE), sliceSub(1, 0, P1)], nil);
1323
    try check(
1324
        &[], &[reserve(0, SLICEC), reserve(1, SLICE), sliceSub(1, 0, P1)], verify::Rule::Mutability
1325
    );
1326
    try check(&[], &[reserve(0, SLICE), reserve(1, BORROW), sliceSub(1, 0, P1)], nil);
1327
    try check(
1328
        &[], &[reserve(0, BORROW), reserve(1, SLICE), sliceSub(1, 0, P1)], verify::Rule::Class
1329
    );
1330
    // A target object takes a sub-slice of nothing, but not of frame storage.
1331
    try check(
1332
        &[param(1, ptrType(BORROW, false, true, false))],
1333
        &[reserve(0, BORROW), sliceSub(1, 0, P1)],
1334
        nil
1335
    );
1336
    try check(
1337
        &[param(1, ptrType(BORROW, false, true, false))],
1338
        &[reserve(0, BORROW), reserve(2, P1), sliceNew(0, reg(2), P1, 1), sliceSub(1, 0, P1)],
1339
        verify::Rule::Return
1340
    );
1341
    try check(&[], &[reserve(0, P16), reserve(1, SLICE), sliceSub(1, 0, P1)], verify::Rule::Slot);
1342
}
1343
1344
/// The length of a slice is set through a slice slot of the element layout.
1345
@test unsafe fn setLength() throws (testing::TestError) {
1346
    try check(&[oneData()], &[reserve(1, SLICE4), sliceLen(1, P4, reg(0))], nil);
1347
    try check(&[], &[reserve(0,          SLICE4C), sliceLen(0, P4, imm(1))], nil);
1348
    try check(&[], &[reserve(0,          SLICE4), sliceLen(0, P1, imm(1))], verify::Rule::View);
1349
    try check(&[], &[reserve(0,          P16), sliceLen(0, P4, imm(1))], verify::Rule::Slot);
1350
    try check(&[], &[reserve(0,          SLICE0), sliceLen(0, P0, imm(1))], nil);
1351
    // Slots of owned pointers are typed memory, so the spare capacity is valid.
1352
    try check(&[], &[reserve(0, SLICECELL), sliceLen(0, CELL, imm(1))], nil);
1353
    // Spare capacity keeps the region facts of the elements that it held.
1354
    try check(&[], &[reserve(0, SLICELOCAL), sliceLen(0, LOCAL, imm(1))], nil);
1355
}
1356
1357
/// The capacity of a slice bounds the lengths that `slice.len` accepts, so no plain store or
1358
/// copy may write it. Reading it stays allowed.
1359
@test unsafe fn capacityProtected() throws (testing::TestError) {
1360
    try check(
1361
        &[], &[reserve(0, SLICE4), store(imm(0x7fffffff), 0, 12)], verify::Rule::Slot
1362
    );
1363
    try check(
1364
        &[], &[reserve(0, SLICE4), store64(imm(0x7fffffff00000000), 0, 8)], verify::Rule::Slot
1365
    );
1366
    // A plain region cannot overwrite the capacity through a blit.
1367
    try check(
1368
        &[], &[reserve(0, SLICE4), reserve(1, P8), blit(0, 1, P8)], verify::Rule::View
1369
    );
1370
    // The capacity can be read.
1371
    try check(
1372
        &[param(0, ptrType(SLICE4, false, false, false))],
1373
        &[
1374
            il::Instr::Load {
1375
                typ: il::Type::W32, dst: il::Reg { n: 1 }, src: il::Reg { n: 0 }, offset: 12
1376
            },
1377
        ],
1378
        nil
1379
    );
1380
}
1381
1382
/// A heap handle with the given rights, in register `n`.
1383
fn heapParam(n: u32, rights: il::HeapType) -> il::Param {
1384
    return param(n, il::ValType::Heap(rights));
1385
}
1386
1387
fn sliceGrow(ok: u32, slice: u32, heap: il::Val, layout: u32, capacity: il::Val) -> il::Instr {
1388
    return il::Instr::SliceGrow {
1389
        ok: il::Reg { n: ok }, slice: il::Reg { n: slice }, heap, layout, capacity
1390
    };
1391
}
1392
1393
/// A slice grows from a heap.
1394
@test unsafe fn growPlain() throws (testing::TestError) {
1395
    let plain = heapParam(0, il::HeapType::Plain);
1396
    let typed = heapParam(0, il::HeapType::Typed);
1397
    try check(&[plain], &[reserve(1, SLICE4), sliceGrow(2, 1, reg(0), P4, imm(8))], nil);
1398
    try check(&[typed], &[reserve(1, SLICE4), sliceGrow(2, 1, reg(0), P4, reg(0))], nil);
1399
    try check(&[plain], &[reserve(1, SLICE0), sliceGrow(2, 1, reg(0), P0, imm(5))], nil);
1400
}
1401
1402
/// Elements that have slots need a heap that is never visible as bytes.
1403
@test unsafe fn growSlots() throws (testing::TestError) {
1404
    try check(
1405
        &[heapParam(0, il::HeapType::Plain)],
1406
        &[reserve(1,   SLICECELL), sliceGrow(2, 1, reg(0), CELL, imm(1))],
1407
        verify::Rule::View
1408
    );
1409
    try check(
1410
        &[heapParam(0, il::HeapType::Typed)],
1411
        &[reserve(1,   SLICECELL), sliceGrow(2, 1, reg(0), CELL, imm(1))],
1412
        nil
1413
    );
1414
}
1415
1416
/// The slot that grows is an owned, writable slice slot of the elements.
1417
@test unsafe fn growSlot() throws (testing::TestError) {
1418
    let plain = heapParam(0, il::HeapType::Plain);
1419
    try check(
1420
        &[plain],
1421
        &[reserve(1, SLICE4C), sliceGrow(2, 1, reg(0), P4, imm(1))],
1422
        verify::Rule::Mutability
1423
    );
1424
    try check(
1425
        &[plain], &[reserve(1, BORROW), sliceGrow(2, 1, reg(0), P1, imm(1))], verify::Rule::Class
1426
    );
1427
    try check(
1428
        &[plain], &[reserve(1, P16), sliceGrow(2, 1, reg(0), P4, imm(1))], verify::Rule::Slot
1429
    );
1430
    try check(
1431
        &[plain], &[reserve(1, SLICE4), sliceGrow(2, 1, reg(0), CELL, imm(1))], verify::Rule::View
1432
    );
1433
}
1434
1435
/// The heap is a handle, and the result is data that is defined once.
1436
@test unsafe fn growOperands() throws (testing::TestError) {
1437
    let plain = heapParam(0, il::HeapType::Plain);
1438
    try check(
1439
        &[oneData()], &[reserve(1, SLICE4), sliceGrow(2, 1, reg(0), P4, imm(1))], verify::Rule::Type
1440
    );
1441
    try check(
1442
        &[plain],
1443
        &[reserve(1, SLICE4), sliceGrow(2, 1, reg(0), P4, imm(1)), load(3, 2, 0)],
1444
        verify::Rule::Type
1445
    );
1446
    try check(
1447
        &[plain],
1448
        &[
1449
            reserve(1, SLICE4),
1450
            sliceGrow(2, 1, reg(0), P4, imm(1)),
1451
            sliceGrow(2, 1, reg(0), P4, imm(1)),
1452
        ],
1453
        verify::Rule::Register
1454
    );
1455
}
1456
1457
/// Heap handles are values of their own. A handle can be stored in a slot of its kind, and
1458
/// can only drop rights. No instruction reads or writes the memory that it names.
1459
@test unsafe fn heapHandles() throws (testing::TestError) {
1460
    let plain = heapParam(0, il::HeapType::Plain);
1461
    let typed = heapParam(0, il::HeapType::Typed);
1462
    try check(&[plain], &[reserve(1, HEAPCELL), storePtr(reg(0), 1, 0)], nil);
1463
    try check(&[typed], &[reserve(1, HEAPCELL), storePtr(reg(0), 1, 0)], nil);
1464
    try check(&[typed], &[reserve(1, HEAPCELLT), storePtr(reg(0), 1, 0)], nil);
1465
    try check(
1466
        &[plain], &[reserve(1, HEAPCELLT), storePtr(reg(0), 1, 0)], verify::Rule::Type
1467
    );
1468
    // A handle is not a pointer or data.
1469
    try check(&[oneData()], &[reserve(1, HEAPCELL), storePtr(reg(0), 1, 0)], verify::Rule::Type);
1470
    try check(
1471
        &[plain], &[reserve(1, P8), storePtr(reg(0), 1, 0)], verify::Rule::Slot
1472
    );
1473
    try check(&[plain], &[reserve(1, P8), store64(reg(0), 1, 0)], nil);
1474
    // A loaded handle has the rights of its slot, and the zero handle is allowed.
1475
    try check(
1476
        &[],
1477
        &[
1478
            reserve(0, HEAPCELLT),
1479
            reserve(1, SLICECELL),
1480
            loadPtr(2, 0, 0),
1481
            sliceGrow(3, 1, reg(2), CELL, imm(1)),
1482
        ],
1483
        nil
1484
    );
1485
    try check(
1486
        &[],
1487
        &[
1488
            reserve(0, HEAPCELL),
1489
            reserve(1, SLICECELL),
1490
            loadPtr(2, 0, 0),
1491
            sliceGrow(3, 1, reg(2), CELL, imm(1)),
1492
        ],
1493
        verify::Rule::View
1494
    );
1495
    try check(&[], &[reserve(0, HEAPCELL), storePtr(imm(0), 0, 0)], nil);
1496
    // The zero handle can be returned as a heap, and an integer register cannot.
1497
    let heapType = il::ValType::Heap(il::HeapType::Typed);
1498
    let mut zero = newBuilder();
1499
    try checkIn(&mut zero, &[], heapType, &[ret(imm(0))], nil);
1500
    let mut integer = newBuilder();
1501
    try checkIn(
1502
        &mut integer,
1503
        &[param(0, il::ValType::Data(il::Type::W64))],
1504
        heapType,
1505
        &[ret(reg(0))],
1506
        verify::Rule::Type
1507
    );
1508
    // A handle cannot be dereferenced.
1509
    try check(
1510
        &[plain],
1511
        &[
1512
            il::Instr::Load {
1513
                typ: il::Type::W64, dst: il::Reg { n: 1 }, src: il::Reg { n: 0 }, offset: 0
1514
            },
1515
        ],
1516
        verify::Rule::Type
1517
    );
1518
}
1519
1520
/// A heap region is zero-filled writable bytes, its symbol is a handle, and no pointer or
1521
/// data initializer names it.
1522
@test unsafe fn heapData() throws (testing::TestError) {
1523
    let mut b = newBuilder();
1524
    let i = addData(&mut b, "pool", P16, false, &[]);
1525
    set b.data[i].heap = il::HeapType::Typed;
1526
    set b.data[i].isZeroInit = true;
1527
    addFn(
1528
        &mut b,
1529
        "main",
1530
        &[],
1531
        il::ValType::Void,
1532
        &[
1533
            copy(0, il::Val::DataSym("pool")), reserve(1, SLICECELL),
1534
            sliceGrow(2, 1, reg(0), CELL, imm(1)), retVoid(),
1535
        ]
1536
    );
1537
    try accepted(&mut b);
1538
1539
    // A plain heap does not provide elements that have slots.
1540
    let mut plain = newBuilder();
1541
    let j = addData(&mut plain, "pool", P16, false, &[]);
1542
    set plain.data[j].heap = il::HeapType::Plain;
1543
    set plain.data[j].isZeroInit = true;
1544
    addFn(
1545
        &mut plain,
1546
        "main",
1547
        &[],
1548
        il::ValType::Void,
1549
        &[
1550
            copy(0, il::Val::DataSym("pool")), reserve(1, SLICECELL),
1551
            sliceGrow(2, 1, reg(0), CELL, imm(1)), retVoid(),
1552
        ]
1553
    );
1554
    try rejected(&mut plain, verify::Rule::View);
1555
1556
    // The region cannot be read or written as bytes.
1557
    let mut bytes = newBuilder();
1558
    let k = addData(&mut bytes, "pool", P16, false, &[]);
1559
    set bytes.data[k].heap = il::HeapType::Typed;
1560
    set bytes.data[k].isZeroInit = true;
1561
    addFn(&mut bytes, "main", &[], il::ValType::Void, &[
1562
        copy(0, il::Val::DataSym("pool")), store(imm(1), 0, 0), retVoid()
1563
    ]);
1564
    try rejected(&mut bytes, verify::Rule::Type);
1565
1566
    // A region is writable, zero-filled and plain.
1567
    let mut readOnly = newBuilder();
1568
    let l = addData(&mut readOnly, "pool", P16, true, &[]);
1569
    set readOnly.data[l].heap = il::HeapType::Typed;
1570
    set readOnly.data[l].isZeroInit = true;
1571
    try rejected(&mut readOnly, verify::Rule::Data);
1572
    let mut filled = newBuilder();
1573
    let m = addData(&mut filled, "pool", P16, false, &[number(il::Type::W64, 1)]);
1574
    set filled.data[m].heap = il::HeapType::Typed;
1575
    try rejected(&mut filled, verify::Rule::Data);
1576
    let mut slots = newBuilder();
1577
    let n = addData(&mut slots, "pool", CELL, false, &[]);
1578
    set slots.data[n].heap = il::HeapType::Typed;
1579
    set slots.data[n].isZeroInit = true;
1580
    try rejected(&mut slots, verify::Rule::Data);
1581
    // A pointer initializer cannot name a region.
1582
    let mut named = newBuilder();
1583
    let o = addData(&mut named, "pool", P16, false, &[]);
1584
    set named.data[o].heap = il::HeapType::Typed;
1585
    set named.data[o].isZeroInit = true;
1586
    addData(&mut named, "p", CELL, false, &[symbol("pool")]);
1587
    try rejected(&mut named, verify::Rule::Data);
1588
}
1589
1590
/// Elements are copied between slices of one plain layout.
1591
@test unsafe fn copyElements() throws (testing::TestError) {
1592
    try check(&[], &[reserve(0, SLICE4), reserve(1, SLICE4), sliceCopy(1, 0, P4)], nil);
1593
    try check(&[], &[reserve(0, SLICE4C), reserve(1, SLICE4), sliceCopy(1, 0, P4)], nil);
1594
    try check(
1595
        &[],
1596
        &[reserve(0, SLICE4), reserve(1, SLICE4C), sliceCopy(1, 0, P4)],
1597
        verify::Rule::Mutability
1598
    );
1599
    try check(
1600
        &[], &[reserve(0, SLICE), reserve(1, SLICE4), sliceCopy(1, 0, P4)], verify::Rule::View
1601
    );
1602
    // A copy of owned slots duplicates pointers, which the verifier allows: it enforces types.
1603
    try check(&[], &[reserve(0, SLICECELL), reserve(1, SLICECELL), sliceCopy(1, 0, CELL)], nil);
1604
    // A copy of borrowed slots carries their region facts to the copy.
1605
    try check(
1606
        &[], &[reserve(0, SLICELOCAL), reserve(1, SLICELOCAL), sliceCopy(1, 0, LOCAL)], nil
1607
    );
1608
    try check(&[], &[reserve(0, SLICE0), reserve(1, SLICE0), sliceCopy(1, 0, P0)], nil);
1609
    try check(&[], &[reserve(0, P16), reserve(1, SLICE4), sliceCopy(1, 0, P4)], verify::Rule::Slot);
1610
}
1611
1612
////////////
1613
// Blits  //
1614
////////////
1615
1616
/// The source holds the copied object. The destination holds it too, or is a plain region.
1617
@test unsafe fn blitLayouts() throws (testing::TestError) {
1618
    try check(&[], &[reserve(0, P16), reserve(1, P16), blit(1, 0, P16)], nil);
1619
    try check(&[], &[reserve(0, P16), reserve(1, P16), blit(1, 0, P8)], nil);
1620
    try check(&[], &[reserve(0, CELL), reserve(1, CELL), blit(1, 0, CELL)], nil);
1621
    try check(&[], &[reserve(0, LOCAL), reserve(1, CELL), blit(1, 0, CELL)], verify::Rule::View);
1622
    try check(&[], &[reserve(0, CELL), reserve(1, P8), blit(1, 0, CELL)], nil);
1623
    try check(&[], &[reserve(0, CELL), reserve(1, P8), blit(1, 0, P8)], verify::Rule::View);
1624
    try check(&[], &[reserve(0, P8), reserve(1, CELL), blit(1, 0, CELL)], verify::Rule::View);
1625
    try check(&[], &[reserve(0, P8), reserve(1, CELL), blit(1, 0, P8)], verify::Rule::View);
1626
    try check(&[], &[reserve(0, P16), reserve(1, SLICE), blit(1, 0, P8)], verify::Rule::View);
1627
    try checkBody(
1628
        &[],
1629
        il::ValType::Void,
1630
        &[
1631
            reserve(0, PAIR), reserve(1, PAIR), field(2, 0, 8),
1632
            field(3,   1, 8), blit(3, 2, CELL), retVoid(),
1633
        ],
1634
        nil
1635
    );
1636
    try checkBody(
1637
        &[],
1638
        il::ValType::Void,
1639
        &[
1640
            reserve(0, PAIR), reserve(1, PAIR), field(2, 0, 8),
1641
            field(3,   1, 8), blit(3, 2, SLICE), retVoid(),
1642
        ],
1643
        verify::Rule::View
1644
    );
1645
    try check(&[], &[reserve(0, PAIR), reserve(1, PAIR), blit(1, 0, PAIR)], nil);
1646
    try check(
1647
        &[param(0, ptrType(P16, true, false, false))],
1648
        &[reserve(1, P16), blit(0, 1, P16)],
1649
        verify::Rule::Mutability
1650
    );
1651
}
1652
1653
/// The copied layout must fit in both regions.
1654
@test unsafe fn blitBounds() throws (testing::TestError) {
1655
    try check(&[], &[reserve(0, P8), reserve(1, P16), blit(1, 0, P16)], verify::Rule::Bounds);
1656
    try check(&[], &[reserve(0, P16), reserve(1, P8), blit(1, 0, P16)], verify::Rule::Bounds);
1657
    try checkBody(
1658
        &[],
1659
        il::ValType::Void,
1660
        &[
1661
            reserve(0, P16), reserve(1, P16), field(2, 0, 8),
1662
            blit(1,    2, P16), retVoid(),
1663
        ],
1664
        verify::Rule::Bounds
1665
    );
1666
    try checkBody(
1667
        &[],
1668
        il::ValType::Void,
1669
        &[
1670
            reserve(0, P16), reserve(1, P16), field(2, 1, 8),
1671
            blit(2,    0, P8), retVoid(),
1672
        ],
1673
        nil
1674
    );
1675
}
1676
1677
/// Check a copy of layout `l` from `src` at offset `os` to `dst` at offset `od`.
1678
unsafe fn blitAt(dst: u32, od: u32, src: u32, os: u32, l: u32, expected: ?verify::Rule)
1679
    throws (testing::TestError)
1680
{
1681
    try checkBody(
1682
        &[],
1683
        il::ValType::Void,
1684
        &[
1685
            reserve(0, src), reserve(1, dst),
1686
            field(2,   0, os), field(3, 1, od), blit(3, 2, l), retVoid(),
1687
        ],
1688
        expected
1689
    );
1690
}
1691
1692
/// A copy of a plain layout starts at an offset that its alignment divides, in an object that
1693
/// is at least as aligned.
1694
@test unsafe fn blitAlignment() throws (testing::TestError) {
1695
    try blitAt(P16, 8, P16, 8, P8, nil);
1696
    try blitAt(P16, 4, P16, 4, P4, nil);
1697
    try blitAt(P16, 4, P16, 4, P8, verify::Rule::View);
1698
    try blitAt(P16, 4, P16, 8, P8, verify::Rule::View);
1699
    try blitAt(P16, 8, P16, 4, P8, verify::Rule::View);
1700
    try blitAt(P16, 2, P16, 2, P4, verify::Rule::View);
1701
    try blitAt(P16, 1, P16, 3, P1, nil);
1702
    try blitAt(P16, 1, P16, 1, P3, nil);
1703
    // An object of byte alignment holds no aligned layout.
1704
    try blitAt(B8, 0, B8, 0, B8, nil);
1705
    try blitAt(B8, 0, B8, 0, P1, nil);
1706
    try blitAt(B8, 0, B8, 0, P4, verify::Rule::View);
1707
    try blitAt(B8, 0, P8, 0, P8, verify::Rule::View);
1708
    try blitAt(P8, 0, B8, 0, P8, verify::Rule::View);
1709
    try blitAt(B8, 4, B8, 4, P4, verify::Rule::View);
1710
    // Slots are copied into a plain region only where an object of the layout can be.
1711
    try blitAt(P16, 8, CELL, 0, CELL, nil);
1712
    try blitAt(P16, 4, CELL, 0, CELL, verify::Rule::View);
1713
    try blitAt(B8, 0, CELL, 0, CELL, verify::Rule::View);
1714
}
1715
1716
/// A pointer to a plain layout views a region of a larger object only at an aligned offset, and
1717
/// only when the object is aligned at least as much.
1718
@test unsafe fn viewAlignment() throws (testing::TestError) {
1719
    let b = newBuilder();
1720
    let scratch = heap::over(&mut SCRATCH[..]);
1721
    let t = try layout::build(&b.layouts[..], CONFIG, scratch) catch {
1722
        throw testing::TestError::Failed;
1723
    };
1724
    try testing::expect(layout::view(&t, P16, 0, P8) and layout::view(&t, P16, 8, P8));
1725
    try testing::expect(not layout::view(&t, P16, 4, P8) and not layout::view(&t, P16, 12, P8));
1726
    try testing::expect(layout::view(&t, P16, 12, P4) and not layout::view(&t, P16, 10, P4));
1727
    try testing::expect(layout::view(&t, P16, 15, P1) and layout::view(&t, P16, 13, P3));
1728
    try testing::expect(layout::view(&t, B8, 0, P1) and layout::view(&t, B8, 7, P1));
1729
    try testing::expect(not layout::view(&t, B8, 0, P4) and not layout::view(&t, B8, 0, P8));
1730
    try testing::expect(layout::view(&t, B8, 0, B8) and layout::view(&t, P8, 0, P8));
1731
}
1732
1733
/// A copy and a read-only pointer read a slot through a view with the same or fewer
1734
/// rights. A destination and a writable pointer need the slot itself.
1735
@test unsafe fn readFewerRights() throws (testing::TestError) {
1736
    try check(&[], &[reserve(0, SLICE), reserve(1, SLICEC), blit(1, 0, SLICEC)], nil);
1737
    try check(&[], &[reserve(0, SLICEC), reserve(1, SLICE), blit(1, 0, SLICE)], verify::Rule::View);
1738
    try check(&[], &[reserve(0, CELL), reserve(1, CELLC), blit(1, 0, CELLC)], nil);
1739
    try check(&[], &[reserve(0, CELLC), reserve(1, CELL), blit(1, 0, CELL)], verify::Rule::View);
1740
    for mutable in 0 .. 2 {
1741
        let mut b = newBuilder();
1742
        let header = ptrType(SLICEC, false, mutable == 1, false);
1743
        addFn(&mut b, "f", &[param(0, header)], il::ValType::Void, &[retVoid()]);
1744
        let passed = args(&mut b, &[reg(0)]);
1745
        addFn(&mut b, "main", &[], il::ValType::Void, &[
1746
            reserve(0, SLICE), call(nil, il::ValType::Void, il::Val::FnAddr("f"), passed), retVoid()
1747
        ]);
1748
        let mut rule: ?verify::Rule = nil;
1749
        if mutable == 1 {
1750
            set rule = verify::Rule::View;
1751
        }
1752
        try expect(&mut b, rule);
1753
    }
1754
}
1755
1756
/// Return values and pointer stores use read-only views but keep writable views exact.
1757
@test unsafe fn readRightsUses() throws (testing::TestError) {
1758
    for mutable in 0 .. 2 {
1759
        let mut b = newBuilder();
1760
        let view = ptrType(SLICEC, true, mutable == 1, false);
1761
        let mut rule: ?verify::Rule = nil;
1762
        if mutable == 1 {
1763
            set rule = verify::Rule::View;
1764
        }
1765
        try checkIn(
1766
            &mut b, &[param(0, ptrType(SLICE, true, true, false))], view, &[ret(reg(0))], rule
1767
        );
1768
        let mut stored = newBuilder();
1769
        let cell = addLayout(&mut stored, 8, 8, &[ptrSlot(0, SLICEC, true, mutable == 1)]);
1770
        try checkIn(
1771
            &mut stored,
1772
            &[param(0, ptrType(SLICE, true, true, false))],
1773
            il::ValType::Void,
1774
            &[reserve(1, cell), storePtr(reg(0), 1, 0), retVoid()],
1775
            rule
1776
        );
1777
    }
1778
}
1779
1780
/// Rights-only reads preserve ownership and pointee identity.
1781
@test unsafe fn readRightsIdentity() throws (testing::TestError) {
1782
    try check(&[], &[reserve(0, CELL), reserve(1, LOCAL), blit(1, 0, LOCAL)], verify::Rule::View);
1783
    try check(&[], &[reserve(0, LOCAL), reserve(1, CELL), blit(1, 0, CELL)], verify::Rule::View);
1784
    try check(
1785
        &[], &[reserve(0, SLICE), reserve(1, BORROW), blit(1, 0, BORROW)], verify::Rule::View
1786
    );
1787
    try check(
1788
        &[], &[reserve(0, SLICE4), reserve(1, SLICEC), blit(1, 0, SLICEC)], verify::Rule::View
1789
    );
1790
    let mut b = newBuilder();
1791
    let other = addLayout(&mut b, 8, 8, &[ptrSlot(0, P1, true, false)]);
1792
    try checkIn(
1793
        &mut b,
1794
        &[],
1795
        il::ValType::Void,
1796
        &[reserve(0, CELL), reserve(1, other), blit(1, 0, other), retVoid()],
1797
        verify::Rule::View
1798
    );
1799
}
1800
1801
/// Nested objects, arrays, and union payloads preserve rights when read.
1802
@test unsafe fn nestedReadRights() throws (testing::TestError) {
1803
    for shape in 0 .. 3 {
1804
        let mut b = newBuilder();
1805
        let mut have: u32 = 0;
1806
        let mut want: u32 = 0;
1807
        if shape == 0 {
1808
            set have = addLayout(&mut b, 24, 8, &[subSlot(8, SLICE)]);
1809
            set want = addLayout(&mut b, 24, 8, &[subSlot(8, SLICEC)]);
1810
        } else if shape == 1 {
1811
            set have = addLayout(&mut b, 32, 8, &[
1812
                il::Slot {
1813
                    offset: 0, kind: il::SlotKind::Array { layout: SLICE, count: 2 }, regions: &[]
1814
                },
1815
            ]);
1816
            set want = addLayout(&mut b, 32, 8, &[
1817
                il::Slot {
1818
                    offset: 0, kind: il::SlotKind::Array { layout: SLICEC, count: 2 }, regions: &[]
1819
                },
1820
            ]);
1821
        } else {
1822
            let source = unionSlot(&mut b, 8, 24, &[variant(0, SLICE), variant(1, nil)]);
1823
            set have = addLayout(&mut b, 24, 8, &[source]);
1824
            let target = unionSlot(&mut b, 8, 24, &[variant(0, SLICEC), variant(1, nil)]);
1825
            set want = addLayout(&mut b, 24, 8, &[target]);
1826
        }
1827
        let t = try layout::build(&b.layouts[..], CONFIG, heap::over(&mut SCRATCH[..])) catch {
1828
            throw testing::TestError::Failed;
1829
        };
1830
        assert layout::holds(&t, have, 0, want);
1831
        assert not layout::holds(&t, want, 0, have);
1832
    }
1833
}
1834
1835
/// Structural reads retain each borrowed region position.
1836
@test unsafe fn nestedReadRegions() throws (testing::TestError) {
1837
    let mut b = newBuilder();
1838
    let shared = addLayout(&mut b, 8, 8, &[ptrSlot(0, P4, false, false)]);
1839
    let have = addLayout(&mut b, 16, 8, &[subSlot(8, LOCAL)]);
1840
    let want = addLayout(&mut b, 16, 8, &[subSlot(8, shared)]);
1841
    let t = try layout::build(&b.layouts[..], CONFIG, heap::over(&mut SCRATCH[..])) catch {
1842
        throw testing::TestError::Failed;
1843
    };
1844
    assert layout::holds(&t, have, 0, want);
1845
    assert layout::viewRegion(&t, have, 0, want, 0) == 0;
1846
    assert not layout::holds(&t, want, 0, have);
1847
}
1848
1849
/// A structural read cannot merge independent borrowed regions.
1850
@test unsafe fn readRegionIdentity() throws (testing::TestError) {
1851
    let mut b = newBuilder();
1852
    let source = addLayout(&mut b, 16, 8, &[
1853
        ptrSlot(0, P4, false, true), ptrSlot(8, P4, false, true)
1854
    ]);
1855
    let mut first = ptrSlot(0, P4, false, false);
1856
    let mut second = ptrSlot(8, P4, false, false);
1857
    set first.regions = &[0];
1858
    set second.regions = &[0];
1859
    let target = addLayout(&mut b, 16, 8, &[first, second]);
1860
    set b.layouts[target].regions = 2;
1861
    let t = try layout::build(&b.layouts[..], CONFIG, heap::over(&mut SCRATCH[..])) catch {
1862
        throw testing::TestError::Failed;
1863
    };
1864
    assert not layout::holds(&t, source, 0, target);
1865
}
1866
1867
/// A copy of borrowed slots stays in the frame, or in a target object when it
1868
/// holds no frame pointer.
1869
@test unsafe fn blitReferences() throws (testing::TestError) {
1870
    try check(&[], &[reserve(0, LOCAL), reserve(1, LOCAL), blit(1, 0, LOCAL)], nil);
1871
    try check(
1872
        &[param(0, ptrType(LOCAL, false, true, false))],
1873
        &[reserve(1, LOCAL), blit(0, 1, LOCAL)],
1874
        nil
1875
    );
1876
    try check(
1877
        &[param(0, ptrType(LOCAL, false, true, false))],
1878
        &[reserve(1, LOCAL), reserve(2, P4), storePtr(reg(2), 1, 0), blit(0, 1, LOCAL)],
1879
        verify::Rule::Return
1880
    );
1881
    try check(
1882
        &[param(0, ptrType(CELL, false, true, false))], &[reserve(1, CELL), blit(0, 1, CELL)], nil
1883
    );
1884
    // Plain bytes hold no pointer, so a destination of plain bytes can be anywhere.
1885
    try check(
1886
        &[param(0, ptrType(P8, false, true, false))], &[reserve(1, LOCAL), blit(0, 1, LOCAL)], nil
1887
    );
1888
}
1889
1890
////////////////////
1891
// Copy and Calls //
1892
////////////////////
1893
1894
/// A data symbol is a pointer to its data, writable unless the data is read-only.
1895
@test unsafe fn dataSymbol() throws (testing::TestError) {
1896
    let mut writable = newBuilder();
1897
    addData(&mut writable, "d", P4, false, &[]);
1898
1899
    try checkIn(
1900
        &mut writable,
1901
        &[],
1902
        il::ValType::Void,
1903
        &[
1904
            copy(0, il::Val::DataSym("d")), store(imm(1), 0, 0), copy(1, reg(0)), load(2, 1, 0),
1905
            retVoid(),
1906
        ],
1907
        nil
1908
    );
1909
    let mut readOnly = newBuilder();
1910
    addData(&mut readOnly, "d", P4, true, &[]);
1911
1912
    try checkIn(
1913
        &mut readOnly,
1914
        &[],
1915
        il::ValType::Void,
1916
        &[copy(0, il::Val::DataSym("d")), store(imm(1), 0, 0), retVoid()],
1917
        verify::Rule::Mutability
1918
    );
1919
    try check(&[], &[copy(0, il::Val::DataSym("d"))], verify::Rule::Symbol);
1920
    let mut asData = newBuilder();
1921
    addData(&mut asData, "d", P4, false, &[]);
1922
1923
    try checkIn(
1924
        &mut asData,
1925
        &[],
1926
        il::ValType::Void,
1927
        &[add(0, il::Val::DataSym("d"), imm(1)), load(1, 0, 0), retVoid()],
1928
        verify::Rule::Type
1929
    );
1930
    let mut passed = newBuilder();
1931
    addData(&mut passed, "d", P4, false, &[]);
1932
1933
    addFn(&mut passed, "f", &[param(0, ptrType(P4, true, true, false))], il::ValType::Void, &[
1934
        retVoid()
1935
    ]);
1936
    let values = args(&mut passed, &[il::Val::DataSym("d")]);
1937
    try checkIn(
1938
        &mut passed,
1939
        &[],
1940
        il::ValType::Void,
1941
        &[call(nil, il::ValType::Void, il::Val::FnAddr("f"), values), retVoid()],
1942
        verify::Rule::Type
1943
    );
1944
}
1945
1946
/// Check a call from `main`, which has parameters `params`, to `f`, which has parameters
1947
/// `callee` and passes `values`.
1948
unsafe fn callCase(
1949
    callee: &[il::Param], params: &[il::Param], values: &[il::Val], rule: ?verify::Rule
1950
) throws (testing::TestError) {
1951
    let mut b = newBuilder();
1952
    addFn(&mut b, "f", callee, il::ValType::Void, &[retVoid()]);
1953
    let passed = args(&mut b, values);
1954
    try checkIn(
1955
        &mut b,
1956
        params,
1957
        il::ValType::Void,
1958
        &[call(nil, il::ValType::Void, il::Val::FnAddr("f"), passed), retVoid()],
1959
        rule
1960
    );
1961
}
1962
1963
/// Arguments match the parameters of the callee.
1964
@test unsafe fn callArguments() throws (testing::TestError) {
1965
    let owned = param(0, ptrType(P4, true, true, false));
1966
    let callee = [owned];
1967
    try callCase(&callee[..], &[owned], &[reg(0)], nil);
1968
    try callCase(
1969
        &callee[..], &[param(0, ptrType(P4, false, true, false))], &[reg(0)], verify::Rule::Class
1970
    );
1971
    try callCase(
1972
        &callee[..],
1973
        &[param(0, ptrType(P4, true, false, false))],
1974
        &[reg(0)],
1975
        verify::Rule::Mutability
1976
    );
1977
    try callCase(
1978
        &callee[..], &[param(0, ptrType(P4, true, true, true))], &[reg(0)], verify::Rule::Null
1979
    );
1980
    try callCase(&callee[..], &[], &[imm(0)], verify::Rule::Null);
1981
    try callCase(&callee[..], &[], &[il::Val::Undef], verify::Rule::Type);
1982
    try callCase(&[param(0, ptrType(P4, true, true, true))], &[], &[imm(0)], nil);
1983
    try callCase(
1984
        &callee[..], &[param(0, ptrType(CELL, true, true, false))], &[reg(0)], verify::Rule::View
1985
    );
1986
    try callCase(&callee[..], &[owned], &[reg(0), reg(0)], verify::Rule::Arity);
1987
    try callCase(&[param(0, dataType())], &[owned], &[reg(0)], nil);
1988
}
1989
1990
/// The callee is a function of the program, and the result has its type.
1991
@test unsafe fn callTargets() throws (testing::TestError) {
1992
    try check(
1993
        &[],
1994
        &[call(nil, il::ValType::Void, il::Val::FnAddr("missing"), none())],
1995
        verify::Rule::Symbol
1996
    );
1997
    let mut external = newBuilder();
1998
    addExtern(&mut external, "e", &[], il::ValType::Void);
1999
    try checkIn(
2000
        &mut external,
2001
        &[],
2002
        il::ValType::Void,
2003
        &[call(nil, il::ValType::Void, il::Val::FnAddr("e"), none()), retVoid()],
2004
        verify::Rule::Symbol
2005
    );
2006
    try check(&[], &[call(nil,          il::ValType::Void, imm(8), none())], verify::Rule::Call);
2007
    try check(&[oneData()], &[call(nil, il::ValType::Void, reg(0), none())], verify::Rule::Call);
2008
    let mut result = newBuilder();
2009
    addFn(&mut result, "f", &[], dataType(), &[ret(imm(1))]);
2010
    try checkIn(
2011
        &mut result,
2012
        &[],
2013
        il::ValType::Void,
2014
        &[call(nil, il::ValType::Void, il::Val::FnAddr("f"), none()), retVoid()],
2015
        verify::Rule::Call
2016
    );
2017
    let mut void = newBuilder();
2018
    addFn(&mut void, "f", &[], il::ValType::Void, &[retVoid()]);
2019
    try checkIn(
2020
        &mut void,
2021
        &[],
2022
        il::ValType::Void,
2023
        &[call(1, il::ValType::Void, il::Val::FnAddr("f"), none()), retVoid()],
2024
        verify::Rule::Call
2025
    );
2026
    let mut value = newBuilder();
2027
    addFn(&mut value, "f", &[], dataType(), &[ret(imm(1))]);
2028
    try checkIn(
2029
        &mut value,
2030
        &[],
2031
        il::ValType::Void,
2032
        &[call(1, dataType(), il::Val::FnAddr("f"), none()), add(2, reg(1), imm(1)), retVoid()],
2033
        nil
2034
    );
2035
    let mut discarded = newBuilder();
2036
    addFn(&mut discarded, "f", &[], dataType(), &[ret(imm(1))]);
2037
    try checkIn(
2038
        &mut discarded,
2039
        &[],
2040
        il::ValType::Void,
2041
        &[call(nil, dataType(), il::Val::FnAddr("f"), none()), retVoid()],
2042
        nil
2043
    );
2044
}
2045
2046
/// A call returns a pointer of the declared type.
2047
@test unsafe fn callResult() throws (testing::TestError) {
2048
    let pointer = ptrType(P4, true, true, false);
2049
    let mut ok = newBuilder();
2050
    addFn(&mut ok, "f", &[param(0, pointer)], pointer, &[ret(reg(0))]);
2051
    let one = args(&mut ok, &[reg(0)]);
2052
    try checkIn(
2053
        &mut ok,
2054
        &[param(0, pointer)],
2055
        il::ValType::Void,
2056
        &[call(1, pointer, il::Val::FnAddr("f"), one), load(2, 1, 0), retVoid()],
2057
        nil
2058
    );
2059
    let mut maybe = newBuilder();
2060
    addFn(&mut maybe, "f", &[param(0, pointer)], ptrType(P4, true, true, true), &[ret(reg(0))]);
2061
    let two = args(&mut maybe, &[reg(0)]);
2062
    try checkIn(
2063
        &mut maybe,
2064
        &[param(0, pointer)],
2065
        il::ValType::Void,
2066
        &[
2067
            call(1, ptrType(P4, true, true, true), il::Val::FnAddr("f"), two), load(2, 1, 0),
2068
            retVoid(),
2069
        ],
2070
        verify::Rule::Null
2071
    );
2072
}
2073
2074
//////////////
2075
// Returns  //
2076
//////////////
2077
2078
/// A function returns the value of its return type, and only owned pointers.
2079
@test unsafe fn returns() throws (testing::TestError) {
2080
    let pointer = ptrType(P4, true, true, false);
2081
    try checkBody(&[param(0,                 pointer)], pointer, &[ret(reg(0))], nil);
2082
    try checkBody(&[], pointer, &[reserve(0, P4), ret(reg(0))], verify::Rule::Class);
2083
    try checkBody(
2084
        &[param(0, ptrType(P4, false, true, false))],
2085
        ptrType(P4, false, true, false),
2086
        &[ret(reg(0))],
2087
        verify::Rule::Return
2088
    );
2089
    try checkBody(
2090
        &[param(0, ptrType(P4, true, true, true))], pointer, &[ret(reg(0))], verify::Rule::Null
2091
    );
2092
    try checkBody(&[], dataType(), &[retVoid()], verify::Rule::Return);
2093
    try checkBody(&[], il::ValType::Void, &[ret(imm(1))], verify::Rule::Type);
2094
    try checkBody(&[param(0, pointer)], dataType(), &[ret(reg(0))], nil);
2095
    try checkBody(&[oneData()], pointer, &[ret(reg(0))], verify::Rule::Type);
2096
    try checkBody(&[], ptrType(P4, true, true, true), &[ret(imm(0))], nil);
2097
}
2098
2099
/// Check `main`, a function of one block whose result borrows from parameter `borrow`.
2100
unsafe fn checkBorrowing(
2101
    params: &[il::Param],
2102
    ret: il::ValType,
2103
    instrs: &[il::Instr],
2104
    borrow: ?u32,
2105
    rule: ?verify::Rule
2106
) throws (testing::TestError) {
2107
    let mut b = newBuilder();
2108
    let one = block(&mut b, &[], instrs);
2109
    addBorrowing(&mut b, "main", params, ret, &[one], borrow);
2110
    try expect(&mut b, rule);
2111
}
2112
2113
/// A function returns a non-owning pointer only when its result borrows from a pointer
2114
/// parameter.
2115
@test unsafe fn borrowedReturnSignature() throws (testing::TestError) {
2116
    let borrowed = ptrType(P4, false, false, false);
2117
    let owned = ptrType(P4, true, false, false);
2118
    try checkBorrowing(&[param(0, borrowed)], borrowed, &[ret(reg(0))], 0, nil);
2119
    try checkBorrowing(&[param(0, borrowed)], owned, &[ret(reg(0))], 0, verify::Rule::Return);
2120
    try checkBorrowing(&[oneData()], borrowed, &[ret(reg(0))], 0, verify::Rule::Return);
2121
    try checkBorrowing(&[param(0, borrowed)], borrowed, &[ret(reg(0))], 1, verify::Rule::Return);
2122
}
2123
2124
/// A borrowed result is reached only from its parameter: not from another parameter or
2125
/// from an object of the frame.
2126
@test unsafe fn borrowedReturnSource() throws (testing::TestError) {
2127
    let borrowed = ptrType(P4, false, false, false);
2128
    let both = [param(0, borrowed), param(1, borrowed)];
2129
    try checkBorrowing(&both[..], borrowed, &[field(2, 0, 0), ret(reg(2))], 0, nil);
2130
    try checkBorrowing(
2131
        &both[..], borrowed, &[field(2, 1, 0), ret(reg(2))], 0, verify::Rule::Return
2132
    );
2133
    try checkBorrowing(&both[..], borrowed, &[ret(reg(1))], 0, verify::Rule::Return);
2134
    try checkBorrowing(&both[..], borrowed, &[ret(reg(1))], 1, nil);
2135
    try checkBorrowing(
2136
        &[param(0, borrowed)],
2137
        ptrType(P4, false, true, false),
2138
        &[reserve(1, P4), ret(reg(1))],
2139
        0,
2140
        verify::Rule::Return
2141
    );
2142
}
2143
2144
/// A foreign pointer reaches a return through a block argument.
2145
@test unsafe fn borrowedReturnMerge() throws (testing::TestError) {
2146
    let borrowed = ptrType(P4, false, false, false);
2147
    let params = [param(0, borrowed), param(1, borrowed), param(2, dataType())];
2148
    for source in 0 .. 2 {
2149
        let mut b = newBuilder();
2150
        let first = args(&mut b, &[reg(0)]);
2151
        let second = args(&mut b, &[reg(source)]);
2152
        let blocks = [
2153
            block(&mut b, &[], &[br(reg(2), 1, 2)]),
2154
            block(&mut b, &[], &[jmp(3, first)]),
2155
            block(&mut b, &[], &[jmp(3, second)]),
2156
            block(&mut b, &[param(3, borrowed)], &[ret(reg(3))]),
2157
        ];
2158
        addBorrowing(&mut b, "main", &params[..], borrowed, &blocks[..], 0);
2159
        if source == 0 {
2160
            try accepted(&mut b);
2161
        } else {
2162
            try rejected(&mut b, verify::Rule::Return);
2163
        }
2164
    }
2165
}
2166
2167
/// The borrowed result of a call is reached from its borrowed argument.
2168
@test unsafe fn borrowedReturnCall() throws (testing::TestError) {
2169
    let borrowed = ptrType(P4, false, false, false);
2170
    let params = [param(0, borrowed), param(1, borrowed)];
2171
    for source in 0 .. 2 {
2172
        let mut b = newBuilder();
2173
        let callee = block(&mut b, &[], &[ret(reg(0))]);
2174
        addBorrowing(&mut b, "f", &[param(0, borrowed)], borrowed, &[callee], 0);
2175
        let passed = args(&mut b, &[reg(source)]);
2176
        let body = block(&mut b, &[], &[
2177
            call(2, borrowed, il::Val::FnAddr("f"), passed), ret(reg(2))
2178
        ]);
2179
        addBorrowing(&mut b, "main", &params[..], borrowed, &[body], 0);
2180
        if source == 0 {
2181
            try accepted(&mut b);
2182
        } else {
2183
            try rejected(&mut b, verify::Rule::Return);
2184
        }
2185
    }
2186
}
2187
2188
/// A borrowed result that returns nothing is written to a writable non-owning buffer, the
2189
/// first parameter, apart from the borrowed one.
2190
@test unsafe fn bufferedReturnSignature() throws (testing::TestError) {
2191
    let buffer = ptrType(BORROW, false, true, false);
2192
    let borrowed = ptrType(BORROW, false, false, false);
2193
    let void = il::ValType::Void;
2194
    let both = [param(0, buffer), param(1, borrowed)];
2195
    try checkBorrowing(&both[..], void, &[retVoid()], 1, nil);
2196
    try checkBorrowing(&both[..], void, &[retVoid()], 0, verify::Rule::Return);
2197
    try checkBorrowing(
2198
        &[param(0, borrowed), param(1, borrowed)], void, &[retVoid()], 1, verify::Rule::Return
2199
    );
2200
    try checkBorrowing(
2201
        &[param(0, ptrType(P16, true, true, false)), param(1, borrowed)],
2202
        void,
2203
        &[retVoid()],
2204
        1,
2205
        verify::Rule::Return
2206
    );
2207
    try checkBorrowing(
2208
        &[oneData(), param(1, borrowed)], void, &[retVoid()], 1, verify::Rule::Return
2209
    );
2210
}
2211
2212
/// A buffered result accepts only its permitted sources. Separate local objects
2213
/// retain their own content facts.
2214
@test unsafe fn bufferedReturnSource() throws (testing::TestError) {
2215
    let params = [
2216
        param(0, ptrType(BORROW, false, true, false)),
2217
        param(1, ptrType(BORROW, false, false, false)),
2218
        param(2, ptrType(BORROW, false, false, false)),
2219
    ];
2220
    try checkBorrowing(
2221
        &params[..], il::ValType::Void, &[blit(0, 1, BORROW), retVoid()], 1, nil
2222
    );
2223
    try checkBorrowing(
2224
        &params[..],
2225
        il::ValType::Void,
2226
        &[reserve(3, BORROW), sliceSub(3, 1, P1), blit(0, 3, BORROW), retVoid()],
2227
        1,
2228
        nil
2229
    );
2230
    try checkBorrowing(
2231
        &params[..], il::ValType::Void, &[blit(0, 2, BORROW), retVoid()], 1, verify::Rule::Return
2232
    );
2233
    try checkBorrowing(
2234
        &params[..],
2235
        il::ValType::Void,
2236
        &[reserve(3, BORROW), sliceSub(3, 2, P1), blit(0, 3, BORROW), retVoid()],
2237
        1,
2238
        verify::Rule::Return
2239
    );
2240
    try checkBorrowing(
2241
        &params[..],
2242
        il::ValType::Void,
2243
        &[reserve(3, P4), sliceNew(0, reg(3), P1, 4), retVoid()],
2244
        1,
2245
        verify::Rule::Return
2246
    );
2247
    try checkBorrowing(
2248
        &params[..],
2249
        il::ValType::Void,
2250
        &[reserve(3, BORROW), blit(3, 2, BORROW), sliceSub(0, 1, P1), retVoid()],
2251
        1,
2252
        nil
2253
    );
2254
}
2255
2256
/// The caller of a buffered result passes an object of its frame, and the buffer holds
2257
/// what its borrowed argument reaches.
2258
@test unsafe fn bufferedReturnCall() throws (testing::TestError) {
2259
    let buffer = ptrType(BORROW, false, true, false);
2260
    let borrowed = ptrType(BORROW, false, false, false);
2261
    let void = il::ValType::Void;
2262
    let params = [param(0, buffer), param(1, borrowed), param(2, borrowed)];
2263
    // The buffer and the borrowed argument of each call.
2264
    let passes: [[u32; 2]; 3] = [[3, 1], [0, 1], [3, 2]];
2265
    for k in 0 .. passes.len {
2266
        let mut b = newBuilder();
2267
        let callee = block(&mut b, &[], &[blit(0, 1, BORROW), retVoid()]);
2268
        addBorrowing(&mut b, "f", &[param(0, buffer), param(1, borrowed)], void, &[callee], 1);
2269
        let passed = args(&mut b, &[reg(passes[k][0]), reg(passes[k][1])]);
2270
        let body = block(
2271
            &mut b,
2272
            &[],
2273
            &[
2274
                reserve(3, BORROW),
2275
                call(nil,  void, il::Val::FnAddr("f"), passed),
2276
                blit(0,    3, BORROW),
2277
                retVoid(),
2278
            ]
2279
        );
2280
        addBorrowing(&mut b, "main", &params[..], void, &[body], 1);
2281
        if k < 2 {
2282
            try accepted(&mut b);
2283
        } else {
2284
            try rejected(&mut b, verify::Rule::Return);
2285
        }
2286
    }
2287
    let mut outside = newBuilder();
2288
    let callee = block(&mut outside, &[], &[blit(0, 1, BORROW), retVoid()]);
2289
    addBorrowing(&mut outside, "f", &[param(0, buffer), param(1, borrowed)], void, &[callee], 1);
2290
    let passed = args(&mut outside, &[reg(0), reg(0)]);
2291
    addFn(&mut outside, "main", &[param(0, buffer)], void, &[
2292
        call(nil, void, il::Val::FnAddr("f"), passed), retVoid()
2293
    ]);
2294
    // The callee stores the address of the target object into its own region.
2295
    try rejected(&mut outside, verify::Rule::Return);
2296
}
2297
2298
/// A borrowed slice passed by a copied header keeps the source of its elements.
2299
@test unsafe fn bufferedReturnCopiedArgument() throws (testing::TestError) {
2300
    let buffer = ptrType(BORROW, false, true, false);
2301
    let borrowed = ptrType(BORROW, false, false, false);
2302
    let void = il::ValType::Void;
2303
    let mut b = newBuilder();
2304
    let callee = block(&mut b, &[], &[blit(0, 1, BORROW), retVoid()]);
2305
    addBorrowingContract(
2306
        &mut b, "f", &[param(0, buffer), param(1, borrowed)], void, &[callee], 1, true
2307
    );
2308
    let passed = args(&mut b, &[reg(2), reg(3)]);
2309
    let body = block(
2310
        &mut b,
2311
        &[],
2312
        &[
2313
            reserve(2, BORROW),
2314
            reserve(3, BORROW),
2315
            blit(3,    1, BORROW),
2316
            call(nil,  void, il::Val::FnAddr("f"), passed),
2317
            blit(0,    2, BORROW),
2318
            retVoid(),
2319
        ]
2320
    );
2321
    addBorrowing(&mut b, "main", &[param(0, buffer), param(1, borrowed)], void, &[body], 1);
2322
    try accepted(&mut b);
2323
}
2324
2325
/// Contents borrows accept stored pointers, and reject the container address.
2326
@test unsafe fn contentsBorrowSource() throws (testing::TestError) {
2327
    let container = ptrType(LOCAL, false, false, false);
2328
    let result = ptrType(P4, false, true, false);
2329
    let params = [param(0, container), param(1, container)];
2330
    for source in 0 .. 2 {
2331
        let mut b = newBuilder();
2332
        let body = block(&mut b, &[], &[
2333
            field(2, source, 0), loadPtr(3, 2, 0), ret(reg(3))
2334
        ]);
2335
        addBorrowingContract(&mut b, "main", &params[..], result, &[body], 0, true);
2336
        let mut rule: ?verify::Rule = nil;
2337
        if source <> 0 {
2338
            set rule = verify::Rule::Return;
2339
        }
2340
        try expect(&mut b, rule);
2341
    }
2342
    let mut address = newBuilder();
2343
    let body = block(&mut address, &[], &[ret(reg(0))]);
2344
    addBorrowingContract(&mut address, "main", &[param(0, container)], container, &[body], 0, true);
2345
    try rejected(&mut address, verify::Rule::Return);
2346
}
2347
2348
/// A merged container retains every input dependency of its contents.
2349
@test unsafe fn contentsBorrowMerge() throws (testing::TestError) {
2350
    let container = ptrType(LOCAL, false, false, false);
2351
    let result = ptrType(P4, false, true, false);
2352
    for source in 0 .. 2 {
2353
        let mut b = newBuilder();
2354
        let first = args(&mut b, &[reg(0)]);
2355
        let second = args(&mut b, &[reg(source)]);
2356
        let blocks = [
2357
            block(&mut b, &[], &[br(reg(2), 1, 2)]),
2358
            block(&mut b, &[], &[jmp(3, first)]),
2359
            block(&mut b, &[], &[jmp(3, second)]),
2360
            block(&mut b, &[param(3, container)], &[loadPtr(4, 3, 0), ret(reg(4))]),
2361
        ];
2362
        let params = [param(0, container), param(1, container), param(2, dataType())];
2363
        addBorrowingContract(&mut b, "main", &params[..], result, &blocks[..], 0, true);
2364
        let mut rule: ?verify::Rule = nil;
2365
        if source <> 0 {
2366
            set rule = verify::Rule::Return;
2367
        }
2368
        try expect(&mut b, rule);
2369
    }
2370
}
2371
2372
/// Calls cannot return pointers from a local slice base or another source.
2373
@test unsafe fn contentsBorrowCallSources() throws (testing::TestError) {
2374
    let buffer = ptrType(BORROW, false, true, false);
2375
    let borrowed = ptrType(BORROW, false, false, false);
2376
    let void = il::ValType::Void;
2377
    for source in 0 .. 3 {
2378
        let mut b = newBuilder();
2379
        let callee = block(&mut b, &[], &[blit(0, 1, BORROW), retVoid()]);
2380
        addBorrowingContract(
2381
            &mut b, "f", &[param(0, buffer), param(1, borrowed)], void, &[callee], 1, true
2382
        );
2383
        let passed = args(&mut b, &[reg(3), reg(4)]);
2384
        let init = blit(4, source + 1, BORROW)
2385
            if source < 2
2386
            else sliceNew(4, reg(5), P1, 4);
2387
        let body = block(
2388
            &mut b,
2389
            &[],
2390
            &[
2391
                reserve(3, BORROW), reserve(4, BORROW), reserve(5, P4), init,
2392
                call(nil,  void, il::Val::FnAddr("f"), passed), blit(0, 3, BORROW), retVoid(),
2393
            ]
2394
        );
2395
        let params = [param(0, buffer), param(1, borrowed), param(2, borrowed)];
2396
        addBorrowingContract(&mut b, "main", &params[..], void, &[body], 1, true);
2397
        let mut rule: ?verify::Rule = nil;
2398
        if source <> 0 {
2399
            set rule = verify::Rule::Return;
2400
        }
2401
        try expect(&mut b, rule);
2402
    }
2403
}
2404
2405
/// An indirect contents contract must match the stored function's contract.
2406
@test unsafe fn contentsBorrowIndirectContract() throws (testing::TestError) {
2407
    let container = ptrType(LOCAL, false, false, false);
2408
    let result = ptrType(P4, false, true, false);
2409
    for mode in 0 .. 2 {
2410
        let mut b = newBuilder();
2411
        let sig = addSignature(&mut b, &[container], result);
2412
        let params = b.signatures[sig].params;
2413
        set b.signatures[sig] = il::Signature {
2414
            params,
2415
            ret: result,
2416
            borrows: &[il::Borrow { target: nil, result: 0, param: 0, source: 0 }],
2417
        };
2418
        let cell = addLayout(&mut b, 8, 8, &[
2419
            il::Slot { offset: 0, kind: il::SlotKind::Fn(sig), regions: &[] }
2420
        ]);
2421
        let callee = block(&mut b, &[], &[loadPtr(1, 0, 0), ret(reg(1))]);
2422
        addBorrowingContract(
2423
            &mut b, "f", &[param(0, container)], result, &[callee], 0, mode == 0
2424
        );
2425
        let passed = args(&mut b, &[reg(1)]);
2426
        let body = block(
2427
            &mut b,
2428
            &[],
2429
            &[
2430
                reserve(1,                     LOCAL), blit(1, 0, LOCAL), reserve(2, cell),
2431
                storePtr(il::Val::FnAddr("f"), 2, 0), loadPtr(3, 2, 0),
2432
                call(4,                        result, reg(3), passed), ret(reg(4)),
2433
            ]
2434
        );
2435
        addBorrowingContract(&mut b, "main", &[param(0, container)], result, &[body], 0, true);
2436
        let mut rule: ?verify::Rule = nil;
2437
        if mode <> 0 {
2438
            set rule = verify::Rule::Type;
2439
        }
2440
        try expect(&mut b, rule);
2441
    }
2442
}
2443
2444
/// A join permits borrowed stores only when every edge supplies frame storage.
2445
@test unsafe fn borrowedFrameMerge() throws (testing::TestError) {
2446
    let buffer = ptrType(LOCAL, false, true, false);
2447
    let source = ptrType(P4, false, true, false);
2448
    for mixed in 0 .. 2 {
2449
        let mut b = newBuilder();
2450
        let local = args(&mut b, &[reg(4)]);
2451
        let other = args(&mut b, &[reg(4) if mixed == 0 else reg(2)]);
2452
        let blocks = [
2453
            block(&mut b, &[], &[reserve(4, LOCAL), br(reg(3), 1, 2)]),
2454
            block(&mut b, &[], &[jmp(3, local)]),
2455
            block(&mut b, &[], &[jmp(3, other)]),
2456
            block(&mut b, &[param(5, buffer)], &[
2457
                storePtr(reg(1), 5, 0), blit(0, 5, LOCAL), retVoid()
2458
            ]),
2459
        ];
2460
        let params = [param(0, buffer), param(1, source), param(2, buffer), param(3, dataType())];
2461
        addBorrowing(&mut b, "main", &params[..], il::ValType::Void, &blocks[..], 1);
2462
        let mut rule: ?verify::Rule = nil;
2463
        if mixed <> 0 {
2464
            set rule = verify::Rule::Class;
2465
        }
2466
        try expect(&mut b, rule);
2467
    }
2468
}
2469
2470
/// An owning pointer to objects with references carries their regions: a result
2471
/// that holds one needs sources for them, and only objects that can hold
2472
/// references take one.
2473
@test unsafe fn ownedLayouts() throws (testing::TestError) {
2474
    let owned = ptrType(LOCAL, true, true, false);
2475
    let mut slot = newBuilder();
2476
    addLayout(&mut slot, 8, 8, &[ptrSlot(0, LOCAL, true, true)]);
2477
    addFn(&mut slot, "f", &[param(0, owned)], il::ValType::Void, &[retVoid()]);
2478
    try accepted(&mut slot);
2479
    let mut unsourced = newBuilder();
2480
    addFn(&mut unsourced, "f", &[param(0, owned)], owned, &[ret(reg(0))]);
2481
    try rejected(&mut unsourced, verify::Rule::Return);
2482
    let sources = [il::Borrow { target: nil, result: 0, param: 0, source: 0 }];
2483
    let mut sourced = newBuilder();
2484
    let returned = block(&mut sourced, &[], &[ret(reg(0))]);
2485
    addSources(&mut sourced, "f", &[param(0, owned)], owned, &[returned], &sources[..]);
2486
    try accepted(&mut sourced);
2487
    // A frame pointer stored into the owned object reaches the region of the result.
2488
    let mut framed = newBuilder();
2489
    let leaked = block(&mut framed, &[], &[reserve(1, P4), storePtr(reg(1), 0, 0), ret(reg(0))]);
2490
    addSources(&mut framed, "f", &[param(0, owned)], owned, &[leaked], &sources[..]);
2491
    try rejected(&mut framed, verify::Rule::Return);
2492
}
2493
2494
/////////////////////
2495
// Function values //
2496
/////////////////////
2497
2498
/// Add the functions that the function value tests refer to: `f` takes and returns data,
2499
/// and `g` takes and returns nothing.
2500
unsafe fn addTargets(b: &mut Builder) {
2501
    addFn(b, "f", &[oneData()], dataType(), &[ret(reg(0))]);
2502
    addFn(b, "g", &[], il::ValType::Void, &[retVoid()]);
2503
}
2504
2505
/// A function value is called through a register that is not null, with the types of
2506
/// its signature.
2507
@test unsafe fn indirectCall() throws (testing::TestError) {
2508
    let mut ok = newBuilder();
2509
    addTargets(&mut ok);
2510
    let one1 = args(&mut ok, &[imm(1)]);
2511
    try checkIn(
2512
        &mut ok,
2513
        &[],
2514
        il::ValType::Void,
2515
        &[
2516
            reserve(0, FNCELL), copy(1, il::Val::FnAddr("f")), storePtr(reg(1), 0, 0),
2517
            loadPtr(3, 0, 0), call(4, dataType(), reg(3), one1), retVoid(),
2518
        ],
2519
        nil
2520
    );
2521
2522
    let mut unchecked = newBuilder();
2523
    addTargets(&mut unchecked);
2524
    let one2 = args(&mut unchecked, &[imm(1)]);
2525
    try checkIn(
2526
        &mut unchecked,
2527
        &[],
2528
        il::ValType::Void,
2529
        &[
2530
            reserve(0, FNCELL), loadNullablePtr(2, 0, 0), call(4, dataType(), reg(2), one2),
2531
            retVoid(),
2532
        ],
2533
        verify::Rule::Null
2534
    );
2535
2536
    let mut wrongSlot = newBuilder();
2537
    addTargets(&mut wrongSlot);
2538
    try checkIn(
2539
        &mut wrongSlot,
2540
        &[],
2541
        il::ValType::Void,
2542
        &[reserve(0, FNCELL), copy(1, il::Val::FnAddr("g")), storePtr(reg(1), 0, 0), retVoid()],
2543
        verify::Rule::Type
2544
    );
2545
2546
    let mut stored = newBuilder();
2547
    addTargets(&mut stored);
2548
    try checkIn(
2549
        &mut stored,
2550
        &[],
2551
        il::ValType::Void,
2552
        &[reserve(0, FNCELL1), copy(1, il::Val::FnAddr("g")), storePtr(reg(1), 0, 0), retVoid()],
2553
        nil
2554
    );
2555
2556
    let mut direct = newBuilder();
2557
    addTargets(&mut direct);
2558
    try checkIn(
2559
        &mut direct,
2560
        &[],
2561
        il::ValType::Void,
2562
        &[reserve(0, FNCELL1), storePtr(il::Val::FnAddr("g"), 0, 0), retVoid()],
2563
        nil
2564
    );
2565
2566
    let mut zero = newBuilder();
2567
    addTargets(&mut zero);
2568
    try checkIn(
2569
        &mut zero,
2570
        &[],
2571
        il::ValType::Void,
2572
        &[reserve(0, FNCELL1), storePtr(imm(0), 0, 0), retVoid()],
2573
        nil
2574
    );
2575
2576
    let mut result = newBuilder();
2577
    addTargets(&mut result);
2578
    let one3 = args(&mut result, &[imm(1)]);
2579
    try checkIn(
2580
        &mut result,
2581
        &[],
2582
        il::ValType::Void,
2583
        &[
2584
            reserve(0, FNCELL), copy(1, il::Val::FnAddr("f")), storePtr(reg(1), 0, 0),
2585
            loadPtr(3, 0, 0), call(4, il::ValType::Void, reg(3), one3), retVoid(),
2586
        ],
2587
        verify::Rule::Call
2588
    );
2589
2590
    let mut count = newBuilder();
2591
    addTargets(&mut count);
2592
    try checkIn(
2593
        &mut count,
2594
        &[],
2595
        il::ValType::Void,
2596
        &[
2597
            reserve(0, FNCELL), copy(1, il::Val::FnAddr("f")), storePtr(reg(1), 0, 0),
2598
            loadPtr(3, 0, 0), call(4, dataType(), reg(3), none()), retVoid(),
2599
        ],
2600
        verify::Rule::Arity
2601
    );
2602
2603
    let mut forged = newBuilder();
2604
    addTargets(&mut forged);
2605
    let one4 = args(&mut forged, &[imm(1)]);
2606
    try checkIn(
2607
        &mut forged,
2608
        &[],
2609
        il::ValType::Void,
2610
        &[reserve(0, P8), loadPtr(1, 0, 0), retVoid()],
2611
        verify::Rule::Slot
2612
    );
2613
    let _ = one4;
2614
}
2615
2616
/// A function value parameter has the signature of the function that is passed.
2617
@test unsafe fn functionArgument() throws (testing::TestError) {
2618
    let mut ok = newBuilder();
2619
    addTargets(&mut ok);
2620
    addFn(&mut ok, "h", &[param(0, il::ValType::Fn(SIG_DATA))], il::ValType::Void, &[retVoid()]);
2621
    let f = args(&mut ok, &[il::Val::FnAddr("f")]);
2622
    try checkIn(
2623
        &mut ok,
2624
        &[],
2625
        il::ValType::Void,
2626
        &[call(nil, il::ValType::Void, il::Val::FnAddr("h"), f), retVoid()],
2627
        nil
2628
    );
2629
2630
    let mut wrong = newBuilder();
2631
    addTargets(&mut wrong);
2632
    addFn(&mut wrong, "h", &[param(0, il::ValType::Fn(SIG_DATA))], il::ValType::Void, &[retVoid()]);
2633
    let g = args(&mut wrong, &[il::Val::FnAddr("g")]);
2634
    try checkIn(
2635
        &mut wrong,
2636
        &[],
2637
        il::ValType::Void,
2638
        &[call(nil, il::ValType::Void, il::Val::FnAddr("h"), g), retVoid()],
2639
        verify::Rule::Type
2640
    );
2641
2642
    let mut loaded = newBuilder();
2643
    addTargets(&mut loaded);
2644
    addFn(&mut loaded, "h", &[param(0, il::ValType::Fn(SIG_DATA))], il::ValType::Void, &[
2645
        retVoid()
2646
    ]);
2647
    let value = args(&mut loaded, &[reg(2)]);
2648
    try checkIn(
2649
        &mut loaded,
2650
        &[],
2651
        il::ValType::Void,
2652
        &[
2653
            reserve(0, FNCELL), loadNullablePtr(2, 0, 0),
2654
            call(nil,  il::ValType::Void, il::Val::FnAddr("h"), value), retVoid(),
2655
        ],
2656
        verify::Rule::Null
2657
    );
2658
2659
    let mut number = newBuilder();
2660
    addTargets(&mut number);
2661
    addFn(&mut number, "h", &[param(0, il::ValType::Fn(SIG_DATA))], il::ValType::Void, &[
2662
        retVoid()
2663
    ]);
2664
    let zero = args(&mut number, &[imm(0)]);
2665
    try checkIn(
2666
        &mut number,
2667
        &[],
2668
        il::ValType::Void,
2669
        &[call(nil, il::ValType::Void, il::Val::FnAddr("h"), zero), retVoid()],
2670
        verify::Rule::Type
2671
    );
2672
}
2673
2674
////////////
2675
// Symbols //
2676
////////////
2677
2678
/// Symbols are non-empty and unique across functions and data.
2679
@test unsafe fn symbolNames() throws (testing::TestError) {
2680
    let mut twice = newBuilder();
2681
    addFn(&mut twice, "f", &[], il::ValType::Void, &[retVoid()]);
2682
    addFn(&mut twice, "f", &[], il::ValType::Void, &[retVoid()]);
2683
    try rejected(&mut twice, verify::Rule::Symbol);
2684
    let mut empty = newBuilder();
2685
    addFn(&mut empty, "", &[], il::ValType::Void, &[retVoid()]);
2686
    try rejected(&mut empty, verify::Rule::Symbol);
2687
    let mut shared = newBuilder();
2688
    addFn(&mut shared, "f", &[], il::ValType::Void, &[retVoid()]);
2689
    addData(&mut shared, "f", P4, true, &[]);
2690
    try rejected(&mut shared, verify::Rule::Symbol);
2691
    let mut dataTwice = newBuilder();
2692
    addData(&mut dataTwice, "d", P4, true, &[]);
2693
    addData(&mut dataTwice, "d", P4, true, &[]);
2694
2695
    try rejected(&mut dataTwice, verify::Rule::Symbol);
2696
    let mut ok = newBuilder();
2697
    addFn(&mut ok, "f", &[], il::ValType::Void, &[retVoid()]);
2698
    addData(&mut ok, "d", P4, true, &[]);
2699
    try accepted(&mut ok);
2700
}
2701
2702
/// A function that is declared extern has no body, and no call or address refers to it.
2703
@test unsafe fn externFunctions() throws (testing::TestError) {
2704
    let mut ok = newBuilder();
2705
    addExtern(&mut ok, "e", &[oneData()], dataType());
2706
    try accepted(&mut ok);
2707
    let mut address = newBuilder();
2708
    addExtern(&mut address, "e", &[], il::ValType::Void);
2709
    try checkIn(
2710
        &mut address,
2711
        &[],
2712
        il::ValType::Void,
2713
        &[copy(0, il::Val::FnAddr("e")), retVoid()],
2714
        verify::Rule::Symbol
2715
    );
2716
}
2717
2718
////////////////////////
2719
// Control flow edges //
2720
////////////////////////
2721
2722
/// A switch passes arguments to every target.
2723
@test unsafe fn switchArguments() throws (testing::TestError) {
2724
    let mut b = newBuilder();
2725
    let one = args(&mut b, &[imm(1)]);
2726
    let two = args(&mut b, &[imm(2)]);
2727
    let sw = il::Instr::Switch {
2728
        val: reg(0), defaultTarget: 1, defaultArgs: one, cases: addCase(&mut b, 3, 2, two)
2729
    };
2730
    let blocks = [
2731
        block(&mut b, &[], &[sw]),
2732
        block(&mut b, &[param(1, dataType())], &[retVoid()]),
2733
        block(&mut b, &[param(2, dataType())], &[retVoid()]),
2734
    ];
2735
    addBlocks(&mut b, "main", &[oneData()], il::ValType::Void, &blocks[..]);
2736
    try accepted(&mut b);
2737
2738
    let mut bad = newBuilder();
2739
    let first = args(&mut bad, &[imm(1)]);
2740
    let swBad = il::Instr::Switch {
2741
        val: reg(0), defaultTarget: 1, defaultArgs: first, cases: addCase(&mut bad, 3, 2, none())
2742
    };
2743
    let blocksBad = [
2744
        block(&mut bad, &[], &[swBad]),
2745
        block(&mut bad, &[param(1, dataType())], &[retVoid()]),
2746
        block(&mut bad, &[param(2, dataType())], &[retVoid()]),
2747
    ];
2748
    addBlocks(&mut bad, "main", &[oneData()], il::ValType::Void, &blocksBad[..]);
2749
    try rejected(&mut bad, verify::Rule::Arity);
2750
}
2751
2752
/////////////////
2753
// Data        //
2754
/////////////////
2755
2756
/// A data item of a typed number.
2757
fn number(typ: il::Type, val: i64) -> il::DataValue {
2758
    return il::DataValue { item: il::DataItem::Val { typ, val }, count: 1 };
2759
}
2760
2761
/// A data item of the address of a symbol.
2762
fn symbol(name: *[u8]) -> il::DataValue {
2763
    return il::DataValue { item: il::DataItem::Sym(name), count: 1 };
2764
}
2765
2766
/// A data item of the address of a function.
2767
fn function(name: *[u8]) -> il::DataValue {
2768
    return il::DataValue { item: il::DataItem::Fn(name), count: 1 };
2769
}
2770
2771
/// A data item repeated `count` times.
2772
fn repeat(item: il::DataItem, count: u32) -> il::DataValue {
2773
    return il::DataValue { item, count };
2774
}
2775
2776
/// Check the program that holds only the data "d" of `layout` with the initializer `values`:
2777
/// it is accepted when `rule` is nil, or rejected for violating `rule`.
2778
unsafe fn dataCase(layout: u32, readOnly: bool, values: &[il::DataValue], rule: ?verify::Rule)
2779
    throws (testing::TestError)
2780
{
2781
    let mut b = newBuilder();
2782
    addData(&mut b, "d", layout, readOnly, values);
2783
    try expect(&mut b, rule);
2784
}
2785
2786
/// Check as [`dataCase`] the program in which data `target` of layout `targetLayout` precedes
2787
/// "d". The data `target` is read-only when `targetReadOnly` is set.
2788
unsafe fn dataCaseAfter(
2789
    target: *[u8],
2790
    targetLayout: u32,
2791
    targetReadOnly: bool,
2792
    layout: u32,
2793
    readOnly: bool,
2794
    values: &[il::DataValue],
2795
    rule: ?verify::Rule
2796
) throws (testing::TestError) {
2797
    let mut b = newBuilder();
2798
    addData(&mut b, target, targetLayout, targetReadOnly, &[]);
2799
    addData(&mut b, "d", layout, readOnly, values);
2800
    try expect(&mut b, rule);
2801
}
2802
2803
/// A slice slot that is initialized to point to `target` with a length.
2804
@test unsafe fn sliceData() throws (testing::TestError) {
2805
    try dataCaseAfter(
2806
        "bytes",
2807
        P16,
2808
        true,
2809
        SLICEC,
2810
        true,
2811
        &[symbol("bytes"), number(il::Type::W32, 4), number(il::Type::W32, 16)],
2812
        verify::Rule::Data
2813
    );
2814
    try dataCaseAfter(
2815
        "bytes",
2816
        P16,
2817
        true,
2818
        SLICEC,
2819
        true,
2820
        &[symbol("bytes"), number(il::Type::W32, 4), number(il::Type::W32, 4)],
2821
        nil
2822
    );
2823
    try dataCaseAfter(
2824
        "bytes",
2825
        P16,
2826
        true,
2827
        SLICEC,
2828
        true,
2829
        &[symbol("bytes"), number(il::Type::W32, 16), number(il::Type::W32, 16)],
2830
        nil
2831
    );
2832
    try dataCaseAfter(
2833
        "bytes",
2834
        P16,
2835
        true,
2836
        SLICEC,
2837
        true,
2838
        &[symbol("bytes"), number(il::Type::W32, 17), number(il::Type::W32, 17)],
2839
        verify::Rule::Data
2840
    );
2841
    try dataCase(
2842
        SLICEC, true, &[number(il::Type::W64, 0), number(il::Type::W32, 4)], verify::Rule::Data
2843
    );
2844
    try dataCase(SLICEC, true, &[number(il::Type::W64, 0), number(il::Type::W64, 0)], nil);
2845
    try dataCase(
2846
        SLICEC, true, &[number(il::Type::W64, 4), number(il::Type::W64, 0)], verify::Rule::Data
2847
    );
2848
    try dataCaseAfter(
2849
        "bytes",
2850
        P16,
2851
        true,
2852
        SLICEC,
2853
        true,
2854
        &[symbol("bytes"), number(il::Type::W64, 4)],
2855
        verify::Rule::Data
2856
    );
2857
    try dataCaseAfter(
2858
        "bytes",
2859
        P16,
2860
        true,
2861
        SLICE,
2862
        true,
2863
        &[symbol("bytes"), number(il::Type::W32, 4), number(il::Type::W32, 4)],
2864
        verify::Rule::Data
2865
    );
2866
    try dataCaseAfter(
2867
        "bytes",
2868
        P16,
2869
        false,
2870
        SLICE,
2871
        true,
2872
        &[symbol("bytes"), number(il::Type::W32, 4), number(il::Type::W32, 4)],
2873
        nil
2874
    );
2875
}
2876
2877
/// A nonempty slice needs a capacity equal to its length, including zero-filled tails.
2878
@test unsafe fn sliceDataCapacity() throws (testing::TestError) {
2879
    for slice in &[SLICE, SLICEC] {
2880
        for length in &[0, 1, 16] {
2881
            let mut rule: ?verify::Rule = nil;
2882
            if length <> 0 {
2883
                set rule = verify::Rule::Data;
2884
            }
2885
            let values = [
2886
                symbol("bytes"), number(il::Type::W32, length), number(il::Type::W32, length)
2887
            ];
2888
            try dataCaseAfter("bytes", P16, false, slice, true, &values[..], nil);
2889
            try dataCaseAfter("bytes", P16, false, slice, true, &values[.. 2], rule);
2890
            for tail in &[
2891
                number(il::Type::W32,                                    0),
2892
                repeat(il::DataItem::Val { typ: il::Type::W16, val: 0 }, 2),
2893
                repeat(il::DataItem::Val { typ: il::Type::W8, val: 0 },  4),
2894
                repeat(il::DataItem::Undef,                              4),
2895
                repeat(il::DataItem::Undef,                              2),
2896
                repeat(il::DataItem::Undef,                              0),
2897
            ] {
2898
                try dataCaseAfter(
2899
                    "bytes",
2900
                    P16,
2901
                    false,
2902
                    slice,
2903
                    true,
2904
                    &[symbol("bytes"), number(il::Type::W32, length), tail],
2905
                    rule
2906
                );
2907
            }
2908
        }
2909
    }
2910
}
2911
2912
/// A capacity check completes each slice in an array inside a union payload.
2913
@test unsafe fn nestedSliceDataCapacity() throws (testing::TestError) {
2914
    for capacity in &[0, 4] {
2915
        let mut b = newBuilder();
2916
        let pair = addLayout(&mut b, 32, 8, &[
2917
            il::Slot {
2918
                offset: 0, kind: il::SlotKind::Array { layout: SLICE, count: 2 }, regions: &[]
2919
            },
2920
        ]);
2921
        let mut variants: *mut [il::UnionVariant] = &mut [];
2922
        try! variants.append(il::UnionVariant { tag: 0, layout: pair, regions: &[] }, b.arena);
2923
        let outer = addLayout(&mut b, 40, 8, &[
2924
            il::Slot {
2925
                offset: 0,
2926
                kind: il::SlotKind::Union {
2927
                    offset: 8, size: 40, variants: &variants[..]
2928
                },
2929
                regions: &[],
2930
            },
2931
        ]);
2932
        addData(&mut b, "bytes", P16, false, &[]);
2933
        addData(
2934
            &mut b,
2935
            "d",
2936
            outer,
2937
            true,
2938
            &[
2939
                number(il::Type::W64,                  0),
2940
                symbol("bytes"), number(il::Type::W32, 4), number(il::Type::W32, capacity),
2941
                symbol("bytes"), number(il::Type::W32, 4), number(il::Type::W32, 4),
2942
            ]
2943
        );
2944
        if capacity == 0 {
2945
            try rejected(&mut b, verify::Rule::Data);
2946
        } else {
2947
            try accepted(&mut b);
2948
        }
2949
    }
2950
}
2951
2952
/// Slice initializers cannot name heap headers, even with no elements.
2953
@test unsafe fn heapSliceData() throws (testing::TestError) {
2954
    let heaps = &[
2955
        il::HeapType::Typed,
2956
        il::HeapType::Plain,
2957
        il::HeapType::Reset,
2958
    ];
2959
    for rights in heaps {
2960
        for slice in &[SLICE, SLICEC] {
2961
            for length in &[0, 1, 16] {
2962
                let mut b = newBuilder();
2963
                let pool = addData(&mut b, "pool", P16, false, &[]);
2964
                set b.data[pool].heap = rights;
2965
                set b.data[pool].isZeroInit = true;
2966
                addData(
2967
                    &mut b,
2968
                    "view",
2969
                    slice,
2970
                    true,
2971
                    &[
2972
                        symbol("pool"), number(il::Type::W32, length),
2973
                        number(il::Type::W32,                 length),
2974
                    ]
2975
                );
2976
                addFn(
2977
                    &mut b,
2978
                    "main",
2979
                    &[],
2980
                    il::ValType::Void,
2981
                    &[
2982
                        copy(0, il::Val::DataSym("view")),
2983
                        sliceElem(1, 0, imm(0), P1),
2984
                        retVoid(),
2985
                    ]
2986
                );
2987
                try rejected(&mut b, verify::Rule::Data);
2988
            }
2989
        }
2990
    }
2991
}
2992
2993
/// Writable data holds no slices, because a slice is two words that another context
2994
/// can overwrite one at a time. Read-only data holds no borrowed slots.
2995
@test unsafe fn dataSlots() throws (testing::TestError) {
2996
    try dataCase(SLICE, false, &[], verify::Rule::Data);
2997
    try dataCase(CELL, false, &[], nil);
2998
    try dataCase(LOCAL, true, &[], verify::Rule::Data);
2999
    try dataCase(FNCELL, false, &[], nil);
3000
    try dataCase(PAIR, false, &[], verify::Rule::Data);
3001
}
3002
3003
/// Writable data holds no pointer to an object with a slice or trait object, however many
3004
/// pointers lie between, because the object would reach every context, and a racing writer could
3005
/// combine the two words of its slice with those of another.
3006
@test unsafe fn dataReachesPairs() throws (testing::TestError) {
3007
    try dataCase(PTRSLICE, false, &[], verify::Rule::Data);
3008
    try dataCase(PTRPTRSLICE, false, &[], verify::Rule::Data);
3009
    try dataCase(PTRSLICE, true, &[], nil);
3010
    try dataCase(PTRPTRSLICE, true, &[], nil);
3011
    try dataCase(CELL, false, &[], nil);
3012
}
3013
3014
/// A pointer slot starts as zero, or as the address of data that has its layout.
3015
@test unsafe fn pointerData() throws (testing::TestError) {
3016
    try dataCaseAfter("t", P4, true, CELLC, true, &[symbol("t")], nil);
3017
    try dataCaseAfter("t", P4, true, CELL, false, &[symbol("t")], verify::Rule::Data);
3018
    try dataCaseAfter("t", P4, false, CELL, false, &[symbol("t")], nil);
3019
    try dataCaseAfter("t", CELL, true, CELLC, true, &[symbol("t")], verify::Rule::Data);
3020
    try dataCase(CELLC, true, &[symbol("t")], verify::Rule::Symbol);
3021
    try dataCase(CELLC, true, &[number(il::Type::W64, 5)], verify::Rule::Data);
3022
    try dataCase(
3023
        CELLC, true, &[number(il::Type::W8, 1), repeat(il::DataItem::Undef, 7)], verify::Rule::Data
3024
    );
3025
    try dataCase(CELLC, true, &[number(il::Type::W32,       0), number(il::Type::W32, 0)], nil);
3026
    try dataCase(CELLC, true, &[repeat(il::DataItem::Undef, 8)], nil);
3027
    try dataCaseAfter(
3028
        "t", P4, true, CELLC, true, &[number(il::Type::W32, 0), symbol("t")], verify::Rule::Data
3029
    );
3030
    let mut callable = newBuilder();
3031
    addFn(&mut callable, "f", &[], il::ValType::Void, &[retVoid()]);
3032
    addData(&mut callable, "d", CELLC, true, &[function("f")]);
3033
    try rejected(&mut callable, verify::Rule::Data);
3034
}
3035
3036
/// Items outside slots are free, but no item runs from plain bytes into a slot.
3037
@test unsafe fn dataAroundSlots() throws (testing::TestError) {
3038
    try dataCaseAfter(
3039
        "t",
3040
        P4,
3041
        false,
3042
        PAIR,
3043
        true,
3044
        &[
3045
            number(il::Type::W64, 5), symbol("t"), number(il::Type::W64, 0),
3046
            number(il::Type::W32, 0), number(il::Type::W32, 7),
3047
        ],
3048
        verify::Rule::Data
3049
    );
3050
    try dataCase(
3051
        PAIR, true, &[number(il::Type::W32, 0), number(il::Type::W64, 5)], verify::Rule::Data
3052
    );
3053
    try dataCase(
3054
        P3, true, &[il::DataValue { item: il::DataItem::Str("abcd"), count: 1 }], verify::Rule::Data
3055
    );
3056
    try dataCase(P3, true, &[il::DataValue { item: il::DataItem::Str("abc"), count: 1 }], nil);
3057
    try dataCase(
3058
        PAIR,
3059
        true,
3060
        &[
3061
            il::DataValue { item: il::DataItem::Str("abc"),      count: 1 },
3062
            repeat(il::DataItem::Undef,                          5),
3063
            il::DataValue { item: il::DataItem::Str("abcdefgh"), count: 1 },
3064
        ],
3065
        verify::Rule::Data
3066
    );
3067
    try dataCase(CELLS, true, &[repeat(il::DataItem::Val { typ: il::Type::W64, val: 0 }, 3)], nil);
3068
    try dataCase(
3069
        CELLS, true, &[number(il::Type::W64, 0), number(il::Type::W64, 9)], verify::Rule::Data
3070
    );
3071
    try dataCase(P8, true, &[symbol("missing")], verify::Rule::Symbol);
3072
    try dataCaseAfter("t", P4, true, P8, true, &[symbol("t")], nil);
3073
    let mut size = newBuilder();
3074
    addData(&mut size, "d", P8, true, &[]);
3075
    set size.data[0].size = 9;
3076
    try rejected(&mut size, verify::Rule::Data);
3077
}
3078
3079
/// A function slot starts as zero, or as a function with the signature of the slot.
3080
@test unsafe fn functionData() throws (testing::TestError) {
3081
    let mut ok = newBuilder();
3082
    addTargets(&mut ok);
3083
    addData(&mut ok, "d", FNCELL, true, &[function("f")]);
3084
    try accepted(&mut ok);
3085
    let mut wrong = newBuilder();
3086
    addTargets(&mut wrong);
3087
    addData(&mut wrong, "d", FNCELL, true, &[function("g")]);
3088
    try rejected(&mut wrong, verify::Rule::Data);
3089
    try dataCase(FNCELL, true, &[function("f")], verify::Rule::Symbol);
3090
    let mut external = newBuilder();
3091
    addExtern(&mut external, "e", &[oneData()], dataType());
3092
    addData(&mut external, "d", FNCELL, true, &[function("e")]);
3093
    try rejected(&mut external, verify::Rule::Symbol);
3094
    try dataCase(FNCELL, true, &[number(il::Type::W64, 0)], nil);
3095
    try dataCase(FNCELL, true, &[number(il::Type::W64, 8)], verify::Rule::Data);
3096
}
3097
3098
////////////////////
3099
// Layout tables  //
3100
////////////////////
3101
3102
/// Layouts stay within the limits of nesting and size.
3103
@test unsafe fn layoutLimits() throws (testing::TestError) {
3104
    let mut deep = newBuilder();
3105
    let mut inner = CELL;
3106
    for _ in 0 .. 4 {
3107
        set inner = addLayout(&mut deep, 8, 8, &[subSlot(0, inner)]);
3108
    }
3109
    try accepted(&mut deep);
3110
    let mut deeper = newBuilder();
3111
    let mut outer = CELL;
3112
    for _ in 0 .. 5 {
3113
        set outer = addLayout(&mut deeper, 8, 8, &[subSlot(0, outer)]);
3114
    }
3115
    try rejected(&mut deeper, verify::Rule::Limit);
3116
    let mut large = newBuilder();
3117
    addLayout(&mut large, 4096, 8, &[]);
3118
    try accepted(&mut large);
3119
    let mut larger = newBuilder();
3120
    addLayout(&mut larger, 4097, 8, &[]);
3121
    try rejected(&mut larger, verify::Rule::Limit);
3122
    let mut forward = newBuilder();
3123
    addLayout(&mut forward, 8, 8, &[subSlot(0, 99)]);
3124
    try rejected(&mut forward, verify::Rule::Layout);
3125
}
3126
3127
/// An object in a frame has the alignment of the stack at most.
3128
@test unsafe fn reserveAlignment() throws (testing::TestError) {
3129
    let mut ok = newBuilder();
3130
    let wide = addLayout(&mut ok, 16, 16, &[]);
3131
    try checkIn(&mut ok, &[], il::ValType::Void, &[reserve(0, wide), retVoid()], nil);
3132
    let mut over = newBuilder();
3133
    let wider = addLayout(&mut over, 16, 32, &[]);
3134
    try checkIn(
3135
        &mut over, &[], il::ValType::Void, &[reserve(0, wider), retVoid()], verify::Rule::Limit
3136
    );
3137
}
3138
3139
//////////////
3140
// Packages //
3141
//////////////
3142
3143
/// Verify the program as a package.
3144
unsafe fn packageVerdict(
3145
    b: &mut Builder, dependencies: *[*[u8]], entry: ?*[u8], exports: &[binary::Export]
3146
) -> ?verify::Error {
3147
    let mut owned: *mut [binary::Export] = &mut [];
3148
    try! owned.extend(exports, b.arena);
3149
    let mut package = binary::Package {
3150
        version: nil,
3151
        symbols: &[],
3152
        name: "p",
3153
        dependencies,
3154
        exports: &owned[..],
3155
        entry,
3156
        program: program(b),
3157
        links: binary::EMPTY_LINKS,
3158
    };
3159
    let scratch = heap::over(&mut SCRATCH[..]);
3160
    let keep = heap::over(&mut KEEP[..]);
3161
    try verify::verifyPackage(&mut package, CONFIG, scratch, keep) catch err {
3162
        return err;
3163
    };
3164
    set EXPORTED = package.exports.len;
3165
    set STARTABLE = 0;
3166
    for item in package.exports {
3167
        if item.startable {
3168
            set STARTABLE += 1;
3169
        }
3170
    }
3171
    return nil;
3172
}
3173
3174
/// Number of exports that the last accepted package kept.
3175
static EXPORTED: u32 = 0;
3176
3177
/// Number of functions that the last accepted package permits as context entries.
3178
static STARTABLE: u32 = 0;
3179
3180
/// Check that the package is rejected for violating the package rules.
3181
unsafe fn packageRejected(
3182
    b: &mut Builder, dependencies: *[*[u8]], entry: ?*[u8], exports: &[binary::Export]
3183
) throws (testing::TestError) {
3184
    let err = packageVerdict(b, dependencies, entry, exports) else {
3185
        throw testing::TestError::Failed;
3186
    };
3187
    try testing::expect(err.rule == verify::Rule::Package);
3188
}
3189
3190
/// Exports are sorted by name, and each one indexes a definition of the same name.
3191
@test unsafe fn packageExportTable() throws (testing::TestError) {
3192
    let a = binary::Export { name: "a", kind: binary::ExportKind::Function(0), startable: false };
3193
    let b = binary::Export { name: "b", kind: binary::ExportKind::Function(1), startable: false };
3194
    let d = binary::Export { name: "d", kind: binary::ExportKind::Data(0), startable: false };
3195
    let mut ok = newBuilder();
3196
    addFn(&mut ok, "a", &[], il::ValType::Void, &[retVoid()]);
3197
    addFn(&mut ok, "b", &[], il::ValType::Void, &[retVoid()]);
3198
    addData(&mut ok, "d", P4, true, &[]);
3199
    try testing::expect(packageVerdict(&mut ok, &[], nil, &[a, b, d]) == nil);
3200
    try packageRejected(&mut ok, &[], nil, &[b, a, d]);
3201
    try packageRejected(&mut ok, &[], nil, &[a, a, d]);
3202
    let mut renamed = b;
3203
    set renamed.kind = binary::ExportKind::Function(0);
3204
    try packageRejected(&mut ok, &[], nil, &[a, renamed]);
3205
    let mut beyond = d;
3206
    set beyond.kind = binary::ExportKind::Data(1);
3207
    try packageRejected(&mut ok, &[], nil, &[a, beyond]);
3208
    let mut kind = d;
3209
    set kind.kind = binary::ExportKind::Function(0);
3210
    try packageRejected(&mut ok, &[], nil, &[kind]);
3211
}
3212
3213
/// A package has no dependencies, and no extern functions.
3214
@test unsafe fn packageIsSelfContained() throws (testing::TestError) {
3215
    let mut ok = newBuilder();
3216
    addFn(&mut ok, "f", &[], il::ValType::Void, &[retVoid()]);
3217
    try testing::expect(packageVerdict(&mut ok, &[], nil, &[]) == nil);
3218
    let mut dependent = newBuilder();
3219
    addFn(&mut dependent, "f", &[], il::ValType::Void, &[retVoid()]);
3220
    try packageRejected(&mut dependent, &["std"], nil, &[]);
3221
    let mut external = newBuilder();
3222
    addExtern(&mut external, "e", &[], il::ValType::Void);
3223
    try packageRejected(&mut external, &[], nil, &[]);
3224
}
3225
3226
/// Check as a package the program with the entry function "entry", which takes `params`. The
3227
/// package is accepted when `rule` is nil, and otherwise rejected.
3228
unsafe fn entryCase(b: &mut Builder, params: &[il::Param], rule: ?verify::Rule)
3229
    throws (testing::TestError)
3230
{
3231
    addFn(b, "entry", params, il::ValType::Void, &[retVoid()]);
3232
    if let _ = rule {
3233
        try packageRejected(b, &[], "entry", &[]);
3234
    } else {
3235
        try testing::expect(packageVerdict(b, &[], "entry", &[]) == nil);
3236
    }
3237
}
3238
3239
/// The entry takes the Env record by a pointer that cannot be written or null.
3240
@test unsafe fn packageEntry() throws (testing::TestError) {
3241
    let env = param(0, ptrType(P16, true, false, false));
3242
    let mut ok = newBuilder();
3243
    try entryCase(&mut ok, &[env], nil);
3244
    let mut missing = newBuilder();
3245
    addFn(&mut missing, "entry", &[env], il::ValType::Void, &[retVoid()]);
3246
    try packageRejected(&mut missing, &[], "other", &[]);
3247
    let rule = verify::Rule::Package;
3248
    let mut none = newBuilder();
3249
    try entryCase(&mut none, &[], nil);
3250
    let mut two = newBuilder();
3251
    try entryCase(&mut two, &[env, param(1, ptrType(P16, true, false, false))], rule);
3252
    let mut data = newBuilder();
3253
    try entryCase(&mut data, &[oneData()], rule);
3254
    let mut writable = newBuilder();
3255
    try entryCase(&mut writable, &[param(0, ptrType(P16, true, true, false))], rule);
3256
    let mut nullable = newBuilder();
3257
    try entryCase(&mut nullable, &[param(0, ptrType(P16, true, false, true))], rule);
3258
    let mut borrowed = newBuilder();
3259
    try entryCase(&mut borrowed, &[param(0, ptrType(P16, false, false, false))], rule);
3260
    let mut slots = newBuilder();
3261
    try entryCase(&mut slots, &[param(0, ptrType(CELL, true, false, false))], rule);
3262
    let mut large = newBuilder();
3263
    let big = addLayout(&mut large, 33, 1, &[]);
3264
    try entryCase(&mut large, &[param(0, ptrType(big, true, false, false))], rule);
3265
    let mut exact = newBuilder();
3266
    let fits = addLayout(&mut exact, 32, 1, &[]);
3267
    try entryCase(&mut exact, &[param(0, ptrType(fits, true, false, false))], nil);
3268
}
3269
3270
/// Public functions retain their call contracts; only data-argument entries can start contexts.
3271
@test unsafe fn packageExports() throws (testing::TestError) {
3272
    let function = binary::Export {
3273
        name: "f",
3274
        kind: binary::ExportKind::Function(0),
3275
        startable: false,
3276
    };
3277
    let mut ok = newBuilder();
3278
    addFn(&mut ok, "f", &[oneData()], dataType(), &[ret(reg(0))]);
3279
    try testing::expect(packageVerdict(&mut ok, &[], nil, &[function]) == nil);
3280
    assert EXPORTED == 1;
3281
    assert STARTABLE == 1;
3282
    let mut two = newBuilder();
3283
    addFn(&mut two, "f", &[oneData(), param(1, dataType())], dataType(), &[ret(reg(0))]);
3284
    try testing::expect(packageVerdict(&mut two, &[], nil, &[function]) == nil);
3285
    assert EXPORTED == 1;
3286
    assert STARTABLE == 1;
3287
    let mut three = newBuilder();
3288
    addFn(&mut three, "f", &[oneData(), param(1, dataType()), param(2, dataType())], dataType(), &[
3289
        ret(reg(0))
3290
    ]);
3291
    try testing::expect(packageVerdict(&mut three, &[], nil, &[function]) == nil);
3292
    assert EXPORTED == 1;
3293
    assert STARTABLE == 0;
3294
    let mut pointer = newBuilder();
3295
    addFn(&mut pointer, "f", &[param(0, ptrType(P4, true, true, false))], il::ValType::Void, &[
3296
        retVoid()
3297
    ]);
3298
    try testing::expect(packageVerdict(&mut pointer, &[], nil, &[function]) == nil);
3299
    assert EXPORTED == 1;
3300
    assert STARTABLE == 0;
3301
    let mut result = newBuilder();
3302
    addFn(
3303
        &mut result,
3304
        "f",
3305
        &[param(0, ptrType(P4, true, true, false))],
3306
        ptrType(P4, true, true, false),
3307
        &[ret(reg(0))]
3308
    );
3309
    try testing::expect(packageVerdict(&mut result, &[], nil, &[function]) == nil);
3310
    assert EXPORTED == 1;
3311
    assert STARTABLE == 0;
3312
    let mut callback = newBuilder();
3313
    addFn(&mut callback, "f", &[param(0, il::ValType::Fn(SIG_DATA))], il::ValType::Void, &[
3314
        retVoid()
3315
    ]);
3316
    try testing::expect(packageVerdict(&mut callback, &[], nil, &[function]) == nil);
3317
    assert EXPORTED == 1;
3318
    assert STARTABLE == 0;
3319
    let mut missing = newBuilder();
3320
    try packageRejected(&mut missing, &[], nil, &[function]);
3321
    let env = param(0, ptrType(P16, true, false, false));
3322
    let entry = binary::Export {
3323
        name: "entry",
3324
        kind: binary::ExportKind::Function(0),
3325
        startable: false,
3326
    };
3327
    let mut exportedEntry = newBuilder();
3328
    addFn(&mut exportedEntry, "entry", &[env], il::ValType::Void, &[retVoid()]);
3329
    try testing::expect(packageVerdict(&mut exportedEntry, &[], "entry", &[entry]) == nil);
3330
    try testing::expect(EXPORTED == 1);
3331
    let mut data = newBuilder();
3332
    addData(&mut data, "d", P4, true, &[]);
3333
3334
    let item = binary::Export {
3335
        name: "d",
3336
        kind: binary::ExportKind::Data(0),
3337
        startable: false,
3338
    };
3339
    try testing::expect(packageVerdict(&mut data, &[], nil, &[item]) == nil);
3340
    let mut absent = newBuilder();
3341
    try packageRejected(&mut absent, &[], nil, &[item]);
3342
}
3343
3344
/// Plain queries on arrays nested to the depth limit. Each level holds two elements of the
3345
/// level below, which has a pointer at its upper half, so that every query is answered along
3346
/// one path of the table.
3347
@test unsafe fn plainBytesInNestedArrays() throws (testing::TestError) {
3348
    let depth: u32 = 16;
3349
    let config = verify::Config {
3350
        registers: 64, blocks: 16, layoutSize: 1048576, layoutDepth: depth, params: 8, envSize: 32
3351
    };
3352
    let mut b = newBuilder();
3353
    // 16 bytes: plain, then a pointer at offset 8.
3354
    let leaf = addLayout(&mut b, 16, 8, &[ptrSlot(8, P4, true, true)]);
3355
    let mut top = leaf;
3356
    let mut width: u32 = 16;
3357
    for _ in 0 .. depth {
3358
        set width *= 2;
3359
        set top = addLayout(&mut b, width, 8, &[
3360
            il::Slot {
3361
                offset: 0, kind: il::SlotKind::Array { layout: top, count: 2 }, regions: &[]
3362
            },
3363
        ]);
3364
    }
3365
    let scratch = heap::over(&mut SCRATCH[..]);
3366
    let t = try layout::build(&b.layouts[..], config, scratch) catch {
3367
        throw testing::TestError::Failed;
3368
    };
3369
    let total = layout::size(&t, top);
3370
    try testing::expect(total == 1048576);
3371
    try testing::expect(layout::plain(&t, top, 0, 8));
3372
    try testing::expect(not layout::plain(&t, top, 0, 9));
3373
    try testing::expect(not layout::plain(&t, top, 8, 16));
3374
    try testing::expect(layout::plain(&t, top, 16, 24));
3375
    try testing::expect(not layout::plain(&t, top, 15, 24));
3376
    try testing::expect(layout::plain(&t, top, total - 16, total - 8));
3377
    try testing::expect(not layout::plain(&t, top, total - 16, total - 7));
3378
    try testing::expect(not layout::plain(&t, top, 0, total));
3379
    try testing::expect(layout::plain(&t, top, 5, 5));
3380
    try testing::expect(layout::plain(&t, top, total, total + 8));
3381
    // A range that spans elements ends at the first pointer.
3382
    try testing::expect(layout::plain(&t, top, 16 * 1000, 16 * 1000 + 8));
3383
    try testing::expect(not layout::plain(&t, top, 16 * 1000, 16 * 1001));
3384
}
3385
3386
/// The capacity of a slice is protected like the rest of it, also inside an array of slices.
3387
@test unsafe fn plainBytesOfSlices() throws (testing::TestError) {
3388
    let mut b = newBuilder();
3389
    let pair = addLayout(&mut b, 32, 8, &[
3390
        il::Slot {
3391
            offset: 0, kind: il::SlotKind::Array { layout: SLICE, count: 2 }, regions: &[]
3392
        },
3393
    ]);
3394
    let scratch = heap::over(&mut SCRATCH[..]);
3395
    let t = try layout::build(&b.layouts[..], CONFIG, scratch) catch {
3396
        throw testing::TestError::Failed;
3397
    };
3398
    try testing::expect(not layout::plain(&t, pair, 12, 16));
3399
    try testing::expect(not layout::plain(&t, pair, 11, 16));
3400
    try testing::expect(not layout::plain(&t, pair, 12, 17));
3401
    try testing::expect(not layout::plain(&t, pair, 28, 32));
3402
    try testing::expect(not layout::plain(&t, SLICE, 12, 16));
3403
}
3404
3405
/////////////
3406
// Errors  //
3407
/////////////
3408
3409
/// An error names the function, block and instruction.
3410
@test unsafe fn errorPlace() throws (testing::TestError) {
3411
    let mut b = newBuilder();
3412
    addFn(&mut b, "f", &[], il::ValType::Void, &[retVoid()]);
3413
    let blocks = [
3414
        block(&mut b, &[], &[jmp(1, none())]),
3415
        block(&mut b, &[], &[copy(0, imm(1)), load(1, 0, 0), retVoid()]),
3416
    ];
3417
    addBlocks(&mut b, "g", &[], il::ValType::Void, &blocks[..]);
3418
    let err = verdict(&mut b) else {
3419
        throw testing::TestError::Failed;
3420
    };
3421
    try testing::expect(err.rule == verify::Rule::Type);
3422
    let case verify::Place::Instr { func, block, instr } = err.place else {
3423
        throw testing::TestError::Failed;
3424
    };
3425
    try testing::expect(func == 1 and block == 1 and instr == 1);
3426
}
3427
3428
/// A scratch arena that is too small is reported, and not a panic.
3429
@test unsafe fn scratchExhausted() throws (testing::TestError) {
3430
    let mut b = newBuilder();
3431
    addFn(&mut b, "f", &[], il::ValType::Void, &[retVoid()]);
3432
    let prog = program(&mut b);
3433
    for size in 0 .. 64 {
3434
        let scratch = heap::withCapacity(&mut SCRATCH[..], size);
3435
        try verify::verifyProgram(&prog, CONFIG, scratch) catch err {
3436
            try testing::expect(err.rule == verify::Rule::Storage);
3437
            continue;
3438
        };
3439
        // The program fits, and so does any larger arena.
3440
        try testing::expect(size >= 32);
3441
        return;
3442
    }
3443
}
3444
3445
////////////////////////////
3446
// Ecall buffer, page.slice //
3447
////////////////////////////
3448
3449
/// An environment call of operation 1 with the given buffer.
3450
fn ecall(dst: u32, buf: ?il::EcallBuf) -> il::Instr {
3451
    return il::Instr::Ecall {
3452
        dst: il::Reg { n: dst }, num: imm(1), a0: imm(0), a1: imm(0), a2: imm(0), a3: imm(0), buf
3453
    };
3454
}
3455
3456
/// A buffer of `size` bytes at register `n`.
3457
fn buffer(n: u32, size: u32) -> ?il::EcallBuf {
3458
    return il::EcallBuf { ptr: il::Reg { n }, size };
3459
}
3460
3461
/// A page access of the handle in register 0, into the slice slot at register `slot`.
3462
fn pageSlice(err: u32, slot: u32, write: bool, layout: u32) -> il::Instr {
3463
    return il::Instr::PageSlice {
3464
        err: il::Reg { n: err }, slot: il::Reg { n: slot }, handle: reg(0), write, layout
3465
    };
3466
}
3467
3468
/// A page heap of the handle in register 0, into the heap slot at register `slot`.
3469
fn pageHeap(err: u32, slot: u32) -> il::Instr {
3470
    return il::Instr::PageHeap {
3471
        err: il::Reg { n: err }, slot: il::Reg { n: slot }, handle: reg(0)
3472
    };
3473
}
3474
3475
/// The kernel writes only the buffer, which is plain writable memory of the caller.
3476
@test unsafe fn ecallBuffer() throws (testing::TestError) {
3477
    try check(&[], &[ecall(0,   nil)], nil);
3478
    try check(&[], &[reserve(0, P16), ecall(1, buffer(0, 16))], nil);
3479
    try check(&[], &[reserve(0, PAIR), field(1, 0, 0), ecall(2, buffer(1, 8))], nil);
3480
    try check(
3481
        &[param(0, ptrType(P16, true, false, false))],
3482
        &[ecall(1, buffer(0, 16))],
3483
        verify::Rule::Mutability
3484
    );
3485
    try check(&[], &[reserve(0, CELL), ecall(1, buffer(0, 8))], verify::Rule::Slot);
3486
    try check(&[], &[reserve(0, SLICE), ecall(1, buffer(0, 12))], verify::Rule::Slot);
3487
    try check(
3488
        &[], &[reserve(0, SLICE), field(1, 0, 12), ecall(2, buffer(1, 4))], verify::Rule::Slot
3489
    );
3490
    try check(&[], &[reserve(0, P16), ecall(1, buffer(0, 17))], verify::Rule::Bounds);
3491
    try check(
3492
        &[param(0, ptrType(P16, true, true, true))], &[ecall(1, buffer(0, 16))], verify::Rule::Null
3493
    );
3494
    try check(&[oneData()], &[ecall(1, buffer(0, 16))], verify::Rule::Type);
3495
}
3496
3497
/// A page heap fills a heap slot, which a plain slot or a read-only place cannot receive.
3498
@test unsafe fn pageHeapSlots() throws (testing::TestError) {
3499
    let handle = [oneData()];
3500
    try check(&handle[..], &[reserve(1,   HEAPCELL), pageHeap(2, 1)], nil);
3501
    try check(&handle[..], &[reserve(1,   HEAPCELLT), pageHeap(2, 1)], nil);
3502
    try check(&handle[..], &[reserve(1,   P16), pageHeap(2, 1)], verify::Rule::Slot);
3503
    try check(&handle[..], &[reserve(1,   SLICE), pageHeap(2, 1)], verify::Rule::Slot);
3504
    try check(&handle[..], &[reserve(1,   CELL), pageHeap(2, 1)], verify::Rule::Slot);
3505
    try check(&[oneData()], &[pageHeap(2, 0)], verify::Rule::Type);
3506
    // The heap in the slot, which has the typed right, grows pointer elements.
3507
    try check(
3508
        &handle[..],
3509
        &[
3510
            reserve(1,  HEAPCELLT),
3511
            pageHeap(2, 1),
3512
            reserve(3,  SLICECELL),
3513
            loadPtr(4,  1, 0),
3514
            sliceGrow(5, 3, reg(4), CELL, imm(1)),
3515
        ],
3516
        nil
3517
    );
3518
}
3519
3520
/// A heap handle with the reset right, in register `n`.
3521
fn resetParam(n: u32) -> il::Param {
3522
    return param(n, il::ValType::Heap(il::HeapType::Reset));
3523
}
3524
3525
/// A reset of the given heap.
3526
fn heapReset(heap: il::Val) -> il::Instr {
3527
    return il::Instr::HeapReset { heap };
3528
}
3529
3530
/// Only a handle with the reset right resets a heap.
3531
@test unsafe fn heapResetRights() throws (testing::TestError) {
3532
    let scratch = [resetParam(0)];
3533
    try check(&scratch[..], &[heapReset(reg(0))], nil);
3534
    try check(&[heapParam(0, il::HeapType::Plain)], &[heapReset(reg(0))], verify::Rule::Type);
3535
    try check(&[heapParam(0, il::HeapType::Typed)], &[heapReset(reg(0))], verify::Rule::Type);
3536
    try check(&[oneData()], &[heapReset(reg(0))], verify::Rule::Type);
3537
    try check(
3538
        &[param(0, ptrType(P16, true, true, false))], &[heapReset(reg(0))], verify::Rule::Type
3539
    );
3540
    try check(&[], &[heapReset(imm(0))], verify::Rule::Type);
3541
    // The handle loaded from a slot keeps the right of the slot.
3542
    try check(
3543
        &scratch[..],
3544
        &[
3545
            reserve(1,       HEAPCELLR),
3546
            storePtr(reg(0), 1, 0),
3547
            loadPtr(2,       1, 0),
3548
            heapReset(reg(2)),
3549
        ],
3550
        nil
3551
    );
3552
    try check(
3553
        &[heapParam(0, il::HeapType::Plain)],
3554
        &[
3555
            reserve(1,       HEAPCELL),
3556
            storePtr(reg(0), 1, 0),
3557
            loadPtr(2,       1, 0),
3558
            heapReset(reg(2)),
3559
        ],
3560
        verify::Rule::Type
3561
    );
3562
}
3563
3564
/// Heap slots follow the same rights relation as heap values.
3565
@test unsafe fn heapSlotViews() throws (testing::TestError) {
3566
    try check(&[], &[reserve(0, HEAPCELLT), reserve(1, HEAPCELL), blit(1, 0, HEAPCELL)], nil);
3567
    try check(&[], &[reserve(0, HEAPCELLR), reserve(1, HEAPCELL), blit(1, 0, HEAPCELL)], nil);
3568
    try check(
3569
        &[],
3570
        &[reserve(0, HEAPCELL), reserve(1, HEAPCELLT), blit(1, 0, HEAPCELLT)],
3571
        verify::Rule::View
3572
    );
3573
    try check(
3574
        &[],
3575
        &[reserve(0, HEAPCELLT), reserve(1, HEAPCELLR), blit(1, 0, HEAPCELLR)],
3576
        verify::Rule::View
3577
    );
3578
    try check(
3579
        &[],
3580
        &[reserve(0, HEAPCELLR), reserve(1, HEAPCELLT), blit(1, 0, HEAPCELLT)],
3581
        verify::Rule::View
3582
    );
3583
}
3584
3585
/// A use of a handle can drop the reset right and can never gain it, so a heap that holds
3586
/// slots never becomes one that can be reset.
3587
@test unsafe fn heapResetNarrowing() throws (testing::TestError) {
3588
    let plainType = il::ValType::Heap(il::HeapType::Plain);
3589
    let typedType = il::ValType::Heap(il::HeapType::Typed);
3590
    let resetType = il::ValType::Heap(il::HeapType::Reset);
3591
    let mut toPlain = newBuilder();
3592
    try checkIn(&mut toPlain, &[resetParam(0)], plainType, &[ret(reg(0))], nil);
3593
    let mut toTyped = newBuilder();
3594
    try checkIn(&mut toTyped, &[resetParam(0)], typedType, &[ret(reg(0))], verify::Rule::Type);
3595
    let mut fromPlain = newBuilder();
3596
    try checkIn(
3597
        &mut fromPlain,
3598
        &[heapParam(0, il::HeapType::Plain)],
3599
        resetType,
3600
        &[ret(reg(0))],
3601
        verify::Rule::Type
3602
    );
3603
    let mut fromTyped = newBuilder();
3604
    try checkIn(
3605
        &mut fromTyped,
3606
        &[heapParam(0, il::HeapType::Typed)],
3607
        resetType,
3608
        &[ret(reg(0))],
3609
        verify::Rule::Type
3610
    );
3611
    // A slot follows the same rule.
3612
    try check(&[resetParam(0)], &[reserve(1, HEAPCELL), storePtr(reg(0), 1, 0)], nil);
3613
    let typed = [heapParam(0, il::HeapType::Typed)];
3614
    try check(&typed[..], &[reserve(1, HEAPCELLR), storePtr(reg(0), 1, 0)], verify::Rule::Type);
3615
    // The memory of a Page is a typed heap, so its slot cannot hold the reset right.
3616
    try check(&[oneData()], &[reserve(1, HEAPCELLR), pageHeap(2, 1)], verify::Rule::Type);
3617
}
3618
3619
/// A heap with the reset right provides plain elements only.
3620
@test unsafe fn heapResetGrowth() throws (testing::TestError) {
3621
    let scratch = [resetParam(0)];
3622
    try check(&scratch[..], &[reserve(1, SLICE), sliceGrow(2, 1, reg(0), P1, imm(1))], nil);
3623
    try check(
3624
        &scratch[..],
3625
        &[reserve(1, SLICECELL), sliceGrow(2, 1, reg(0), CELL, imm(1))],
3626
        verify::Rule::View
3627
    );
3628
}
3629
3630
/// The symbol of a heap region with the reset right is a handle with it.
3631
@test unsafe fn heapResetData() throws (testing::TestError) {
3632
    let mut b = newBuilder();
3633
    let i = addData(&mut b, "pool", P16, false, &[]);
3634
    set b.data[i].heap = il::HeapType::Reset;
3635
    set b.data[i].isZeroInit = true;
3636
    addFn(&mut b, "main", &[], il::ValType::Void, &[
3637
        copy(0, il::Val::DataSym("pool")), heapReset(reg(0)), retVoid()
3638
    ]);
3639
    try accepted(&mut b);
3640
3641
    let mut typed = newBuilder();
3642
    let j = addData(&mut typed, "pool", P16, false, &[]);
3643
    set typed.data[j].heap = il::HeapType::Typed;
3644
    set typed.data[j].isZeroInit = true;
3645
    addFn(&mut typed, "main", &[], il::ValType::Void, &[
3646
        copy(0, il::Val::DataSym("pool")), heapReset(reg(0)), retVoid()
3647
    ]);
3648
    try rejected(&mut typed, verify::Rule::Type);
3649
}
3650
3651
/// A page access fills an owned slice slot of plain elements.
3652
@test unsafe fn pageSliceSlots() throws (testing::TestError) {
3653
    let handle = [oneData()];
3654
    try check(&handle[..], &[reserve(1, SLICE), pageSlice(2, 1, true, P1)], nil);
3655
    try check(&handle[..], &[reserve(1, SLICEC), pageSlice(2, 1, false, P1)], nil);
3656
    try check(
3657
        &handle[..], &[reserve(1, SLICEC), pageSlice(2, 1, true, P1)], verify::Rule::Mutability
3658
    );
3659
    try check(
3660
        &handle[..], &[reserve(1, SLICE), pageSlice(2, 1, false, P1)], verify::Rule::Mutability
3661
    );
3662
    try check(&handle[..], &[reserve(1, BORROW), pageSlice(2, 1, true, P1)], verify::Rule::Class);
3663
    try check(&handle[..], &[reserve(1, P16), pageSlice(2, 1, true, P1)], verify::Rule::Slot);
3664
    try check(&handle[..], &[reserve(1, SLICE), pageSlice(2, 1, true, P4)], verify::Rule::View);
3665
    let mut readOnlyDestination = newBuilder();
3666
    try checkIn(
3667
        &mut readOnlyDestination,
3668
        &[oneData(), param(1, ptrType(SLICE, false, false, false))],
3669
        il::ValType::Void,
3670
        &[pageSlice(2, 1, true, P1), retVoid()],
3671
        verify::Rule::Mutability
3672
    );
3673
    try check(&handle[..], &[pageSlice(2, 0, true, P1)], verify::Rule::Type);
3674
}
3675
3676
/// The elements of a page are plain data: a pointer cannot be put in page memory.
3677
@test unsafe fn pageSliceElements() throws (testing::TestError) {
3678
    let handle = [oneData()];
3679
    let slotted = [param(0, dataType())];
3680
    let mut b = newBuilder();
3681
    let cells = addLayout(&mut b, 16, 8, &[sliceSlot(0, CELL, true, true)]);
3682
    try checkIn(
3683
        &mut b,
3684
        &slotted[..],
3685
        il::ValType::Void,
3686
        &[reserve(1, cells), pageSlice(2, 1, true, CELL), retVoid()],
3687
        verify::Rule::View
3688
    );
3689
    let mut empty = newBuilder();
3690
    let zero = addLayout(&mut empty, 0, 1, &[]);
3691
    let sliceOfZero = addLayout(&mut empty, 16, 8, &[sliceSlot(0, zero, true, true)]);
3692
    try checkIn(
3693
        &mut empty,
3694
        &handle[..],
3695
        il::ValType::Void,
3696
        &[reserve(1, sliceOfZero), pageSlice(2, 1, true, zero), retVoid()],
3697
        verify::Rule::View
3698
    );
3699
    try check(
3700
        &handle[..], &[reserve(1, SLICE), pageSlice(2, 1, true, P1), add(3, reg(2), imm(1))], nil
3701
    );
3702
}
3703
3704
/// Block order in the file is free: a block can come before the blocks that dominate it.
3705
/// The backend must not depend on it.
3706
@test unsafe fn layoutBeforeDominator() throws (testing::TestError) {
3707
    let mut b = newBuilder();
3708
    let entry = block(&mut b, &[], &[jmp(2, none())]);
3709
    let reader = block(&mut b, &[], &[
3710
        copy(3, imm(0x1000)), load64(4, 1, 0), add(5, reg(4), reg(3)), ret(reg(5))
3711
    ]);
3712
    let writer = block(&mut b, &[], &[
3713
        copy(0, imm(5)), reserve(1, P8), add(2, reg(0), reg(0)), jmp(1, none())
3714
    ]);
3715
    addBlocks(&mut b, "main", &[], dataType(), &[entry, reader, writer]);
3716
    try accepted(&mut b);
3717
}
3718
3719
///////////////////
3720
// Trait objects //
3721
///////////////////
3722
3723
/// Layouts of the trait objects of trait 0.
3724
record Objects: Copy {
3725
    /// A trait object that borrows a writable receiver.
3726
    object: u32,
3727
    /// A trait object that borrows a read-only receiver.
3728
    constObject: u32,
3729
    /// A trait object that owns a writable receiver.
3730
    ownObject: u32,
3731
}
3732
3733
/// A function value slot of signature `sig` at `offset`.
3734
fn fnSlot(offset: u32, sig: u32) -> il::Slot {
3735
    return il::Slot { offset, kind: il::SlotKind::Fn(sig), regions: &[] };
3736
}
3737
3738
/// A trait object slot of trait 0 at offset 0.
3739
fn objectSlot(own: bool, mutable: bool) -> il::Slot {
3740
    return il::Slot {
3741
        offset: 0,
3742
        kind: il::SlotKind::Trait(il::ObjectType {
3743
            iface: 0, own, mutable
3744
        }),
3745
        regions: &[],
3746
    };
3747
}
3748
3749
/// Add a trait, and return its index.
3750
fn addTrait(b: &mut Builder, methods: &[il::Method]) -> u32 {
3751
    let index = b.traits.len;
3752
    let mut copy: *mut [il::Method] = &mut [];
3753
    try! copy.extend(methods, b.arena);
3754
    try! b.traits.append(il::Trait { methods: &copy[..] }, b.arena);
3755
    return index;
3756
}
3757
3758
/// Add trait 0, whose method 0 reads its receiver and returns data, and whose method 1
3759
/// writes it and takes data. Add `get` and `put`, which implement them for a `P4` receiver,
3760
/// and their read-only method table `table`. Add the read-only table `short`, which lacks
3761
/// method 1, the writable table `open`, and the table `cells` of the methods for a `CELL`
3762
/// receiver.
3763
fn addObjects(b: &mut Builder) -> Objects {
3764
    let getSig = addSignature(b, &[], dataType());
3765
    let putSig = addSignature(b, &[dataType()], il::ValType::Void);
3766
    let getP4 = addSignature(b, &[ptrType(P4, false, false, false)], dataType());
3767
    let putP4 = addSignature(
3768
        b, &[ptrType(P4, false, true, false), dataType()], il::ValType::Void
3769
    );
3770
    let getCell = addSignature(b, &[ptrType(CELL, false, false, false)], dataType());
3771
    let putCell = addSignature(
3772
        b, &[ptrType(CELL, false, true, false), dataType()], il::ValType::Void
3773
    );
3774
    addTrait(
3775
        b,
3776
        &[
3777
            il::Method { sig: getSig, receiver: 0, own: false, mutable: false },
3778
            il::Method { sig: putSig, receiver: 0, own: false, mutable: true },
3779
        ]
3780
    );
3781
    let table = addLayout(b, 16, 8, &[fnSlot(0, getP4), fnSlot(8, putP4)]);
3782
    let short = addLayout(b, 8, 8, &[fnSlot(0, getP4)]);
3783
    let cells = addLayout(b, 16, 8, &[fnSlot(0, getCell), fnSlot(8, putCell)]);
3784
    addFn(b, "get", &[param(0, ptrType(P4, false, false, false))], dataType(), &[
3785
        load(1, 0, 0), ret(reg(1))
3786
    ]);
3787
    addFn(
3788
        b,
3789
        "put",
3790
        &[param(0, ptrType(P4, false, true, false)), param(1, dataType())],
3791
        il::ValType::Void,
3792
        &[store(reg(1), 0, 0), retVoid()]
3793
    );
3794
    addFn(b, "getCell", &[param(0, ptrType(CELL, false, false, false))], dataType(), &[
3795
        load64(1, 0, 0), ret(reg(1))
3796
    ]);
3797
    addFn(
3798
        b,
3799
        "putCell",
3800
        &[param(0, ptrType(CELL, false, true, false)), param(1, dataType())],
3801
        il::ValType::Void,
3802
        &[retVoid()]
3803
    );
3804
    addData(b, "table", table, true, &[function("get"), function("put")]);
3805
    addData(b, "open", table, false, &[function("get"), function("put")]);
3806
    addData(b, "short", short, true, &[function("get")]);
3807
    addData(b, "cells", cells, true, &[function("getCell"), function("putCell")]);
3808
    return Objects {
3809
        object: addLayout(b, 16, 8, &[objectSlot(false, true)]),
3810
        constObject: addLayout(b, 16, 8, &[objectSlot(false, false)]),
3811
        ownObject: addLayout(b, 16, 8, &[objectSlot(true, true)]),
3812
    };
3813
}
3814
3815
/// Build a trait object in the slot at `dst` from the receiver `recv` and the table `table`.
3816
fn traitNew(dst: u32, recv: u32, table: il::Val) -> il::Instr {
3817
    return il::Instr::TraitNew { dst: il::Reg { n: dst }, recv: il::Reg { n: recv }, table };
3818
}
3819
3820
/// Call method `method` of the trait object at `obj`, with the receiver at `receiver`.
3821
fn traitCall(
3822
    dst: ?u32, retTy: il::ValType, obj: u32, method: u32, receiver: u32, values: il::ArgRange
3823
) -> il::Instr {
3824
    let mut result: ?il::Reg = nil;
3825
    if let n = dst {
3826
        set result = il::Reg { n };
3827
    }
3828
    return il::Instr::TraitCall {
3829
        retTy, dst: result, obj: il::Reg { n: obj }, method, receiver, args: values
3830
    };
3831
}
3832
3833
/// Check `main`, which builds a trait object of layout `object` in its frame from a
3834
/// receiver of layout `recv` in its frame and the table `table`, and then runs `instrs`.
3835
/// The receiver is register 0 and the object register 1.
3836
unsafe fn objectCase(
3837
    recv: u32, object: u32, table: *[u8], instrs: &[il::Instr], rule: ?verify::Rule
3838
) throws (testing::TestError) {
3839
    let mut b = newBuilder();
3840
    addObjects(&mut b);
3841
    let mut body: *mut [il::Instr] = &mut [];
3842
    try! body.append(reserve(0, recv), b.arena);
3843
    try! body.append(reserve(1, object), b.arena);
3844
    try! body.append(traitNew(1, 0, il::Val::DataSym(table)), b.arena);
3845
    try! body.extend(instrs, b.arena);
3846
    try! body.append(retVoid(), b.arena);
3847
    try checkIn(&mut b, &[], il::ValType::Void, &body[..], rule);
3848
}
3849
3850
/// Layout of the trait objects that [`objectCase`] builds, which [`addObjects`] adds after
3851
/// the tables. The first is the object, then the read-only and the owning object.
3852
constant OBJECT: u32 = 30;
3853
3854
/// Check that a trait object built from a receiver and its method table can call the
3855
/// methods that its rights allow, and that the methods get the receiver.
3856
@test unsafe fn traitObjectCalls() throws (testing::TestError) {
3857
    let mut b = newBuilder();
3858
    let objects = addObjects(&mut b);
3859
    try testing::expect(objects.object == OBJECT);
3860
    let get = args(&mut b, &[il::Val::Undef]);
3861
    let put = args(&mut b, &[il::Val::Undef, imm(5)]);
3862
    try checkIn(
3863
        &mut b,
3864
        &[],
3865
        il::ValType::Void,
3866
        &[
3867
            reserve(0, P4),
3868
            reserve(1, objects.object),
3869
            traitNew(1, 0, il::Val::DataSym("table")),
3870
            traitCall(2,   dataType(), 1, 0, 0, get),
3871
            traitCall(nil, il::ValType::Void, 1, 1, 0, put),
3872
            retVoid(),
3873
        ],
3874
        nil
3875
    );
3876
3877
    // The rights to the receiver are those of the slot, also through a read-only pointer
3878
    // to the object.
3879
    let mut c = newBuilder();
3880
    let held = addObjects(&mut c);
3881
    let putHeld = args(&mut c, &[il::Val::Undef, imm(5)]);
3882
    try checkIn(
3883
        &mut c,
3884
        &[param(0, ptrType(held.object, false, false, false))],
3885
        il::ValType::Void,
3886
        &[
3887
            traitCall(nil, il::ValType::Void, 0, 1, 0, putHeld), retVoid()
3888
        ],
3889
        nil
3890
    );
3891
}
3892
3893
/// Check that a trait object is built only from a receiver that its method table fits:
3894
/// read-only data with a function of the right type for each method.
3895
@test unsafe fn traitObjectTables() throws (testing::TestError) {
3896
    try objectCase(P4, OBJECT, "table", &[], nil);
3897
    // The table is for another receiver layout, or the receiver views another layout.
3898
    try objectCase(P4, OBJECT, "cells", &[], verify::Rule::Type);
3899
    try objectCase(CELL, OBJECT, "table", &[], verify::Rule::Type);
3900
    try objectCase(CELL, OBJECT, "cells", &[], nil);
3901
    // A table that lacks a method, or that can be written.
3902
    try objectCase(P4, OBJECT, "short", &[], verify::Rule::Type);
3903
    try objectCase(P4, OBJECT, "open", &[], verify::Rule::Mutability);
3904
    try objectCase(P4, OBJECT, "missing", &[], verify::Rule::Symbol);
3905
3906
    // A table must be a symbol, not a value.
3907
    let mut b = newBuilder();
3908
    addObjects(&mut b);
3909
    try checkIn(
3910
        &mut b,
3911
        &[],
3912
        il::ValType::Void,
3913
        &[
3914
            reserve(0, P4), reserve(1, OBJECT), traitNew(1, 0, imm(0)), retVoid()
3915
        ],
3916
        verify::Rule::Type
3917
    );
3918
3919
    // The destination must be a trait object slot.
3920
    let mut c = newBuilder();
3921
    addObjects(&mut c);
3922
    try checkIn(
3923
        &mut c,
3924
        &[],
3925
        il::ValType::Void,
3926
        &[
3927
            reserve(0, P4), reserve(1, P16), traitNew(1, 0, il::Val::DataSym("table")), retVoid()
3928
        ],
3929
        verify::Rule::Slot
3930
    );
3931
}
3932
3933
/// Check that the receiver of a trait object has the class and rights of its slot.
3934
@test unsafe fn traitObjectReceivers() throws (testing::TestError) {
3935
    // An owning slot needs an owning receiver.
3936
    try objectCase(P4, OBJECT + 2, "table", &[], verify::Rule::Class);
3937
3938
    // A borrowed receiver stays in the frame.
3939
    let mut b = newBuilder();
3940
    addObjects(&mut b);
3941
    try checkIn(
3942
        &mut b,
3943
        &[param(0, ptrType(OBJECT, false, true, false))],
3944
        il::ValType::Void,
3945
        &[
3946
            reserve(1, P4), traitNew(0, 1, il::Val::DataSym("table")), retVoid()
3947
        ],
3948
        verify::Rule::Return
3949
    );
3950
3951
    // A writable slot needs a writable receiver.
3952
    let mut c = newBuilder();
3953
    addObjects(&mut c);
3954
    try checkIn(
3955
        &mut c,
3956
        &[param(0, ptrType(P4, false, false, false))],
3957
        il::ValType::Void,
3958
        &[
3959
            reserve(1, OBJECT), traitNew(1, 0, il::Val::DataSym("table")), retVoid()
3960
        ],
3961
        verify::Rule::Mutability
3962
    );
3963
    let mut d = newBuilder();
3964
    addObjects(&mut d);
3965
    try checkIn(
3966
        &mut d,
3967
        &[param(0, ptrType(P4, false, false, false))],
3968
        il::ValType::Void,
3969
        &[
3970
            reserve(1, OBJECT + 1), traitNew(1, 0, il::Val::DataSym("table")), retVoid()
3971
        ],
3972
        nil
3973
    );
3974
}
3975
3976
/// Check one call through the object that [`objectCase`] builds from a `P4` receiver.
3977
unsafe fn methodCase(
3978
    object: u32,
3979
    dst: ?u32,
3980
    retTy: il::ValType,
3981
    method: u32,
3982
    receiver: u32,
3983
    values: &[il::Val],
3984
    rule: ?verify::Rule
3985
) throws (testing::TestError) {
3986
    let mut b = newBuilder();
3987
    addObjects(&mut b);
3988
    let range = args(&mut b, values);
3989
    try checkIn(
3990
        &mut b,
3991
        &[],
3992
        il::ValType::Void,
3993
        &[
3994
            reserve(0, P4),
3995
            reserve(1, object),
3996
            traitNew(1, 0, il::Val::DataSym("table")),
3997
            traitCall(dst, retTy, 1, method, receiver, range),
3998
            retVoid(),
3999
        ],
4000
        rule
4001
    );
4002
}
4003
4004
/// Check the method, receiver position, arguments and result of a trait call.
4005
@test unsafe fn traitObjectMethods() throws (testing::TestError) {
4006
    let none = il::Val::Undef;
4007
    try methodCase(OBJECT, 2, dataType(), 0, 0, &[none], nil);
4008
    try methodCase(OBJECT, nil, il::ValType::Void, 1, 0, &[none, imm(1)], nil);
4009
    // A read-only object reads, and does not write.
4010
    try methodCase(OBJECT + 1, 2, dataType(), 0, 0, &[none], nil);
4011
    try methodCase(
4012
        OBJECT + 1, nil, il::ValType::Void, 1, 0, &[none, imm(1)], verify::Rule::Mutability
4013
    );
4014
    // The method exists, and the receiver is at its position, with no argument there.
4015
    try methodCase(OBJECT, 2, dataType(), 2, 0, &[none], verify::Rule::Call);
4016
    try methodCase(OBJECT, nil, il::ValType::Void, 1, 1, &[imm(1), none], verify::Rule::Call);
4017
    try methodCase(OBJECT, 2, dataType(), 0, 0, &[imm(1)], verify::Rule::Call);
4018
    try methodCase(OBJECT, 2, dataType(), 0, 0, &[reg(0)], verify::Rule::Call);
4019
    // The arguments and the result fit the method.
4020
    try methodCase(OBJECT, 2, dataType(), 0, 0, &[none, imm(1)], verify::Rule::Arity);
4021
    try methodCase(OBJECT, nil, il::ValType::Void, 1, 0, &[none], verify::Rule::Arity);
4022
    try methodCase(OBJECT, nil, il::ValType::Void, 0, 0, &[none], verify::Rule::Call);
4023
    try methodCase(OBJECT, 2, il::ValType::Void, 0, 0, &[none], verify::Rule::Call);
4024
}
4025
4026
/// Check that only the trait instructions write or read a trait object slot as such.
4027
@test unsafe fn traitObjectSlots() throws (testing::TestError) {
4028
    try objectCase(P4, OBJECT, "table", &[store64(imm(0),  1, 8)], verify::Rule::Slot);
4029
    try objectCase(P4, OBJECT, "table", &[store(imm(0),    1, 4)], verify::Rule::Slot);
4030
    try objectCase(P4, OBJECT, "table", &[storePtr(imm(0), 1, 0)], verify::Rule::Slot);
4031
    try objectCase(P4, OBJECT, "table", &[loadPtr(2,       1, 8)], verify::Rule::Slot);
4032
    // Reading the bytes as data is allowed, and so is copying the whole object.
4033
    try objectCase(P4, OBJECT, "table", &[load64(2,  1, 8)], nil);
4034
    try objectCase(P4, OBJECT, "table", &[reserve(2, OBJECT), blit(2, 1, OBJECT)], nil);
4035
    // The copy keeps a borrowed receiver in the frame.
4036
    let mut b = newBuilder();
4037
    addObjects(&mut b);
4038
    try checkIn(
4039
        &mut b,
4040
        &[param(0, ptrType(OBJECT, false, true, false))],
4041
        il::ValType::Void,
4042
        &[
4043
            reserve(1, P4),
4044
            reserve(2, OBJECT),
4045
            traitNew(2, 1, il::Val::DataSym("table")),
4046
            blit(0, 2, OBJECT),
4047
            retVoid(),
4048
        ],
4049
        verify::Rule::Return
4050
    );
4051
    // A call needs a trait object slot.
4052
    let mut c = newBuilder();
4053
    addObjects(&mut c);
4054
    let get = args(&mut c, &[il::Val::Undef]);
4055
    try checkIn(
4056
        &mut c,
4057
        &[],
4058
        il::ValType::Void,
4059
        &[
4060
            reserve(0, P16), traitCall(1, dataType(), 0, 0, 0, get), retVoid()
4061
        ],
4062
        verify::Rule::Slot
4063
    );
4064
}
4065
4066
/// Check that static trait objects are owning, read-only and zero, and that the trait table
4067
/// places receivers within the parameters.
4068
@test unsafe fn traitObjectTablesAndData() throws (testing::TestError) {
4069
    let mut b = newBuilder();
4070
    addObjects(&mut b);
4071
    addData(&mut b, "d", OBJECT + 2, true, &[repeat(il::DataItem::Undef, 16)]);
4072
    try accepted(&mut b);
4073
    // Several contexts can write mutable data, and a borrowed receiver would outlive its
4074
    // frame.
4075
    let mut c = newBuilder();
4076
    addObjects(&mut c);
4077
    addData(&mut c, "d", OBJECT + 2, false, &[repeat(il::DataItem::Undef, 16)]);
4078
    try rejected(&mut c, verify::Rule::Data);
4079
    let mut d = newBuilder();
4080
    addObjects(&mut d);
4081
    addData(&mut d, "d", OBJECT, true, &[repeat(il::DataItem::Undef, 16)]);
4082
    try rejected(&mut d, verify::Rule::Data);
4083
    // An initializer cannot build an object.
4084
    let mut e = newBuilder();
4085
    addObjects(&mut e);
4086
    addData(&mut e, "d", OBJECT + 2, true, &[symbol("table"), symbol("table")]);
4087
    try rejected(&mut e, verify::Rule::Data);
4088
    // A receiver goes among the parameters of the method.
4089
    let mut f = newBuilder();
4090
    addTrait(&mut f, &[il::Method { sig: SIG_VOID, receiver: 1, own: false, mutable: false }]);
4091
    try rejected(&mut f, verify::Rule::Layout);
4092
    // An owning pointer can point to an object with a borrowed receiver.
4093
    let mut g = newBuilder();
4094
    addObjects(&mut g);
4095
    addLayout(&mut g, 8, 8, &[ptrSlot(0, OBJECT, true, false)]);
4096
    try accepted(&mut g);
4097
}
4098
4099
/// Copy the trait object at `src` to the slot at `dst`.
4100
fn traitCopy(dst: u32, src: u32) -> il::Instr {
4101
    return il::Instr::TraitCopy { dst: il::Reg { n: dst }, src: il::Reg { n: src } };
4102
}
4103
4104
/// A trait slot can be read with fewer receiver rights without a separate copy.
4105
@test unsafe fn traitObjectViews() throws (testing::TestError) {
4106
    let mut b = newBuilder();
4107
    addObjects(&mut b);
4108
    try checkIn(
4109
        &mut b,
4110
        &[],
4111
        il::ValType::Void,
4112
        &[
4113
            reserve(0, OBJECT), reserve(1, OBJECT + 1), blit(1, 0, OBJECT + 1), retVoid()
4114
        ],
4115
        nil
4116
    );
4117
    let mut reversed = newBuilder();
4118
    addObjects(&mut reversed);
4119
    try checkIn(
4120
        &mut reversed,
4121
        &[],
4122
        il::ValType::Void,
4123
        &[
4124
            reserve(0, OBJECT + 1), reserve(1, OBJECT), blit(1, 0, OBJECT), retVoid()
4125
        ],
4126
        verify::Rule::View
4127
    );
4128
}
4129
4130
/// A trait view preserves both the interface and ownership class.
4131
@test unsafe fn traitViewIdentity() throws (testing::TestError) {
4132
    let mut b = newBuilder();
4133
    addObjects(&mut b);
4134
    addTrait(&mut b, &[]);
4135
    let other = addLayout(&mut b, 16, 8, &[
4136
        il::Slot {
4137
            offset: 0,
4138
            kind: il::SlotKind::Trait(il::ObjectType {
4139
                iface: 1, own: false, mutable: false
4140
            }),
4141
            regions: &[],
4142
        },
4143
    ]);
4144
    let t = try layout::build(&b.layouts[..], CONFIG, heap::over(&mut SCRATCH[..])) catch {
4145
        throw testing::TestError::Failed;
4146
    };
4147
    assert not layout::holds(&t, OBJECT, 0, other);
4148
    assert not layout::holds(&t, OBJECT + 2, 0, OBJECT + 1);
4149
    assert not layout::holds(&t, OBJECT + 1, 0, OBJECT + 2);
4150
}
4151
4152
/// Check that a trait object is copied only to a slot of the same trait with the same or
4153
/// fewer rights, and that a borrowed receiver stays in the frame.
4154
@test unsafe fn traitObjectCopies() throws (testing::TestError) {
4155
    try objectCase(P4, OBJECT, "table", &[reserve(2, OBJECT + 1), traitCopy(2, 1)], nil);
4156
    try objectCase(P4, OBJECT, "table", &[reserve(2, OBJECT), traitCopy(2, 1)], nil);
4157
    // A copy cannot gain the right to write, or ownership.
4158
    let mut b = newBuilder();
4159
    addObjects(&mut b);
4160
    try checkIn(
4161
        &mut b,
4162
        &[param(0, ptrType(P4, false, false, false))],
4163
        il::ValType::Void,
4164
        &[
4165
            reserve(1, OBJECT + 1),
4166
            traitNew(1, 0, il::Val::DataSym("table")),
4167
            reserve(2,   OBJECT),
4168
            traitCopy(2, 1),
4169
            retVoid(),
4170
        ],
4171
        verify::Rule::Mutability
4172
    );
4173
    try objectCase(
4174
        P4, OBJECT, "table", &[reserve(2, OBJECT + 2), traitCopy(2, 1)], verify::Rule::Class
4175
    );
4176
    // A borrowed receiver is not copied out of the frame.
4177
    let mut c = newBuilder();
4178
    addObjects(&mut c);
4179
    try checkIn(
4180
        &mut c,
4181
        &[param(0, ptrType(OBJECT, false, true, false))],
4182
        il::ValType::Void,
4183
        &[
4184
            reserve(1, P4),
4185
            reserve(2, OBJECT),
4186
            traitNew(2, 1, il::Val::DataSym("table")),
4187
            traitCopy(0, 2),
4188
            retVoid(),
4189
        ],
4190
        verify::Rule::Return
4191
    );
4192
    // Both slots are trait objects of the same trait.
4193
    try objectCase(P4, OBJECT, "table", &[reserve(2, P16), traitCopy(2, 1)], verify::Rule::Slot);
4194
    let mut d = newBuilder();
4195
    addObjects(&mut d);
4196
    addTrait(&mut d, &[]);
4197
    let other = addLayout(&mut d, 16, 8, &[
4198
        il::Slot {
4199
            offset: 0,
4200
            kind: il::SlotKind::Trait(il::ObjectType {
4201
                iface: 1, own: false, mutable: false
4202
            }),
4203
            regions: &[],
4204
        },
4205
    ]);
4206
    try checkIn(
4207
        &mut d,
4208
        &[],
4209
        il::ValType::Void,
4210
        &[
4211
            reserve(0, P4),
4212
            reserve(1, OBJECT),
4213
            traitNew(1, 0, il::Val::DataSym("table")),
4214
            reserve(2,   other),
4215
            traitCopy(2, 1),
4216
            retVoid(),
4217
        ],
4218
        verify::Rule::View
4219
    );
4220
}
4221
4222
/// Pair reachability follows forward pointers, cycles, and nonempty nested layouts.
4223
@test unsafe fn pairReachabilityGraph() throws (testing::TestError) {
4224
    let mut b = newBuilder();
4225
    let first = b.layouts.len;
4226
    for i in 0 .. 128 {
4227
        addLayout(&mut b, 8, 8, &[ptrSlot(0, first + i + 1, true, true)]);
4228
    }
4229
    let last = addLayout(&mut b, 16, 8, &[sliceSlot(0, P4, true, true)]);
4230
    let cycle = b.layouts.len;
4231
    addLayout(&mut b, 8, 8, &[ptrSlot(0, cycle + 1, true, true)]);
4232
    addLayout(&mut b, 8, 8, &[ptrSlot(0, cycle, true, true)]);
4233
    let nested = addLayout(&mut b, 8, 8, &[subSlot(0, first)]);
4234
    let empty = addLayout(&mut b, 0, 8, &[
4235
        il::Slot { offset: 0, kind: il::SlotKind::Array { layout: last, count: 0 }, regions: &[] }
4236
    ]);
4237
    let pairedCycle = b.layouts.len;
4238
    addLayout(&mut b, 8, 8, &[ptrSlot(0, pairedCycle + 1, true, true)]);
4239
    addLayout(&mut b, 24, 8, &[
4240
        ptrSlot(0, pairedCycle, true, true), sliceSlot(8, P4, true, true)
4241
    ]);
4242
    let scratch = heap::over(&mut SCRATCH[..]);
4243
    let table = try! layout::build(&b.layouts[..], CONFIG, scratch);
4244
    assert table.infos[first].reaches and table.infos[last].reaches;
4245
    assert table.infos[nested].reaches;
4246
    assert not table.infos[cycle].reaches;
4247
    assert not table.infos[cycle + 1].reaches;
4248
    assert not table.infos[empty].reaches;
4249
    assert table.infos[pairedCycle].reaches;
4250
    assert table.infos[pairedCycle + 1].reaches;
4251
}
4252
4253
///////////////////
4254
// Union slots   //
4255
///////////////////
4256
4257
/// Sixteen bytes: a union with a tag byte and a payload at offset 8, whose variants are 0, a
4258
/// `CELL`; 1, a `P4`; and 2, no payload. [`addUnions`] adds it after the layouts above.
4259
constant UNION: u32 = 27;
4260
/// Sixteen bytes: a union with the single variant 0, a `LOCAL`.
4261
constant BORROWED: u32 = 28;
4262
/// Eight bytes: an owned writable pointer to a `UNION`.
4263
constant UNIONPTR: u32 = 29;
4264
/// Sixteen bytes: a union with the variants 0, a `CELLC`; 1, a `P4`; and 2, no payload.
4265
constant UNIONRO: u32 = 30;
4266
/// Forty bytes: a union with the variants 0, a `PAIR`; and 1, a `P4`.
4267
constant UNIONPART: u32 = 31;
4268
4269
/// A variant of a union slot.
4270
fn variant(tag: u32, layout: ?u32) -> il::UnionVariant {
4271
    return il::UnionVariant { tag, layout, regions: &[] };
4272
}
4273
4274
/// A union slot at offset 0 of `size` bytes with its payload at `offset`.
4275
fn unionSlot(b: &mut Builder, offset: u32, size: u32, variants: &[il::UnionVariant]) -> il::Slot {
4276
    let mut own: *mut [il::UnionVariant] = &mut [];
4277
    try! own.extend(variants, b.arena);
4278
    return il::Slot {
4279
        offset: 0, kind: il::SlotKind::Union { offset, size, variants: &own[..] }, regions: &[]
4280
    };
4281
}
4282
4283
/// Reading a read-only union payload cannot produce a writable slot.
4284
@test unsafe fn unionReadRights() throws (testing::TestError) {
4285
    let mut b = newBuilder();
4286
    addUnions(&mut b);
4287
    try checkIn(
4288
        &mut b,
4289
        &[],
4290
        il::ValType::Void,
4291
        &[reserve(0, UNIONRO), reserve(1, CELL), unionGet(1, 0, 0, 8, CELL), retVoid()],
4292
        verify::Rule::View
4293
    );
4294
}
4295
4296
/// Add the layouts of the union tests, which have the indices named above.
4297
fn addUnions(b: &mut Builder) {
4298
    let first = unionSlot(b, 8, 16, &[variant(0, CELL), variant(1, P4), variant(2, nil)]);
4299
    assert addLayout(b, 16, 8, &[first]) == UNION;
4300
    let second = unionSlot(b, 8, 16, &[variant(0, LOCAL)]);
4301
    assert addLayout(b, 16, 8, &[second]) == BORROWED;
4302
    assert addLayout(b, 8, 8, &[ptrSlot(0, UNION, true, true)]) == UNIONPTR;
4303
    let third = unionSlot(b, 8, 16, &[variant(0, CELLC), variant(1, P4), variant(2, nil)]);
4304
    assert addLayout(b, 16, 8, &[third]) == UNIONRO;
4305
    let fourth = unionSlot(b, 8, 40, &[variant(0, PAIR), variant(1, P4)]);
4306
    assert addLayout(b, 40, 8, &[fourth]) == UNIONPART;
4307
}
4308
4309
/// Read the payload of the variant `tag` at `offset` of the union `src` into `dst`.
4310
fn unionGet(dst: u32, src: u32, tag: u32, offset: u32, layout: u32) -> il::Instr {
4311
    return il::Instr::UnionGet {
4312
        dst: il::Reg { n: dst }, src: il::Reg { n: src }, tag, offset, layout
4313
    };
4314
}
4315
4316
/// Write the variant `tag` into the union `dst`, with the payload at `src` or without one.
4317
fn unionSet(dst: u32, tag: u32, offset: u32, src: il::Val, layout: ?u32) -> il::Instr {
4318
    return il::Instr::UnionSet { dst: il::Reg { n: dst }, tag, offset, src, layout };
4319
}
4320
4321
/// Check `main`, which has a `UNION` in register 0, a `CELL` in register 1 and a `P4` in
4322
/// register 2, and then runs `instrs`.
4323
unsafe fn unionCase(instrs: &[il::Instr], rule: ?verify::Rule) throws (testing::TestError) {
4324
    let mut b = newBuilder();
4325
    addUnions(&mut b);
4326
    let mut body: *mut [il::Instr] = &mut [];
4327
    try! body.append(reserve(0, UNION), b.arena);
4328
    try! body.append(reserve(1, CELL), b.arena);
4329
    try! body.append(reserve(2, P4), b.arena);
4330
    try! body.extend(instrs, b.arena);
4331
    try! body.append(retVoid(), b.arena);
4332
    try checkIn(&mut b, &[], il::ValType::Void, &body[..], rule);
4333
}
4334
4335
/// Check that a union is written with a variant and read back with the same tag and layout,
4336
/// and that its tag and whole value are readable as data.
4337
@test unsafe fn unionSlotAccess() throws (testing::TestError) {
4338
    try unionCase(
4339
        &[
4340
            unionSet(0, 0, 8, reg(1), CELL),
4341
            unionGet(1, 0, 0, 8, CELL),
4342
            unionSet(0, 1, 8, reg(2), P4),
4343
            unionGet(2, 0, 1, 8, P4),
4344
            unionSet(0, 2, 8, il::Val::Undef, nil),
4345
            load(3,     0, 0),
4346
            reserve(4,  UNION),
4347
            blit(4,     0, UNION),
4348
        ],
4349
        nil
4350
    );
4351
}
4352
4353
/// Check `main`, which has a `UNIONPART` in register 0, and then runs `instrs`. The payload is at
4354
/// offset 8, and the `PAIR` has a `CELL` at 8 and a `SLICE` at 16 of its own offsets.
4355
unsafe fn partCase(instrs: &[il::Instr], rule: ?verify::Rule) throws (testing::TestError) {
4356
    let mut b = newBuilder();
4357
    addUnions(&mut b);
4358
    let mut body: *mut [il::Instr] = &mut [];
4359
    try! body.append(reserve(0, UNIONPART), b.arena);
4360
    try! body.extend(instrs, b.arena);
4361
    try! body.append(retVoid(), b.arena);
4362
    try checkIn(&mut b, &[], il::ValType::Void, &body[..], rule);
4363
}
4364
4365
/// Check that a read takes a part of the payload that the layout of the variant has there: a
4366
/// slot that fills a destination of its own, a nested object, or plain bytes, and nothing else.
4367
@test unsafe fn unionSlotParts() throws (testing::TestError) {
4368
    // The whole payload, a pointer, a slice and plain bytes, and the pointer is then loaded.
4369
    try partCase(&[reserve(1, PAIR), unionGet(1, 0, 0, 8, PAIR)], nil);
4370
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 0, 16, CELL), loadPtr(2, 1, 0)], nil);
4371
    try partCase(&[reserve(1, SLICE), unionGet(1, 0, 0, 24, SLICE)], nil);
4372
    try partCase(&[reserve(1, P8), unionGet(1, 0, 0, 8, P8)], nil);
4373
    try partCase(&[reserve(1, P4), unionGet(1, 0, 1, 8, P4)], nil);
4374
    // An offset that is not where a slot of that layout is, or is before the payload.
4375
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 0, 17, CELL)], verify::Rule::View);
4376
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 0, 24, CELL)], verify::Rule::View);
4377
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 0, 8, CELL)], verify::Rule::View);
4378
    try partCase(&[reserve(1, P8), unionGet(1, 0, 0, 4, P8)], verify::Rule::View);
4379
    // A part read with fewer rights than its slot, but not of another kind.
4380
    try partCase(&[reserve(1, CELLC), unionGet(1, 0, 0, 16, CELLC)], nil);
4381
    try partCase(&[reserve(1, SLICEC), unionGet(1, 0, 0, 24, SLICEC)], nil);
4382
    try partCase(&[reserve(1, SLICE), unionGet(1, 0, 0, 16, SLICE)], verify::Rule::View);
4383
    // A part that straddles a slot, or is bytes of one.
4384
    try partCase(&[reserve(1, P16), unionGet(1, 0, 0, 16, P16)], verify::Rule::View);
4385
    try partCase(&[reserve(1, P8), unionGet(1, 0, 0, 16, P8)], verify::Rule::View);
4386
    try partCase(&[reserve(1, P8), unionGet(1, 0, 0, 24, P8)], verify::Rule::View);
4387
    // A part that runs past the payload of the variant, or that belongs to another variant.
4388
    try partCase(&[reserve(1, P16), unionGet(1, 0, 1, 8, P16)], verify::Rule::View);
4389
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 1, 8, CELL)], verify::Rule::View);
4390
    try partCase(&[reserve(1, CELL), unionGet(1, 0, 1, 16, CELL)], verify::Rule::View);
4391
    // A write takes the whole payload.
4392
    try partCase(&[reserve(1, PAIR), unionSet(0, 0, 8, reg(1), PAIR)], nil);
4393
    try partCase(&[reserve(1, CELL), unionSet(0, 0, 16, reg(1), CELL)], verify::Rule::View);
4394
}
4395
4396
/// Check that the tag, the payload offset and the layout of a read or write match a variant
4397
/// of the slot, and that a variant without a payload takes none.
4398
@test unsafe fn unionSlotVariants() throws (testing::TestError) {
4399
    try unionCase(&[unionGet(1, 0, 3, 8, CELL)], verify::Rule::View);
4400
    try unionCase(&[unionGet(1, 0, 1, 8, CELL)], verify::Rule::View);
4401
    try unionCase(&[unionGet(1, 0, 0, 4, CELL)], verify::Rule::View);
4402
    try unionCase(&[unionGet(1, 0, 2, 8, CELL)], verify::Rule::View);
4403
    try unionCase(&[unionSet(0, 3, 8, reg(1), CELL)], verify::Rule::View);
4404
    try unionCase(&[unionSet(0, 0, 8, reg(2), P4)], verify::Rule::View);
4405
    try unionCase(&[unionSet(0, 0, 4, reg(1), CELL)], verify::Rule::View);
4406
    try unionCase(&[unionSet(0, 2, 8, reg(1), nil)], verify::Rule::Type);
4407
    try unionCase(&[unionSet(0, 2, 8, il::Val::Undef, CELL)], verify::Rule::View);
4408
    try unionCase(&[unionSet(0, 0, 8, il::Val::Undef, CELL)], verify::Rule::Type);
4409
    try unionCase(&[unionSet(0, 0, 8, imm(0), CELL)], verify::Rule::Type);
4410
    // The objects that carry the payload have the layout of the variant.
4411
    try unionCase(&[unionGet(1, 0, 1, 8, P4)], verify::Rule::View);
4412
    try unionCase(&[reserve(3,  P8), unionSet(0, 0, 8, reg(3), CELL)], verify::Rule::View);
4413
    // A payload that has slots can be read into plain bytes of its size.
4414
    try unionCase(&[reserve(3, P8), unionGet(3, 0, 0, 8, CELL)], nil);
4415
}
4416
4417
/// Check that the instructions need a pointer to the start of a writable union slot.
4418
@test unsafe fn unionSlotPointers() throws (testing::TestError) {
4419
    // The pointer is at the start of the slot.
4420
    try unionCase(&[field(3, 0, 8), unionGet(1, 3, 0, 8, CELL)], verify::Rule::Slot);
4421
    try unionCase(&[field(3, 0, 8), unionSet(3, 0, 8, reg(1), CELL)], verify::Rule::Slot);
4422
    try unionCase(&[field(3, 0, 4), unionSet(3, 1, 8, reg(2), P4)], verify::Rule::Slot);
4423
    // It addresses a union, and a writable one for a write.
4424
    try unionCase(&[unionGet(2, 1, 0, 8, P4)], verify::Rule::Slot);
4425
    try unionCase(&[unionSet(1, 0, 8, reg(1), CELL)], verify::Rule::Slot);
4426
    let mut b = newBuilder();
4427
    addUnions(&mut b);
4428
    try checkIn(
4429
        &mut b,
4430
        &[
4431
            param(0, ptrType(UNION, false, false, false)),
4432
            param(1, ptrType(CELL, false, true, false)),
4433
        ],
4434
        il::ValType::Void,
4435
        &[unionSet(0, 0, 8, reg(1), CELL), retVoid()],
4436
        verify::Rule::Mutability
4437
    );
4438
    // A union can be read through a read-only pointer, but not through a nullable one.
4439
    let mut c = newBuilder();
4440
    addUnions(&mut c);
4441
    try checkIn(
4442
        &mut c,
4443
        &[
4444
            param(0, ptrType(UNION, false, false, false)),
4445
            param(1, ptrType(CELL, false, true, false)),
4446
        ],
4447
        il::ValType::Void,
4448
        &[unionGet(1, 0, 0, 8, CELL), retVoid()],
4449
        nil
4450
    );
4451
    let mut d = newBuilder();
4452
    addUnions(&mut d);
4453
    try checkIn(
4454
        &mut d,
4455
        &[
4456
            param(0, ptrType(UNION, false, false, true)),
4457
            param(1, ptrType(CELL, false, true, false)),
4458
        ],
4459
        il::ValType::Void,
4460
        &[unionGet(1, 0, 0, 8, CELL), retVoid()],
4461
        verify::Rule::Null
4462
    );
4463
}
4464
4465
/// Check that nothing but the union instructions writes a tag or a payload, and that no
4466
/// interior pointer views them.
4467
@test unsafe fn unionSlotProtection() throws (testing::TestError) {
4468
    // Plain stores over the tag, the padding and the payload.
4469
    try unionCase(
4470
        &[
4471
            il::Instr::Store {
4472
                typ: il::Type::W8, src: imm(0), dst: il::Reg { n: 0 }, offset: 0
4473
            },
4474
        ],
4475
        verify::Rule::Slot
4476
    );
4477
    try unionCase(&[store(imm(0),   0, 4)], verify::Rule::Slot);
4478
    try unionCase(&[store(imm(0),   0, 8)], verify::Rule::Slot);
4479
    try unionCase(&[store64(imm(0), 0, 8)], verify::Rule::Slot);
4480
    // Typed accesses of the payload as a pointer.
4481
    try unionCase(&[storePtr(imm(0), 0, 8)], verify::Rule::Slot);
4482
    try unionCase(&[storePtr(imm(0), 0, 0)], verify::Rule::Slot);
4483
    try unionCase(&[loadPtr(3,       0, 8)], verify::Rule::Slot);
4484
    try unionCase(&[loadPtr(3,       0, 0)], verify::Rule::Slot);
4485
    // Reads as data are allowed.
4486
    try unionCase(&[load64(3, 0, 8), load64(4, 0, 0)], nil);
4487
    // An interior pointer does not view the payload, as data or as its layout.
4488
    try unionCase(&[field(3, 0, 8), blit(2, 3, P4)], verify::Rule::View);
4489
    try unionCase(&[field(3, 0, 8), blit(3, 2, P4)], verify::Rule::View);
4490
    try unionCase(&[field(3, 0, 8), blit(1, 3, CELL)], verify::Rule::View);
4491
    try unionCase(&[field(3, 0, 8), store(imm(0), 3, 0)], verify::Rule::Slot);
4492
    // Plain bytes cannot be copied over a union, and a union is copied as a whole only.
4493
    try unionCase(&[reserve(3, P16), blit(0, 3, P16)], verify::Rule::View);
4494
    try unionCase(&[reserve(3, P16), blit(3, 0, P16)], verify::Rule::View);
4495
    try unionCase(&[reserve(3, BORROWED), blit(3, 0, UNION)], verify::Rule::View);
4496
}
4497
4498
/// Check that a payload with a borrowed slot stays in the frame, as a copy of it does,
4499
/// or reaches a target object only with pointers that it permits.
4500
@test unsafe fn unionSlotBorrows() throws (testing::TestError) {
4501
    let mut b = newBuilder();
4502
    addUnions(&mut b);
4503
    try checkIn(
4504
        &mut b,
4505
        &[param(0, ptrType(BORROWED, false, true, false))],
4506
        il::ValType::Void,
4507
        &[reserve(1, LOCAL), unionSet(0, 0, 8, reg(1), LOCAL), retVoid()],
4508
        nil
4509
    );
4510
    let mut framed = newBuilder();
4511
    addUnions(&mut framed);
4512
    try checkIn(
4513
        &mut framed,
4514
        &[param(0, ptrType(BORROWED, false, true, false))],
4515
        il::ValType::Void,
4516
        &[
4517
            reserve(1,       LOCAL),
4518
            reserve(2,       P4),
4519
            storePtr(reg(2), 1, 0),
4520
            unionSet(0,      0, 8, reg(1), LOCAL),
4521
            retVoid(),
4522
        ],
4523
        verify::Rule::Return
4524
    );
4525
    let mut c = newBuilder();
4526
    addUnions(&mut c);
4527
    try checkIn(
4528
        &mut c,
4529
        &[param(0, ptrType(BORROWED, false, true, false))],
4530
        il::ValType::Void,
4531
        &[reserve(1, LOCAL), unionGet(1, 0, 0, 8, LOCAL), retVoid()],
4532
        nil
4533
    );
4534
    let mut d = newBuilder();
4535
    addUnions(&mut d);
4536
    try checkIn(
4537
        &mut d,
4538
        &[
4539
            param(0, ptrType(LOCAL, false, true, false)),
4540
            param(1, ptrType(BORROWED, false, true, false)),
4541
        ],
4542
        il::ValType::Void,
4543
        &[unionGet(0, 1, 0, 8, LOCAL), retVoid()],
4544
        verify::Rule::Return
4545
    );
4546
    let mut e = newBuilder();
4547
    addUnions(&mut e);
4548
    try checkIn(
4549
        &mut e,
4550
        &[],
4551
        il::ValType::Void,
4552
        &[reserve(0, BORROWED), reserve(1, LOCAL), unionSet(0, 0, 8, reg(1), LOCAL), retVoid()],
4553
        nil
4554
    );
4555
}
4556
4557
/// Check the program that holds the read-only data "t" of a `P4` and the data "d" of a `UNIONRO`
4558
/// with the initializer `values`: it is accepted when `rule` is nil, or rejected for `rule`.
4559
unsafe fn unionData(readOnly: bool, values: &[il::DataValue], rule: ?verify::Rule)
4560
    throws (testing::TestError)
4561
{
4562
    let mut b = newBuilder();
4563
    addUnions(&mut b);
4564
    addData(&mut b, "t", P4, true, &[number(il::Type::W32, 5)]);
4565
    addData(&mut b, "d", UNIONRO, readOnly, values);
4566
    try expect(&mut b, rule);
4567
}
4568
4569
/// Check that read-only data holds a union with the tag of a variant and a payload that fits the
4570
/// layout of that variant, and that mutable data cannot hold or reach a union, as for a slice.
4571
@test unsafe fn unionSlotData() throws (testing::TestError) {
4572
    let pad = repeat(il::DataItem::Undef, 7);
4573
    let rest = repeat(il::DataItem::Undef, 8);
4574
    // Zero is every variant at once.
4575
    try unionData(true, &[repeat(il::DataItem::Undef, 16)], nil);
4576
    try unionData(true, &[number(il::Type::W64,       0), number(il::Type::W64, 0)], nil);
4577
    // A pointer under the variant with a pointer, a number under the other, and no payload.
4578
    try unionData(true, &[number(il::Type::W8, 0), pad, symbol("t")], nil);
4579
    try unionData(
4580
        true,
4581
        &[number(il::Type::W8, 1), pad, number(il::Type::W32, 7), repeat(il::DataItem::Undef, 4)],
4582
        nil
4583
    );
4584
    try unionData(true, &[number(il::Type::W8, 2), pad, rest], nil);
4585
    // An unknown tag, or a tag that is not a byte.
4586
    try unionData(true, &[number(il::Type::W8, 9), pad, rest], verify::Rule::Data);
4587
    try unionData(
4588
        true, &[number(il::Type::W16, 1), repeat(il::DataItem::Undef, 14)], verify::Rule::Data
4589
    );
4590
    // A payload that does not match the layout of the tag: an address under the plain variant, a
4591
    // number under the pointer, an address that does not fit, and a payload under a variant
4592
    // without one.
4593
    try unionData(true, &[number(il::Type::W8, 1), pad, symbol("t")], verify::Rule::Data);
4594
    try unionData(
4595
        true, &[number(il::Type::W8, 0), pad, number(il::Type::W64, 5)], verify::Rule::Data
4596
    );
4597
    try unionData(true, &[number(il::Type::W8, 0), pad, symbol("d")], verify::Rule::Data);
4598
    try unionData(
4599
        true, &[number(il::Type::W8, 2), pad, number(il::Type::W64, 5)], verify::Rule::Data
4600
    );
4601
    // The padding is zero.
4602
    try unionData(
4603
        true,
4604
        &[number(il::Type::W8, 1), number(il::Type::W8, 1), repeat(il::DataItem::Undef, 6), rest],
4605
        verify::Rule::Data
4606
    );
4607
    // Mutable data cannot hold a union, or reach one.
4608
    try unionData(false, &[repeat(il::DataItem::Undef, 16)], verify::Rule::Data);
4609
    let mut d = newBuilder();
4610
    addUnions(&mut d);
4611
    addData(&mut d, "d", UNIONPTR, false, &[number(il::Type::W64, 0)]);
4612
    try rejected(&mut d, verify::Rule::Data);
4613
    let mut e = newBuilder();
4614
    addUnions(&mut e);
4615
    addData(&mut e, "d", UNIONPTR, true, &[number(il::Type::W64, 0)]);
4616
    try accepted(&mut e);
4617
}
4618
4619
/// Check nested union initializers with separate tags for the parent and each child.
4620
unsafe fn nestedUnionData(values: &[il::DataValue], rule: ?verify::Rule)
4621
    throws (testing::TestError)
4622
{
4623
    let mut b = newBuilder();
4624
    addUnions(&mut b);
4625
    let payload = addLayout(&mut b, 40, 8, &[subSlot(0, UNIONRO), subSlot(24, UNIONRO)]);
4626
    let slot = unionSlot(&mut b, 8, 48, &[variant(0, P4), variant(1, payload)]);
4627
    let outer = addLayout(&mut b, 48, 8, &[slot]);
4628
    addData(&mut b, "t", P4, true, &[number(il::Type::W32, 5)]);
4629
    addData(&mut b, "d", outer, true, values);
4630
    try expect(&mut b, rule);
4631
}
4632
4633
/// Nested tags select their own payload layouts and preserve the parent's tag.
4634
@test unsafe fn nestedUnionSlotData() throws (testing::TestError) {
4635
    let pad = repeat(il::DataItem::Undef, 7);
4636
    let mut values = [
4637
        number(il::Type::W8,  1), pad,
4638
        number(il::Type::W8,  1), pad, number(il::Type::W32, 7), repeat(il::DataItem::Undef, 4),
4639
        number(il::Type::W64, 9),
4640
        number(il::Type::W8,  0), pad, symbol("t"),
4641
    ];
4642
    try nestedUnionData(&values[..], nil);
4643
    // An unknown child tag cannot select a payload.
4644
    set values[2] = number(il::Type::W8, 9);
4645
    try nestedUnionData(&values[..], verify::Rule::Data);
4646
    // A numeric payload cannot initialize the pointer variant.
4647
    set values[2] = number(il::Type::W8, 0);
4648
    try nestedUnionData(&values[..], verify::Rule::Data);
4649
    set values[2] = number(il::Type::W8, 1);
4650
    // The second child cannot use the tag of its sibling.
4651
    set values[7] = number(il::Type::W8, 1);
4652
    try nestedUnionData(&values[..], verify::Rule::Data);
4653
    set values[7] = number(il::Type::W8, 0);
4654
    // Nested pointers must have the declared target layout.
4655
    set values[9] = symbol("d");
4656
    try nestedUnionData(&values[..], verify::Rule::Data);
4657
    set values[9] = symbol("t");
4658
    // Padding between a child tag and its payload is zero.
4659
    set values[3] = repeat(il::DataItem::Val { typ: il::Type::W8, val: 1 }, 7);
4660
    try nestedUnionData(&values[..], verify::Rule::Data);
4661
}
4662
4663
/// Check that a malformed union slot is rejected: a variant layout that does not precede the
4664
/// layout, a repeated or oversized tag, and a payload that does not fit or is not aligned.
4665
@test unsafe fn unionSlotLayouts() throws (testing::TestError) {
4666
    let mut a = newBuilder();
4667
    let own = a.layouts.len;
4668
    let slotA = unionSlot(&mut a, 8, 16, &[variant(0, own)]);
4669
    addLayout(&mut a, 16, 8, &[slotA]);
4670
    try rejected(&mut a, verify::Rule::Layout);
4671
    let mut b = newBuilder();
4672
    let slotB = unionSlot(&mut b, 8, 16, &[variant(0, P4), variant(0, P8)]);
4673
    addLayout(&mut b, 16, 8, &[slotB]);
4674
    try rejected(&mut b, verify::Rule::Layout);
4675
    let mut c = newBuilder();
4676
    let slotC = unionSlot(&mut c, 8, 16, &[variant(256, P4)]);
4677
    addLayout(&mut c, 16, 8, &[slotC]);
4678
    try rejected(&mut c, verify::Rule::Layout);
4679
    // The payload ends after the union.
4680
    let mut d = newBuilder();
4681
    let slotD = unionSlot(&mut d, 8, 16, &[variant(0, P16)]);
4682
    addLayout(&mut d, 16, 8, &[slotD]);
4683
    try rejected(&mut d, verify::Rule::Layout);
4684
    // The payload is not aligned, or overlaps the tag.
4685
    let mut e = newBuilder();
4686
    let slotE = unionSlot(&mut e, 4, 16, &[variant(0, P8)]);
4687
    addLayout(&mut e, 16, 8, &[slotE]);
4688
    try rejected(&mut e, verify::Rule::Layout);
4689
    let mut f = newBuilder();
4690
    let slotF = unionSlot(&mut f, 0, 16, &[variant(0, P8)]);
4691
    addLayout(&mut f, 16, 8, &[slotF]);
4692
    try rejected(&mut f, verify::Rule::Layout);
4693
    // A union that fits is accepted, also with variants only without payloads.
4694
    let mut g = newBuilder();
4695
    let slotG = unionSlot(&mut g, 4, 8, &[variant(255, P4), variant(7, nil)]);
4696
    addLayout(&mut g, 8, 4, &[slotG]);
4697
    try accepted(&mut g);
4698
    // A union is paired, and a borrowed payload makes the layout borrowed.
4699
    let mut h = newBuilder();
4700
    addUnions(&mut h);
4701
    let scratch = heap::over(&mut SCRATCH[..]);
4702
    let table = try! layout::build(&h.layouts[..], CONFIG, scratch);
4703
    assert table.infos[UNION].pairs and table.infos[UNION].reaches;
4704
    assert table.layouts[BORROWED].regions > 0 and table.layouts[UNION].regions == 0;
4705
    assert table.infos[UNIONPTR].reaches;
4706
    assert layout::size(&table, UNION) == 16;
4707
    assert not layout::isPlain(&table, UNION);
4708
    assert not layout::plain(&table, UNION, 0, 16);
4709
    assert layout::plain(&table, UNION, 0, 0);
4710
}
4711
4712
/// Independent fields keep their source through views, copies and calls.
4713
@test unsafe fn independentBorrowedLeaves() throws (testing::TestError) {
4714
    for mode in 0 .. 7 {
4715
        let mut b = newBuilder();
4716
        let pair = addLayout(&mut b, 32, 8, &[subSlot(0, BORROW), subSlot(16, BORROW)]);
4717
        let buffer = ptrType(pair, false, true, false);
4718
        let input = ptrType(BORROW, false, false, false);
4719
        let body = block(
4720
            &mut b,
4721
            &[],
4722
            &[
4723
                field(3, 0, 0), blit(3, 1, BORROW),
4724
                field(4, 0, 16), blit(4, 2, BORROW), retVoid(),
4725
            ]
4726
        );
4727
        let first = il::Borrow { target: nil, result: 0, param: 1, source: 0 };
4728
        let mut second = il::Borrow { target: nil, result: 1, param: 2, source: 0 };
4729
        if mode == 1 {
4730
            set second.param = 1;
4731
        } else if mode == 2 {
4732
            set second.source = 1;
4733
        } else if mode == 3 {
4734
            set second.result = 2;
4735
        }
4736
        let contracts = [first, second];
4737
        let count: u32 = 1 if mode == 4 else 2;
4738
        addSources(
4739
            &mut b,
4740
            "pair",
4741
            &[param(0, buffer), param(1, input), param(2, input)],
4742
            il::ValType::Void,
4743
            &[body],
4744
            &contracts[.. count]
4745
        );
4746
        if mode >= 5 {
4747
            let passed = args(&mut b, &[reg(2), reg(0), reg(1)]);
4748
            let offset: u32 = 0 if mode == 5 else 16;
4749
            let wrapper = block(
4750
                &mut b,
4751
                &[],
4752
                &[
4753
                    reserve(2,   pair),
4754
                    call(nil,    il::ValType::Void, il::Val::FnAddr("pair"), passed),
4755
                    reserve(3,   BORROW), field(4, 2, offset), blit(3, 4, BORROW),
4756
                    sliceElem(5, 3, imm(0), P1), ret(reg(5)),
4757
                ]
4758
            );
4759
            addSources(
4760
                &mut b,
4761
                "main",
4762
                &[param(0, input), param(1, input)],
4763
                ptrType(P1, false, true, false),
4764
                &[wrapper],
4765
                &[il::Borrow { target: nil, result: 0, param: 0, source: 0 }]
4766
            );
4767
        }
4768
        let mut rule: ?verify::Rule = nil;
4769
        if (mode > 0 and mode < 5) or mode == 6 {
4770
            set rule = verify::Rule::Return;
4771
        }
4772
        try expect(&mut b, rule);
4773
    }
4774
}
4775
4776
/// Slice elements keep content sources separate from their storage source.
4777
@test unsafe fn borrowedElementSources() throws (testing::TestError) {
4778
    for mode in 0 .. 8 {
4779
        let mut b = newBuilder();
4780
        let pair = addLayout(&mut b, 32, 8, &[subSlot(0, BORROW), subSlot(16, BORROW)]);
4781
        let indirect = mode >= 5;
4782
        let mut view: u32 = undefined;
4783
        if indirect {
4784
            set view = addLayout(&mut b, 8, 8, &[ptrSlot(0, pair, false, false)]);
4785
        } else {
4786
            set view = addLayout(&mut b, 16, 8, &[sliceSlot(0, pair, false, false)]);
4787
        }
4788
        let input = ptrType(view, false, false, false);
4789
        let output = ptrType(BORROW, false, true, false);
4790
        let mut instructions: *mut [il::Instr] = &mut [];
4791
        if mode == 4 {
4792
            try! instructions.append(reserve(5, view), b.arena);
4793
            try! instructions.append(
4794
                il::Instr::SliceSub {
4795
                    dst: il::Reg { n: 5 },
4796
                    src: il::Reg { n: 1 },
4797
                    layout: pair,
4798
                    start: imm(0),
4799
                    end: imm(1),
4800
                },
4801
                b.arena
4802
            );
4803
        }
4804
        if indirect {
4805
            try! instructions.append(loadPtr(2, 1, 0), b.arena);
4806
        } else {
4807
            try! instructions.append(sliceElem(2, 5 if mode == 4 else 1, imm(0), pair), b.arena);
4808
        }
4809
        try! instructions.append(field(3, 2, 16), b.arena);
4810
        try! instructions.append(blit(0, 3, BORROW), b.arena);
4811
        try! instructions.append(retVoid(), b.arena);
4812
        let body = block(&mut b, &[], &instructions[..]);
4813
        let source: u32 = 2
4814
            if mode == 0 or mode == 4 or mode == 5
4815
            else 3 if mode == 3 else mode - 6 if indirect else mode - 1;
4816
        addSources(
4817
            &mut b,
4818
            "second",
4819
            &[param(0, output), param(1, input)],
4820
            il::ValType::Void,
4821
            &[body],
4822
            &[il::Borrow { target: nil, result: 0, param: 1, source }]
4823
        );
4824
        let mut rule: ?verify::Rule = nil;
4825
        if (mode > 0 and mode < 4) or mode > 5 {
4826
            set rule = verify::Rule::Return;
4827
        }
4828
        try expect(&mut b, rule);
4829
    }
4830
}
4831
4832
/// Calls retain the independent fields of locally constructed slice elements.
4833
@test unsafe fn borrowedSliceCalls() throws (testing::TestError) {
4834
    for source in 0 .. 2 {
4835
        let mut b = newBuilder();
4836
        let pair = addLayout(&mut b, 32, 8, &[subSlot(0, BORROW), subSlot(16, BORROW)]);
4837
        let view = addLayout(&mut b, 16, 8, &[sliceSlot(0, pair, false, false)]);
4838
        let input = ptrType(BORROW, false, false, false);
4839
        let getter = block(&mut b, &[], &[
4840
            sliceElem(2, 1, imm(0), pair), field(3, 2, 16), blit(0, 3, BORROW), retVoid()
4841
        ]);
4842
        addSources(
4843
            &mut b,
4844
            "second",
4845
            &[
4846
                param(0, ptrType(BORROW, false, true, false)),
4847
                param(1, ptrType(view, false, false, false)),
4848
            ],
4849
            il::ValType::Void,
4850
            &[getter],
4851
            &[il::Borrow { target: nil, result: 0, param: 1, source: 2 }]
4852
        );
4853
        let passed = args(&mut b, &[reg(5), reg(4)]);
4854
        let wrapper = block(
4855
            &mut b,
4856
            &[],
4857
            &[
4858
                reserve(2,   pair), blit(2, 0, BORROW), field(3, 2, 16), blit(3, 1, BORROW),
4859
                reserve(4,   view), sliceNew(4, reg(2), pair, 1), reserve(5, BORROW),
4860
                call(nil,    il::ValType::Void, il::Val::FnAddr("second"), passed),
4861
                sliceElem(6, 5, imm(0), P1), ret(reg(6)),
4862
            ]
4863
        );
4864
        addSources(
4865
            &mut b,
4866
            "wrapper",
4867
            &[param(0, input), param(1, input)],
4868
            ptrType(P1, false, true, false),
4869
            &[wrapper],
4870
            &[il::Borrow { target: nil, result: 0, param: source, source: 0 }]
4871
        );
4872
        let mut rule: ?verify::Rule = nil;
4873
        if source == 0 {
4874
            set rule = verify::Rule::Return;
4875
        }
4876
        try expect(&mut b, rule);
4877
    }
4878
}
4879
4880
/// A parameter's object receives only pointers of its own regions, or of the
4881
/// sources that a target contract names. A caller marks the region of its
4882
/// argument with the sources that it passes.
4883
@test unsafe fn targetContracts() throws (testing::TestError) {
4884
    let object = ptrType(LOCAL, false, true, false);
4885
    let source = ptrType(P4, false, true, false);
4886
    let store = [storePtr(reg(1), 0, 0), retVoid()];
4887
    let permits = [il::Borrow { target: 0, result: 0, param: 1, source: nil }];
4888
    // Without a contract, another parameter's pointer is foreign to the object.
4889
    let mut bare = newBuilder();
4890
    let bareBody = block(&mut bare, &[], &store[..]);
4891
    addSources(
4892
        &mut bare,
4893
        "main",
4894
        &[param(0, object), param(1, source)],
4895
        il::ValType::Void,
4896
        &[bareBody],
4897
        &[]
4898
    );
4899
    try rejected(&mut bare, verify::Rule::Return);
4900
    // A contract permits the storage of the other parameter.
4901
    let mut permitted = newBuilder();
4902
    let permittedBody = block(&mut permitted, &[], &store[..]);
4903
    addSources(
4904
        &mut permitted,
4905
        "main",
4906
        &[param(0, object), param(1, source)],
4907
        il::ValType::Void,
4908
        &[permittedBody],
4909
        &permits[..]
4910
    );
4911
    try accepted(&mut permitted);
4912
    // A caller that passes a frame pointer to it puts that pointer in its own target.
4913
    let mut caller = newBuilder();
4914
    let callerBody = block(&mut caller, &[], &store[..]);
4915
    addSources(
4916
        &mut caller,
4917
        "f",
4918
        &[param(0, object), param(1, source)],
4919
        il::ValType::Void,
4920
        &[callerBody],
4921
        &permits[..]
4922
    );
4923
    let passed = args(&mut caller, &[reg(0), reg(1)]);
4924
    addFn(&mut caller, "main", &[param(0, object)], il::ValType::Void, &[
4925
        reserve(1, P4), call(nil, il::ValType::Void, il::Val::FnAddr("f"), passed), retVoid()
4926
    ]);
4927
    try rejected(&mut caller, verify::Rule::Return);
4928
    // The object of a target argument must be one that can hold borrowed pointers. A join
4929
    // of frame storage and a target object is neither.
4930
    let mut joined = newBuilder();
4931
    let joinedBody = block(&mut joined, &[], &store[..]);
4932
    addSources(
4933
        &mut joined,
4934
        "f",
4935
        &[param(0, object), param(1, source)],
4936
        il::ValType::Void,
4937
        &[joinedBody],
4938
        &permits[..]
4939
    );
4940
    let local = args(&mut joined, &[reg(2)]);
4941
    let outer = args(&mut joined, &[reg(0)]);
4942
    let forwarded = args(&mut joined, &[reg(5), reg(1)]);
4943
    let blocks = [
4944
        block(&mut joined, &[], &[reserve(2, LOCAL), br(reg(3), 1, 2)]),
4945
        block(&mut joined, &[], &[jmp(3, local)]),
4946
        block(&mut joined, &[], &[jmp(3, outer)]),
4947
        block(&mut joined, &[param(5, object)], &[
4948
            call(nil, il::ValType::Void, il::Val::FnAddr("f"), forwarded), retVoid()
4949
        ]),
4950
    ];
4951
    let params = [param(0, object), param(1, source), param(3, dataType())];
4952
    addSources(&mut joined, "main", &params[..], il::ValType::Void, &blocks[..], &[]);
4953
    try rejected(&mut joined, verify::Rule::Class);
4954
}
4955
4956
/// A pointer result has the region of its address, then the regions of its
4957
/// pointee, and each needs a source.
4958
@test unsafe fn borrowedPointerResultRegions() throws (testing::TestError) {
4959
    let ret = il::Instr::Ret { val: il::Val::Reg(il::Reg { n: 0 }) };
4960
    let pairs: [[il::Borrow; 2]; 3] = [
4961
        [
4962
            il::Borrow { target: nil, result: 0, param: 0, source: nil },
4963
            il::Borrow { target: nil, result: 1, param: 0, source: 0 },
4964
        ],
4965
        [
4966
            il::Borrow { target: nil, result: 0, param: 0, source: nil },
4967
            il::Borrow { target: nil, result: 1, param: 1, source: 0 },
4968
        ],
4969
        [
4970
            il::Borrow { target: nil, result: 0, param: 0, source: nil },
4971
            il::Borrow { target: nil, result: 0, param: 1, source: nil },
4972
        ],
4973
    ];
4974
    let rules: [?verify::Rule; 3] = [nil, verify::Rule::Return, verify::Rule::Return];
4975
    for borrows, i in pairs {
4976
        let mut b = newBuilder();
4977
        let boxed = addLayout(&mut b, 8, 8, &[ptrSlot(0, P4, false, false)]);
4978
        let body = block(&mut b, &[], &[ret]);
4979
        let view = ptrType(boxed, false, false, false);
4980
        addSources(&mut b, "main", &[param(0, view), param(1, view)], view, &[body], &borrows[..]);
4981
        try expect(&mut b, rules[i]);
4982
    }
4983
}
4984
4985
/// A layout can reach itself through a borrowed pointer: its regions name the
4986
/// pointee's regions, so a recursive shape has finitely many regions.
4987
@test unsafe fn borrowedSourceCycles() throws (testing::TestError) {
4988
    let mut b = newBuilder();
4989
    let index = b.layouts.len;
4990
    addLabeled(&mut b, ptrSlot(0, index, false, false), &[0, 0]);
4991
    addFn(&mut b, "main", &[], il::ValType::Void, &[retVoid()]);
4992
    try accepted(&mut b);
4993
4994
    // Each position of a slot names a region of its layout.
4995
    let mut wrong = newBuilder();
4996
    let next = wrong.layouts.len;
4997
    addLabeled(&mut wrong, ptrSlot(0, next, false, false), &[0, 1]);
4998
    addFn(&mut wrong, "main", &[], il::ValType::Void, &[retVoid()]);
4999
    try expect(&mut wrong, verify::Rule::Layout);
5000
}
5001
5002
/// Add a layout of one word with one region and a slot with the given regions.
5003
fn addLabeled(b: &mut Builder, slot: il::Slot, regions: *[u32]) {
5004
    let mut slots: *mut [il::Slot] = &mut [];
5005
    let mut item = slot;
5006
    set item.regions = regions;
5007
    try! slots.append(item, b.arena);
5008
    try! b.layouts.append(
5009
        il::Layout { size: 8, alignment: 8, slots: &slots[..], regions: 1 }, b.arena
5010
    );
5011
}
5012
5013
/// Protected union payload copies preserve every borrowed variant leaf.
5014
@test unsafe fn borrowedUnionLeafCopy() throws (testing::TestError) {
5015
    let mut b = newBuilder();
5016
    let pair = addLayout(&mut b, 32, 8, &[subSlot(0, BORROW), subSlot(16, BORROW)]);
5017
    let mut variants: *mut [il::UnionVariant] = &mut [];
5018
    try! variants.extend(
5019
        &[
5020
            il::UnionVariant { tag: 0, layout: pair, regions: &[] },
5021
            il::UnionVariant { tag: 3, layout: pair, regions: &[] },
5022
        ],
5023
        b.arena
5024
    );
5025
    let slots = [
5026
        il::Slot {
5027
            offset: 0,
5028
            kind: il::SlotKind::Union { offset: 8, size: 40, variants: &variants[..] },
5029
            regions: &[],
5030
        },
5031
    ];
5032
    let source = addLayout(&mut b, 40, 8, &slots[..]);
5033
    let target = addLayout(&mut b, 40, 8, &slots[..]);
5034
    let mut outerVariants: *mut [il::UnionVariant] = &mut [];
5035
    try! outerVariants.append(il::UnionVariant { tag: 0, layout: source, regions: &[] }, b.arena);
5036
    let outer = addLayout(&mut b, 48, 8, &[
5037
        il::Slot {
5038
            offset: 0,
5039
            kind: il::SlotKind::Union { offset: 8, size: 48, variants: &outerVariants[..] },
5040
            regions: &[],
5041
        },
5042
    ]);
5043
    let body = block(
5044
        &mut b,
5045
        &[],
5046
        &[
5047
            il::Instr::UnionGet {
5048
                dst: il::Reg { n: 0 }, src: il::Reg { n: 1 }, tag: 0, offset: 8, layout: target
5049
            },
5050
            retVoid(),
5051
        ]
5052
    );
5053
    addSources(
5054
        &mut b,
5055
        "main",
5056
        &[
5057
            param(0, ptrType(target, false, true, false)),
5058
            param(1, ptrType(outer, false, false, false)),
5059
        ],
5060
        il::ValType::Void,
5061
        &[body],
5062
        &[
5063
            il::Borrow { target: nil, result: 0, param: 1, source: 0 },
5064
            il::Borrow { target: nil, result: 1, param: 1, source: 1 },
5065
            il::Borrow { target: nil, result: 2, param: 1, source: 2 },
5066
            il::Borrow { target: nil, result: 3, param: 1, source: 3 },
5067
        ]
5068
    );
5069
    try accepted(&mut b);
5070
}
5071
5072
/// Copying reference elements requires sources for the destination region.
5073
@test unsafe fn sliceCopyTargetRegions() throws (testing::TestError) {
5074
    let input = ptrType(SLICELOCAL, false, true, false);
5075
    let mut b = newBuilder();
5076
    addFn(&mut b, "f", &[param(0, input), param(1, input)], il::ValType::Void, &[
5077
        sliceCopy(0, 1, LOCAL), retVoid()
5078
    ]);
5079
    try rejected(&mut b, verify::Rule::Return);
5080
}
5081
5082
/// Copying frame references into caller slice elements is rejected.
5083
@test unsafe fn sliceCopyFrameEscape() throws (testing::TestError) {
5084
    let input = ptrType(SLICELOCAL, false, true, false);
5085
    try check(
5086
        &[param(0, input)],
5087
        &[
5088
            reserve(1,   P4), reserve(2, LOCAL), storePtr(reg(1), 2, 0),
5089
            reserve(3,   SLICELOCAL), sliceNew(3, reg(2), LOCAL, 1),
5090
            sliceCopy(0, 3, LOCAL),
5091
        ],
5092
        verify::Rule::Return
5093
    );
5094
}
5095
5096
/// Mutable sub-slices share element provenance with their source slice.
5097
@test unsafe fn subSliceFrameEscape() throws (testing::TestError) {
5098
    let input = ptrType(SLICELOCAL, false, true, false);
5099
    for depth in 0 .. 2 {
5100
        for frame in 0 .. 2 {
5101
            let mut b = newBuilder();
5102
            let mut body: *mut [il::Instr] = &mut [];
5103
            try! body.extend(
5104
                &[
5105
                    reserve(1, P4), reserve(2, LOCAL),
5106
                    storePtr(reg(1) if frame == 1 else imm(0), 2, 0),
5107
                    reserve(3, SLICELOCAL), sliceNew(3, reg(2), LOCAL, 1),
5108
                    reserve(4, SLICELOCAL),
5109
                    il::Instr::SliceSub {
5110
                        dst: il::Reg { n: 4 },
5111
                        src: il::Reg { n: 0 },
5112
                        layout: LOCAL,
5113
                        start: imm(0),
5114
                        end: imm(1),
5115
                    },
5116
                ],
5117
                b.arena
5118
            );
5119
            let mut target: u32 = 4;
5120
            if depth == 1 {
5121
                try! body.extend(
5122
                    &[
5123
                        reserve(5, SLICELOCAL),
5124
                        il::Instr::SliceSub {
5125
                            dst: il::Reg { n: 5 },
5126
                            src: il::Reg { n: 4 },
5127
                            layout: LOCAL,
5128
                            start: imm(0),
5129
                            end: imm(1),
5130
                        },
5131
                    ],
5132
                    b.arena
5133
                );
5134
                set target = 5;
5135
            }
5136
            try! body.extend(&[sliceCopy(target, 3, LOCAL), retVoid()], b.arena);
5137
            let mut rule: ?verify::Rule = nil;
5138
            if frame == 1 {
5139
                set rule = verify::Rule::Return;
5140
            }
5141
            try checkIn(&mut b, &[param(0, input)], il::ValType::Void, &body[..], rule);
5142
        }
5143
    }
5144
}
5145
5146
/// Copied slice headers share mutable element provenance.
5147
@test unsafe fn copiedSliceFrameEscape() throws (testing::TestError) {
5148
    let input = ptrType(SLICELOCAL, false, true, false);
5149
    try check(
5150
        &[param(0, input)],
5151
        &[
5152
            reserve(1,   P4), reserve(2, LOCAL), storePtr(reg(1), 2, 0),
5153
            reserve(3,   SLICELOCAL), sliceNew(3, reg(2), LOCAL, 1),
5154
            reserve(4,   SLICELOCAL), blit(4, 0, SLICELOCAL),
5155
            sliceCopy(4, 3, LOCAL),
5156
        ],
5157
        verify::Rule::Return
5158
    );
5159
}
5160
5161
/// A mutable borrowed call result retains the regions of its argument.
5162
@test unsafe fn callAliasFrameEscape() throws (testing::TestError) {
5163
    let input = ptrType(SLICELOCAL, false, true, false);
5164
    let mut b = newBuilder();
5165
    let identity = block(&mut b, &[], &[ret(reg(0))]);
5166
    addSources(
5167
        &mut b,
5168
        "identity",
5169
        &[param(0, input)],
5170
        input,
5171
        &[identity],
5172
        &[
5173
            il::Borrow { target: nil, result: 0, param: 0, source: nil },
5174
            il::Borrow { target: nil, result: 1, param: 0, source: 0 },
5175
            il::Borrow { target: nil, result: 2, param: 0, source: 1 },
5176
        ]
5177
    );
5178
    let passed = args(&mut b, &[reg(0)]);
5179
    addFn(
5180
        &mut b,
5181
        "f",
5182
        &[param(0, input)],
5183
        il::ValType::Void,
5184
        &[
5185
            reserve(1,   P4), reserve(2, LOCAL), storePtr(reg(1), 2, 0),
5186
            reserve(3,   SLICELOCAL), sliceNew(3, reg(2), LOCAL, 1),
5187
            call(4,      input, il::Val::FnAddr("identity"), passed),
5188
            sliceCopy(4, 3, LOCAL), retVoid(),
5189
        ]
5190
    );
5191
    try rejected(&mut b, verify::Rule::Return);
5192
}
5193
5194
/// A whole-object source retains aliases to every region it permits.
5195
@test unsafe fn wholeSourceAliasFrameEscape() throws (testing::TestError) {
5196
    let input = ptrType(SLICELOCAL, false, true, false);
5197
    let mut b = newBuilder();
5198
    let identity = block(&mut b, &[], &[ret(reg(0))]);
5199
    addSources(
5200
        &mut b,
5201
        "identity",
5202
        &[param(0, input)],
5203
        input,
5204
        &[identity],
5205
        &[
5206
            il::Borrow { target: nil, result: 0, param: 0, source: nil },
5207
            il::Borrow { target: nil, result: 1, param: 0, source: nil },
5208
            il::Borrow { target: nil, result: 2, param: 0, source: nil },
5209
        ]
5210
    );
5211
    let passed = args(&mut b, &[reg(0)]);
5212
    addFn(
5213
        &mut b,
5214
        "f",
5215
        &[param(0, input)],
5216
        il::ValType::Void,
5217
        &[
5218
            reserve(1,   P4), reserve(2, LOCAL), storePtr(reg(1), 2, 0),
5219
            reserve(3,   SLICELOCAL), sliceNew(3, reg(2), LOCAL, 1),
5220
            call(4,      input, il::Val::FnAddr("identity"), passed),
5221
            sliceCopy(4, 3, LOCAL), retVoid(),
5222
        ]
5223
    );
5224
    try rejected(&mut b, verify::Rule::Return);
5225
}
5226
5227
/// Aggregate copies retain aliases through nested slots and read-only pointers.
5228
@test unsafe fn aggregateAliasFrameEscape() throws (testing::TestError) {
5229
    for kind in 0 .. 3 {
5230
        for frame in 0 .. 2 {
5231
            let mut b = newBuilder();
5232
            let mut container: u32 = undefined;
5233
            if kind == 0 {
5234
                set container = addLayout(&mut b, 8, 8, &[ptrSlot(0, SLICELOCAL, false, false)]);
5235
            } else if kind == 1 {
5236
                set container = addLayout(&mut b, 16, 8, &[subSlot(0, SLICELOCAL)]);
5237
            } else {
5238
                set container = addLayout(&mut b, 16, 8, &[
5239
                    il::Slot {
5240
                        offset: 0,
5241
                        kind: il::SlotKind::Array { layout: SLICELOCAL, count: 1 },
5242
                        regions: &[],
5243
                    },
5244
                ]);
5245
            }
5246
            let input = ptrType(container, false, true, false);
5247
            let mut rule: ?verify::Rule = nil;
5248
            if frame == 1 {
5249
                set rule = verify::Rule::Return;
5250
            }
5251
            try checkIn(
5252
                &mut b,
5253
                &[param(0, input)],
5254
                il::ValType::Void,
5255
                &[
5256
                    reserve(1, P4), reserve(2, LOCAL),
5257
                    storePtr(reg(1) if frame == 1 else imm(0), 2, 0),
5258
                    reserve(3, SLICELOCAL), sliceNew(3, reg(2), LOCAL, 1),
5259
                    reserve(4, container), blit(4, 0, container),
5260
                    loadPtr(5, 4, 0) if kind == 0 else field(5, 4, 0),
5261
                    sliceCopy(5, 3, LOCAL), retVoid(),
5262
                ],
5263
                rule
5264
            );
5265
        }
5266
    }
5267
}
5268
5269
/// Union payload and slice element copies preserve mutable pointer aliases.
5270
@test unsafe fn payloadAliasFrameEscape() throws (testing::TestError) {
5271
    let input = ptrType(SLICELOCAL, false, true, false);
5272
    for kind in 0 .. 2 {
5273
        for frame in 0 .. 2 {
5274
            let mut b = newBuilder();
5275
            let mut body: *mut [il::Instr] = &mut [];
5276
            try! body.extend(
5277
                &[
5278
                    reserve(1, P4), reserve(2, LOCAL),
5279
                    storePtr(reg(1) if frame == 1 else imm(0), 2, 0),
5280
                    reserve(3, SLICELOCAL), sliceNew(3, reg(2), LOCAL, 1),
5281
                    reserve(5, SLICELOCAL),
5282
                ],
5283
                b.arena
5284
            );
5285
            if kind == 0 {
5286
                let mut variant: *mut [il::UnionVariant] = &mut [];
5287
                try! variant.append(
5288
                    il::UnionVariant { tag: 0, layout: SLICELOCAL, regions: &[] }, b.arena
5289
                );
5290
                let payload = addLayout(&mut b, 24, 8, &[
5291
                    il::Slot {
5292
                        offset: 0,
5293
                        kind: il::SlotKind::Union { offset: 8, size: 24, variants: &variant[..] },
5294
                        regions: &[],
5295
                    },
5296
                ]);
5297
                try! body.extend(
5298
                    &[
5299
                        reserve(4,  payload), unionSet(4, 0, 8, reg(0), SLICELOCAL),
5300
                        unionGet(5, 4, 0, 8, SLICELOCAL),
5301
                    ],
5302
                    b.arena
5303
                );
5304
            } else {
5305
                let headers = addLayout(&mut b, 16, 8, &[sliceSlot(0, SLICELOCAL, false, true)]);
5306
                try! body.extend(
5307
                    &[
5308
                        reserve(4,   headers), sliceNew(4, reg(0), SLICELOCAL, 1),
5309
                        reserve(6,   headers), sliceNew(6, reg(5), SLICELOCAL, 1),
5310
                        sliceCopy(6, 4, SLICELOCAL),
5311
                    ],
5312
                    b.arena
5313
                );
5314
            }
5315
            try! body.extend(&[sliceCopy(5, 3, LOCAL), retVoid()], b.arena);
5316
            let mut rule: ?verify::Rule = nil;
5317
            if frame == 1 {
5318
                set rule = verify::Rule::Return;
5319
            }
5320
            try checkIn(&mut b, &[param(0, input)], il::ValType::Void, &body[..], rule);
5321
        }
5322
    }
5323
}
5324
5325
/// A join of frame and caller storage keeps aliases to both objects.
5326
@test unsafe fn mergedAliasFrameEscape() throws (testing::TestError) {
5327
    let input = ptrType(SLICELOCAL, false, true, false);
5328
    let mut b = newBuilder();
5329
    let caller = args(&mut b, &[reg(0)]);
5330
    let frame = args(&mut b, &[reg(4)]);
5331
    let blocks = [
5332
        block(
5333
            &mut b,
5334
            &[],
5335
            &[
5336
                reserve(2, P4), reserve(3, LOCAL), storePtr(reg(2), 3, 0),
5337
                reserve(4, SLICELOCAL), sliceNew(4, reg(3), LOCAL, 1), br(reg(1), 1, 2),
5338
            ]
5339
        ),
5340
        block(&mut b, &[], &[jmp(3, caller)]),
5341
        block(&mut b, &[], &[jmp(3, frame)]),
5342
        block(&mut b, &[param(5, input)], &[sliceCopy(5, 4, LOCAL), retVoid()]),
5343
    ];
5344
    addBlocks(
5345
        &mut b, "f", &[param(0, input), param(1, dataType())], il::ValType::Void, &blocks[..]
5346
    );
5347
    try rejected(&mut b, verify::Rule::Return);
5348
}
5349
5350
/// Copied reference fields and read-only referents retain independent regions.
5351
@test unsafe fn independentCopiedRegions() throws (testing::TestError) {
5352
    try check(
5353
        &[param(0, ptrType(LOCAL, false, true, false))],
5354
        &[
5355
            reserve(1,       P4), reserve(2, LOCAL), blit(2, 0, LOCAL),
5356
            storePtr(reg(1), 2, 0),
5357
        ],
5358
        nil
5359
    );
5360
    let mut b = newBuilder();
5361
    let readonly = addLayout(&mut b, 16, 8, &[sliceSlot(0, LOCAL, false, false)]);
5362
    let input = ptrType(readonly, false, false, false);
5363
    try checkIn(
5364
        &mut b,
5365
        &[param(0, input), param(1, input)],
5366
        il::ValType::Void,
5367
        &[
5368
            reserve(2, readonly), blit(2, 0, readonly), blit(2, 1, readonly), retVoid()
5369
        ],
5370
        nil
5371
    );
5372
}
5373
5374
/// Mutable regions propagate through recursive read-only pointer paths.
5375
@test unsafe fn recursiveSharedRegions() throws (testing::TestError) {
5376
    for mutable in 0 .. 2 {
5377
        let mut b = newBuilder();
5378
        let first = b.layouts.len;
5379
        addLabeled(&mut b, ptrSlot(0, first + 1, true, false), &[0]);
5380
        addLabeled(&mut b, ptrSlot(0, first, true, mutable == 1), &[0]);
5381
        let table = try! layout::build(&b.layouts[..], CONFIG, heap::over(&mut SCRATCH[..]));
5382
        assert table.infos[first].shared[0] == (mutable == 1);
5383
        assert table.infos[first + 1].shared[0] == (mutable == 1);
5384
    }
5385
}
5386
5387
/// Borrowed result buffers retain mutable aliases to their input regions.
5388
@test unsafe fn bufferedAliasFrameEscape() throws (testing::TestError) {
5389
    let input = ptrType(SLICELOCAL, false, true, false);
5390
    let mut b = newBuilder();
5391
    let copied = block(&mut b, &[], &[blit(0, 1, SLICELOCAL), retVoid()]);
5392
    addSources(
5393
        &mut b,
5394
        "copy",
5395
        &[param(0, input), param(1, input)],
5396
        il::ValType::Void,
5397
        &[copied],
5398
        &[
5399
            il::Borrow { target: nil, result: 0, param: 1, source: 0 },
5400
            il::Borrow { target: nil, result: 1, param: 1, source: 1 },
5401
        ]
5402
    );
5403
    let passed = args(&mut b, &[reg(4), reg(0)]);
5404
    addFn(
5405
        &mut b,
5406
        "f",
5407
        &[param(0, input)],
5408
        il::ValType::Void,
5409
        &[
5410
            reserve(1,   P4), reserve(2, LOCAL), storePtr(reg(1), 2, 0),
5411
            reserve(3,   SLICELOCAL), sliceNew(3, reg(2), LOCAL, 1),
5412
            reserve(4,   SLICELOCAL), call(nil, il::ValType::Void, il::Val::FnAddr("copy"), passed),
5413
            sliceCopy(4, 3, LOCAL), retVoid(),
5414
        ]
5415
    );
5416
    try rejected(&mut b, verify::Rule::Return);
5417
}
5418
5419
/// Result buffers cannot supply undeclared inputs to target stores.
5420
@test unsafe fn resultBufferInputEscape() throws (testing::TestError) {
5421
    let slot = ptrType(LOCAL, false, true, false);
5422
    let source = ptrType(P4, false, false, false);
5423
    let mut b = newBuilder();
5424
    let body = block(&mut b, &[], &[blit(1, 0, LOCAL), retVoid()]);
5425
    addSources(
5426
        &mut b,
5427
        "f",
5428
        &[param(0, slot), param(1, slot), param(2, source)],
5429
        il::ValType::Void,
5430
        &[body],
5431
        &[
5432
            il::Borrow { target: nil, result: 0, param: 2, source: nil },
5433
            il::Borrow { target: 1,   result: 0, param: 2, source: nil },
5434
        ]
5435
    );
5436
    let passed = args(&mut b, &[reg(3), reg(0), reg(1)]);
5437
    let caller = block(
5438
        &mut b,
5439
        &[],
5440
        &[
5441
            reserve(2, P4), reserve(3, LOCAL), storePtr(reg(2), 3, 0),
5442
            call(nil,  il::ValType::Void, il::Val::FnAddr("f"), passed), retVoid(),
5443
        ]
5444
    );
5445
    addSources(&mut b, "g", &[param(0, slot), param(1, source)], il::ValType::Void, &[caller], &[
5446
        il::Borrow { target: 0, result: 0, param: 1, source: nil }
5447
    ]);
5448
    try rejected(&mut b, verify::Rule::Return);
5449
}
5450
5451
/// A protected slice can use a prefix of its backing array.
5452
@test unsafe fn sliceArrayPrefixView() throws (testing::TestError) {
5453
    let params = [param(0, ptrType(CELLS, true, true, false))];
5454
    try check(&params[..], &[reserve(1, SLICECELL), sliceNew(1, reg(0), CELL, 3)], nil);
5455
    try check(
5456
        &params[..],
5457
        &[reserve(1, SLICECELL), sliceNew(1, reg(0), CELL, 4)],
5458
        verify::Rule::Bounds
5459
    );
5460
    try check(&params[..], &[reserve(1, SLICECELL), sliceNew(1, reg(0), CELL, 2)], nil);
5461
}
5462
5463
/// A result buffer retains each input region without mixing independent sources.
5464
@test unsafe fn resultBufferRegions() throws (testing::TestError) {
5465
    for cross in &[false, true] {
5466
        let mut b = newBuilder();
5467
        let pair = addLayout(&mut b, 16, 8, &[subSlot(0, LOCAL), subSlot(8, LOCAL)]);
5468
        let entry = block(&mut b, &[], &[
5469
            field(2, 0, 0), field(3, 0, 8), blit(2, 3, LOCAL), retVoid()
5470
        ])
5471
            if cross
5472
            else block(&mut b, &[], &[retVoid()]);
5473
        addSources(
5474
            &mut b,
5475
            "f",
5476
            &[
5477
                param(0, ptrType(pair, false, true, false)),
5478
                param(1, ptrType(P4, false, false, false)),
5479
            ],
5480
            il::ValType::Void,
5481
            &[entry],
5482
            &[
5483
                il::Borrow { target: nil, result: 0, param: 1, source: nil },
5484
                il::Borrow { target: nil, result: 1, param: 1, source: nil },
5485
            ]
5486
        );
5487
        if cross {
5488
            try rejected(&mut b, verify::Rule::Return);
5489
        } else {
5490
            try accepted(&mut b);
5491
        }
5492
    }
5493
}
5494
5495
/// A write-only result buffer shares mutable contents with its declared source.
5496
@test unsafe fn bufferedMutableContents() throws (testing::TestError) {
5497
    let mut b = newBuilder();
5498
    let body = block(&mut b, &[], &[
5499
        reserve(2, SLICELOCAL), sliceSub(2, 1, LOCAL), blit(0, 2, SLICELOCAL), retVoid()
5500
    ]);
5501
    addSources(
5502
        &mut b,
5503
        "f",
5504
        &[
5505
            param(0, ptrType(SLICELOCAL, false, true, false)),
5506
            param(1, ptrType(SLICELOCAL, false, false, false)),
5507
        ],
5508
        il::ValType::Void,
5509
        &[body],
5510
        &[
5511
            il::Borrow { target: nil, result: 0, param: 1, source: 0 },
5512
            il::Borrow { target: nil, result: 1, param: 1, source: 1 },
5513
        ]
5514
    );
5515
    try accepted(&mut b);
5516
}
5517
5518
/// Byte operations accept plain bytes and enforce element write permission.
5519
@test unsafe fn byteAccess() throws (testing::TestError) {
5520
    for width in &[il::Type::W8, il::Type::W16, il::Type::W32, il::Type::W64] {
5521
        let read = il::Instr::BytesLoad {
5522
            typ: width, dst: il::Reg { n: 1 }, slice: il::Reg { n: 0 }, offset: imm(0)
5523
        };
5524
        let write = il::Instr::BytesStore {
5525
            typ: width, slice: il::Reg { n: 0 }, offset: imm(0), value: imm(0)
5526
        };
5527
        for slot in &[SLICE, SLICEC, BORROW, SLICE4, SLICECELL, P16] {
5528
            let input = param(0, ptrType(slot, false, false, false));
5529
            let invalid = slot == SLICE4 or slot == SLICECELL;
5530
            let expected = verify::Rule::View if invalid else verify::Rule::Slot;
5531
            try check(&[input], &[read], expected if invalid or slot == P16 else nil);
5532
            if slot == SLICEC {
5533
                try check(&[input], &[write], verify::Rule::Mutability);
5534
            } else {
5535
                try check(&[input], &[write], expected if invalid or slot == P16 else nil);
5536
            }
5537
        }
5538
        let nullable = param(0, ptrType(SLICE, false, false, true));
5539
        try check(&[nullable], &[read], verify::Rule::Null);
5540
        try check(&[nullable], &[write], verify::Rule::Null);
5541
    }
5542
}
5543
5544
/// Verified data-only dependency function used by the import environment tests.
5545
constant IMPORT_TARGET: il::Fn = il::Fn {
5546
    name: "dep::id",
5547
    params: &[il::Param { value: il::Reg { n: 0 }, type: il::ValType::Data(il::Type::W64) }],
5548
    returnType: il::ValType::Data(il::Type::W64),
5549
    isExtern: false,
5550
    isLeaf: true,
5551
    blocks: &[
5552
        il::Block {
5553
            label: il::BlockLabel { base: "entry", suffix: nil },
5554
            params: &[],
5555
            instrs: &[il::Instr::Ret { val: il::Val::Reg(il::Reg { n: 0 }) }],
5556
            locs: &[],
5557
            preds: &[],
5558
            loopDepth: 0,
5559
        },
5560
    ],
5561
    vals: &[],
5562
    cases: &[],
5563
    borrows: &[],
5564
};
5565
5566
/// Independent storage for the verified dependency declaration.
5567
static IMPORT_MEMORY: [u8; 4096] = [0; 4096];
5568
5569
/// An imported function gets its checked signature from an exact dependency binding.
5570
@test unsafe fn typedPackageImport() throws (testing::TestError) {
5571
    let providerArena = heap::over(&mut IMPORT_MEMORY[..]);
5572
    let mut declarations: *mut [il::Fn] = &mut [];
5573
    try! declarations.append(IMPORT_TARGET, providerArena);
5574
    let frozen: *[il::Fn] = &declarations[..];
5575
    let mut functions: *mut [*il::Fn] = &mut [];
5576
    try! functions.append(&frozen[0], providerArena);
5577
    let mut provider = binary::Package {
5578
        version: nil,
5579
        symbols: &["dep", "dep::id"],
5580
        name: "dep",
5581
        dependencies: &[],
5582
        exports: &[
5583
            binary::Export {
5584
                name: "dep::id", kind: binary::ExportKind::Function(0), startable: false
5585
            },
5586
        ],
5587
        entry: nil,
5588
        program: il::Program {
5589
            data: &[], fns: &functions[..], layouts: &[], signatures: &[], traits: &[]
5590
        },
5591
        links: binary::EMPTY_LINKS,
5592
    };
5593
    let scratch = heap::over(&mut SCRATCH[..]);
5594
    try! verify::verifyProgram(&provider.program, CONFIG, scratch);
5595
    let mut b = newBuilder();
5596
    let arguments = args(&mut b, &[imm(42)]);
5597
    addFn(&mut b, "caller", &[], dataType(), &[
5598
        call(0, dataType(), il::Val::FnAddr("dep::id"), arguments), ret(reg(0))
5599
    ]);
5600
    let identity = linkage::imageId("provider image");
5601
    set provider.links.metadata = identity;
5602
    let mut pins: *mut [binary::Id] = &mut [];
5603
    try! pins.append(
5604
        identity, b.arena
5605
    );
5606
    let mut package = binary::Package {
5607
        version: nil,
5608
        symbols: &[],
5609
        name: "p",
5610
        dependencies: &["dep"],
5611
        exports: &[],
5612
        entry: nil,
5613
        program: program(&mut b),
5614
        links: binary::Links {
5615
            metadata: binary::Id { bytes: [0; linkage::ID_BYTES] },
5616
            pins: &pins[..],
5617
            imports: &[
5618
                binary::Import {
5619
                    dependency: 0,
5620
                    exported: "dep::id",
5621
                    kind: binary::ImportKind::Function(SIG_DATA),
5622
                },
5623
            ],
5624
            image: nil,
5625
            verified: false,
5626
        },
5627
    };
5628
    let mut supplied: *mut [linking::Provider] = &mut [];
5629
    try! supplied.append(
5630
        linking::Provider { image: identity, contract: provider }, b.arena
5631
    );
5632
    let work = heap::over(&mut SCRATCH[..]);
5633
    let keep = heap::over(&mut KEEP[..]);
5634
    try! verify::verifyLinkedPackage(&mut package, &supplied[..], CONFIG, work, keep);
5635
}
5636
5637
/// Layouts in a pointer chain, more than the 4096 descriptor pairs of a small workspace.
5638
constant CHAIN: u32 = 4100;
5639
5640
/// Storage for the layout chain, which the provider and the client share.
5641
static CHAIN_MEMORY: [u8; 524288] = [0; 524288];
5642
/// Working storage for the comparison of the chain.
5643
static CHAIN_SCRATCH: [u8; 2097152] = [0; 2097152];
5644
5645
/// An imported data contract binds when its layout graph has more pairs than a small
5646
/// fixed workspace holds.
5647
@test unsafe fn longImportedLayoutChain() throws (testing::TestError) {
5648
    let arena = heap::over(&mut CHAIN_MEMORY[..]);
5649
    let mut layouts: *mut [il::Layout] = &mut [];
5650
    try! layouts.reserve(CHAIN, arena);
5651
    try! layouts.append(il::Layout { size: 8, alignment: 8, slots: &[], regions: 0 }, arena);
5652
    for i in 1 .. CHAIN {
5653
        let mut slots: *mut [il::Slot] = &mut [];
5654
        try! slots.append(ptrSlot(0, i - 1, false, false), arena);
5655
        try! layouts.append(
5656
            il::Layout { size: 8, alignment: 8, slots: &slots[..], regions: 0 }, arena
5657
        );
5658
    }
5659
    let mut data: *mut [il::Data] = &mut [];
5660
    try! data.append(
5661
        il::Data {
5662
            name: "dep::d",
5663
            size: 8,
5664
            alignment: 8,
5665
            layout: CHAIN - 1,
5666
            readOnly: true,
5667
            heap: nil,
5668
            isZeroInit: true,
5669
            values: &[],
5670
        },
5671
        arena
5672
    );
5673
    let identity = linkage::imageId("chain image");
5674
    let mut provider = binary::Package {
5675
        version: nil,
5676
        symbols: &["dep", "dep::d"],
5677
        name: "dep",
5678
        dependencies: &[],
5679
        exports: &[
5680
            binary::Export { name: "dep::d", kind: binary::ExportKind::Data(0), startable: false }
5681
        ],
5682
        entry: nil,
5683
        program: il::Program {
5684
            data: &data[..], fns: &[], layouts: &layouts[..], signatures: &[], traits: &[]
5685
        },
5686
        links: binary::EMPTY_LINKS,
5687
    };
5688
    set provider.links.metadata = identity;
5689
    let mut pins: *mut [binary::Id] = &mut [];
5690
    try! pins.append(identity, arena);
5691
    let mut imports: *mut [binary::Import] = &mut [];
5692
    try! imports.append(
5693
        binary::Import {
5694
            dependency: 0,
5695
            exported: "dep::d",
5696
            kind: binary::ImportKind::Data { layout: CHAIN - 1, readOnly: true, heap: nil },
5697
        },
5698
        arena
5699
    );
5700
    let package = binary::Package {
5701
        version: nil,
5702
        symbols: &[],
5703
        name: "p",
5704
        dependencies: &["dep"],
5705
        exports: &[],
5706
        entry: nil,
5707
        program: il::Program {
5708
            data: &[], fns: &[], layouts: &layouts[..], signatures: &[], traits: &[]
5709
        },
5710
        links: binary::Links {
5711
            metadata: binary::Id { bytes: [0; linkage::ID_BYTES] },
5712
            pins: &pins[..],
5713
            imports: &imports[..],
5714
            image: nil,
5715
            verified: false,
5716
        },
5717
    };
5718
    let mut supplied: *mut [linking::Provider] = &mut [];
5719
    try! supplied.append(linking::Provider { image: identity, contract: provider }, arena);
5720
    let scratch = heap::over(&mut CHAIN_SCRATCH[..]);
5721
    let resolved = try linking::bind(&package, &supplied[..], scratch) catch {
5722
        throw testing::TestError::Failed;
5723
    };
5724
    try testing::expect(resolved.data.len == 1);
5725
}