-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
cpi.rs
2942 lines (2689 loc) · 102 KB
/
cpi.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 {
super::*,
crate::serialization::account_data_region_memory_state,
scopeguard::defer,
solana_program_runtime::invoke_context::SerializedAccountMetadata,
solana_rbpf::{
ebpf,
memory_region::{MemoryRegion, MemoryState},
},
solana_sdk::{
feature_set::enable_bpf_loader_set_authority_checked_ix,
stable_layout::stable_instruction::StableInstruction,
syscalls::{
MAX_CPI_ACCOUNT_INFOS, MAX_CPI_INSTRUCTION_ACCOUNTS, MAX_CPI_INSTRUCTION_DATA_LEN,
},
transaction_context::BorrowedAccount,
},
std::{mem, ptr},
};
fn check_account_info_pointer(
invoke_context: &InvokeContext,
vm_addr: u64,
expected_vm_addr: u64,
field: &str,
) -> Result<(), Error> {
if vm_addr != expected_vm_addr {
ic_msg!(
invoke_context,
"Invalid account info pointer `{}': {:#x} != {:#x}",
field,
vm_addr,
expected_vm_addr
);
return Err(SyscallError::InvalidPointer.into());
}
Ok(())
}
enum VmValue<'a, 'b, T> {
VmAddress {
vm_addr: u64,
memory_mapping: &'b MemoryMapping<'a>,
check_aligned: bool,
},
// Once direct mapping is activated, this variant can be removed and the
// enum can be made a struct.
Translated(&'a mut T),
}
impl<'a, 'b, T> VmValue<'a, 'b, T> {
fn get(&self) -> Result<&T, Error> {
match self {
VmValue::VmAddress {
vm_addr,
memory_mapping,
check_aligned,
} => translate_type(memory_mapping, *vm_addr, *check_aligned),
VmValue::Translated(addr) => Ok(*addr),
}
}
fn get_mut(&mut self) -> Result<&mut T, Error> {
match self {
VmValue::VmAddress {
vm_addr,
memory_mapping,
check_aligned,
} => translate_type_mut(memory_mapping, *vm_addr, *check_aligned),
VmValue::Translated(addr) => Ok(*addr),
}
}
}
/// Host side representation of AccountInfo or SolAccountInfo passed to the CPI syscall.
///
/// At the start of a CPI, this can be different from the data stored in the
/// corresponding BorrowedAccount, and needs to be synched.
struct CallerAccount<'a, 'b> {
lamports: &'a mut u64,
owner: &'a mut Pubkey,
// The original data length of the account at the start of the current
// instruction. We use this to determine wether an account was shrunk or
// grown before or after CPI, and to derive the vm address of the realloc
// region.
original_data_len: usize,
// This points to the data section for this account, as serialized and
// mapped inside the vm (see serialize_parameters() in
// BpfExecutor::execute).
//
// This is only set when direct mapping is off (see the relevant comment in
// CallerAccount::from_account_info).
serialized_data: &'a mut [u8],
// Given the corresponding input AccountInfo::data, vm_data_addr points to
// the pointer field and ref_to_len_in_vm points to the length field.
vm_data_addr: u64,
ref_to_len_in_vm: VmValue<'b, 'a, u64>,
}
impl<'a, 'b> CallerAccount<'a, 'b> {
// Create a CallerAccount given an AccountInfo.
fn from_account_info(
invoke_context: &InvokeContext,
memory_mapping: &'b MemoryMapping<'a>,
_vm_addr: u64,
account_info: &AccountInfo,
account_metadata: &SerializedAccountMetadata,
) -> Result<CallerAccount<'a, 'b>, Error> {
let direct_mapping = invoke_context
.feature_set
.is_active(&feature_set::bpf_account_data_direct_mapping::id());
if direct_mapping {
check_account_info_pointer(
invoke_context,
account_info.key as *const _ as u64,
account_metadata.vm_key_addr,
"key",
)?;
check_account_info_pointer(
invoke_context,
account_info.owner as *const _ as u64,
account_metadata.vm_owner_addr,
"owner",
)?;
}
// account_info points to host memory. The addresses used internally are
// in vm space so they need to be translated.
let lamports = {
// Double translate lamports out of RefCell
let ptr = translate_type::<u64>(
memory_mapping,
account_info.lamports.as_ptr() as u64,
invoke_context.get_check_aligned(),
)?;
if direct_mapping {
check_account_info_pointer(
invoke_context,
*ptr,
account_metadata.vm_lamports_addr,
"lamports",
)?;
}
translate_type_mut::<u64>(memory_mapping, *ptr, invoke_context.get_check_aligned())?
};
let owner = translate_type_mut::<Pubkey>(
memory_mapping,
account_info.owner as *const _ as u64,
invoke_context.get_check_aligned(),
)?;
let (serialized_data, vm_data_addr, ref_to_len_in_vm) = {
// Double translate data out of RefCell
let data = *translate_type::<&[u8]>(
memory_mapping,
account_info.data.as_ptr() as *const _ as u64,
invoke_context.get_check_aligned(),
)?;
if direct_mapping {
check_account_info_pointer(
invoke_context,
data.as_ptr() as u64,
account_metadata.vm_data_addr,
"data",
)?;
}
consume_compute_meter(
invoke_context,
(data.len() as u64)
.checked_div(invoke_context.get_compute_budget().cpi_bytes_per_unit)
.unwrap_or(u64::MAX),
)?;
let ref_to_len_in_vm = if direct_mapping {
let vm_addr = (account_info.data.as_ptr() as *const u64 as u64)
.saturating_add(size_of::<u64>() as u64);
// In the same vein as the other check_account_info_pointer() checks, we don't lock
// this pointer to a specific address but we don't want it to be inside accounts, or
// callees might be able to write to the pointed memory.
if vm_addr >= ebpf::MM_INPUT_START {
return Err(SyscallError::InvalidPointer.into());
}
VmValue::VmAddress {
vm_addr,
memory_mapping,
check_aligned: invoke_context.get_check_aligned(),
}
} else {
let translated = translate(
memory_mapping,
AccessType::Store,
(account_info.data.as_ptr() as *const u64 as u64)
.saturating_add(size_of::<u64>() as u64),
8,
)? as *mut u64;
VmValue::Translated(unsafe { &mut *translated })
};
let vm_data_addr = data.as_ptr() as u64;
let serialized_data = if direct_mapping {
// when direct mapping is enabled, the permissions on the
// realloc region can change during CPI so we must delay
// translating until when we know whether we're going to mutate
// the realloc region or not. Consider this case:
//
// [caller can't write to an account] <- we are here
// [callee grows and assigns account to the caller]
// [caller can now write to the account]
//
// If we always translated the realloc area here, we'd get a
// memory access violation since we can't write to the account
// _yet_, but we will be able to once the caller returns.
&mut []
} else {
translate_slice_mut::<u8>(
memory_mapping,
vm_data_addr,
data.len() as u64,
invoke_context.get_check_aligned(),
)?
};
(serialized_data, vm_data_addr, ref_to_len_in_vm)
};
Ok(CallerAccount {
lamports,
owner,
original_data_len: account_metadata.original_data_len,
serialized_data,
vm_data_addr,
ref_to_len_in_vm,
})
}
// Create a CallerAccount given a SolAccountInfo.
fn from_sol_account_info(
invoke_context: &InvokeContext,
memory_mapping: &'b MemoryMapping<'a>,
vm_addr: u64,
account_info: &SolAccountInfo,
account_metadata: &SerializedAccountMetadata,
) -> Result<CallerAccount<'a, 'b>, Error> {
let direct_mapping = invoke_context
.feature_set
.is_active(&feature_set::bpf_account_data_direct_mapping::id());
if direct_mapping {
check_account_info_pointer(
invoke_context,
account_info.key_addr,
account_metadata.vm_key_addr,
"key",
)?;
check_account_info_pointer(
invoke_context,
account_info.owner_addr,
account_metadata.vm_owner_addr,
"owner",
)?;
check_account_info_pointer(
invoke_context,
account_info.lamports_addr,
account_metadata.vm_lamports_addr,
"lamports",
)?;
check_account_info_pointer(
invoke_context,
account_info.data_addr,
account_metadata.vm_data_addr,
"data",
)?;
}
// account_info points to host memory. The addresses used internally are
// in vm space so they need to be translated.
let lamports = translate_type_mut::<u64>(
memory_mapping,
account_info.lamports_addr,
invoke_context.get_check_aligned(),
)?;
let owner = translate_type_mut::<Pubkey>(
memory_mapping,
account_info.owner_addr,
invoke_context.get_check_aligned(),
)?;
consume_compute_meter(
invoke_context,
account_info
.data_len
.checked_div(invoke_context.get_compute_budget().cpi_bytes_per_unit)
.unwrap_or(u64::MAX),
)?;
let serialized_data = if direct_mapping {
// See comment in CallerAccount::from_account_info()
&mut []
} else {
translate_slice_mut::<u8>(
memory_mapping,
account_info.data_addr,
account_info.data_len,
invoke_context.get_check_aligned(),
)?
};
// we already have the host addr we want: &mut account_info.data_len.
// The account info might be read only in the vm though, so we translate
// to ensure we can write. This is tested by programs/sbf/rust/ro_modify
// which puts SolAccountInfo in rodata.
let data_len_vm_addr = vm_addr
.saturating_add(&account_info.data_len as *const u64 as u64)
.saturating_sub(account_info as *const _ as *const u64 as u64);
let ref_to_len_in_vm = if direct_mapping {
// In the same vein as the other check_account_info_pointer() checks, we don't lock this
// pointer to a specific address but we don't want it to be inside accounts, or callees
// might be able to write to the pointed memory.
if data_len_vm_addr >= ebpf::MM_INPUT_START {
return Err(SyscallError::InvalidPointer.into());
}
VmValue::VmAddress {
vm_addr: data_len_vm_addr,
memory_mapping,
check_aligned: invoke_context.get_check_aligned(),
}
} else {
let data_len_addr = translate(
memory_mapping,
AccessType::Store,
data_len_vm_addr,
size_of::<u64>() as u64,
)?;
VmValue::Translated(unsafe { &mut *(data_len_addr as *mut u64) })
};
Ok(CallerAccount {
lamports,
owner,
original_data_len: account_metadata.original_data_len,
serialized_data,
vm_data_addr: account_info.data_addr,
ref_to_len_in_vm,
})
}
fn realloc_region(
&self,
memory_mapping: &'b MemoryMapping<'_>,
is_loader_deprecated: bool,
) -> Result<Option<&'a MemoryRegion>, Error> {
account_realloc_region(
memory_mapping,
self.vm_data_addr,
self.original_data_len,
is_loader_deprecated,
)
}
}
type TranslatedAccounts<'a, 'b> = Vec<(IndexOfAccount, Option<CallerAccount<'a, 'b>>)>;
/// Implemented by language specific data structure translators
trait SyscallInvokeSigned {
fn translate_instruction(
addr: u64,
memory_mapping: &MemoryMapping,
invoke_context: &mut InvokeContext,
) -> Result<StableInstruction, Error>;
fn translate_accounts<'a, 'b>(
instruction_accounts: &[InstructionAccount],
program_indices: &[IndexOfAccount],
account_infos_addr: u64,
account_infos_len: u64,
is_loader_deprecated: bool,
memory_mapping: &'b MemoryMapping<'a>,
invoke_context: &mut InvokeContext,
) -> Result<TranslatedAccounts<'a, 'b>, Error>;
fn translate_signers(
program_id: &Pubkey,
signers_seeds_addr: u64,
signers_seeds_len: u64,
memory_mapping: &MemoryMapping,
invoke_context: &InvokeContext,
) -> Result<Vec<Pubkey>, Error>;
}
declare_builtin_function!(
/// Cross-program invocation called from Rust
SyscallInvokeSignedRust,
fn rust(
invoke_context: &mut InvokeContext,
instruction_addr: u64,
account_infos_addr: u64,
account_infos_len: u64,
signers_seeds_addr: u64,
signers_seeds_len: u64,
memory_mapping: &mut MemoryMapping,
) -> Result<u64, Error> {
cpi_common::<Self>(
invoke_context,
instruction_addr,
account_infos_addr,
account_infos_len,
signers_seeds_addr,
signers_seeds_len,
memory_mapping,
)
}
);
impl SyscallInvokeSigned for SyscallInvokeSignedRust {
fn translate_instruction(
addr: u64,
memory_mapping: &MemoryMapping,
invoke_context: &mut InvokeContext,
) -> Result<StableInstruction, Error> {
let ix = translate_type::<StableInstruction>(
memory_mapping,
addr,
invoke_context.get_check_aligned(),
)?;
check_instruction_size(ix.accounts.len(), ix.data.len(), invoke_context)?;
let account_metas = translate_slice::<AccountMeta>(
memory_mapping,
ix.accounts.as_ptr() as u64,
ix.accounts.len() as u64,
invoke_context.get_check_aligned(),
)?;
let mut accounts = Vec::with_capacity(ix.accounts.len());
#[allow(clippy::needless_range_loop)]
for account_index in 0..ix.accounts.len() {
#[allow(clippy::indexing_slicing)]
let account_meta = &account_metas[account_index];
if unsafe {
std::ptr::read_volatile(&account_meta.is_signer as *const _ as *const u8) > 1
|| std::ptr::read_volatile(&account_meta.is_writable as *const _ as *const u8)
> 1
} {
return Err(Box::new(InstructionError::InvalidArgument));
}
accounts.push(account_meta.clone());
}
let ix_data_len = ix.data.len() as u64;
if invoke_context
.feature_set
.is_active(&feature_set::loosen_cpi_size_restriction::id())
{
consume_compute_meter(
invoke_context,
(ix_data_len)
.checked_div(invoke_context.get_compute_budget().cpi_bytes_per_unit)
.unwrap_or(u64::MAX),
)?;
}
let data = translate_slice::<u8>(
memory_mapping,
ix.data.as_ptr() as u64,
ix_data_len,
invoke_context.get_check_aligned(),
)?
.to_vec();
Ok(StableInstruction {
accounts: accounts.into(),
data: data.into(),
program_id: ix.program_id,
})
}
fn translate_accounts<'a, 'b>(
instruction_accounts: &[InstructionAccount],
program_indices: &[IndexOfAccount],
account_infos_addr: u64,
account_infos_len: u64,
is_loader_deprecated: bool,
memory_mapping: &'b MemoryMapping<'a>,
invoke_context: &mut InvokeContext,
) -> Result<TranslatedAccounts<'a, 'b>, Error> {
let (account_infos, account_info_keys) = translate_account_infos(
account_infos_addr,
account_infos_len,
|account_info: &AccountInfo| account_info.key as *const _ as u64,
memory_mapping,
invoke_context,
)?;
translate_and_update_accounts(
instruction_accounts,
program_indices,
&account_info_keys,
account_infos,
account_infos_addr,
is_loader_deprecated,
invoke_context,
memory_mapping,
CallerAccount::from_account_info,
)
}
fn translate_signers(
program_id: &Pubkey,
signers_seeds_addr: u64,
signers_seeds_len: u64,
memory_mapping: &MemoryMapping,
invoke_context: &InvokeContext,
) -> Result<Vec<Pubkey>, Error> {
let mut signers = Vec::new();
if signers_seeds_len > 0 {
let signers_seeds = translate_slice::<&[&[u8]]>(
memory_mapping,
signers_seeds_addr,
signers_seeds_len,
invoke_context.get_check_aligned(),
)?;
if signers_seeds.len() > MAX_SIGNERS {
return Err(Box::new(SyscallError::TooManySigners));
}
for signer_seeds in signers_seeds.iter() {
let untranslated_seeds = translate_slice::<&[u8]>(
memory_mapping,
signer_seeds.as_ptr() as *const _ as u64,
signer_seeds.len() as u64,
invoke_context.get_check_aligned(),
)?;
if untranslated_seeds.len() > MAX_SEEDS {
return Err(Box::new(InstructionError::MaxSeedLengthExceeded));
}
let seeds = untranslated_seeds
.iter()
.map(|untranslated_seed| {
translate_slice::<u8>(
memory_mapping,
untranslated_seed.as_ptr() as *const _ as u64,
untranslated_seed.len() as u64,
invoke_context.get_check_aligned(),
)
})
.collect::<Result<Vec<_>, Error>>()?;
let signer = Pubkey::create_program_address(&seeds, program_id)
.map_err(SyscallError::BadSeeds)?;
signers.push(signer);
}
Ok(signers)
} else {
Ok(vec![])
}
}
}
/// Rust representation of C's SolInstruction
#[derive(Debug)]
#[repr(C)]
struct SolInstruction {
program_id_addr: u64,
accounts_addr: u64,
accounts_len: u64,
data_addr: u64,
data_len: u64,
}
/// Rust representation of C's SolAccountMeta
#[derive(Debug)]
#[repr(C)]
struct SolAccountMeta {
pubkey_addr: u64,
is_writable: bool,
is_signer: bool,
}
/// Rust representation of C's SolAccountInfo
#[derive(Debug)]
#[repr(C)]
struct SolAccountInfo {
key_addr: u64,
lamports_addr: u64,
data_len: u64,
data_addr: u64,
owner_addr: u64,
rent_epoch: u64,
#[allow(dead_code)]
is_signer: bool,
#[allow(dead_code)]
is_writable: bool,
executable: bool,
}
/// Rust representation of C's SolSignerSeed
#[derive(Debug)]
#[repr(C)]
struct SolSignerSeedC {
addr: u64,
len: u64,
}
/// Rust representation of C's SolSignerSeeds
#[derive(Debug)]
#[repr(C)]
struct SolSignerSeedsC {
addr: u64,
len: u64,
}
declare_builtin_function!(
/// Cross-program invocation called from C
SyscallInvokeSignedC,
fn rust(
invoke_context: &mut InvokeContext,
instruction_addr: u64,
account_infos_addr: u64,
account_infos_len: u64,
signers_seeds_addr: u64,
signers_seeds_len: u64,
memory_mapping: &mut MemoryMapping,
) -> Result<u64, Error> {
cpi_common::<Self>(
invoke_context,
instruction_addr,
account_infos_addr,
account_infos_len,
signers_seeds_addr,
signers_seeds_len,
memory_mapping,
)
}
);
impl SyscallInvokeSigned for SyscallInvokeSignedC {
fn translate_instruction(
addr: u64,
memory_mapping: &MemoryMapping,
invoke_context: &mut InvokeContext,
) -> Result<StableInstruction, Error> {
let ix_c = translate_type::<SolInstruction>(
memory_mapping,
addr,
invoke_context.get_check_aligned(),
)?;
check_instruction_size(
ix_c.accounts_len as usize,
ix_c.data_len as usize,
invoke_context,
)?;
let program_id = translate_type::<Pubkey>(
memory_mapping,
ix_c.program_id_addr,
invoke_context.get_check_aligned(),
)?;
let account_metas = translate_slice::<SolAccountMeta>(
memory_mapping,
ix_c.accounts_addr,
ix_c.accounts_len,
invoke_context.get_check_aligned(),
)?;
let ix_data_len = ix_c.data_len;
if invoke_context
.feature_set
.is_active(&feature_set::loosen_cpi_size_restriction::id())
{
consume_compute_meter(
invoke_context,
(ix_data_len)
.checked_div(invoke_context.get_compute_budget().cpi_bytes_per_unit)
.unwrap_or(u64::MAX),
)?;
}
let data = translate_slice::<u8>(
memory_mapping,
ix_c.data_addr,
ix_data_len,
invoke_context.get_check_aligned(),
)?
.to_vec();
let mut accounts = Vec::with_capacity(ix_c.accounts_len as usize);
#[allow(clippy::needless_range_loop)]
for account_index in 0..ix_c.accounts_len as usize {
#[allow(clippy::indexing_slicing)]
let account_meta = &account_metas[account_index];
if unsafe {
std::ptr::read_volatile(&account_meta.is_signer as *const _ as *const u8) > 1
|| std::ptr::read_volatile(&account_meta.is_writable as *const _ as *const u8)
> 1
} {
return Err(Box::new(InstructionError::InvalidArgument));
}
let pubkey = translate_type::<Pubkey>(
memory_mapping,
account_meta.pubkey_addr,
invoke_context.get_check_aligned(),
)?;
accounts.push(AccountMeta {
pubkey: *pubkey,
is_signer: account_meta.is_signer,
is_writable: account_meta.is_writable,
});
}
Ok(StableInstruction {
accounts: accounts.into(),
data: data.into(),
program_id: *program_id,
})
}
fn translate_accounts<'a, 'b>(
instruction_accounts: &[InstructionAccount],
program_indices: &[IndexOfAccount],
account_infos_addr: u64,
account_infos_len: u64,
is_loader_deprecated: bool,
memory_mapping: &'b MemoryMapping<'a>,
invoke_context: &mut InvokeContext,
) -> Result<TranslatedAccounts<'a, 'b>, Error> {
let (account_infos, account_info_keys) = translate_account_infos(
account_infos_addr,
account_infos_len,
|account_info: &SolAccountInfo| account_info.key_addr,
memory_mapping,
invoke_context,
)?;
translate_and_update_accounts(
instruction_accounts,
program_indices,
&account_info_keys,
account_infos,
account_infos_addr,
is_loader_deprecated,
invoke_context,
memory_mapping,
CallerAccount::from_sol_account_info,
)
}
fn translate_signers(
program_id: &Pubkey,
signers_seeds_addr: u64,
signers_seeds_len: u64,
memory_mapping: &MemoryMapping,
invoke_context: &InvokeContext,
) -> Result<Vec<Pubkey>, Error> {
if signers_seeds_len > 0 {
let signers_seeds = translate_slice::<SolSignerSeedsC>(
memory_mapping,
signers_seeds_addr,
signers_seeds_len,
invoke_context.get_check_aligned(),
)?;
if signers_seeds.len() > MAX_SIGNERS {
return Err(Box::new(SyscallError::TooManySigners));
}
Ok(signers_seeds
.iter()
.map(|signer_seeds| {
let seeds = translate_slice::<SolSignerSeedC>(
memory_mapping,
signer_seeds.addr,
signer_seeds.len,
invoke_context.get_check_aligned(),
)?;
if seeds.len() > MAX_SEEDS {
return Err(Box::new(InstructionError::MaxSeedLengthExceeded) as Error);
}
let seeds_bytes = seeds
.iter()
.map(|seed| {
translate_slice::<u8>(
memory_mapping,
seed.addr,
seed.len,
invoke_context.get_check_aligned(),
)
})
.collect::<Result<Vec<_>, Error>>()?;
Pubkey::create_program_address(&seeds_bytes, program_id)
.map_err(|err| Box::new(SyscallError::BadSeeds(err)) as Error)
})
.collect::<Result<Vec<_>, Error>>()?)
} else {
Ok(vec![])
}
}
}
fn translate_account_infos<'a, T, F>(
account_infos_addr: u64,
account_infos_len: u64,
key_addr: F,
memory_mapping: &MemoryMapping,
invoke_context: &mut InvokeContext,
) -> Result<(&'a [T], Vec<&'a Pubkey>), Error>
where
F: Fn(&T) -> u64,
{
let account_infos = translate_slice::<T>(
memory_mapping,
account_infos_addr,
account_infos_len,
invoke_context.get_check_aligned(),
)?;
check_account_infos(account_infos.len(), invoke_context)?;
let mut account_info_keys = Vec::with_capacity(account_infos_len as usize);
#[allow(clippy::needless_range_loop)]
for account_index in 0..account_infos_len as usize {
#[allow(clippy::indexing_slicing)]
let account_info = &account_infos[account_index];
account_info_keys.push(translate_type::<Pubkey>(
memory_mapping,
key_addr(account_info),
invoke_context.get_check_aligned(),
)?);
}
Ok((account_infos, account_info_keys))
}
// Finish translating accounts, build CallerAccount values and update callee
// accounts in preparation of executing the callee.
fn translate_and_update_accounts<'a, 'b, T, F>(
instruction_accounts: &[InstructionAccount],
program_indices: &[IndexOfAccount],
account_info_keys: &[&Pubkey],
account_infos: &[T],
account_infos_addr: u64,
is_loader_deprecated: bool,
invoke_context: &mut InvokeContext,
memory_mapping: &'b MemoryMapping<'a>,
do_translate: F,
) -> Result<TranslatedAccounts<'a, 'b>, Error>
where
F: Fn(
&InvokeContext,
&'b MemoryMapping<'a>,
u64,
&T,
&SerializedAccountMetadata,
) -> Result<CallerAccount<'a, 'b>, Error>,
{
let transaction_context = &invoke_context.transaction_context;
let instruction_context = transaction_context.get_current_instruction_context()?;
let mut accounts = Vec::with_capacity(instruction_accounts.len().saturating_add(1));
let program_account_index = program_indices
.last()
.ok_or_else(|| Box::new(InstructionError::MissingAccount))?;
accounts.push((*program_account_index, None));
// unwrapping here is fine: we're in a syscall and the method below fails
// only outside syscalls
let accounts_metadata = &invoke_context
.get_syscall_context()
.unwrap()
.accounts_metadata;
let direct_mapping = invoke_context
.feature_set
.is_active(&feature_set::bpf_account_data_direct_mapping::id());
for (instruction_account_index, instruction_account) in instruction_accounts.iter().enumerate()
{
if instruction_account_index as IndexOfAccount != instruction_account.index_in_callee {
continue; // Skip duplicate account
}
let callee_account = instruction_context.try_borrow_instruction_account(
transaction_context,
instruction_account.index_in_caller,
)?;
let account_key = invoke_context
.transaction_context
.get_key_of_account_at_index(instruction_account.index_in_transaction)?;
if callee_account.is_executable() {
// Use the known account
consume_compute_meter(
invoke_context,
(callee_account.get_data().len() as u64)
.checked_div(invoke_context.get_compute_budget().cpi_bytes_per_unit)
.unwrap_or(u64::MAX),
)?;
accounts.push((instruction_account.index_in_caller, None));
} else if let Some(caller_account_index) =
account_info_keys.iter().position(|key| *key == account_key)
{
let serialized_metadata = accounts_metadata
.get(instruction_account.index_in_caller as usize)
.ok_or_else(|| {
ic_msg!(
invoke_context,
"Internal error: index mismatch for account {}",
account_key
);
Box::new(InstructionError::MissingAccount)
})?;
// build the CallerAccount corresponding to this account.
if caller_account_index >= account_infos.len() {
return Err(Box::new(SyscallError::InvalidLength));
}
#[allow(clippy::indexing_slicing)]
let caller_account =
do_translate(
invoke_context,
memory_mapping,
account_infos_addr.saturating_add(
caller_account_index.saturating_mul(mem::size_of::<T>()) as u64,
),
&account_infos[caller_account_index],
serialized_metadata,
)?;
// before initiating CPI, the caller may have modified the
// account (caller_account). We need to update the corresponding
// BorrowedAccount (callee_account) so the callee can see the
// changes.
update_callee_account(
invoke_context,
memory_mapping,
is_loader_deprecated,
&caller_account,
callee_account,
direct_mapping,
)?;
let caller_account = if instruction_account.is_writable {
Some(caller_account)
} else {
None
};
accounts.push((instruction_account.index_in_caller, caller_account));
} else {
ic_msg!(
invoke_context,
"Instruction references an unknown account {}",
account_key
);
return Err(Box::new(InstructionError::MissingAccount));
}
}
Ok(accounts)
}
fn check_instruction_size(
num_accounts: usize,
data_len: usize,
invoke_context: &mut InvokeContext,
) -> Result<(), Error> {
if invoke_context
.feature_set
.is_active(&feature_set::loosen_cpi_size_restriction::id())
{
let data_len = data_len as u64;
let max_data_len = MAX_CPI_INSTRUCTION_DATA_LEN;
if data_len > max_data_len {
return Err(Box::new(SyscallError::MaxInstructionDataLenExceeded {
data_len,
max_data_len,
}));
}
let num_accounts = num_accounts as u64;
let max_accounts = MAX_CPI_INSTRUCTION_ACCOUNTS as u64;
if num_accounts > max_accounts {
return Err(Box::new(SyscallError::MaxInstructionAccountsExceeded {
num_accounts,
max_accounts,
}));
}
} else {
let max_size = invoke_context.get_compute_budget().max_cpi_instruction_size;
let size = num_accounts
.saturating_mul(size_of::<AccountMeta>())
.saturating_add(data_len);
if size > max_size {
return Err(Box::new(SyscallError::InstructionTooLarge(size, max_size)));
}
}
Ok(())
}
fn check_account_infos(
num_account_infos: usize,
invoke_context: &mut InvokeContext,
) -> Result<(), Error> {
if invoke_context