-
Notifications
You must be signed in to change notification settings - Fork 296
/
sandbox_server.rs
1471 lines (1323 loc) · 52.8 KB
/
sandbox_server.rs
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::sync::Arc;
/// This module provides the RPC "glue" code to expose the API
/// functionality of the sandbox towards the controller. There is no
/// actual "logic" in this module, just bridging the interfaces.
use crate::sandbox_manager::SandboxManager;
use ic_canister_sandbox_common::{protocol::sbxsvc::*, rpc, sandbox_service::SandboxService};
/// This is the implementation of the RPC interface exposed by the
/// sandbox process and "binds everything together": All RPCs pass
/// through here and are mapped to the "business" logic code contained
/// in SandboxManager.
pub struct SandboxServer {
/// The SandboxManager contains the business logic (sets up wasm
/// runtimes, executes things, ...). RPC calls map to methods in
/// the manager.
manager: Arc<SandboxManager>,
}
impl SandboxServer {
/// Creates new sandbox server, taking constructed sandbox manager.
pub fn new(manager: SandboxManager) -> Self {
SandboxServer {
manager: Arc::new(manager),
}
}
}
impl SandboxService for SandboxServer {
fn terminate(&self, _req: TerminateRequest) -> rpc::Call<TerminateReply> {
std::process::exit(0);
}
fn open_wasm(&self, req: OpenWasmRequest) -> rpc::Call<OpenWasmReply> {
let result = self
.manager
.open_wasm(req.wasm_id, req.wasm_src)
.map(|(_cache, result, serialized_module)| (result, serialized_module));
rpc::Call::new_resolved(Ok(OpenWasmReply(result)))
}
fn open_wasm_serialized(
&self,
req: OpenWasmSerializedRequest,
) -> rpc::Call<OpenWasmSerializedReply> {
let result = self
.manager
.open_wasm_serialized(req.wasm_id, &req.serialized_module)
.map(|_| ());
rpc::Call::new_resolved(Ok(OpenWasmSerializedReply(result)))
}
fn close_wasm(&self, req: CloseWasmRequest) -> rpc::Call<CloseWasmReply> {
self.manager.close_wasm(req.wasm_id);
rpc::Call::new_resolved(Ok(CloseWasmReply { success: true }))
}
fn open_memory(&self, req: OpenMemoryRequest) -> rpc::Call<OpenMemoryReply> {
self.manager.open_memory(req);
rpc::Call::new_resolved(Ok(OpenMemoryReply { success: true }))
}
fn close_memory(&self, req: CloseMemoryRequest) -> rpc::Call<CloseMemoryReply> {
self.manager.close_memory(req.memory_id);
rpc::Call::new_resolved(Ok(CloseMemoryReply { success: true }))
}
fn start_execution(&self, req: StartExecutionRequest) -> rpc::Call<StartExecutionReply> {
let StartExecutionRequest {
exec_id,
wasm_id,
wasm_memory_id,
stable_memory_id,
exec_input,
} = req;
rpc::Call::new_resolved({
SandboxManager::start_execution(
&self.manager,
exec_id,
wasm_id,
wasm_memory_id,
stable_memory_id,
exec_input,
);
Ok(StartExecutionReply { success: true })
})
}
fn resume_execution(&self, req: ResumeExecutionRequest) -> rpc::Call<ResumeExecutionReply> {
rpc::Call::new_resolved({
SandboxManager::resume_execution(&self.manager, req.exec_id);
Ok(ResumeExecutionReply { success: true })
})
}
fn abort_execution(&self, req: AbortExecutionRequest) -> rpc::Call<AbortExecutionReply> {
rpc::Call::new_resolved({
SandboxManager::abort_execution(&self.manager, req.exec_id);
Ok(AbortExecutionReply { success: true })
})
}
fn create_execution_state(
&self,
req: CreateExecutionStateRequest,
) -> rpc::Call<CreateExecutionStateReply> {
let result = self.manager.create_execution_state(
req.wasm_id,
req.wasm_binary,
req.wasm_page_map,
req.next_wasm_memory_id,
req.canister_id,
req.stable_memory_page_map,
);
rpc::Call::new_resolved(Ok(CreateExecutionStateReply(result)))
}
fn create_execution_state_serialized(
&self,
req: CreateExecutionStateSerializedRequest,
) -> rpc::Call<CreateExecutionStateSerializedReply> {
let result = self.manager.create_execution_state_serialized(
req.wasm_id,
req.serialized_module,
req.wasm_page_map,
req.next_wasm_memory_id,
req.canister_id,
req.stable_memory_page_map,
);
rpc::Call::new_resolved(Ok(CreateExecutionStateSerializedReply(result)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use ic_base_types::{NumSeconds, PrincipalId};
use ic_canister_sandbox_common::{
controller_service::ControllerService,
fdenum::EnumerateInnerFileDescriptors,
protocol::{
self,
id::{ExecId, MemoryId, WasmId},
structs::SandboxExecInput,
},
};
use ic_config::subnet_config::{CyclesAccountManagerConfig, SchedulerConfig};
use ic_config::{embedders::Config as EmbeddersConfig, flag_status::FlagStatus};
use ic_constants::SMALL_APP_SUBNET_MAX_SIZE;
use ic_cycles_account_manager::{CyclesAccountManager, ResourceSaturation};
use ic_interfaces::execution_environment::{ExecutionMode, SubnetAvailableMemory};
use ic_logger::replica_logger::no_op_logger;
use ic_registry_subnet_type::SubnetType;
use ic_replicated_state::{Global, NumWasmPages, PageIndex, PageMap};
use ic_system_api::{
sandbox_safe_system_state::{CanisterStatusView, SandboxSafeSystemState},
ApiType, ExecutionParameters, InstructionLimits,
};
use ic_test_utilities::types::ids::{canister_test_id, subnet_test_id, user_test_id};
use ic_types::{
ingress::WasmResult,
messages::{CallContextId, RequestMetadata},
methods::{FuncRef, WasmMethod},
time::Time,
CanisterTimer, ComputeAllocation, Cycles, MemoryAllocation, NumBytes, NumInstructions,
};
use mockall::*;
use std::collections::{BTreeMap, BTreeSet};
use std::convert::TryFrom;
use std::sync::{Arc, Condvar, Mutex};
const INSTRUCTION_LIMIT: u64 = 100_000;
fn execution_parameters() -> ExecutionParameters {
ExecutionParameters {
instruction_limits: InstructionLimits::new(
FlagStatus::Disabled,
NumInstructions::new(INSTRUCTION_LIMIT),
NumInstructions::new(INSTRUCTION_LIMIT),
),
canister_memory_limit: NumBytes::new(4 << 30),
memory_allocation: MemoryAllocation::default(),
compute_allocation: ComputeAllocation::default(),
subnet_type: SubnetType::Application,
execution_mode: ExecutionMode::Replicated,
subnet_memory_saturation: ResourceSaturation::default(),
}
}
fn sandbox_safe_system_state() -> SandboxSafeSystemState {
let mut ic00_aliases = BTreeSet::new();
ic00_aliases.insert(canister_test_id(0));
let controller = user_test_id(0).get();
SandboxSafeSystemState::new_internal(
canister_test_id(0),
CanisterStatusView::Running,
NumSeconds::from(3600),
MemoryAllocation::BestEffort,
ComputeAllocation::default(),
Cycles::new(1_000_000),
Cycles::zero(),
None,
BTreeMap::new(),
CyclesAccountManager::new(
NumInstructions::from(1_000_000_000),
SubnetType::Application,
subnet_test_id(0),
CyclesAccountManagerConfig::application_subnet(),
),
Some(0),
BTreeMap::new(),
0,
ic00_aliases,
SMALL_APP_SUBNET_MAX_SIZE,
SchedulerConfig::application_subnet().dirty_page_overhead,
CanisterTimer::Inactive,
0,
BTreeSet::from([controller]),
RequestMetadata::new(0, Time::from_nanos_since_unix_epoch(0)),
)
}
fn serialize_memory(page_map: &PageMap, num_wasm_pages: NumWasmPages) -> MemorySerialization {
let mut memory = MemorySerialization {
page_map: page_map.serialize(),
num_wasm_pages,
};
// Duplicate all file descriptors to simulate sending them to another process.
let mut fds: Vec<&mut std::os::unix::io::RawFd> = vec![];
memory.enumerate_fds(&mut fds);
for fd in fds.into_iter() {
*fd = nix::unistd::dup(*fd).unwrap();
}
memory
}
fn exec_input_for_update(
method_name: &str,
incoming_payload: &[u8],
globals: Vec<Global>,
next_wasm_memory_id: MemoryId,
next_stable_memory_id: MemoryId,
) -> SandboxExecInput {
SandboxExecInput {
func_ref: FuncRef::Method(WasmMethod::Update(method_name.to_string())),
api_type: ApiType::update(
Time::from_nanos_since_unix_epoch(0),
incoming_payload.to_vec(),
Cycles::zero(),
PrincipalId::try_from([0].as_ref()).unwrap(),
CallContextId::from(0),
),
globals,
canister_current_memory_usage: NumBytes::from(0),
canister_current_message_memory_usage: NumBytes::from(0),
execution_parameters: execution_parameters(),
subnet_available_memory: SubnetAvailableMemory::new(
i64::MAX / 2,
i64::MAX / 2,
i64::MAX / 2,
),
next_wasm_memory_id,
next_stable_memory_id,
sandbox_safe_system_state: sandbox_safe_system_state(),
wasm_reserved_pages: NumWasmPages::from(0),
}
}
fn exec_input_for_query(
method_name: &str,
incoming_payload: &[u8],
globals: Vec<Global>,
) -> SandboxExecInput {
SandboxExecInput {
func_ref: FuncRef::Method(WasmMethod::Query(method_name.to_string())),
api_type: ApiType::replicated_query(
Time::from_nanos_since_unix_epoch(0),
incoming_payload.to_vec(),
PrincipalId::try_from([0].as_ref()).unwrap(),
None,
),
globals,
canister_current_memory_usage: NumBytes::from(0),
canister_current_message_memory_usage: NumBytes::from(0),
execution_parameters: execution_parameters(),
subnet_available_memory: SubnetAvailableMemory::new(
i64::MAX / 2,
i64::MAX / 2,
i64::MAX / 2,
),
next_wasm_memory_id: MemoryId::new(),
next_stable_memory_id: MemoryId::new(),
sandbox_safe_system_state: sandbox_safe_system_state(),
wasm_reserved_pages: NumWasmPages::from(0),
}
}
mock! {
pub ControllerService {
}
impl ControllerService for ControllerService {
fn execution_finished(
&self, req : protocol::ctlsvc::ExecutionFinishedRequest
) -> rpc::Call<protocol::ctlsvc::ExecutionFinishedReply>;
fn execution_paused(
&self, req : protocol::ctlsvc::ExecutionPausedRequest
) -> rpc::Call<protocol::ctlsvc::ExecutionPausedReply>;
fn log_via_replica(&self, log: protocol::logging::LogRequest) -> rpc::Call<()>;
}
}
struct SyncCell<T> {
item: Mutex<Option<T>>,
cond: Condvar,
}
impl<T> SyncCell<T> {
pub fn new() -> Self {
Self {
item: Mutex::new(None),
cond: Condvar::new(),
}
}
pub fn get(&self) -> T {
let mut guard = self.item.lock().unwrap();
loop {
if let Some(item) = (*guard).take() {
break item;
} else {
guard = self.cond.wait(guard).unwrap();
}
}
}
pub fn put(&self, item: T) {
let mut guard = self.item.lock().unwrap();
*guard = Some(item);
self.cond.notify_one();
}
}
fn make_counter_canister_wasm() -> Vec<u8> {
let wat_data = r#"
;; Counter with global variable ;;
(module
(import "ic0" "msg_reply" (func $msg_reply))
(import "ic0" "msg_reply_data_append"
(func $msg_reply_data_append (param i32 i32)))
(func $read
(i32.store
(i32.const 0)
(global.get 0)
)
(call $msg_reply_data_append
(i32.const 0)
(i32.const 4))
(call $msg_reply))
(func $write
(global.set 0
(i32.add
(global.get 0)
(i32.const 1)
)
)
(call $read)
)
(memory $memory 1)
(export "memory" (memory $memory))
(global (export "counter_global") (mut i32) (i32.const 0))
(export "canister_query read" (func $read))
(export "canister_query inc_read" (func $write))
(export "canister_update write" (func $write))
)
"#;
wat::parse_str(wat_data).unwrap().as_slice().to_vec()
}
fn make_memory_canister_wasm() -> Vec<u8> {
// This canister supports two calls:
// - write: requires 4 bytes of "address" followed by N bytes of payload; writes
// the N payload bytes at given "address" into memory
// - read: requires 4 bytes of "address" followed by 4 bytes of "size"; reads
// "size" bytes from "address" in memory and returns the data as reply
let wat_data = r#"
(module
(import "ic0" "msg_arg_data_size"
(func $msg_arg_data_size (result i32)))
(import "ic0" "msg_arg_data_copy"
(func $msg_arg_data_copy (param i32 i32 i32)))
(import "ic0" "msg_reply" (func $msg_reply))
(import "ic0" "msg_reply_data_append"
(func $msg_reply_data_append (param i32) (param i32)))
(import "ic0" "stable_write"
(func $stable_write (param i32 i32 i32)))
(import "ic0" "stable_read"
(func $stable_read (param i32 i32 i32)))
(func $read
(call $msg_arg_data_copy
(i32.const 0) ;; dst
(i32.const 0) ;; offset
(i32.const 8) ;; size
)
(call $msg_reply_data_append
(i32.load (i32.const 0)) ;; src
(i32.load (i32.const 4)) ;; size
)
(call $msg_reply)
)
(func $write
(call $msg_arg_data_copy
(i32.const 0) ;; dst ;;
(i32.const 0) ;; offset ;;
(i32.const 4) ;; size ;;
)
(call $msg_arg_data_copy
(i32.load (i32.const 0)) ;; dst ;;
(i32.const 4) ;; offset ;;
(i32.sub (call $msg_arg_data_size) (i32.const 4)) ;; size
)
(call $msg_reply)
)
(func $read_stable
(call $msg_arg_data_copy
(i32.const 0) ;; dst
(i32.const 0) ;; offset
(i32.const 8) ;; size
)
(call $stable_read
(i32.const 8) ;; dst
(i32.load (i32.const 0)) ;; offset
(i32.load (i32.const 4)) ;; size
)
(call $msg_reply_data_append
(i32.const 8) ;; src
(i32.load (i32.const 4)) ;; size
)
(call $msg_reply)
)
(func $write_stable
(call $msg_arg_data_copy ;; copy entire message ;;
(i32.const 0) ;; dst ;;
(i32.const 0) ;; offset ;;
(call $msg_arg_data_size) ;; size ;;
)
(call $stable_write
(i32.load (i32.const 0)) ;; stable memory offset ;;
(i32.const 4) ;; src (first 4 bytes were offset) ;;
(i32.sub (call $msg_arg_data_size) (i32.const 4)) ;; size ;;
)
(call $msg_reply)
)
(memory $memory 1)
(export "memory" (memory $memory))
(export "canister_query read" (func $read))
(export "canister_update write" (func $write))
(export "canister_query read_stable" (func $read_stable))
(export "canister_update write_stable" (func $write_stable))
)
"#;
wat::parse_str(wat_data).unwrap().as_slice().to_vec()
}
fn make_long_running_canister_wasm() -> Vec<u8> {
// This canister supports a `run` method that takes 8 bytes
// representing an integer number of instructions to run as an argument.
let wat_data = r#"
(module
(import "ic0" "msg_arg_data_copy"
(func $msg_arg_data_copy (param i32 i32 i32)))
(import "ic0" "msg_reply" (func $msg_reply))
(import "ic0" "msg_reply_data_append"
(func $msg_reply_data_append (param i32) (param i32)))
(import "ic0" "performance_counter"
(func $performance_counter (param i32) (result i64)))
(func $run
(local $limit i64)
(call $msg_arg_data_copy ;; copy i64 argument ;;
(i32.const 0) ;; dst ;;
(i32.const 0) ;; offset ;;
(i32.const 8) ;; size of (i64) ;;
)
(i64.load (i32.const 0))
(local.set $limit)
(loop $loop
(call $performance_counter (i32.const 0))
local.get $limit
i64.lt_s
br_if $loop
)
(call $msg_reply)
)
(memory $memory 1)
(export "memory" (memory $memory))
(export "canister_update run" (func $run))
)
"#;
wat::parse_str(wat_data).unwrap().as_slice().to_vec()
}
/// Create a "mock" controller service that handles the IPC requests
/// incoming from sandbox. It will ignore most of them, with the
/// following important exceptions:
/// - when receiving "ExecFinished" it will put the result in the given
/// SyncCell
/// - when receiving a "special" syscall, it will pass the number of
/// instructions to set up for instrumentation
fn setup_mock_controller(
exec_finished_sync: Arc<SyncCell<protocol::ctlsvc::ExecutionFinishedRequest>>,
) -> Arc<dyn ControllerService> {
let mut controller = MockControllerService::new();
controller
.expect_execution_finished()
.returning(move |req| {
(*exec_finished_sync).put(req);
rpc::Call::new_resolved(Ok(protocol::ctlsvc::ExecutionFinishedReply {}))
});
controller
.expect_log_via_replica()
.returning(move |_req| rpc::Call::new_resolved(Ok(())));
Arc::new(controller)
}
fn open_memory(srv: &SandboxServer, page_map: &PageMap, num_pages: usize) -> MemoryId {
let memory_id = MemoryId::new();
let rep = srv
.open_memory(OpenMemoryRequest {
memory_id,
memory: serialize_memory(page_map, NumWasmPages::new(num_pages)),
})
.sync()
.unwrap();
assert!(rep.success);
memory_id
}
fn close_memory(srv: &SandboxServer, memory_id: MemoryId) {
let rep = srv
.close_memory(protocol::sbxsvc::CloseMemoryRequest { memory_id })
.sync()
.unwrap();
assert!(rep.success);
}
/// Verifies that we can create a simple canister and run something on
/// it.
#[test]
fn test_simple_canister() {
let exec_finished_sync =
Arc::new(SyncCell::<protocol::ctlsvc::ExecutionFinishedRequest>::new());
let srv = SandboxServer::new(SandboxManager::new(
setup_mock_controller(exec_finished_sync.clone()),
EmbeddersConfig::default(),
no_op_logger(),
));
let wasm_id = WasmId::new();
let rep = srv
.open_wasm(OpenWasmRequest {
wasm_id,
wasm_src: make_counter_canister_wasm(),
})
.sync()
.unwrap();
assert!(rep.0.is_ok());
let wasm_memory = PageMap::new_for_testing();
let wasm_memory_id = open_memory(&srv, &wasm_memory, 0);
let stable_memory = PageMap::new_for_testing();
let stable_memory_id = open_memory(&srv, &stable_memory, 0);
// First time around, issue an update to increase the counter.
let exec_id_1 = ExecId::new();
let rep = srv
.start_execution(protocol::sbxsvc::StartExecutionRequest {
exec_id: exec_id_1,
wasm_id,
wasm_memory_id,
stable_memory_id,
exec_input: exec_input_for_update(
"write",
&[],
vec![Global::I32(0), Global::I64(0)],
MemoryId::new(),
MemoryId::new(),
),
})
.sync()
.unwrap();
assert!(rep.success);
let result = exec_finished_sync.get();
assert!(
result.exec_output.wasm.num_instructions_left
< NumInstructions::from(INSTRUCTION_LIMIT)
);
let wasm_result = result.exec_output.wasm.wasm_result.unwrap().unwrap();
let globals = result.exec_output.state.unwrap().globals;
assert_eq!(WasmResult::Reply([1, 0, 0, 0].to_vec()), wasm_result);
// Second time around, issue a query to read the counter. We
// will still read the same value of the counter.
let exec_id_2 = ExecId::new();
let rep = srv
.start_execution(protocol::sbxsvc::StartExecutionRequest {
exec_id: exec_id_2,
wasm_id,
wasm_memory_id,
stable_memory_id,
exec_input: exec_input_for_query("read", &[], globals),
})
.sync()
.unwrap();
assert!(rep.success);
let result = exec_finished_sync.get();
assert!(
result.exec_output.wasm.num_instructions_left
< NumInstructions::from(INSTRUCTION_LIMIT)
);
let wasm_result = result.exec_output.wasm.wasm_result.unwrap().unwrap();
assert_eq!(WasmResult::Reply([1, 0, 0, 0].to_vec()), wasm_result);
}
/// Verify that memory writes result in correct page being marked
/// dirty and passed back.
#[test]
fn test_memory_write_dirty() {
let exec_finished_sync =
Arc::new(SyncCell::<protocol::ctlsvc::ExecutionFinishedRequest>::new());
let srv = SandboxServer::new(SandboxManager::new(
setup_mock_controller(exec_finished_sync.clone()),
EmbeddersConfig::default(),
no_op_logger(),
));
let wasm_id = WasmId::new();
let rep = srv
.open_wasm(OpenWasmRequest {
wasm_id,
wasm_src: make_memory_canister_wasm(),
})
.sync()
.unwrap();
assert!(rep.0.is_ok());
let mut wasm_memory = PageMap::new_for_testing();
let wasm_memory_id = open_memory(&srv, &wasm_memory, 0);
let stable_memory = PageMap::new_for_testing();
let stable_memory_id = open_memory(&srv, &stable_memory, 0);
// Issue a write of bytes [1, 2, 3, 4] at address 16.
let exec_id = ExecId::new();
let rep = srv
.start_execution(protocol::sbxsvc::StartExecutionRequest {
exec_id,
wasm_id,
wasm_memory_id,
stable_memory_id,
exec_input: exec_input_for_update(
"write",
&[16, 0, 0, 0, 1, 2, 3, 4],
vec![Global::I64(0)],
MemoryId::new(),
MemoryId::new(),
),
})
.sync()
.unwrap();
assert!(rep.success);
let result = exec_finished_sync.get();
let wasm_result = result.exec_output.wasm.wasm_result.unwrap().unwrap();
let state_modifications = result.exec_output.state.unwrap();
assert_eq!(WasmResult::Reply([].to_vec()), wasm_result);
wasm_memory.deserialize_delta(state_modifications.wasm_memory.page_delta);
assert_eq!(
vec![1, 2, 3, 4],
wasm_memory.get_page(PageIndex::new(0))[16..20].to_vec()
);
}
/// Verify that state is set up correctly with given page contents
/// such that memory reads yield the correct data.
#[test]
fn test_memory_read_after_write_state() {
let exec_finished_sync =
Arc::new(SyncCell::<protocol::ctlsvc::ExecutionFinishedRequest>::new());
let srv = SandboxServer::new(SandboxManager::new(
setup_mock_controller(exec_finished_sync.clone()),
EmbeddersConfig::default(),
no_op_logger(),
));
let wasm_id = WasmId::new();
let rep = srv
.open_wasm(OpenWasmRequest {
wasm_id,
wasm_src: make_memory_canister_wasm(),
})
.sync()
.unwrap();
assert!(rep.0.is_ok());
let wasm_memory = PageMap::new_for_testing();
let wasm_memory_id = open_memory(&srv, &wasm_memory, 0);
let stable_memory = PageMap::new_for_testing();
let stable_memory_id = open_memory(&srv, &stable_memory, 0);
let next_wasm_memory_id = MemoryId::new();
let next_stable_memory_id = MemoryId::new();
// Issue a write of bytes [1, 2, 3, 4] at address 16.
let exec_id = ExecId::new();
let rep = srv
.start_execution(protocol::sbxsvc::StartExecutionRequest {
exec_id,
wasm_id,
wasm_memory_id,
stable_memory_id,
exec_input: exec_input_for_update(
"write",
&[16, 0, 0, 0, 1, 2, 3, 4],
vec![Global::I64(0)],
next_wasm_memory_id,
next_stable_memory_id,
),
})
.sync()
.unwrap();
assert!(rep.success);
exec_finished_sync.get();
// Issue a read of size 4 against address 16.
let exec_id = ExecId::new();
let rep = srv
.start_execution(protocol::sbxsvc::StartExecutionRequest {
exec_id,
wasm_id,
wasm_memory_id: next_wasm_memory_id,
stable_memory_id: next_stable_memory_id,
exec_input: exec_input_for_query(
"read",
&[16, 0, 0, 0, 4, 0, 0, 0],
vec![Global::I64(0)],
),
})
.sync()
.unwrap();
assert!(rep.success);
let result = exec_finished_sync.get();
let wasm_result = result.exec_output.wasm.wasm_result.unwrap().unwrap();
assert_eq!(WasmResult::Reply([1, 2, 3, 4].to_vec()), wasm_result);
}
/// Verifies that we can create a simple canister and run multiple
/// queries with the same Wasm cache.
#[test]
fn test_simple_canister_wasm_cache() {
let exec_finished_sync =
Arc::new(SyncCell::<protocol::ctlsvc::ExecutionFinishedRequest>::new());
let exec_finished_sync_clone = Arc::clone(&exec_finished_sync);
let mut controller = MockControllerService::new();
controller
.expect_execution_finished()
.returning(move |req| {
(*exec_finished_sync_clone).put(req);
rpc::Call::new_resolved(Ok(protocol::ctlsvc::ExecutionFinishedReply {}))
});
controller
.expect_log_via_replica()
.returning(move |_req| rpc::Call::new_resolved(Ok(())));
let controller = Arc::new(controller);
let srv = SandboxServer::new(SandboxManager::new(
controller,
EmbeddersConfig::default(),
no_op_logger(),
));
let wasm_id = WasmId::new();
let rep = srv
.open_wasm(OpenWasmRequest {
wasm_id,
wasm_src: make_counter_canister_wasm(),
})
.sync()
.unwrap();
assert!(rep.0.is_ok());
let wasm_memory = PageMap::new_for_testing();
let wasm_memory_id = open_memory(&srv, &wasm_memory, 0);
let stable_memory = PageMap::new_for_testing();
let stable_memory_id = open_memory(&srv, &stable_memory, 0);
// First time around, issue an update to increase the counter.
let exec_id = ExecId::new();
let rep = srv
.start_execution(protocol::sbxsvc::StartExecutionRequest {
exec_id,
wasm_id,
wasm_memory_id,
stable_memory_id,
exec_input: exec_input_for_update(
"write",
&[],
vec![Global::I32(0), Global::I64(0)],
MemoryId::new(),
MemoryId::new(),
),
})
.sync()
.unwrap();
assert!(rep.success);
let result = exec_finished_sync.get();
assert!(
result.exec_output.wasm.num_instructions_left
< NumInstructions::from(INSTRUCTION_LIMIT)
);
let wasm_result = result.exec_output.wasm.wasm_result.unwrap().unwrap();
let globals = result.exec_output.state.unwrap().globals;
assert_eq!(WasmResult::Reply([1, 0, 0, 0].to_vec()), wasm_result);
assert_eq!(Global::I32(1), globals[0]);
// Ensure we close Wasm and stable memory.
close_memory(&srv, wasm_memory_id);
close_memory(&srv, stable_memory_id);
// Now re-issue the same call but with the previous cache on.
let wasm_memory = PageMap::new_for_testing();
let wasm_memory_id = open_memory(&srv, &wasm_memory, 0);
let stable_memory = PageMap::new_for_testing();
let stable_memory_id = open_memory(&srv, &stable_memory, 0);
// First time around, issue an update to increase the counter.
let rep = srv
.start_execution(protocol::sbxsvc::StartExecutionRequest {
exec_id,
wasm_id,
wasm_memory_id,
stable_memory_id,
exec_input: exec_input_for_update(
"write",
&[],
globals,
MemoryId::new(),
MemoryId::new(),
),
})
.sync()
.unwrap();
assert!(rep.success);
let result = exec_finished_sync.get();
assert!(
result.exec_output.wasm.num_instructions_left
< NumInstructions::from(INSTRUCTION_LIMIT)
);
let wasm_result = result.exec_output.wasm.wasm_result.unwrap().unwrap();
let globals = result.exec_output.state.unwrap().globals;
assert_eq!(WasmResult::Reply([2, 0, 0, 0].to_vec()), wasm_result);
// Second time around, issue a query to read the counter. We
// expect to be able to read back the modified counter value
// (since we committed the previous state).
let rep = srv
.start_execution(protocol::sbxsvc::StartExecutionRequest {
exec_id,
wasm_id,
wasm_memory_id,
stable_memory_id,
exec_input: exec_input_for_query("read", &[], globals),
})
.sync()
.unwrap();
assert!(rep.success);
let result = exec_finished_sync.get();
let instructions_used = NumInstructions::from(INSTRUCTION_LIMIT)
- result.exec_output.wasm.num_instructions_left;
assert!(instructions_used.get() > 0);
let wasm_result = result.exec_output.wasm.wasm_result.unwrap().unwrap();
assert_eq!(WasmResult::Reply([2, 0, 0, 0].to_vec()), wasm_result);
}
/// Verify that stable memory writes result in correct page being marked
/// dirty and passed back.
#[test]
fn test_stable_memory_write_dirty() {
let exec_finished_sync =
Arc::new(SyncCell::<protocol::ctlsvc::ExecutionFinishedRequest>::new());
let srv = SandboxServer::new(SandboxManager::new(
setup_mock_controller(exec_finished_sync.clone()),
EmbeddersConfig::default(),
no_op_logger(),
));
let wasm_id = WasmId::new();
let rep = srv
.open_wasm(OpenWasmRequest {
wasm_id,
wasm_src: make_memory_canister_wasm(),
})
.sync()
.unwrap();
assert!(rep.0.is_ok());
let wasm_memory = PageMap::new_for_testing();
let wasm_memory_id = open_memory(&srv, &wasm_memory, 0);
let mut stable_memory = PageMap::new_for_testing();
let stable_memory_id = open_memory(&srv, &stable_memory, 1);
// Issue a write of bytes [1, 2, 3, 4] at address 16 in stable memory.
let exec_id = ExecId::new();
let rep = srv
.start_execution(protocol::sbxsvc::StartExecutionRequest {
exec_id,
wasm_id,
wasm_memory_id,
stable_memory_id,
exec_input: exec_input_for_update(
"write_stable",
&[16, 0, 0, 0, 1, 2, 3, 4],
vec![Global::I64(0)],
MemoryId::new(),
MemoryId::new(),
),
})
.sync()
.unwrap();
assert!(rep.success);
let result = exec_finished_sync.get();
let wasm_result = result.exec_output.wasm.wasm_result.unwrap().unwrap();
let state_modifications = result.exec_output.state.unwrap();
assert_eq!(WasmResult::Reply([].to_vec()), wasm_result);
stable_memory.deserialize_delta(state_modifications.stable_memory.page_delta);
assert_eq!(
vec![1, 2, 3, 4],
stable_memory.get_page(PageIndex::new(0))[16..20].to_vec()
);
}
/// Verify that state is set up correctly with given page contents
/// such that memory reads yield the correct data.
#[test]
fn test_stable_memory_read_after_write_state() {
let exec_finished_sync =
Arc::new(SyncCell::<protocol::ctlsvc::ExecutionFinishedRequest>::new());
let srv = SandboxServer::new(SandboxManager::new(
setup_mock_controller(exec_finished_sync.clone()),
EmbeddersConfig::default(),
no_op_logger(),
));
let wasm_id = WasmId::new();
let rep = srv
.open_wasm(OpenWasmRequest {
wasm_id,
wasm_src: make_memory_canister_wasm(),
})
.sync()
.unwrap();
assert!(rep.0.is_ok());
let wasm_memory = PageMap::new_for_testing();
let wasm_memory_id = open_memory(&srv, &wasm_memory, 0);
let stable_memory = PageMap::new_for_testing();
let stable_memory_id = open_memory(&srv, &stable_memory, 1);
let next_wasm_memory_id = MemoryId::new();
let next_stable_memory_id = MemoryId::new();