-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
syscalls.rs
2319 lines (2187 loc) · 75.5 KB
/
syscalls.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 crate::{alloc, BPFError};
use alloc::Alloc;
use curve25519_dalek::{ristretto::RistrettoPoint, scalar::Scalar};
use solana_rbpf::{
ebpf::MM_HEAP_START,
error::EbpfError,
memory_region::{AccessType, MemoryMapping},
question_mark,
vm::{EbpfVm, SyscallObject, SyscallRegistry},
};
use solana_runtime::message_processor::MessageProcessor;
use solana_sdk::{
account::Account,
account_info::AccountInfo,
account_utils::StateMut,
bpf_loader, bpf_loader_deprecated,
bpf_loader_upgradeable::{self, UpgradeableLoaderState},
entrypoint::{MAX_PERMITTED_DATA_INCREASE, SUCCESS},
feature_set::{
abort_on_all_cpi_failures, limit_cpi_loader_invoke, pubkey_log_syscall_enabled,
ristretto_mul_syscall_enabled, sha256_syscall_enabled, sol_log_compute_units_syscall,
try_find_program_address_syscall_enabled, use_loaded_executables,
use_loaded_program_accounts,
},
hash::{Hasher, HASH_BYTES},
instruction::{AccountMeta, Instruction, InstructionError},
keyed_account::KeyedAccount,
native_loader,
process_instruction::{stable_log, ComputeMeter, InvokeContext, Logger},
program_error::ProgramError,
pubkey::{Pubkey, PubkeyError, MAX_SEEDS},
};
use std::{
alloc::Layout,
cell::{Ref, RefCell, RefMut},
convert::TryFrom,
mem::{align_of, size_of},
rc::Rc,
slice::from_raw_parts_mut,
str::{from_utf8, Utf8Error},
};
use thiserror::Error as ThisError;
/// Maximum signers
pub const MAX_SIGNERS: usize = 16;
/// Error definitions
#[derive(Debug, ThisError, PartialEq)]
pub enum SyscallError {
#[error("{0}: {1:?}")]
InvalidString(Utf8Error, Vec<u8>),
#[error("BPF program panicked")]
Abort,
#[error("BPF program Panicked in {0} at {1}:{2}")]
Panic(String, u64, u64),
#[error("cannot borrow invoke context")]
InvokeContextBorrowFailed,
#[error("malformed signer seed: {0}: {1:?}")]
MalformedSignerSeed(Utf8Error, Vec<u8>),
#[error("Could not create program address with signer seeds: {0}")]
BadSeeds(PubkeyError),
#[error("Program id is not supported by cross-program invocations")]
ProgramNotSupported,
#[error("{0}")]
InstructionError(InstructionError),
#[error("Unaligned pointer")]
UnalignedPointer,
#[error("Too many signers")]
TooManySigners,
}
impl From<SyscallError> for EbpfError<BPFError> {
fn from(error: SyscallError) -> Self {
EbpfError::UserError(error.into())
}
}
trait SyscallConsume {
fn consume(&mut self, amount: u64) -> Result<(), EbpfError<BPFError>>;
}
impl SyscallConsume for Rc<RefCell<dyn ComputeMeter>> {
fn consume(&mut self, amount: u64) -> Result<(), EbpfError<BPFError>> {
self.try_borrow_mut()
.map_err(|_| SyscallError::InvokeContextBorrowFailed)?
.consume(amount)
.map_err(SyscallError::InstructionError)?;
Ok(())
}
}
/// Program heap allocators are intended to allocate/free from a given
/// chunk of memory. The specific allocator implementation is
/// selectable at build-time.
/// Only one allocator is currently supported
/// Simple bump allocator, never frees
use crate::allocator_bump::BPFAllocator;
pub fn register_syscalls(
invoke_context: &mut dyn InvokeContext,
) -> Result<SyscallRegistry, EbpfError<BPFError>> {
let mut syscall_registry = SyscallRegistry::default();
syscall_registry.register_syscall_by_name(b"abort", SyscallAbort::call)?;
syscall_registry.register_syscall_by_name(b"sol_panic_", SyscallPanic::call)?;
syscall_registry.register_syscall_by_name(b"sol_log_", SyscallLog::call)?;
syscall_registry.register_syscall_by_name(b"sol_log_64_", SyscallLogU64::call)?;
if invoke_context.is_feature_active(&sol_log_compute_units_syscall::id()) {
syscall_registry
.register_syscall_by_name(b"sol_log_compute_units_", SyscallLogBpfComputeUnits::call)?;
}
if invoke_context.is_feature_active(&pubkey_log_syscall_enabled::id()) {
syscall_registry.register_syscall_by_name(b"sol_log_pubkey", SyscallLogPubkey::call)?;
}
if invoke_context.is_feature_active(&sha256_syscall_enabled::id()) {
syscall_registry.register_syscall_by_name(b"sol_sha256", SyscallSha256::call)?;
}
if invoke_context.is_feature_active(&ristretto_mul_syscall_enabled::id()) {
syscall_registry
.register_syscall_by_name(b"sol_ristretto_mul", SyscallRistrettoMul::call)?;
}
syscall_registry.register_syscall_by_name(
b"sol_create_program_address",
SyscallCreateProgramAddress::call,
)?;
if invoke_context.is_feature_active(&try_find_program_address_syscall_enabled::id()) {
syscall_registry.register_syscall_by_name(
b"sol_try_find_program_address",
SyscallTryFindProgramAddress::call,
)?;
}
syscall_registry
.register_syscall_by_name(b"sol_invoke_signed_c", SyscallInvokeSignedC::call)?;
syscall_registry
.register_syscall_by_name(b"sol_invoke_signed_rust", SyscallInvokeSignedRust::call)?;
syscall_registry.register_syscall_by_name(b"sol_alloc_free_", SyscallAllocFree::call)?;
Ok(syscall_registry)
}
pub fn bind_syscall_context_objects<'a>(
loader_id: &'a Pubkey,
vm: &mut EbpfVm<'a, BPFError, crate::ThisInstructionMeter>,
callers_keyed_accounts: &'a [KeyedAccount<'a>],
invoke_context: &'a mut dyn InvokeContext,
heap: Vec<u8>,
) -> Result<(), EbpfError<BPFError>> {
let bpf_compute_budget = invoke_context.get_bpf_compute_budget();
// Syscall functions common across languages
vm.bind_syscall_context_object(Box::new(SyscallAbort {}), None)?;
vm.bind_syscall_context_object(Box::new(SyscallPanic { loader_id }), None)?;
vm.bind_syscall_context_object(
Box::new(SyscallLog {
cost: bpf_compute_budget.log_units,
compute_meter: invoke_context.get_compute_meter(),
logger: invoke_context.get_logger(),
loader_id,
}),
None,
)?;
vm.bind_syscall_context_object(
Box::new(SyscallLogU64 {
cost: bpf_compute_budget.log_64_units,
compute_meter: invoke_context.get_compute_meter(),
logger: invoke_context.get_logger(),
}),
None,
)?;
if invoke_context.is_feature_active(&sol_log_compute_units_syscall::id()) {
vm.bind_syscall_context_object(
Box::new(SyscallLogBpfComputeUnits {
cost: 0,
compute_meter: invoke_context.get_compute_meter(),
logger: invoke_context.get_logger(),
}),
None,
)?;
}
if invoke_context.is_feature_active(&pubkey_log_syscall_enabled::id()) {
vm.bind_syscall_context_object(
Box::new(SyscallLogPubkey {
cost: bpf_compute_budget.log_pubkey_units,
compute_meter: invoke_context.get_compute_meter(),
logger: invoke_context.get_logger(),
loader_id,
}),
None,
)?;
}
if invoke_context.is_feature_active(&sha256_syscall_enabled::id()) {
vm.bind_syscall_context_object(
Box::new(SyscallSha256 {
sha256_base_cost: bpf_compute_budget.sha256_base_cost,
sha256_byte_cost: bpf_compute_budget.sha256_byte_cost,
compute_meter: invoke_context.get_compute_meter(),
loader_id,
}),
None,
)?;
}
if invoke_context.is_feature_active(&ristretto_mul_syscall_enabled::id()) {
vm.bind_syscall_context_object(
Box::new(SyscallRistrettoMul {
cost: 0,
compute_meter: invoke_context.get_compute_meter(),
loader_id,
}),
None,
)?;
}
vm.bind_syscall_context_object(
Box::new(SyscallCreateProgramAddress {
cost: bpf_compute_budget.create_program_address_units,
compute_meter: invoke_context.get_compute_meter(),
loader_id,
}),
None,
)?;
if invoke_context.is_feature_active(&try_find_program_address_syscall_enabled::id()) {
vm.bind_syscall_context_object(
Box::new(SyscallTryFindProgramAddress {
cost: bpf_compute_budget.create_program_address_units,
compute_meter: invoke_context.get_compute_meter(),
loader_id,
}),
None,
)?;
}
// Cross-program invocation syscalls
let invoke_context = Rc::new(RefCell::new(invoke_context));
vm.bind_syscall_context_object(
Box::new(SyscallInvokeSignedC {
callers_keyed_accounts,
invoke_context: invoke_context.clone(),
loader_id,
}),
None,
)?;
vm.bind_syscall_context_object(
Box::new(SyscallInvokeSignedRust {
callers_keyed_accounts,
invoke_context: invoke_context.clone(),
loader_id,
}),
None,
)?;
// Memory allocator
vm.bind_syscall_context_object(
Box::new(SyscallAllocFree {
aligned: *loader_id != bpf_loader_deprecated::id(),
allocator: BPFAllocator::new(heap, MM_HEAP_START),
}),
None,
)?;
Ok(())
}
fn translate(
memory_mapping: &MemoryMapping,
access_type: AccessType,
vm_addr: u64,
len: u64,
) -> Result<u64, EbpfError<BPFError>> {
memory_mapping.map::<BPFError>(access_type, vm_addr, len)
}
fn translate_type_inner<'a, T>(
memory_mapping: &MemoryMapping,
access_type: AccessType,
vm_addr: u64,
loader_id: &Pubkey,
) -> Result<&'a mut T, EbpfError<BPFError>> {
if loader_id != &bpf_loader_deprecated::id()
&& (vm_addr as u64 as *mut T).align_offset(align_of::<T>()) != 0
{
Err(SyscallError::UnalignedPointer.into())
} else {
unsafe {
match translate(memory_mapping, access_type, vm_addr, size_of::<T>() as u64) {
Ok(value) => Ok(&mut *(value as *mut T)),
Err(e) => Err(e),
}
}
}
}
fn translate_type_mut<'a, T>(
memory_mapping: &MemoryMapping,
vm_addr: u64,
loader_id: &Pubkey,
) -> Result<&'a mut T, EbpfError<BPFError>> {
translate_type_inner::<T>(memory_mapping, AccessType::Store, vm_addr, loader_id)
}
fn translate_type<'a, T>(
memory_mapping: &MemoryMapping,
vm_addr: u64,
loader_id: &Pubkey,
) -> Result<&'a T, EbpfError<BPFError>> {
match translate_type_inner::<T>(memory_mapping, AccessType::Load, vm_addr, loader_id) {
Ok(value) => Ok(&*value),
Err(e) => Err(e),
}
}
fn translate_slice_inner<'a, T>(
memory_mapping: &MemoryMapping,
access_type: AccessType,
vm_addr: u64,
len: u64,
loader_id: &Pubkey,
) -> Result<&'a mut [T], EbpfError<BPFError>> {
if loader_id != &bpf_loader_deprecated::id()
&& (vm_addr as u64 as *mut T).align_offset(align_of::<T>()) != 0
{
Err(SyscallError::UnalignedPointer.into())
} else if len == 0 {
Ok(unsafe { from_raw_parts_mut(0x1 as *mut T, len as usize) })
} else {
match translate(
memory_mapping,
access_type,
vm_addr,
len.saturating_mul(size_of::<T>() as u64),
) {
Ok(value) => Ok(unsafe { from_raw_parts_mut(value as *mut T, len as usize) }),
Err(e) => Err(e),
}
}
}
fn translate_slice_mut<'a, T>(
memory_mapping: &MemoryMapping,
vm_addr: u64,
len: u64,
loader_id: &Pubkey,
) -> Result<&'a mut [T], EbpfError<BPFError>> {
translate_slice_inner::<T>(memory_mapping, AccessType::Store, vm_addr, len, loader_id)
}
fn translate_slice<'a, T>(
memory_mapping: &MemoryMapping,
vm_addr: u64,
len: u64,
loader_id: &Pubkey,
) -> Result<&'a [T], EbpfError<BPFError>> {
match translate_slice_inner::<T>(memory_mapping, AccessType::Load, vm_addr, len, loader_id) {
Ok(value) => Ok(&*value),
Err(e) => Err(e),
}
}
/// Take a virtual pointer to a string (points to BPF VM memory space), translate it
/// pass it to a user-defined work function
fn translate_string_and_do(
memory_mapping: &MemoryMapping,
addr: u64,
len: u64,
loader_id: &Pubkey,
work: &mut dyn FnMut(&str) -> Result<u64, EbpfError<BPFError>>,
) -> Result<u64, EbpfError<BPFError>> {
let buf = translate_slice::<u8>(memory_mapping, addr, len, loader_id)?;
let i = match buf.iter().position(|byte| *byte == 0) {
Some(i) => i,
None => len as usize,
};
match from_utf8(&buf[..i]) {
Ok(message) => work(message),
Err(err) => Err(SyscallError::InvalidString(err, buf[..i].to_vec()).into()),
}
}
/// Abort syscall functions, called when the BPF program calls `abort()`
/// LLVM will insert calls to `abort()` if it detects an untenable situation,
/// `abort()` is not intended to be called explicitly by the program.
/// Causes the BPF program to be halted immediately
pub struct SyscallAbort {}
impl SyscallObject<BPFError> for SyscallAbort {
fn call(
&mut self,
_arg1: u64,
_arg2: u64,
_arg3: u64,
_arg4: u64,
_arg5: u64,
_memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
*result = Err(SyscallError::Abort.into());
}
}
/// Panic syscall function, called when the BPF program calls 'sol_panic_()`
/// Causes the BPF program to be halted immediately
/// Log a user's info message
pub struct SyscallPanic<'a> {
loader_id: &'a Pubkey,
}
impl<'a> SyscallObject<BPFError> for SyscallPanic<'a> {
fn call(
&mut self,
file: u64,
len: u64,
line: u64,
column: u64,
_arg5: u64,
memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
*result = translate_string_and_do(
memory_mapping,
file,
len,
&self.loader_id,
&mut |string: &str| Err(SyscallError::Panic(string.to_string(), line, column).into()),
);
}
}
/// Log a user's info message
pub struct SyscallLog<'a> {
cost: u64,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
logger: Rc<RefCell<dyn Logger>>,
loader_id: &'a Pubkey,
}
impl<'a> SyscallObject<BPFError> for SyscallLog<'a> {
fn call(
&mut self,
addr: u64,
len: u64,
_arg3: u64,
_arg4: u64,
_arg5: u64,
memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
question_mark!(self.compute_meter.consume(self.cost), result);
question_mark!(
translate_string_and_do(
memory_mapping,
addr,
len,
&self.loader_id,
&mut |string: &str| {
stable_log::program_log(&self.logger, string);
Ok(0)
},
),
result
);
*result = Ok(0);
}
}
/// Log 5 64-bit values
pub struct SyscallLogU64 {
cost: u64,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
logger: Rc<RefCell<dyn Logger>>,
}
impl SyscallObject<BPFError> for SyscallLogU64 {
fn call(
&mut self,
arg1: u64,
arg2: u64,
arg3: u64,
arg4: u64,
arg5: u64,
_memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
question_mark!(self.compute_meter.consume(self.cost), result);
stable_log::program_log(
&self.logger,
&format!(
"{:#x}, {:#x}, {:#x}, {:#x}, {:#x}",
arg1, arg2, arg3, arg4, arg5
),
);
*result = Ok(0);
}
}
/// Log current compute consumption
pub struct SyscallLogBpfComputeUnits {
cost: u64,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
logger: Rc<RefCell<dyn Logger>>,
}
impl SyscallObject<BPFError> for SyscallLogBpfComputeUnits {
fn call(
&mut self,
_arg1: u64,
_arg2: u64,
_arg3: u64,
_arg4: u64,
_arg5: u64,
_memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
question_mark!(self.compute_meter.consume(self.cost), result);
let logger = question_mark!(
self.logger
.try_borrow_mut()
.map_err(|_| SyscallError::InvokeContextBorrowFailed),
result
);
if logger.log_enabled() {
logger.log(&format!(
"Program consumption: {} units remaining",
self.compute_meter.borrow().get_remaining()
));
}
*result = Ok(0);
}
}
/// Log 5 64-bit values
pub struct SyscallLogPubkey<'a> {
cost: u64,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
logger: Rc<RefCell<dyn Logger>>,
loader_id: &'a Pubkey,
}
impl<'a> SyscallObject<BPFError> for SyscallLogPubkey<'a> {
fn call(
&mut self,
pubkey_addr: u64,
_arg2: u64,
_arg3: u64,
_arg4: u64,
_arg5: u64,
memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
question_mark!(self.compute_meter.consume(self.cost), result);
let pubkey = question_mark!(
translate_type::<Pubkey>(memory_mapping, pubkey_addr, self.loader_id),
result
);
stable_log::program_log(&self.logger, &pubkey.to_string());
*result = Ok(0);
}
}
/// Dynamic memory allocation syscall called when the BPF program calls
/// `sol_alloc_free_()`. The allocator is expected to allocate/free
/// from/to a given chunk of memory and enforce size restrictions. The
/// memory chunk is given to the allocator during allocator creation and
/// information about that memory (start address and size) is passed
/// to the VM to use for enforcement.
pub struct SyscallAllocFree {
aligned: bool,
allocator: BPFAllocator,
}
impl SyscallObject<BPFError> for SyscallAllocFree {
fn call(
&mut self,
size: u64,
free_addr: u64,
_arg3: u64,
_arg4: u64,
_arg5: u64,
_memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
let align = if self.aligned {
align_of::<u128>()
} else {
align_of::<u8>()
};
let layout = match Layout::from_size_align(size as usize, align) {
Ok(layout) => layout,
Err(_) => {
*result = Ok(0);
return;
}
};
*result = if free_addr == 0 {
match self.allocator.alloc(layout) {
Ok(addr) => Ok(addr as u64),
Err(_) => Ok(0),
}
} else {
self.allocator.dealloc(free_addr, layout);
Ok(0)
};
}
}
fn translate_program_address_inputs<'a>(
seeds_addr: u64,
seeds_len: u64,
program_id_addr: u64,
memory_mapping: &MemoryMapping,
loader_id: &Pubkey,
) -> Result<(Vec<&'a [u8]>, &'a Pubkey), EbpfError<BPFError>> {
let untranslated_seeds =
translate_slice::<&[&u8]>(memory_mapping, seeds_addr, seeds_len, loader_id)?;
if untranslated_seeds.len() > MAX_SEEDS {
return Err(SyscallError::BadSeeds(PubkeyError::MaxSeedLengthExceeded).into());
}
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,
loader_id,
)
})
.collect::<Result<Vec<_>, EbpfError<BPFError>>>()?;
let program_id = translate_type::<Pubkey>(memory_mapping, program_id_addr, loader_id)?;
Ok((seeds, program_id))
}
/// Create a program address
struct SyscallCreateProgramAddress<'a> {
cost: u64,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
loader_id: &'a Pubkey,
}
impl<'a> SyscallObject<BPFError> for SyscallCreateProgramAddress<'a> {
fn call(
&mut self,
seeds_addr: u64,
seeds_len: u64,
program_id_addr: u64,
address_addr: u64,
_arg5: u64,
memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
let (seeds, program_id) = question_mark!(
translate_program_address_inputs(
seeds_addr,
seeds_len,
program_id_addr,
memory_mapping,
self.loader_id,
),
result
);
question_mark!(self.compute_meter.consume(self.cost), result);
let new_address = match Pubkey::create_program_address(&seeds, program_id) {
Ok(address) => address,
Err(_) => {
*result = Ok(1);
return;
}
};
let address = question_mark!(
translate_slice_mut::<u8>(memory_mapping, address_addr, 32, self.loader_id),
result
);
address.copy_from_slice(new_address.as_ref());
*result = Ok(0);
}
}
/// Create a program address
struct SyscallTryFindProgramAddress<'a> {
cost: u64,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
loader_id: &'a Pubkey,
}
impl<'a> SyscallObject<BPFError> for SyscallTryFindProgramAddress<'a> {
fn call(
&mut self,
seeds_addr: u64,
seeds_len: u64,
program_id_addr: u64,
address_addr: u64,
bump_seed_addr: u64,
memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
let (seeds, program_id) = question_mark!(
translate_program_address_inputs(
seeds_addr,
seeds_len,
program_id_addr,
memory_mapping,
self.loader_id,
),
result
);
let mut bump_seed = [std::u8::MAX];
for _ in 0..std::u8::MAX {
{
let mut seeds_with_bump = seeds.to_vec();
seeds_with_bump.push(&bump_seed);
question_mark!(self.compute_meter.consume(self.cost), result);
if let Ok(new_address) =
Pubkey::create_program_address(&seeds_with_bump, program_id)
{
let bump_seed_ref = question_mark!(
translate_type_mut::<u8>(memory_mapping, bump_seed_addr, self.loader_id),
result
);
let address = question_mark!(
translate_slice_mut::<u8>(memory_mapping, address_addr, 32, self.loader_id),
result
);
*bump_seed_ref = bump_seed[0];
address.copy_from_slice(new_address.as_ref());
*result = Ok(0);
return;
}
}
bump_seed[0] -= 1;
}
*result = Ok(1);
}
}
/// SHA256
pub struct SyscallSha256<'a> {
sha256_base_cost: u64,
sha256_byte_cost: u64,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
loader_id: &'a Pubkey,
}
impl<'a> SyscallObject<BPFError> for SyscallSha256<'a> {
fn call(
&mut self,
vals_addr: u64,
vals_len: u64,
result_addr: u64,
_arg4: u64,
_arg5: u64,
memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
question_mark!(self.compute_meter.consume(self.sha256_base_cost), result);
let hash_result = question_mark!(
translate_slice_mut::<u8>(
memory_mapping,
result_addr,
HASH_BYTES as u64,
self.loader_id
),
result
);
let mut hasher = Hasher::default();
if vals_len > 0 {
let vals = question_mark!(
translate_slice::<&[u8]>(memory_mapping, vals_addr, vals_len, self.loader_id),
result
);
for val in vals.iter() {
let bytes = question_mark!(
translate_slice::<u8>(
memory_mapping,
val.as_ptr() as u64,
val.len() as u64,
self.loader_id
),
result
);
question_mark!(
self.compute_meter
.consume(self.sha256_byte_cost * (val.len() as u64 / 2)),
result
);
hasher.hash(bytes);
}
}
hash_result.copy_from_slice(&hasher.result().to_bytes());
*result = Ok(0);
}
}
/// Ristretto point multiply
pub struct SyscallRistrettoMul<'a> {
cost: u64,
compute_meter: Rc<RefCell<dyn ComputeMeter>>,
loader_id: &'a Pubkey,
}
impl<'a> SyscallObject<BPFError> for SyscallRistrettoMul<'a> {
fn call(
&mut self,
point_addr: u64,
scalar_addr: u64,
result_addr: u64,
_arg4: u64,
_arg5: u64,
memory_mapping: &MemoryMapping,
result: &mut Result<u64, EbpfError<BPFError>>,
) {
question_mark!(self.compute_meter.consume(self.cost), result);
let point = question_mark!(
translate_type::<RistrettoPoint>(memory_mapping, point_addr, self.loader_id),
result
);
let scalar = question_mark!(
translate_type::<Scalar>(memory_mapping, scalar_addr, self.loader_id),
result
);
let output = question_mark!(
translate_type_mut::<RistrettoPoint>(memory_mapping, result_addr, self.loader_id),
result
);
*output = point * scalar;
*result = Ok(0);
}
}
// Cross-program invocation syscalls
struct AccountReferences<'a> {
lamports: &'a mut u64,
owner: &'a mut Pubkey,
data: &'a mut [u8],
vm_data_addr: u64,
ref_to_len_in_vm: &'a mut u64,
serialized_len_ptr: &'a mut u64,
}
type TranslatedAccount<'a> = (Rc<RefCell<Account>>, Option<AccountReferences<'a>>);
type TranslatedAccounts<'a> = (
Vec<Rc<RefCell<Account>>>,
Vec<Option<AccountReferences<'a>>>,
);
/// Implemented by language specific data structure translators
trait SyscallInvokeSigned<'a> {
fn get_context_mut(&self) -> Result<RefMut<&'a mut dyn InvokeContext>, EbpfError<BPFError>>;
fn get_context(&self) -> Result<Ref<&'a mut dyn InvokeContext>, EbpfError<BPFError>>;
fn get_callers_keyed_accounts(&self) -> &'a [KeyedAccount<'a>];
fn translate_instruction(
&self,
addr: u64,
memory_mapping: &MemoryMapping,
) -> Result<Instruction, EbpfError<BPFError>>;
fn translate_accounts(
&self,
account_keys: &[Pubkey],
program_account_index: usize,
account_infos_addr: u64,
account_infos_len: u64,
memory_mapping: &MemoryMapping,
) -> Result<TranslatedAccounts<'a>, EbpfError<BPFError>>;
fn translate_signers(
&self,
program_id: &Pubkey,
signers_seeds_addr: u64,
signers_seeds_len: u64,
memory_mapping: &MemoryMapping,
) -> Result<Vec<Pubkey>, EbpfError<BPFError>>;
}
/// Cross-program invocation called from Rust
pub struct SyscallInvokeSignedRust<'a> {
callers_keyed_accounts: &'a [KeyedAccount<'a>],
invoke_context: Rc<RefCell<&'a mut dyn InvokeContext>>,
loader_id: &'a Pubkey,
}
impl<'a> SyscallInvokeSigned<'a> for SyscallInvokeSignedRust<'a> {
fn get_context_mut(&self) -> Result<RefMut<&'a mut dyn InvokeContext>, EbpfError<BPFError>> {
self.invoke_context
.try_borrow_mut()
.map_err(|_| SyscallError::InvokeContextBorrowFailed.into())
}
fn get_context(&self) -> Result<Ref<&'a mut dyn InvokeContext>, EbpfError<BPFError>> {
self.invoke_context
.try_borrow()
.map_err(|_| SyscallError::InvokeContextBorrowFailed.into())
}
fn get_callers_keyed_accounts(&self) -> &'a [KeyedAccount<'a>] {
self.callers_keyed_accounts
}
fn translate_instruction(
&self,
addr: u64,
memory_mapping: &MemoryMapping,
) -> Result<Instruction, EbpfError<BPFError>> {
let ix = translate_type::<Instruction>(memory_mapping, addr, self.loader_id)?;
check_instruction_size(
ix.accounts.len(),
ix.data.len(),
self.invoke_context
.borrow()
.get_bpf_compute_budget()
.max_cpi_instruction_size,
)?;
let accounts = translate_slice::<AccountMeta>(
memory_mapping,
ix.accounts.as_ptr() as u64,
ix.accounts.len() as u64,
self.loader_id,
)?
.to_vec();
let data = translate_slice::<u8>(
memory_mapping,
ix.data.as_ptr() as u64,
ix.data.len() as u64,
self.loader_id,
)?
.to_vec();
Ok(Instruction {
program_id: ix.program_id,
accounts,
data,
})
}
fn translate_accounts(
&self,
account_keys: &[Pubkey],
program_account_index: usize,
account_infos_addr: u64,
account_infos_len: u64,
memory_mapping: &MemoryMapping,
) -> Result<TranslatedAccounts<'a>, EbpfError<BPFError>> {
let invoke_context = self.invoke_context.borrow();
let account_infos = translate_slice::<AccountInfo>(
memory_mapping,
account_infos_addr,
account_infos_len,
self.loader_id,
)?;
check_account_infos(account_infos.len(), &invoke_context)?;
let account_info_keys = account_infos
.iter()
.map(|account_info| {
translate_type::<Pubkey>(
memory_mapping,
account_info.key as *const _ as u64,
self.loader_id,
)
})
.collect::<Result<Vec<_>, EbpfError<BPFError>>>()?;
let translate = |account_info: &AccountInfo| {
// Translate the account from user space
let lamports = {
// Double translate lamports out of RefCell
let ptr = translate_type::<u64>(
memory_mapping,
account_info.lamports.as_ptr() as u64,
self.loader_id,
)?;
translate_type_mut::<u64>(memory_mapping, *ptr, self.loader_id)?
};
let owner = translate_type_mut::<Pubkey>(
memory_mapping,
account_info.owner as *const _ as u64,
self.loader_id,
)?;
let (data, vm_data_addr, ref_to_len_in_vm, serialized_len_ptr) = {
// Double translate data out of RefCell
let data = *translate_type::<&[u8]>(
memory_mapping,
account_info.data.as_ptr() as *const _ as u64,
self.loader_id,
)?;
let translated = translate(
memory_mapping,
AccessType::Store,
unsafe { (account_info.data.as_ptr() as *const u64).offset(1) as u64 },
8,
)? as *mut u64;
let ref_to_len_in_vm = unsafe { &mut *translated };
let ref_of_len_in_input_buffer = unsafe { data.as_ptr().offset(-8) };
let serialized_len_ptr = translate_type_mut::<u64>(
memory_mapping,
ref_of_len_in_input_buffer as *const _ as u64,
self.loader_id,
)?;
let vm_data_addr = data.as_ptr() as u64;
(
translate_slice_mut::<u8>(
memory_mapping,
vm_data_addr,
data.len() as u64,
self.loader_id,
)?,