-
Notifications
You must be signed in to change notification settings - Fork 318
/
lib.rs
3040 lines (2850 loc) · 109 KB
/
lib.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
pub mod cycles_balance_change;
mod request_in_prep;
mod routing;
pub mod sandbox_safe_system_state;
mod stable_memory;
use ic_base_types::PrincipalIdBlobParseError;
use ic_config::flag_status::FlagStatus;
use ic_cycles_account_manager::ResourceSaturation;
use ic_error_types::RejectCode;
use ic_interfaces::execution_environment::{
ExecutionMode,
HypervisorError::{self, *},
HypervisorResult, OutOfInstructionsHandler, PerformanceCounterType, StableGrowOutcome,
StableMemoryApi, SubnetAvailableMemory, SystemApi, SystemApiCallCounters,
TrapCode::{self, CyclesAmountTooBigFor64Bit},
};
use ic_logger::{error, ReplicaLogger};
use ic_registry_subnet_type::SubnetType;
use ic_replicated_state::{
canister_state::WASM_PAGE_SIZE_IN_BYTES, memory_required_to_push_request, Memory, NumWasmPages,
PageIndex,
};
use ic_sys::PageBytes;
use ic_types::{
ingress::WasmResult,
messages::{CallContextId, RejectContext, Request, MAX_INTER_CANISTER_PAYLOAD_IN_BYTES},
methods::{SystemMethod, WasmClosure},
CanisterId, CanisterTimer, ComputeAllocation, Cycles, MemoryAllocation, NumBytes,
NumInstructions, NumPages, PrincipalId, SubnetId, Time, MAX_STABLE_MEMORY_IN_BYTES,
};
use ic_utils::deterministic_operations::deterministic_copy_from_slice;
use request_in_prep::{into_request, RequestInPrep};
use sandbox_safe_system_state::{CanisterStatusView, SandboxSafeSystemState, SystemStateChanges};
use serde::{Deserialize, Serialize};
use stable_memory::StableMemory;
use std::{
convert::{From, TryFrom},
rc::Rc,
};
pub const MULTIPLIER_MAX_SIZE_LOCAL_SUBNET: u64 = 5;
const MAX_NON_REPLICATED_QUERY_REPLY_SIZE: NumBytes = NumBytes::new(3 << 20);
const CERTIFIED_DATA_MAX_LENGTH: u32 = 32;
// Enables tracing of system calls for local debugging.
const TRACE_SYSCALLS: bool = false;
/// This error should be displayed if stable memory is used through the system
/// API when Wasm-native stable memory is enabled.
const WASM_NATIVE_STABLE_MEMORY_ERROR: &str = "Stable memory cannot be accessed through the System API when Wasm-native stable memory is enabled.";
const MAX_32_BIT_STABLE_MEMORY_IN_PAGES: u64 = 64 * 1024; // 4GiB
// This macro is used in system calls for tracing.
macro_rules! trace_syscall {
($self:ident, $name:ident, $result:expr $( , $args:expr )*) => {{
if TRACE_SYSCALLS {
// Output to both logger and stderr to simplify debugging.
error!(
$self.log,
"[system-api][{}] {}: {:?} => {:?}",
$self.sandbox_safe_system_state.canister_id,
stringify!($name),
($(&$args, )*),
&$result
);
eprintln!(
"[system-api][{}] {}: {:?} => {:?}",
$self.sandbox_safe_system_state.canister_id,
stringify!($name),
($(&$args, )*),
&$result
);
}
}}
}
// This helper is used in system calls for displaying a summary hash of a heap region.
#[inline]
fn summarize(heap: &[u8], start: u32, size: u32) -> u64 {
if TRACE_SYSCALLS {
let start = (start as usize).min(heap.len());
let end = (start + (size as usize)).min(heap.len());
// The actual hash function doesn't matter much as long as it is
// cheap to compute and maps the input to u64 reasonably well.
let mut sum = 0;
for (i, byte) in heap[start..end].iter().enumerate() {
sum += (i + 1) as u64 * *byte as u64
}
sum
} else {
0
}
}
/// Keeps the message instruction limit and the maximum slice instruction limit.
/// Supports operations to reduce the message limit while keeping the maximum
/// slice limit the same, which is useful for messages that have multiple
/// execution steps such as install, upgrade, and response.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct InstructionLimits {
/// The total instruction limit for message execution. With deterministic
/// time slicing this limit may exceed the per-round instruction limit. The
/// message fails with an `InstructionLimitExceeded` error if it executes
/// more instructions than this limit.
message: NumInstructions,
/// The number of instructions in the largest possible slice. It may
/// exceed `self.message()` if the latter was reduced or updated by the
/// previous executions.
max_slice: NumInstructions,
}
impl InstructionLimits {
/// Returns the message and slice instruction limits based on the
/// deterministic time slicing flag.
pub fn new(dts: FlagStatus, message: NumInstructions, max_slice: NumInstructions) -> Self {
Self {
message,
max_slice: match dts {
FlagStatus::Enabled => max_slice,
FlagStatus::Disabled => message,
},
}
}
/// See the comments of the corresponding field.
pub fn message(&self) -> NumInstructions {
self.message
}
/// Returns the effective slice size, which is the smallest of
/// `self.max_slice` and `self.message`.
pub fn slice(&self) -> NumInstructions {
self.max_slice.min(self.message)
}
/// Reduces the message instruction limit by the given number.
/// Note that with DTS, the slice size is constant for a fixed message type.
pub fn reduce_by(&mut self, used: NumInstructions) {
self.message = NumInstructions::from(self.message.get().saturating_sub(used.get()));
}
/// Sets the message instruction limit to the given number.
/// Note that with DTS, the slice size is constant for a fixed message type.
pub fn update(&mut self, left: NumInstructions) {
self.message = left;
}
}
// Canister and subnet configuration parameters required for execution.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ExecutionParameters {
pub instruction_limits: InstructionLimits,
pub canister_memory_limit: NumBytes,
pub memory_allocation: MemoryAllocation,
pub compute_allocation: ComputeAllocation,
pub subnet_type: SubnetType,
pub execution_mode: ExecutionMode,
pub subnet_memory_saturation: ResourceSaturation,
}
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[doc(hidden)]
pub enum ResponseStatus {
// Indicates that the current call context was never replied.
NotRepliedYet,
// Indicates that the current call context was replied in one of other
// executions belonging to this call context (other callbacks, e.g.).
AlreadyReplied,
// Contains the response assigned during the current execution.
JustRepliedWith(Option<WasmResult>),
}
/// This enum indicates whether execution of a non-replicated query
/// should keep track of the state or not. The distinction is necessary
/// because some non-replicated queries can call other queries. In such
/// a case the caller has too keep the state until the callee returns.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum NonReplicatedQueryKind {
Stateful {
call_context_id: CallContextId,
/// Optional outgoing request under construction. If `None` no outgoing
/// request is currently under construction.
outgoing_request: Option<RequestInPrep>,
},
Pure,
}
/// This enum indicates whether state modifications are important for
/// an API type or not.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ModificationTracking {
Ignore,
Track,
}
/// Describes the context within which a canister message is executed.
///
/// The `Arc` values in this type are safe to serialize because the contain
/// read-only data that is only shared for cheap cloning. Serializing and
/// deserializing will result in duplication of the data, but no issues in
/// correctness.
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Serialize, Deserialize)]
pub enum ApiType {
/// For executing the `canister_start` method
Start {
time: Time,
},
/// For executing the `canister_init` method
Init {
time: Time,
#[serde(with = "serde_bytes")]
incoming_payload: Vec<u8>,
caller: PrincipalId,
},
/// For executing canister methods marked as `update`
Update {
time: Time,
#[serde(with = "serde_bytes")]
incoming_payload: Vec<u8>,
incoming_cycles: Cycles,
caller: PrincipalId,
call_context_id: CallContextId,
/// Begins as empty and used to accumulate data for sending replies.
#[serde(with = "serde_bytes")]
response_data: Vec<u8>,
response_status: ResponseStatus,
/// Optional outgoing request under construction. If `None` no outgoing
/// request is currently under construction.
outgoing_request: Option<RequestInPrep>,
max_reply_size: NumBytes,
},
// For executing canister methods marked as `query`
ReplicatedQuery {
time: Time,
#[serde(with = "serde_bytes")]
incoming_payload: Vec<u8>,
caller: PrincipalId,
#[serde(with = "serde_bytes")]
response_data: Vec<u8>,
response_status: ResponseStatus,
data_certificate: Option<Vec<u8>>,
max_reply_size: NumBytes,
},
NonReplicatedQuery {
time: Time,
caller: PrincipalId,
own_subnet_id: SubnetId,
#[serde(with = "serde_bytes")]
incoming_payload: Vec<u8>,
data_certificate: Option<Vec<u8>>,
// Begins as empty and used to accumulate data for sending replies.
#[serde(with = "serde_bytes")]
response_data: Vec<u8>,
response_status: ResponseStatus,
max_reply_size: NumBytes,
query_kind: NonReplicatedQueryKind,
},
// For executing closures when a `Reply` is received
ReplyCallback {
time: Time,
caller: PrincipalId,
#[serde(with = "serde_bytes")]
incoming_payload: Vec<u8>,
incoming_cycles: Cycles,
call_context_id: CallContextId,
// Begins as empty and used to accumulate data for sending replies.
#[serde(with = "serde_bytes")]
response_data: Vec<u8>,
response_status: ResponseStatus,
/// Optional outgoing request under construction. If `None` no outgoing
/// request is currently under construction.
outgoing_request: Option<RequestInPrep>,
max_reply_size: NumBytes,
execution_mode: ExecutionMode,
/// The total number of instructions executed in the call context
call_context_instructions_executed: NumInstructions,
},
// For executing closures when a `Reject` is received
RejectCallback {
time: Time,
caller: PrincipalId,
reject_context: RejectContext,
incoming_cycles: Cycles,
call_context_id: CallContextId,
// Begins as empty and used to accumulate data for sending replies.
#[serde(with = "serde_bytes")]
response_data: Vec<u8>,
response_status: ResponseStatus,
/// Optional outgoing request under construction. If `None` no outgoing
/// request is currently under construction.
outgoing_request: Option<RequestInPrep>,
max_reply_size: NumBytes,
execution_mode: ExecutionMode,
/// The total number of instructions executed in the call context
call_context_instructions_executed: NumInstructions,
},
PreUpgrade {
caller: PrincipalId,
time: Time,
},
/// For executing canister_inspect_message method that allows the canister
/// to decide pre-consensus if it actually wants to accept the message or
/// not.
InspectMessage {
caller: PrincipalId,
method_name: String,
#[serde(with = "serde_bytes")]
incoming_payload: Vec<u8>,
time: Time,
message_accepted: bool,
},
// For executing the `canister_heartbeat` or `canister_global_timer` methods
SystemTask {
caller: PrincipalId,
/// System task to execute.
/// Only `canister_heartbeat` and `canister_global_timer` are allowed.
system_task: SystemMethod,
time: Time,
call_context_id: CallContextId,
/// Optional outgoing request under construction. If `None` no outgoing
/// request is currently under construction.
outgoing_request: Option<RequestInPrep>,
},
/// For executing the `call_on_cleanup` callback.
///
/// The `call_on_cleanup` callback is executed iff the `reply` or the
/// `reject` callback was executed and trapped (for any reason).
///
/// See https://sdk.dfinity.org/docs/interface-spec/index.html#system-api-call
Cleanup {
caller: PrincipalId,
time: Time,
/// The total number of instructions executed in the call context
call_context_instructions_executed: NumInstructions,
},
}
impl ApiType {
pub fn start(time: Time) -> Self {
Self::Start { time }
}
pub fn init(time: Time, incoming_payload: Vec<u8>, caller: PrincipalId) -> Self {
Self::Init {
time,
incoming_payload,
caller,
}
}
pub fn system_task(
caller: PrincipalId,
system_task: SystemMethod,
time: Time,
call_context_id: CallContextId,
) -> Self {
Self::SystemTask {
caller,
time,
call_context_id,
outgoing_request: None,
system_task,
}
}
#[allow(clippy::too_many_arguments)]
pub fn update(
time: Time,
incoming_payload: Vec<u8>,
incoming_cycles: Cycles,
caller: PrincipalId,
call_context_id: CallContextId,
) -> Self {
Self::Update {
time,
incoming_payload,
incoming_cycles,
caller,
call_context_id,
response_data: vec![],
response_status: ResponseStatus::NotRepliedYet,
outgoing_request: None,
max_reply_size: MAX_INTER_CANISTER_PAYLOAD_IN_BYTES,
}
}
pub fn replicated_query(
time: Time,
incoming_payload: Vec<u8>,
caller: PrincipalId,
data_certificate: Option<Vec<u8>>,
) -> Self {
Self::ReplicatedQuery {
time,
incoming_payload,
caller,
response_data: vec![],
response_status: ResponseStatus::NotRepliedYet,
data_certificate,
max_reply_size: MAX_INTER_CANISTER_PAYLOAD_IN_BYTES,
}
}
#[allow(clippy::too_many_arguments)]
pub fn non_replicated_query(
time: Time,
caller: PrincipalId,
own_subnet_id: SubnetId,
incoming_payload: Vec<u8>,
data_certificate: Option<Vec<u8>>,
query_kind: NonReplicatedQueryKind,
) -> Self {
Self::NonReplicatedQuery {
time,
caller,
own_subnet_id,
incoming_payload,
data_certificate,
response_data: vec![],
response_status: ResponseStatus::NotRepliedYet,
max_reply_size: MAX_NON_REPLICATED_QUERY_REPLY_SIZE,
query_kind,
}
}
#[allow(clippy::too_many_arguments)]
pub fn reply_callback(
time: Time,
caller: PrincipalId,
incoming_payload: Vec<u8>,
incoming_cycles: Cycles,
call_context_id: CallContextId,
replied: bool,
execution_mode: ExecutionMode,
call_context_instructions_executed: NumInstructions,
) -> Self {
Self::ReplyCallback {
time,
caller,
incoming_payload,
incoming_cycles,
call_context_id,
response_data: vec![],
response_status: if replied {
ResponseStatus::AlreadyReplied
} else {
ResponseStatus::NotRepliedYet
},
outgoing_request: None,
max_reply_size: MAX_INTER_CANISTER_PAYLOAD_IN_BYTES,
execution_mode,
call_context_instructions_executed,
}
}
#[allow(clippy::too_many_arguments)]
pub fn reject_callback(
time: Time,
caller: PrincipalId,
reject_context: RejectContext,
incoming_cycles: Cycles,
call_context_id: CallContextId,
replied: bool,
execution_mode: ExecutionMode,
call_context_instructions_executed: NumInstructions,
) -> Self {
Self::RejectCallback {
time,
caller,
reject_context,
incoming_cycles,
call_context_id,
response_data: vec![],
response_status: if replied {
ResponseStatus::AlreadyReplied
} else {
ResponseStatus::NotRepliedYet
},
outgoing_request: None,
max_reply_size: MAX_INTER_CANISTER_PAYLOAD_IN_BYTES,
execution_mode,
call_context_instructions_executed,
}
}
pub fn pre_upgrade(time: Time, caller: PrincipalId) -> Self {
Self::PreUpgrade { time, caller }
}
pub fn inspect_message(
caller: PrincipalId,
method_name: String,
incoming_payload: Vec<u8>,
time: Time,
) -> Self {
Self::InspectMessage {
caller,
method_name,
incoming_payload,
time,
message_accepted: false,
}
}
/// Indicates whether state modifications are important for this API type or
/// not.
pub fn modification_tracking(&self) -> ModificationTracking {
match self {
ApiType::ReplicatedQuery { .. }
| ApiType::NonReplicatedQuery {
query_kind: NonReplicatedQueryKind::Pure,
..
}
| ApiType::InspectMessage { .. } => ModificationTracking::Ignore,
ApiType::NonReplicatedQuery {
query_kind: NonReplicatedQueryKind::Stateful { .. },
..
}
| ApiType::Start { .. }
| ApiType::Init { .. }
| ApiType::Update { .. }
| ApiType::ReplyCallback { .. }
| ApiType::RejectCallback { .. }
| ApiType::PreUpgrade { .. }
| ApiType::SystemTask { .. }
| ApiType::Cleanup { .. } => ModificationTracking::Track,
}
}
/// Returns a string slice representation of the enum variant name for use
/// e.g. as a metric label.
pub fn as_str(&self) -> &'static str {
match self {
ApiType::Start { .. } => "start",
ApiType::Init { .. } => "init",
ApiType::SystemTask { system_task, .. } => match system_task {
SystemMethod::CanisterHeartbeat => "heartbeat",
SystemMethod::CanisterGlobalTimer => "global timer",
_ => panic!("Only `canister_heartbeat` and `canister_global_timer` are allowed."),
},
ApiType::Update { .. } => "update",
ApiType::ReplicatedQuery { .. } => "replicated query",
ApiType::NonReplicatedQuery { .. } => "non replicated query",
ApiType::ReplyCallback { execution_mode, .. } => match execution_mode {
ExecutionMode::Replicated => "replicated reply callback",
ExecutionMode::NonReplicated => "non-replicated reply callback",
},
ApiType::RejectCallback { execution_mode, .. } => match execution_mode {
ExecutionMode::Replicated => "replicated reject callback",
ExecutionMode::NonReplicated => "non-replicated reject callback",
},
ApiType::PreUpgrade { .. } => "pre upgrade",
ApiType::InspectMessage { .. } => "inspect message",
ApiType::Cleanup { .. } => "cleanup",
}
}
}
// This type is potentially serialized and exposed to the external world. We
// use custom formatting to avoid exposing its internal details.
impl std::fmt::Display for ApiType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// A struct to gather the relevant fields that correspond to a canister's
/// memory consumption.
struct MemoryUsage {
/// Upper limit on how much the memory the canister could use.
limit: NumBytes,
/// The current amount of execution memory that the canister is using.
current_usage: NumBytes,
/// The current amount of message memory that the canister is using.
current_message_usage: NumBytes,
// This is the amount of memory that the subnet has available. Any
// expansions in the canister's memory need to be deducted from here.
subnet_available_memory: SubnetAvailableMemory,
/// Execution memory allocated during this message execution, i.e. the canister
/// memory (Wasm binary, Wasm memory, stable memory) without message memory.
allocated_execution_memory: NumBytes,
/// Message memory allocated during this message execution.
allocated_message_memory: NumBytes,
/// The memory allocation of the canister.
memory_allocation: MemoryAllocation,
}
impl MemoryUsage {
fn new(
log: ReplicaLogger,
canister_id: CanisterId,
limit: NumBytes,
current_usage: NumBytes,
current_message_usage: NumBytes,
subnet_available_memory: SubnetAvailableMemory,
memory_allocation: MemoryAllocation,
) -> Self {
// A canister's current usage should never exceed its limit. This is
// most probably a bug. Panicking here due to this inconsistency has the
// danger of putting the entire subnet in a crash loop. Log an error
// message to page the on-call team and try to stumble along.
if current_usage > limit {
error!(
log,
"[EXC-BUG] Canister {}: current_usage {} > limit {}",
canister_id,
current_usage,
limit
);
}
Self {
limit,
current_usage,
current_message_usage,
subnet_available_memory,
allocated_execution_memory: NumBytes::from(0),
allocated_message_memory: NumBytes::from(0),
memory_allocation,
}
}
/// Tries to allocate the requested amount of the Wasm or stable memory.
///
/// If the canister has memory allocation, then this function doesn't allocate
/// bytes, but only increases `current_usage`.
///
/// Returns `Err(HypervisorError::OutOfMemory)` and leaves `self` unchanged
/// if either the canister memory limit or the subnet memory limit would be
/// exceeded.
///
/// Returns `Err(HypervisorError::InsufficientCyclesInMemoryGrow)` and
/// leaves `self` unchanged if freezing threshold check is needed for the
/// given API type and canister would be frozen after the allocation.
fn allocate_execution_memory(
&mut self,
execution_bytes: NumBytes,
api_type: &ApiType,
sandbox_safe_system_state: &mut SandboxSafeSystemState,
subnet_memory_saturation: &ResourceSaturation,
) -> HypervisorResult<()> {
let (new_usage, overflow) = self
.current_usage
.get()
.overflowing_add(execution_bytes.get());
if overflow || new_usage > self.limit.get() {
return Err(HypervisorError::OutOfMemory);
}
sandbox_safe_system_state.check_freezing_threshold_for_memory_grow(
api_type,
self.current_message_usage,
self.current_usage,
NumBytes::new(new_usage),
)?;
match self.memory_allocation {
MemoryAllocation::BestEffort => {
match self.subnet_available_memory.check_available_memory(
execution_bytes,
NumBytes::from(0),
NumBytes::from(0),
) {
Ok(()) => {
sandbox_safe_system_state.reserve_storage_cycles(
execution_bytes,
&subnet_memory_saturation.add(self.allocated_execution_memory.get()),
api_type,
)?;
// All state changes after this point should not fail
// because the cycles have already been reserved.
self.subnet_available_memory
.try_decrement(execution_bytes, NumBytes::from(0), NumBytes::from(0))
.expect(
"Decrementing subnet available memory is \
guaranteed to succeed by check_available_memory().",
);
self.current_usage = NumBytes::from(new_usage);
self.allocated_execution_memory += execution_bytes;
Ok(())
}
Err(_err) => Err(HypervisorError::OutOfMemory),
}
}
MemoryAllocation::Reserved(reserved_bytes) => {
// The canister can increase its memory usage up to the reserved bytes
// without decrementing the subnet available memory and without
// reserving cycles because it has already done that during the
// original reservation.
if new_usage > reserved_bytes.get() {
// Note that this branch should be unreachable because
// `self.limit` should already be set to `reserved_bytes` and
// the guard above should have returned an error. In order to
// keep code robust, we repeat the check here again.
return Err(HypervisorError::OutOfMemory);
}
self.current_usage = NumBytes::from(new_usage);
Ok(())
}
}
}
/// Tries to allocate the requested amount of message memory.
///
/// Returns `Err(HypervisorError::OutOfMemory)` and leaves `self` unchanged
/// if the message memory limit would be exceeded.
///
/// Returns `Err(HypervisorError::InsufficientCyclesInMessageMemoryGrow)`
/// and leaves `self` unchanged if freezing threshold check is needed
/// for the given API type and canister would be frozen after the
/// allocation.
fn allocate_message_memory(
&mut self,
message_bytes: NumBytes,
api_type: &ApiType,
sandbox_safe_system_state: &SandboxSafeSystemState,
) -> HypervisorResult<()> {
let (new_usage, overflow) = self
.current_message_usage
.get()
.overflowing_add(message_bytes.get());
if overflow {
return Err(HypervisorError::OutOfMemory);
}
sandbox_safe_system_state.check_freezing_threshold_for_message_memory_grow(
api_type,
self.current_usage,
self.current_message_usage,
NumBytes::new(new_usage),
)?;
match self.subnet_available_memory.try_decrement(
NumBytes::from(0),
message_bytes,
NumBytes::from(0),
) {
Ok(()) => {
self.allocated_message_memory += message_bytes;
self.current_message_usage = NumBytes::from(new_usage);
Ok(())
}
Err(_err) => Err(HypervisorError::OutOfMemory),
}
}
/// Deallocates the given number of message bytes.
/// Should only be called immediately after `allocate_message_memory()`, with the
/// same number of bytes, in case allocation failed.
fn deallocate_message_memory(&mut self, message_bytes: NumBytes) {
assert!(
self.allocated_message_memory >= message_bytes,
"Precondition of self.allocated_message_memory in deallocate_message_memory failed: {} >= {}",
self.allocated_message_memory,
message_bytes
);
assert!(
self.current_message_usage >= message_bytes,
"Precondition of self.current_message_usage in deallocate_message_memory failed: {} >= {}",
self.current_message_usage,
message_bytes
);
self.subnet_available_memory
.increment(NumBytes::from(0), message_bytes, NumBytes::from(0));
self.allocated_message_memory -= message_bytes;
self.current_message_usage -= message_bytes;
}
}
/// Struct that implements the SystemApi trait. This trait enables a canister to
/// have mediated access to its system state.
pub struct SystemApiImpl {
/// An execution error of the current message.
execution_error: Option<HypervisorError>,
log: ReplicaLogger,
/// The variant of ApiType being executed.
api_type: ApiType,
memory_usage: MemoryUsage,
execution_parameters: ExecutionParameters,
/// Wasm-native stable memory is enabled. This means that stable memory
/// should not be accessed through the public stable memory APIs. It can
/// still be read through the hidden read API for speed on the first access.
wasm_native_stable_memory: FlagStatus,
/// The maximum sum of `<name>` lengths in exported functions called `canister_update <name>`,
/// `canister_query <name>`, or `canister_composite_query <name>`.
max_sum_exported_function_name_lengths: usize,
/// Should not be accessed directly from public APIs. Instead read through
/// [`Self::stable_memory`] or [`Self::stable_memory_mut`].
stable_memory: StableMemory,
/// System state information that is cached so that we don't need to go
/// through the `SystemStateAccessor` to read it. This saves on IPC
/// communication between the sandboxed canister process and the main
/// replica process.
sandbox_safe_system_state: SandboxSafeSystemState,
/// A handler that is invoked when the instruction counter becomes negative
/// (exceeds the current slice instruction limit).
out_of_instructions_handler: Rc<dyn OutOfInstructionsHandler>,
/// The instruction limit of the currently executing slice. It is
/// initialized to `execution_parameters.instruction_limits.slice()` and
/// updated after each out-of-instructions call that starts a new slice.
current_slice_instruction_limit: i64,
/// The total number of instructions executed before the current slice. It
/// is initialized to 0 and updated after each out-of-instructions call that
/// starts a new slice.
instructions_executed_before_current_slice: i64,
/// How many times each tracked System API call was invoked.
call_counters: SystemApiCallCounters,
}
impl SystemApiImpl {
#[allow(clippy::too_many_arguments)]
pub fn new(
api_type: ApiType,
sandbox_safe_system_state: SandboxSafeSystemState,
canister_current_memory_usage: NumBytes,
canister_current_message_memory_usage: NumBytes,
execution_parameters: ExecutionParameters,
subnet_available_memory: SubnetAvailableMemory,
wasm_native_stable_memory: FlagStatus,
max_sum_exported_function_name_lengths: usize,
stable_memory: Memory,
out_of_instructions_handler: Rc<dyn OutOfInstructionsHandler>,
log: ReplicaLogger,
) -> Self {
let memory_usage = MemoryUsage::new(
log.clone(),
sandbox_safe_system_state.canister_id,
execution_parameters.canister_memory_limit,
canister_current_memory_usage,
canister_current_message_memory_usage,
subnet_available_memory,
execution_parameters.memory_allocation,
);
let stable_memory = StableMemory::new(stable_memory);
let slice_limit = execution_parameters.instruction_limits.slice().get();
Self {
execution_error: None,
api_type,
memory_usage,
execution_parameters,
wasm_native_stable_memory,
max_sum_exported_function_name_lengths,
stable_memory,
sandbox_safe_system_state,
out_of_instructions_handler,
log,
current_slice_instruction_limit: i64::try_from(slice_limit).unwrap_or(i64::MAX),
instructions_executed_before_current_slice: 0,
call_counters: SystemApiCallCounters::default(),
}
}
/// Refunds any cycles used for an outgoing request that doesn't get sent
/// and returns the result of execution.
pub fn take_execution_result(
&mut self,
wasm_run_error: Option<&HypervisorError>,
) -> HypervisorResult<Option<WasmResult>> {
match &mut self.api_type {
ApiType::Start { .. }
| ApiType::Init { .. }
| ApiType::Cleanup { .. }
| ApiType::ReplicatedQuery { .. }
| ApiType::PreUpgrade { .. }
| ApiType::InspectMessage { .. }
| ApiType::NonReplicatedQuery { .. } => (),
ApiType::SystemTask {
outgoing_request, ..
}
| ApiType::Update {
outgoing_request, ..
}
| ApiType::ReplyCallback {
outgoing_request, ..
}
| ApiType::RejectCallback {
outgoing_request, ..
} => {
if let Some(outgoing_request) = outgoing_request.take() {
self.sandbox_safe_system_state
.refund_cycles(outgoing_request.take_cycles());
}
}
}
if let Some(err) = wasm_run_error
.cloned()
.or_else(|| self.execution_error.take())
{
// There is no need to deallocate memory because all state changes
// are discarded for failed executions anyway.
return Err(err);
}
match &mut self.api_type {
ApiType::Start { .. }
| ApiType::Init { .. }
| ApiType::PreUpgrade { .. }
| ApiType::Cleanup { .. }
| ApiType::SystemTask { .. } => Ok(None),
ApiType::InspectMessage {
message_accepted, ..
} => {
if *message_accepted {
Ok(None)
} else {
Err(HypervisorError::MessageRejected)
}
}
ApiType::Update {
response_status, ..
}
| ApiType::ReplicatedQuery {
response_status, ..
}
| ApiType::NonReplicatedQuery {
response_status, ..
}
| ApiType::ReplyCallback {
response_status, ..
}
| ApiType::RejectCallback {
response_status, ..
} => match response_status {
ResponseStatus::JustRepliedWith(ref mut result) => Ok(result.take()),
_ => Ok(None),
},
}
}
/// Note that this function is made public only for the tests
#[doc(hidden)]
pub fn get_current_memory_usage(&self) -> NumBytes {
self.memory_usage.current_usage
}
/// Bytes allocated in the Wasm/stable memory.
pub fn get_allocated_bytes(&self) -> NumBytes {
self.memory_usage.allocated_execution_memory
}
/// Bytes allocated in messages.
pub fn get_allocated_message_bytes(&self) -> NumBytes {
self.memory_usage.allocated_message_memory
}
fn error_for(&self, method_name: &str) -> HypervisorError {
HypervisorError::ContractViolation(format!(
"\"{}\" cannot be executed in {} mode",
method_name, self.api_type
))
}
fn get_msg_caller_id(&self, method_name: &str) -> Result<PrincipalId, HypervisorError> {
match &self.api_type {
ApiType::Start { .. } => Err(self.error_for(method_name)),
ApiType::SystemTask { caller, .. }
| ApiType::Cleanup { caller, .. }
| ApiType::ReplyCallback { caller, .. }
| ApiType::RejectCallback { caller, .. }
| ApiType::Init { caller, .. }
| ApiType::Update { caller, .. }
| ApiType::ReplicatedQuery { caller, .. }
| ApiType::PreUpgrade { caller, .. }
| ApiType::InspectMessage { caller, .. }
| ApiType::NonReplicatedQuery { caller, .. } => Ok(*caller),
}
}
fn get_response_info(&mut self) -> Option<(&mut Vec<u8>, &NumBytes, &mut ResponseStatus)> {
match &mut self.api_type {