-
Notifications
You must be signed in to change notification settings - Fork 296
/
validation.rs
1395 lines (1348 loc) · 45.9 KB
/
validation.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
//! This module is responsible for validating the wasm binaries that are
//! installed on the Internet Computer.
use super::{wasm_transform::Body, Complexity, WasmImportsDetails, WasmValidationDetails};
use ic_config::embedders::Config as EmbeddersConfig;
use ic_replicated_state::canister_state::execution_state::{
CustomSection, CustomSectionType, WasmMetadata,
};
use ic_types::{NumBytes, NumInstructions};
use ic_wasm_types::{BinaryEncodedWasm, WasmValidationError};
use std::{
cmp,
collections::{BTreeMap, HashMap, HashSet},
};
use wasmtime::Config;
use crate::wasm_utils::instrumentation::{
ACCESSED_PAGES_COUNTER_GLOBAL_NAME, DIRTY_PAGES_COUNTER_GLOBAL_NAME,
};
use crate::{
wasm_utils::wasm_transform::{DataSegment, DataSegmentKind, Module},
wasmtime_embedder::{STABLE_BYTEMAP_MEMORY_NAME, STABLE_MEMORY_NAME, WASM_HEAP_MEMORY_NAME},
};
use wasmparser::{ExternalKind, FuncType, Operator, StructuralType, TypeRef, ValType};
/// Symbols that are reserved and cannot be exported by canisters.
#[doc(hidden)] // pub for usage in tests
pub const RESERVED_SYMBOLS: [&str; 6] = [
"canister counter_instructions",
"canister_start",
DIRTY_PAGES_COUNTER_GLOBAL_NAME,
ACCESSED_PAGES_COUNTER_GLOBAL_NAME,
STABLE_MEMORY_NAME,
STABLE_BYTEMAP_MEMORY_NAME,
];
const WASM_FUNCTION_COMPLEXITY_LIMIT: Complexity = Complexity(1_000_000);
const WASM_FUNCTION_SIZE_LIMIT: usize = 1_000_000;
const MAX_CODE_SECTION_SIZE_IN_BYTES: u32 = 10 * 1024 * 1024;
// Represents the expected function signature for any System APIs the Internet
// Computer provides or any special exported user functions.
struct FunctionSignature {
pub param_types: Vec<ValType>,
pub return_type: Vec<ValType>,
}
const METHOD_MODULE: &str = "method";
pub(super) const API_VERSION_IC0: &str = "ic0";
// Constructs a map of function name -> HashMap<String,
// `FunctionSignature`> (to allow the same function to be imported from
// multiple modules) based on the System API.
//
// We use a two-level hashmap to be able to differentiate between the case a
// user tries to import a function that doesn't exist in any of the expected
// modules vs the case where the function exists but is imported from the wrong
// module.
fn get_valid_system_apis() -> HashMap<String, HashMap<String, FunctionSignature>> {
let valid_system_apis = vec![
(
// Public methods
"msg_caller_size",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
(
"msg_caller_copy",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"msg_arg_data_size",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
(
"msg_arg_data_copy",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"msg_method_name_size",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
(
"msg_method_name_copy",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"accept_message",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
)],
),
(
"msg_reject_code",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
(
"msg_reject_msg_size",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
(
"msg_reject_msg_copy",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"msg_reply_data_append",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"msg_reply",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
)],
),
(
"msg_reject",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"canister_self_size",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
(
"canister_self_copy",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
// Inter-canister method calls
(
"public",
vec![(
METHOD_MODULE,
FunctionSignature {
param_types: vec![ValType::I64, ValType::I32, ValType::I32],
return_type: vec![ValType::I64],
},
)],
),
(
"call_new",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![
ValType::I32,
ValType::I32,
ValType::I32,
ValType::I32,
ValType::I32,
ValType::I32,
ValType::I32,
ValType::I32,
],
return_type: vec![],
},
)],
),
(
"call_data_append",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"call_on_cleanup",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"call_cycles_add",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I64],
return_type: vec![],
},
)],
),
(
"call_perform",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
// Debugging aids
(
"debug_print",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"stable_size",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
(
"stable_grow",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32],
return_type: vec![ValType::I32],
},
)],
),
(
"stable_read",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"stable_write",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"stable64_size",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I64],
},
)],
),
(
"stable64_grow",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I64],
return_type: vec![ValType::I64],
},
)],
),
(
"stable64_read",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I64, ValType::I64, ValType::I64],
return_type: vec![],
},
)],
),
(
"stable64_write",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I64, ValType::I64, ValType::I64],
return_type: vec![],
},
)],
),
(
"time",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I64],
},
)],
),
(
"global_timer_set",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I64],
return_type: vec![ValType::I64],
},
)],
),
(
"performance_counter",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32],
return_type: vec![ValType::I64],
},
)],
),
(
"canister_version",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I64],
},
)],
),
(
"trap",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"canister_cycle_balance",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I64],
},
)],
),
(
"msg_cycles_available",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I64],
},
)],
),
(
"msg_cycles_refunded",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I64],
},
)],
),
(
"msg_cycles_accept",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I64],
return_type: vec![ValType::I64],
},
)],
),
(
"certified_data_set",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"data_certificate_present",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
(
"data_certificate_size",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
(
"data_certificate_copy",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32, ValType::I32],
return_type: vec![],
},
)],
),
(
"canister_status",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![],
return_type: vec![ValType::I32],
},
)],
),
(
"mint_cycles",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I64],
return_type: vec![ValType::I64],
},
)],
),
(
"call_cycles_add128",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I64, ValType::I64],
return_type: vec![],
},
)],
),
(
"canister_cycle_balance128",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32],
return_type: vec![],
},
)],
),
(
"msg_cycles_available128",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32],
return_type: vec![],
},
)],
),
(
"msg_cycles_refunded128",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32],
return_type: vec![],
},
)],
),
(
"msg_cycles_accept128",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I64, ValType::I64, ValType::I32],
return_type: vec![],
},
)],
),
(
"is_controller",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I32, ValType::I32],
return_type: vec![ValType::I32],
},
)],
),
(
"cycles_burn128",
vec![(
API_VERSION_IC0,
FunctionSignature {
param_types: vec![ValType::I64, ValType::I64, ValType::I32],
return_type: vec![],
},
)],
),
];
valid_system_apis
.into_iter()
.map(|(func_name, signatures)| {
(
func_name.to_string(),
signatures
.into_iter()
.map(|(module, signature)| (module.to_string(), signature))
.collect(),
)
})
.collect()
}
// Constructs a map of function name -> `FunctionSignature` based on the
// special user exported functions allowed in the interface spec.
fn get_valid_exported_functions() -> HashMap<String, FunctionSignature> {
let valid_exported_functions = vec![
(
"canister_init",
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
),
(
"canister_update",
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
),
(
"canister_query",
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
),
(
"canister_composite_query",
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
),
(
"canister_pre_upgrade",
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
),
(
"canister_post_upgrade",
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
),
(
"canister_inspect_message",
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
),
(
"canister_heartbeat",
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
),
(
"canister_global_timer",
FunctionSignature {
param_types: vec![],
return_type: vec![],
},
),
];
valid_exported_functions
.into_iter()
.map(|(func_name, signature)| (func_name.to_string(), signature))
.collect()
}
// Validates an input function signature by comparing against the provided
// expected function signature.
fn validate_function_signature(
expected_signature: &FunctionSignature,
field: &str,
function_type: &FuncType,
) -> Result<(), WasmValidationError> {
if function_type.params() != expected_signature.param_types.as_slice() {
return Err(WasmValidationError::InvalidFunctionSignature(format!(
"Expected input params {:?} for '{}', got {:?}.",
expected_signature.param_types,
field,
function_type.params()
)));
}
if function_type.results() != expected_signature.return_type {
return Err(WasmValidationError::InvalidFunctionSignature(format!(
"Expected return type {:?} for '{}', got {:?}.",
expected_signature.return_type,
field,
function_type.results()
)));
}
Ok(())
}
fn set_imports_details(import_details: &mut WasmImportsDetails, import_module: &str, field: &str) {
if import_module != API_VERSION_IC0 {
return;
}
match field {
"call_cycles_add" => import_details.imports_call_cycles_add = true,
"canister_cycle_balance" => import_details.imports_canister_cycle_balance = true,
"msg_cycles_available" => import_details.imports_msg_cycles_available = true,
"msg_cycles_refunded" => import_details.imports_msg_cycles_refunded = true,
"msg_cycles_accept" => import_details.imports_msg_cycles_accept = true,
"mint_cycles" => import_details.imports_mint_cycles = true,
_ => {}
}
}
// Performs the following checks for the import section:
// * If we import memory or table, we can only import from “env”.
// * Any imported functions that appear in `valid_system_apis` have the correct
// signatures.
//
// Returns information about what IC0 methods are imported via
// `WasmImportsDetails`.
fn validate_import_section(module: &Module) -> Result<WasmImportsDetails, WasmValidationError> {
let mut imports_details = WasmImportsDetails::default();
if !module.imports.is_empty() {
let valid_system_apis = get_valid_system_apis();
for entry in &module.imports {
let import_module = entry.module;
let field = entry.name;
match &entry.ty {
TypeRef::Func(index) => {
let func_ty = if let StructuralType::Func(func_ty) =
&module.types[*index as usize].structural_type
{
func_ty
} else {
return Err(WasmValidationError::InvalidImportSection(format!(
"Function import doesn't have a function type. Type found: {:?}",
&module.types[*index as usize]
)));
};
set_imports_details(&mut imports_details, import_module, field);
match valid_system_apis.get(field) {
Some(signatures) => {
match signatures.get(import_module) {
Some(signature) => {
validate_function_signature(
signature,
field,
func_ty,
)?;
},
None => {return Err(WasmValidationError::InvalidImportSection(format!(
"Module imports function {:?} from {:?}, expected to be imported from one of {:?} instead.",
field, import_module, signatures.keys(),
)))}
}
},
None => {
return Err(WasmValidationError::InvalidImportSection(format!(
"Module imports function '{}' from '{}' that is not exported by the runtime.",
field, import_module,
)))
}
}
}
TypeRef::Table(_) => {
if field == "table" && import_module != "env" {
return Err(WasmValidationError::InvalidImportSection(
"Only tables imported from env.table are allowed.".to_string(),
));
}
}
TypeRef::Memory(_) => {
if field == WASM_HEAP_MEMORY_NAME && import_module != "env" {
return Err(WasmValidationError::InvalidImportSection(
"Only memory imported from env.memory is allowed.".to_string(),
));
};
}
TypeRef::Global(_) => {
return Err(WasmValidationError::InvalidImportSection(
"Importing globals is not allowed.".to_string(),
))
}
TypeRef::Tag(_) => {
return Err(WasmValidationError::InvalidImportSection(
"Importing tags is not allowed.".to_string(),
))
}
}
}
}
Ok(imports_details)
}
// Performs the following checks:
// * Validates signatures of exported canister_update and canister_query
// methods.
// * Validates the signatures of other allowed exported functions (like
// `canister_init` or `canister_pre_upgrade`) if present.
// * Validates that the canister doesn't export any reserved symbols
// * Validates that all exported functions whose names start
// with the reserved "canister_" prefix are in the list of allowed exports.
fn validate_export_section(
module: &Module,
max_number_exported_functions: usize,
max_sum_exported_function_name_lengths: usize,
) -> Result<(), WasmValidationError> {
if !module.exports.is_empty() {
let num_imported_functions = module
.imports
.iter()
.filter(|i| matches!(i.ty, TypeRef::Func(_)))
.count();
let mut seen_funcs: HashSet<&str> = HashSet::new();
let valid_exported_functions = get_valid_exported_functions();
let valid_system_functions = vec![
"canister_init",
"canister_pre_upgrade",
"canister_post_upgrade",
"canister_inspect_message",
"canister_heartbeat",
"canister_global_timer",
];
let mut number_exported_functions = 0;
let mut sum_exported_function_name_lengths = 0;
for export in &module.exports {
// Verify that the exported symbol's name isn't reserved.
if RESERVED_SYMBOLS.contains(&export.name) {
return Err(WasmValidationError::InvalidExportSection(format!(
"Exporting reserved symbol {} not allowed.",
export.name
)));
}
if ExternalKind::Func == export.kind {
let fn_index = export.index;
let mut func_name = export.name;
// func_name holds either:
// - the entire exported non-IC function names, or
// - canister_query or canister_update part in case of the IC functions.
if func_name.starts_with("canister_query ")
|| func_name.starts_with("canister_composite_query ")
|| func_name.starts_with("canister_update ")
{
let parts: Vec<&str> = func_name.splitn(2, ' ').collect();
func_name = parts[0];
let unmangled_func_name = parts[1];
if seen_funcs.contains(unmangled_func_name) {
return Err(WasmValidationError::InvalidExportSection(format!(
"Duplicate function '{}' exported multiple times \
with different call types: update, query, or composite_query.",
unmangled_func_name
)));
}
seen_funcs.insert(unmangled_func_name);
number_exported_functions += 1;
sum_exported_function_name_lengths += unmangled_func_name.len();
} else if func_name.starts_with("canister_") {
// The "canister_" prefix is reserved and only functions allowed by the spec
// can be exported.
if !valid_system_functions.contains(&func_name) {
return Err(WasmValidationError::InvalidExportSection(format!(
"Exporting reserved function '{}' with \"canister_\" prefix",
func_name
)));
}
}
if let Some(valid_signature) = valid_exported_functions.get(func_name) {
// The function section contains only the functions defined locally in the
// module, so we need to subtract the number of imported functions to get the
// correct index from the general function space.
let fn_index = fn_index as usize;
let import_count = num_imported_functions;
if fn_index < import_count {
return Err(WasmValidationError::InvalidFunctionIndex {
index: fn_index,
import_count,
});
}
let actual_fn_index = fn_index - import_count;
let type_index = module.functions[actual_fn_index] as usize;
let func_ty = if let StructuralType::Func(func_ty) =
&module.types[type_index].structural_type
{
func_ty
} else {
return Err(WasmValidationError::InvalidExportSection(format!(
"Function export doesn't have a function type. Type found: {:?}",
&module.types[type_index]
)));
};
validate_function_signature(valid_signature, export.name, func_ty)?;
}
}
}
if number_exported_functions > max_number_exported_functions {
let err = format!("The number of exported functions called `canister_update <name>`, `canister_query <name>`, or `canister_composite_query <name>` exceeds {}.", max_number_exported_functions);
return Err(WasmValidationError::InvalidExportSection(err));
}
if sum_exported_function_name_lengths > max_sum_exported_function_name_lengths {
let err = format!("The sum of `<name>` lengths in exported functions called `canister_update <name>`, `canister_query <name>`, or `canister_composite_query <name>` exceeds {}.", max_sum_exported_function_name_lengths);
return Err(WasmValidationError::InvalidExportSection(err));
}
}
Ok(())
}
// Checks that offset-expressions in data sections consist of only one constant
// expression. Required because of OP. See also:
// instrumentation.rs
fn validate_data_section(module: &Module) -> Result<(), WasmValidationError> {
fn validate_segment(s: &DataSegment) -> Result<(), WasmValidationError> {
match &s.kind {
DataSegmentKind::Passive => Err(WasmValidationError::InvalidDataSection(
"Empty offset in data segment.".to_string(),
)),
DataSegmentKind::Active {
memory_index: _,
offset_expr,
} => match offset_expr {
Operator::I32Const { .. } => Ok(()),
_ => Err(WasmValidationError::InvalidDataSection(format!(
"Invalid offset expression in data segment: {:?}",
offset_expr
))),
},
}
}
for d in &module.data {
validate_segment(d)?;
}
Ok(())
}
// Checks that no more than `max_globals` are defined in the module.
fn validate_global_section(module: &Module, max_globals: usize) -> Result<(), WasmValidationError> {
if module.globals.len() > max_globals {
return Err(WasmValidationError::TooManyGlobals {
defined: module.globals.len(),
allowed: max_globals,
});
}
Ok(())
}
// Checks that no more than `max_functions` are defined in the
// module.
fn validate_function_section(
module: &Module,
max_functions: usize,
) -> Result<(), WasmValidationError> {
if module.functions.len() > max_functions {
return Err(WasmValidationError::TooManyFunctions {
defined: module.functions.len(),
allowed: max_functions,
});
}
Ok(())
}
// Extracts the name of the custom section.
// Possible options:
// * icp:public <name>
// * icp:private <name>
// Where <name> is an arbitrary string (empty names are allowed).
// If the name starts with the prefix `icp:` but does not define
// the visibility `private` or `public` then this custom name is invalid.
#[doc(hidden)] // pub for usage in tests
pub fn extract_custom_section_name(
section_name: &str,
) -> Result<Option<(&str, CustomSectionType)>, WasmValidationError> {
if !section_name.starts_with("icp:") {
// Ignore custom section name which does not start with `icp:`.
return Ok(None);
}
if let Some(name) = section_name.strip_prefix("icp:public ") {
return Ok(Some((name, CustomSectionType::Public)));
}
if let Some(name) = section_name.strip_prefix("icp:private ") {
return Ok(Some((name, CustomSectionType::Private)));
}