1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
#[macro_export]
macro_rules! host_tests {
    ( $TestRegion:path ) => {
        use lazy_static::lazy_static;
        use libc::c_void;
        use lucet_runtime::vmctx::{lucet_vmctx, Vmctx};
        use lucet_runtime::{
            lucet_hostcall, lucet_hostcall_terminate, DlModule, Error, Limits, Region,
            TerminationDetails, TrapCode,
        };
        use std::sync::{Arc, Mutex};
        use $TestRegion as TestRegion;
        use $crate::build::test_module_c;
        use $crate::helpers::{FunctionPointer, MockExportBuilder, MockModuleBuilder};
        #[test]
        fn load_module() {
            let _module = test_module_c("host", "trivial.c").expect("build and load module");
        }

        #[test]
        fn load_nonexistent_module() {
            let module = DlModule::load("/non/existient/file");
            assert!(module.is_err());
        }

        const ERROR_MESSAGE: &'static str = "hostcall_test_func_hostcall_error";

        lazy_static! {
            static ref HOSTCALL_MUTEX: Mutex<()> = Mutex::new(());
        }

        #[lucet_hostcall]
        #[no_mangle]
        pub fn hostcall_test_func_hostcall_error(_vmctx: &mut Vmctx) {
            lucet_hostcall_terminate!(ERROR_MESSAGE);
        }

        #[lucet_hostcall]
        #[no_mangle]
        pub fn hostcall_test_func_hello(vmctx: &mut Vmctx, hello_ptr: u32, hello_len: u32) {
            let heap = vmctx.heap();
            let hello = heap.as_ptr() as usize + hello_ptr as usize;
            if !vmctx.check_heap(hello as *const c_void, hello_len as usize) {
                lucet_hostcall_terminate!("heap access");
            }
            let hello =
                unsafe { std::slice::from_raw_parts(hello as *const u8, hello_len as usize) };
            if hello.starts_with(b"hello") {
                *vmctx.get_embed_ctx_mut::<bool>() = true;
            }
        }

        #[lucet_hostcall]
        #[allow(unreachable_code)]
        #[no_mangle]
        pub fn hostcall_test_func_hostcall_error_unwind(_vmctx: &mut Vmctx) {
            let _lock = HOSTCALL_MUTEX.lock().unwrap();
            unsafe {
                lucet_hostcall_terminate!(ERROR_MESSAGE);
            }
            drop(_lock);
        }

        #[lucet_hostcall]
        #[no_mangle]
        pub fn hostcall_bad_borrow(vmctx: &mut Vmctx) -> bool {
            let heap = vmctx.heap();
            let mut other_heap = vmctx.heap_mut();
            heap[0] == other_heap[0]
        }

        #[lucet_hostcall]
        #[no_mangle]
        pub fn hostcall_missing_embed_ctx(vmctx: &mut Vmctx) -> bool {
            struct S {
                x: bool,
            }
            let ctx = vmctx.get_embed_ctx::<S>();
            ctx.x
        }

        #[lucet_hostcall]
        #[no_mangle]
        pub fn hostcall_multiple_vmctx(vmctx: &mut Vmctx) -> bool {
            let mut vmctx1 = unsafe { Vmctx::from_raw(vmctx.as_raw()) };
            vmctx1.heap_mut()[0] = 0xAF;
            drop(vmctx1);

            let mut vmctx2 = unsafe { Vmctx::from_raw(vmctx.as_raw()) };
            let res = vmctx2.heap()[0] == 0xAF;
            drop(vmctx2);

            res
        }

        #[lucet_hostcall]
        #[no_mangle]
        pub fn hostcall_yields(vmctx: &mut Vmctx) {
            vmctx.yield_();
        }

        #[lucet_hostcall]
        #[no_mangle]
        pub fn hostcall_yield_expects_5(vmctx: &mut Vmctx) -> u64 {
            vmctx.yield_expecting_val()
        }

        #[lucet_hostcall]
        #[no_mangle]
        pub fn hostcall_yields_5(vmctx: &mut Vmctx) {
            vmctx.yield_val(5u64);
        }

        #[lucet_hostcall]
        #[no_mangle]
        pub fn hostcall_yield_facts(vmctx: &mut Vmctx, n: u64) -> u64 {
            fn fact(vmctx: &mut Vmctx, n: u64) -> u64 {
                let result = if n <= 1 { 1 } else { n * fact(vmctx, n - 1) };
                vmctx.yield_val(result);
                result
            }
            fact(vmctx, n)
        }

        pub enum CoopFactsK {
            Mult(u64, u64),
            Result(u64),
        }

        #[lucet_hostcall]
        #[no_mangle]
        pub fn hostcall_coop_facts(vmctx: &mut Vmctx, n: u64) -> u64 {
            fn fact(vmctx: &mut Vmctx, n: u64) -> u64 {
                let result = if n <= 1 {
                    1
                } else {
                    let n_rec = fact(vmctx, n - 1);
                    vmctx.yield_val_expecting_val(CoopFactsK::Mult(n, n_rec))
                };
                vmctx.yield_val(CoopFactsK::Result(result));
                result
            }
            fact(vmctx, n)
        }

        #[test]
        fn instantiate_trivial() {
            let module = test_module_c("host", "trivial.c").expect("build and load module");
            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let inst = region
                .new_instance(module)
                .expect("instance can be created");
        }

        #[test]
        fn run_trivial() {
            let module = test_module_c("host", "trivial.c").expect("build and load module");
            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");
            inst.run("main", &[0u32.into(), 0i32.into()])
                .expect("instance runs");
        }

        #[test]
        fn run_hello() {
            let module = test_module_c("host", "hello.c").expect("build and load module");
            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");

            let mut inst = region
                .new_instance_builder(module)
                .with_embed_ctx(false)
                .build()
                .expect("instance can be created");

            inst.run("main", &[0u32.into(), 0i32.into()])
                .expect("instance runs");

            assert!(*inst.get_embed_ctx::<bool>().unwrap().unwrap());
        }

        #[test]
        fn run_hostcall_error() {
            let module = test_module_c("host", "hostcall_error.c").expect("build and load module");
            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            match inst.run("main", &[0u32.into(), 0i32.into()]) {
                Err(Error::RuntimeTerminated(term)) => {
                    assert_eq!(
                        *term
                            .provided_details()
                            .expect("user provided termination reason")
                            .downcast_ref::<&'static str>()
                            .expect("error was static str"),
                        ERROR_MESSAGE
                    );
                }
                res => panic!("unexpected result: {:?}", res),
            }
        }

        #[test]
        fn run_hostcall_error_unwind() {
            let module =
                test_module_c("host", "hostcall_error_unwind.c").expect("build and load module");
            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            match inst.run("main", &[0u32.into(), 0u32.into()]) {
                Err(Error::RuntimeTerminated(term)) => {
                    assert_eq!(
                        *term
                            .provided_details()
                            .expect("user provided termination reason")
                            .downcast_ref::<&'static str>()
                            .expect("error was static str"),
                        ERROR_MESSAGE
                    );
                }
                res => panic!("unexpected result: {:?}", res),
            }

            assert!(HOSTCALL_MUTEX.is_poisoned());
        }

        #[test]
        fn run_fpe() {
            let module = test_module_c("host", "fpe.c").expect("build and load module");
            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            match inst.run("trigger_div_error", &[0u32.into()]) {
                Err(Error::RuntimeFault(details)) => {
                    assert_eq!(details.trapcode, Some(TrapCode::IntegerDivByZero));
                }
                res => {
                    panic!("unexpected result: {:?}", res);
                }
            }
        }

        #[test]
        fn run_hostcall_bad_borrow() {
            extern "C" {
                fn hostcall_bad_borrow(vmctx: *mut lucet_vmctx) -> bool;
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) {
                hostcall_bad_borrow(vmctx);
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            match inst.run("f", &[]) {
                Err(Error::RuntimeTerminated(details)) => {
                    assert_eq!(details, TerminationDetails::BorrowError("heap_mut"));
                }
                res => {
                    panic!("unexpected result: {:?}", res);
                }
            }
        }

        #[test]
        fn run_hostcall_missing_embed_ctx() {
            extern "C" {
                fn hostcall_missing_embed_ctx(vmctx: *mut lucet_vmctx) -> bool;
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) {
                hostcall_missing_embed_ctx(vmctx);
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            match inst.run("f", &[]) {
                Err(Error::RuntimeTerminated(details)) => {
                    assert_eq!(details, TerminationDetails::CtxNotFound);
                }
                res => {
                    panic!("unexpected result: {:?}", res);
                }
            }
        }

        #[test]
        fn run_hostcall_multiple_vmctx() {
            extern "C" {
                fn hostcall_multiple_vmctx(vmctx: *mut lucet_vmctx) -> bool;
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) {
                hostcall_multiple_vmctx(vmctx);
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            let retval = inst
                .run("f", &[])
                .expect("instance runs")
                .expect_returned("instance returned");
            assert_eq!(bool::from(retval), true);
        }

        #[test]
        fn run_hostcall_yields_5() {
            extern "C" {
                fn hostcall_yields_5(vmctx: *mut lucet_vmctx);
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) {
                hostcall_yields_5(vmctx);
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            assert_eq!(
                *inst
                    .run("f", &[])
                    .unwrap()
                    .unwrap_yielded()
                    .downcast::<u64>()
                    .unwrap(),
                5u64
            );
        }

        #[test]
        fn run_hostcall_yield_expects_5() {
            extern "C" {
                fn hostcall_yield_expects_5(vmctx: *mut lucet_vmctx) -> u64;
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) -> u64 {
                hostcall_yield_expects_5(vmctx)
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            assert!(inst.run("f", &[]).unwrap().unwrap_yielded().is_none());

            let retval = inst
                .resume_with_val(5u64)
                .expect("instance resumes")
                .unwrap_returned();
            assert_eq!(u64::from(retval), 5u64);
        }

        #[test]
        fn yield_factorials() {
            extern "C" {
                fn hostcall_yield_facts(vmctx: *mut lucet_vmctx, n: u64) -> u64;
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) -> u64 {
                hostcall_yield_facts(vmctx, 5)
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            let mut facts = vec![];

            let mut res = inst.run("f", &[]).unwrap();

            while res.is_yielded() {
                facts.push(*res.unwrap_yielded().downcast::<u64>().unwrap());
                res = inst.resume().unwrap();
            }

            assert_eq!(facts.as_slice(), &[1, 2, 6, 24, 120]);
            assert_eq!(u64::from(res.unwrap_returned()), 120u64);
        }

        #[test]
        fn coop_factorials() {
            extern "C" {
                fn hostcall_coop_facts(vmctx: *mut lucet_vmctx, n: u64) -> u64;
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) -> u64 {
                hostcall_coop_facts(vmctx, 5)
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            let mut facts = vec![];

            let mut res = inst.run("f", &[]).unwrap();

            while let Ok(val) = res.yielded_ref() {
                if let Some(k) = val.downcast_ref::<CoopFactsK>() {
                    match k {
                        CoopFactsK::Mult(n, n_rec) => {
                            // guest wants us to multiply for it
                            res = inst.resume_with_val(n * n_rec).unwrap();
                        }
                        CoopFactsK::Result(n) => {
                            // guest is returning an answer
                            facts.push(*n);
                            res = inst.resume().unwrap();
                        }
                    }
                } else {
                    panic!("didn't yield with expected type");
                }
            }

            assert_eq!(facts.as_slice(), &[1, 2, 6, 24, 120]);
            assert_eq!(u64::from(res.unwrap_returned()), 120u64);
        }

        #[test]
        fn resume_unexpected() {
            extern "C" {
                fn hostcall_yields_5(vmctx: *mut lucet_vmctx);
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) {
                hostcall_yields_5(vmctx);
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            assert_eq!(
                *inst
                    .run("f", &[])
                    .unwrap()
                    .unwrap_yielded()
                    .downcast::<u64>()
                    .unwrap(),
                5u64
            );

            match inst.resume_with_val(5u64) {
                Err(Error::InvalidArgument(_)) => (),
                Err(e) => panic!("unexpected error: {}", e),
                Ok(_) => panic!("unexpected success"),
            }
        }

        #[test]
        fn missing_resume_val() {
            extern "C" {
                fn hostcall_yield_expects_5(vmctx: *mut lucet_vmctx) -> u64;
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) -> u64 {
                hostcall_yield_expects_5(vmctx)
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            assert!(inst.run("f", &[]).unwrap().unwrap_yielded().is_none());

            match inst.resume() {
                Err(Error::InvalidArgument(_)) => (),
                Err(e) => panic!("unexpected error: {}", e),
                Ok(_) => panic!("unexpected success"),
            }
        }

        #[test]
        fn resume_wrong_type() {
            extern "C" {
                fn hostcall_yield_expects_5(vmctx: *mut lucet_vmctx) -> u64;
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) -> u64 {
                hostcall_yield_expects_5(vmctx)
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            assert!(inst.run("f", &[]).unwrap().unwrap_yielded().is_none());

            match inst.resume_with_val(true) {
                Err(Error::InvalidArgument(_)) => (),
                Err(e) => panic!("unexpected error: {}", e),
                Ok(_) => panic!("unexpected success"),
            }
        }

        /// This test shows that we can send an `InstanceHandle` to another thread while a guest is
        /// yielded, and it resumes successfully.
        #[test]
        fn switch_threads_resume() {
            extern "C" {
                fn hostcall_yields_5(vmctx: *mut lucet_vmctx);
            }

            unsafe extern "C" fn f(vmctx: *mut lucet_vmctx) -> u64 {
                hostcall_yields_5(vmctx);
                42
            }

            let module = MockModuleBuilder::new()
                .with_export_func(MockExportBuilder::new(
                    "f",
                    FunctionPointer::from_usize(f as usize),
                ))
                .build();

            let region = TestRegion::create(1, &Limits::default()).expect("region can be created");
            let mut inst = region
                .new_instance(module)
                .expect("instance can be created");

            // make sure we yield with 5 on the original thread
            assert_eq!(
                *inst
                    .run("f", &[])
                    .unwrap()
                    .unwrap_yielded()
                    .downcast::<u64>()
                    .unwrap(),
                5u64
            );

            let res = std::thread::spawn(move || {
                // but then move the instance to another thread and resume it from there
                inst.resume()
                    .expect("instance resumes")
                    .returned()
                    .expect("returns 42")
            })
            .join()
            .unwrap();
            assert_eq!(u64::from(res), 42u64);
        }
    };
}