-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
lib.rs
3702 lines (3499 loc) · 146 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
#![allow(clippy::integer_arithmetic)]
pub mod alloc;
pub mod allocator_bump;
pub mod deprecated;
pub mod serialization;
pub mod syscalls;
pub mod upgradeable;
pub mod upgradeable_with_jit;
pub mod with_jit;
#[macro_use]
extern crate solana_metrics;
use {
crate::{
serialization::{deserialize_parameters, serialize_parameters},
syscalls::SyscallError,
},
log::{log_enabled, trace, Level::Trace},
solana_measure::measure::Measure,
solana_rbpf::{
aligned_memory::AlignedMemory,
ebpf::HOST_ALIGN,
elf::Executable,
error::{EbpfError, UserDefinedError},
static_analysis::Analysis,
verifier::{self, VerifierError},
vm::{Config, EbpfVm, InstructionMeter},
},
solana_runtime::message_processor::MessageProcessor,
solana_sdk::{
account::{ReadableAccount, WritableAccount},
account_utils::State,
bpf_loader, bpf_loader_deprecated,
bpf_loader_upgradeable::{self, UpgradeableLoaderState},
clock::Clock,
entrypoint::{HEAP_LENGTH, SUCCESS},
feature_set::{
add_missing_program_error_mappings, close_upgradeable_program_accounts,
fix_write_privs, reduce_required_deploy_balance, reject_all_elf_rw,
reject_deployment_of_unresolved_syscalls,
reject_section_virtual_address_file_offset_mismatch, start_verify_shift32_imm,
stop_verify_mul64_imm_nonzero, upgradeable_close_instruction,
},
ic_logger_msg, ic_msg,
instruction::{AccountMeta, InstructionError},
keyed_account::{from_keyed_account, keyed_account_at_index, KeyedAccount},
loader_instruction::LoaderInstruction,
loader_upgradeable_instruction::UpgradeableLoaderInstruction,
process_instruction::{stable_log, ComputeMeter, Executor, InvokeContext, Logger},
program_error::{ACCOUNT_NOT_RENT_EXEMPT, BORSH_IO_ERROR},
program_utils::limited_deserialize,
pubkey::Pubkey,
rent::Rent,
saturating_add_assign,
system_instruction::{self, MAX_PERMITTED_DATA_LENGTH},
},
std::{cell::RefCell, fmt::Debug, pin::Pin, rc::Rc, sync::Arc},
thiserror::Error,
};
solana_sdk::declare_builtin!(
solana_sdk::bpf_loader::ID,
solana_bpf_loader_program,
solana_bpf_loader_program::process_instruction
);
/// Errors returned by functions the BPF Loader registers with the VM
#[derive(Debug, Error, PartialEq)]
pub enum BpfError {
#[error("{0}")]
VerifierError(#[from] VerifierError),
#[error("{0}")]
SyscallError(#[from] SyscallError),
}
impl UserDefinedError for BpfError {}
fn map_ebpf_error(invoke_context: &dyn InvokeContext, e: EbpfError<BpfError>) -> InstructionError {
ic_msg!(invoke_context, "{}", e);
InstructionError::InvalidAccountData
}
mod executor_metrics {
#[derive(Debug, Default)]
pub struct CreateMetrics {
pub program_id: String,
pub load_elf_us: u64,
pub verify_code_us: u64,
pub jit_compile_us: u64,
}
impl CreateMetrics {
pub fn submit_datapoint(&self) {
datapoint_trace!(
"create_executor_trace",
("program_id", self.program_id, String),
("load_elf_us", self.load_elf_us, i64),
("verify_code_us", self.verify_code_us, i64),
("jit_compile_us", self.jit_compile_us, i64),
);
}
}
}
pub fn create_executor(
program_account_index: usize,
program_data_offset: usize,
invoke_context: &mut dyn InvokeContext,
use_jit: bool,
reject_deployment_of_broken_elfs: bool,
) -> Result<Arc<BpfExecutor>, InstructionError> {
let mut register_syscalls_time = Measure::start("register_syscalls_time");
let register_syscall_result = syscalls::register_syscalls(invoke_context);
register_syscalls_time.stop();
saturating_add_assign!(
invoke_context
.get_timings()
.create_executor_register_syscalls_us,
register_syscalls_time.as_us()
);
let syscall_registry = register_syscall_result.map_err(|e| {
ic_msg!(invoke_context, "Failed to register syscalls: {}", e);
InstructionError::ProgramEnvironmentSetupFailure
})?;
let bpf_compute_budget = invoke_context.get_bpf_compute_budget();
let config = Config {
max_call_depth: bpf_compute_budget.max_call_depth,
stack_frame_size: bpf_compute_budget.stack_frame_size,
enable_instruction_tracing: log_enabled!(Trace),
reject_unresolved_syscalls: reject_deployment_of_broken_elfs
&& invoke_context.is_feature_active(&reject_deployment_of_unresolved_syscalls::id()),
reject_section_virtual_address_file_offset_mismatch: reject_deployment_of_broken_elfs
&& invoke_context
.is_feature_active(&reject_section_virtual_address_file_offset_mismatch::id()),
verify_mul64_imm_nonzero: !invoke_context
.is_feature_active(&stop_verify_mul64_imm_nonzero::id()),
verify_shift32_imm: invoke_context.is_feature_active(&start_verify_shift32_imm::id()),
reject_all_writable_sections: invoke_context.is_feature_active(&reject_all_elf_rw::id()),
..Config::default()
};
let mut create_executor_metrics = executor_metrics::CreateMetrics::default();
let executable_result = {
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let program = keyed_account_at_index(keyed_accounts, program_account_index)?;
create_executor_metrics.program_id = program.unsigned_key().to_string();
let account = program.try_account_ref()?;
let data = &account.data()[program_data_offset..];
let mut load_elf_time = Measure::start("load_elf_time");
let executable = Executable::<BpfError, ThisInstructionMeter>::from_elf(
data,
None,
config,
syscall_registry,
);
load_elf_time.stop();
create_executor_metrics.load_elf_us = load_elf_time.as_us();
executable
};
saturating_add_assign!(
invoke_context.get_timings().create_executor_load_elf_us,
create_executor_metrics.load_elf_us
);
let mut executable = executable_result.map_err(|e| map_ebpf_error(invoke_context, e))?;
let text_bytes = executable.get_text_bytes().1;
let mut verify_code_time = Measure::start("verify_code_time");
verifier::check(text_bytes, &config)
.map_err(|e| map_ebpf_error(invoke_context, EbpfError::UserError(e.into())))?;
verify_code_time.stop();
create_executor_metrics.verify_code_us = verify_code_time.as_us();
saturating_add_assign!(
invoke_context.get_timings().create_executor_verify_code_us,
create_executor_metrics.verify_code_us
);
if use_jit {
let mut jit_compile_time = Measure::start("jit_compile_time");
let jit_compile_result =
Executable::<BpfError, ThisInstructionMeter>::jit_compile(&mut executable);
jit_compile_time.stop();
create_executor_metrics.jit_compile_us = jit_compile_time.as_us();
saturating_add_assign!(
invoke_context.get_timings().create_executor_jit_compile_us,
create_executor_metrics.jit_compile_us
);
if let Err(err) = jit_compile_result {
ic_msg!(invoke_context, "Failed to compile program {:?}", err);
return Err(InstructionError::ProgramFailedToCompile);
}
}
create_executor_metrics.submit_datapoint();
Ok(Arc::new(BpfExecutor { executable }))
}
fn write_program_data(
program_account_index: usize,
program_data_offset: usize,
bytes: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let program = keyed_account_at_index(keyed_accounts, program_account_index)?;
let mut account = program.try_account_ref_mut()?;
let data = &mut account.data_as_mut_slice();
let len = bytes.len();
if data.len() < program_data_offset + len {
ic_msg!(
invoke_context,
"Write overflow: {} < {}",
data.len(),
program_data_offset + len
);
return Err(InstructionError::AccountDataTooSmall);
}
data[program_data_offset..program_data_offset + len].copy_from_slice(bytes);
Ok(())
}
fn check_loader_id(id: &Pubkey) -> bool {
bpf_loader::check_id(id)
|| bpf_loader_deprecated::check_id(id)
|| bpf_loader_upgradeable::check_id(id)
}
/// Create the BPF virtual machine
pub fn create_vm<'a>(
loader_id: &'a Pubkey,
program: &'a Pin<Box<Executable<BpfError, ThisInstructionMeter>>>,
parameter_bytes: &mut [u8],
invoke_context: &'a mut dyn InvokeContext,
) -> Result<EbpfVm<'a, BpfError, ThisInstructionMeter>, EbpfError<BpfError>> {
let bpf_compute_budget = invoke_context.get_bpf_compute_budget();
let mut heap = AlignedMemory::new_with_size(
bpf_compute_budget.heap_size.unwrap_or(HEAP_LENGTH),
HOST_ALIGN,
);
let mut vm = EbpfVm::new(program, heap.as_slice_mut(), parameter_bytes)?;
syscalls::bind_syscall_context_objects(loader_id, &mut vm, invoke_context, heap)?;
Ok(vm)
}
pub fn process_instruction(
program_id: &Pubkey,
instruction_data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
process_instruction_common(program_id, instruction_data, invoke_context, false)
}
pub fn process_instruction_jit(
program_id: &Pubkey,
instruction_data: &[u8],
invoke_context: &mut dyn InvokeContext,
) -> Result<(), InstructionError> {
process_instruction_common(program_id, instruction_data, invoke_context, true)
}
fn process_instruction_common(
program_id: &Pubkey,
instruction_data: &[u8],
invoke_context: &mut dyn InvokeContext,
use_jit: bool,
) -> Result<(), InstructionError> {
let logger = invoke_context.get_logger();
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let first_account = keyed_account_at_index(keyed_accounts, 0)?;
if first_account.executable()? {
if first_account.unsigned_key() != program_id {
ic_logger_msg!(logger, "Program id mismatch");
return Err(InstructionError::IncorrectProgramId);
}
let program_data_offset = if bpf_loader_upgradeable::check_id(&first_account.owner()?) {
if let UpgradeableLoaderState::Program {
programdata_address,
} = first_account.state()?
{
let programdata = keyed_account_at_index(keyed_accounts, 1)?;
if programdata_address != *programdata.unsigned_key() {
ic_logger_msg!(logger, "Wrong ProgramData account for this Program account");
return Err(InstructionError::InvalidArgument);
}
if !matches!(
programdata.state()?,
UpgradeableLoaderState::ProgramData {
slot: _,
upgrade_authority_address: _,
}
) {
ic_logger_msg!(logger, "Program has been closed");
return Err(InstructionError::InvalidAccountData);
}
invoke_context.remove_first_keyed_account()?;
UpgradeableLoaderState::programdata_data_offset()?
} else {
ic_logger_msg!(logger, "Invalid Program account");
return Err(InstructionError::InvalidAccountData);
}
} else {
0
};
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let program = keyed_account_at_index(keyed_accounts, 0)?;
let loader_id = &program.owner()?;
if !check_loader_id(loader_id) {
ic_logger_msg!(logger, "Executable account not owned by the BPF loader");
return Err(InstructionError::IncorrectProgramId);
}
let mut get_or_create_executor_time = Measure::start("get_or_create_executor_time");
let maybe_executor = invoke_context.get_executor(program_id);
let executor = match maybe_executor {
Some(executor) => executor,
None => {
let executor =
create_executor(0, program_data_offset, invoke_context, use_jit, false)?;
invoke_context.add_executor(program_id, executor.clone());
executor
}
};
get_or_create_executor_time.stop();
saturating_add_assign!(
invoke_context.get_timings().get_or_create_executor_us,
get_or_create_executor_time.as_us()
);
executor.execute(
loader_id,
program_id,
instruction_data,
invoke_context,
use_jit,
)?
} else {
if !check_loader_id(program_id) {
ic_logger_msg!(logger, "Invalid BPF loader id");
return Err(InstructionError::IncorrectProgramId);
}
if bpf_loader_upgradeable::check_id(program_id) {
process_loader_upgradeable_instruction(
program_id,
instruction_data,
invoke_context,
use_jit,
)?;
} else {
process_loader_instruction(program_id, instruction_data, invoke_context, use_jit)?;
}
}
Ok(())
}
fn process_loader_upgradeable_instruction(
program_id: &Pubkey,
instruction_data: &[u8],
invoke_context: &mut dyn InvokeContext,
use_jit: bool,
) -> Result<(), InstructionError> {
let logger = invoke_context.get_logger();
let keyed_accounts = invoke_context.get_keyed_accounts()?;
match limited_deserialize(instruction_data)? {
UpgradeableLoaderInstruction::InitializeBuffer => {
let buffer = keyed_account_at_index(keyed_accounts, 0)?;
if UpgradeableLoaderState::Uninitialized != buffer.state()? {
ic_logger_msg!(logger, "Buffer account already initialized");
return Err(InstructionError::AccountAlreadyInitialized);
}
let authority = keyed_account_at_index(keyed_accounts, 1)?;
buffer.set_state(&UpgradeableLoaderState::Buffer {
authority_address: Some(*authority.unsigned_key()),
})?;
}
UpgradeableLoaderInstruction::Write { offset, bytes } => {
let buffer = keyed_account_at_index(keyed_accounts, 0)?;
let authority = keyed_account_at_index(keyed_accounts, 1)?;
if let UpgradeableLoaderState::Buffer { authority_address } = buffer.state()? {
if authority_address.is_none() {
ic_logger_msg!(logger, "Buffer is immutable");
return Err(InstructionError::Immutable); // TODO better error code
}
if authority_address != Some(*authority.unsigned_key()) {
ic_logger_msg!(logger, "Incorrect buffer authority provided");
return Err(InstructionError::IncorrectAuthority);
}
if authority.signer_key().is_none() {
ic_logger_msg!(logger, "Buffer authority did not sign");
return Err(InstructionError::MissingRequiredSignature);
}
} else {
ic_logger_msg!(logger, "Invalid Buffer account");
return Err(InstructionError::InvalidAccountData);
}
write_program_data(
0,
UpgradeableLoaderState::buffer_data_offset()? + offset as usize,
&bytes,
invoke_context,
)?;
}
UpgradeableLoaderInstruction::DeployWithMaxDataLen { max_data_len } => {
let payer = keyed_account_at_index(keyed_accounts, 0)?;
let programdata = keyed_account_at_index(keyed_accounts, 1)?;
let program = keyed_account_at_index(keyed_accounts, 2)?;
let buffer = keyed_account_at_index(keyed_accounts, 3)?;
let rent = from_keyed_account::<Rent>(keyed_account_at_index(keyed_accounts, 4)?)?;
let clock = from_keyed_account::<Clock>(keyed_account_at_index(keyed_accounts, 5)?)?;
let authority = keyed_account_at_index(keyed_accounts, 7)?;
let upgrade_authority_address = Some(*authority.unsigned_key());
let upgrade_authority_signer = authority.signer_key().is_none();
// Verify Program account
if UpgradeableLoaderState::Uninitialized != program.state()? {
ic_logger_msg!(logger, "Program account already initialized");
return Err(InstructionError::AccountAlreadyInitialized);
}
if program.data_len()? < UpgradeableLoaderState::program_len()? {
ic_logger_msg!(logger, "Program account too small");
return Err(InstructionError::AccountDataTooSmall);
}
if program.lamports()? < rent.minimum_balance(program.data_len()?) {
ic_logger_msg!(logger, "Program account not rent-exempt");
return Err(InstructionError::ExecutableAccountNotRentExempt);
}
let new_program_id = *program.unsigned_key();
// Verify Buffer account
if let UpgradeableLoaderState::Buffer { authority_address } = buffer.state()? {
if authority_address != upgrade_authority_address {
ic_logger_msg!(logger, "Buffer and upgrade authority don't match");
return Err(InstructionError::IncorrectAuthority);
}
if upgrade_authority_signer {
ic_logger_msg!(logger, "Upgrade authority did not sign");
return Err(InstructionError::MissingRequiredSignature);
}
} else {
ic_logger_msg!(logger, "Invalid Buffer account");
return Err(InstructionError::InvalidArgument);
}
let buffer_data_offset = UpgradeableLoaderState::buffer_data_offset()?;
let buffer_data_len = buffer.data_len()?.saturating_sub(buffer_data_offset);
let programdata_data_offset = UpgradeableLoaderState::programdata_data_offset()?;
let programdata_len = UpgradeableLoaderState::programdata_len(max_data_len)?;
if buffer.data_len()? < UpgradeableLoaderState::buffer_data_offset()?
|| buffer_data_len == 0
{
ic_logger_msg!(logger, "Buffer account too small");
return Err(InstructionError::InvalidAccountData);
}
if max_data_len < buffer_data_len {
ic_logger_msg!(logger, "Max data length is too small to hold Buffer data");
return Err(InstructionError::AccountDataTooSmall);
}
if programdata_len > MAX_PERMITTED_DATA_LENGTH as usize {
ic_logger_msg!(logger, "Max data length is too large");
return Err(InstructionError::InvalidArgument);
}
// Create ProgramData account
let (derived_address, bump_seed) =
Pubkey::find_program_address(&[new_program_id.as_ref()], program_id);
if derived_address != *programdata.unsigned_key() {
ic_logger_msg!(logger, "ProgramData address is not derived");
return Err(InstructionError::InvalidArgument);
}
let predrain_buffer = invoke_context
.is_feature_active(&reduce_required_deploy_balance::id())
&& invoke_context.is_feature_active(&fix_write_privs::id());
if predrain_buffer {
// Drain the Buffer account to payer before paying for programdata account
payer
.try_account_ref_mut()?
.checked_add_lamports(buffer.lamports()?)?;
buffer.try_account_ref_mut()?.set_lamports(0);
}
let mut instruction = system_instruction::create_account(
payer.unsigned_key(),
programdata.unsigned_key(),
1.max(rent.minimum_balance(programdata_len)),
programdata_len as u64,
program_id,
);
// pass an extra account to avoid the overly strict UnbalancedInstruction error
instruction
.accounts
.push(AccountMeta::new(*buffer.unsigned_key(), false));
let caller_program_id = invoke_context.get_caller()?;
let signers = [&[new_program_id.as_ref(), &[bump_seed]]]
.iter()
.map(|seeds| Pubkey::create_program_address(*seeds, caller_program_id))
.collect::<Result<Vec<Pubkey>, solana_sdk::pubkey::PubkeyError>>()?;
MessageProcessor::native_invoke(
invoke_context,
instruction,
&[0, 1, 3, 6],
signers.as_slice(),
)?;
// Load and verify the program bits
let executor = create_executor(3, buffer_data_offset, invoke_context, use_jit, true)?;
invoke_context.update_executor(&new_program_id, executor);
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let payer = keyed_account_at_index(keyed_accounts, 0)?;
let programdata = keyed_account_at_index(keyed_accounts, 1)?;
let program = keyed_account_at_index(keyed_accounts, 2)?;
let buffer = keyed_account_at_index(keyed_accounts, 3)?;
// Update the ProgramData account and record the program bits
programdata.set_state(&UpgradeableLoaderState::ProgramData {
slot: clock.slot,
upgrade_authority_address,
})?;
programdata.try_account_ref_mut()?.data_as_mut_slice()
[programdata_data_offset..programdata_data_offset + buffer_data_len]
.copy_from_slice(&buffer.try_account_ref()?.data()[buffer_data_offset..]);
// Update the Program account
program.set_state(&UpgradeableLoaderState::Program {
programdata_address: *programdata.unsigned_key(),
})?;
program.try_account_ref_mut()?.set_executable(true);
if !predrain_buffer {
// Drain the Buffer account back to the payer
payer
.try_account_ref_mut()?
.checked_add_lamports(buffer.lamports()?)?;
buffer.try_account_ref_mut()?.set_lamports(0);
}
ic_logger_msg!(logger, "Deployed program {:?}", new_program_id);
}
UpgradeableLoaderInstruction::Upgrade => {
let programdata = keyed_account_at_index(keyed_accounts, 0)?;
let program = keyed_account_at_index(keyed_accounts, 1)?;
let buffer = keyed_account_at_index(keyed_accounts, 2)?;
let rent = from_keyed_account::<Rent>(keyed_account_at_index(keyed_accounts, 4)?)?;
let clock = from_keyed_account::<Clock>(keyed_account_at_index(keyed_accounts, 5)?)?;
let authority = keyed_account_at_index(keyed_accounts, 6)?;
// Verify Program account
if !program.executable()? {
ic_logger_msg!(logger, "Program account not executable");
return Err(InstructionError::AccountNotExecutable);
}
if !program.is_writable() {
ic_logger_msg!(logger, "Program account not writeable");
return Err(InstructionError::InvalidArgument);
}
if &program.owner()? != program_id {
ic_logger_msg!(logger, "Program account not owned by loader");
return Err(InstructionError::IncorrectProgramId);
}
if let UpgradeableLoaderState::Program {
programdata_address,
} = program.state()?
{
if programdata_address != *programdata.unsigned_key() {
ic_logger_msg!(logger, "Program and ProgramData account mismatch");
return Err(InstructionError::InvalidArgument);
}
} else {
ic_logger_msg!(logger, "Invalid Program account");
return Err(InstructionError::InvalidAccountData);
}
let new_program_id = *program.unsigned_key();
// Verify Buffer account
if let UpgradeableLoaderState::Buffer { authority_address } = buffer.state()? {
if authority_address != Some(*authority.unsigned_key()) {
ic_logger_msg!(logger, "Buffer and upgrade authority don't match");
return Err(InstructionError::IncorrectAuthority);
}
if authority.signer_key().is_none() {
ic_logger_msg!(logger, "Upgrade authority did not sign");
return Err(InstructionError::MissingRequiredSignature);
}
} else {
ic_logger_msg!(logger, "Invalid Buffer account");
return Err(InstructionError::InvalidArgument);
}
let buffer_data_offset = UpgradeableLoaderState::buffer_data_offset()?;
let buffer_data_len = buffer.data_len()?.saturating_sub(buffer_data_offset);
let programdata_data_offset = UpgradeableLoaderState::programdata_data_offset()?;
let programdata_balance_required = 1.max(rent.minimum_balance(programdata.data_len()?));
if buffer.data_len()? < UpgradeableLoaderState::buffer_data_offset()?
|| buffer_data_len == 0
{
ic_logger_msg!(logger, "Buffer account too small");
return Err(InstructionError::InvalidAccountData);
}
// Verify ProgramData account
if programdata.data_len()? < UpgradeableLoaderState::programdata_len(buffer_data_len)? {
ic_logger_msg!(logger, "ProgramData account not large enough");
return Err(InstructionError::AccountDataTooSmall);
}
if programdata.lamports()? + buffer.lamports()? < programdata_balance_required {
ic_logger_msg!(logger, "Buffer account balance too low to fund upgrade");
return Err(InstructionError::InsufficientFunds);
}
if let UpgradeableLoaderState::ProgramData {
slot: _,
upgrade_authority_address,
} = programdata.state()?
{
if upgrade_authority_address.is_none() {
ic_logger_msg!(logger, "Program not upgradeable");
return Err(InstructionError::Immutable);
}
if upgrade_authority_address != Some(*authority.unsigned_key()) {
ic_logger_msg!(logger, "Incorrect upgrade authority provided");
return Err(InstructionError::IncorrectAuthority);
}
if authority.signer_key().is_none() {
ic_logger_msg!(logger, "Upgrade authority did not sign");
return Err(InstructionError::MissingRequiredSignature);
}
} else {
ic_logger_msg!(logger, "Invalid ProgramData account");
return Err(InstructionError::InvalidAccountData);
}
// Load and verify the program bits
let executor = create_executor(2, buffer_data_offset, invoke_context, use_jit, true)?;
invoke_context.update_executor(&new_program_id, executor);
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let programdata = keyed_account_at_index(keyed_accounts, 0)?;
let buffer = keyed_account_at_index(keyed_accounts, 2)?;
let spill = keyed_account_at_index(keyed_accounts, 3)?;
let authority = keyed_account_at_index(keyed_accounts, 6)?;
// Update the ProgramData account, record the upgraded data, and zero
// the rest
programdata.set_state(&UpgradeableLoaderState::ProgramData {
slot: clock.slot,
upgrade_authority_address: Some(*authority.unsigned_key()),
})?;
programdata.try_account_ref_mut()?.data_as_mut_slice()
[programdata_data_offset..programdata_data_offset + buffer_data_len]
.copy_from_slice(&buffer.try_account_ref()?.data()[buffer_data_offset..]);
programdata.try_account_ref_mut()?.data_as_mut_slice()
[programdata_data_offset + buffer_data_len..]
.fill(0);
// Fund ProgramData to rent-exemption, spill the rest
spill.try_account_ref_mut()?.checked_add_lamports(
(programdata.lamports()? + buffer.lamports()?)
.saturating_sub(programdata_balance_required),
)?;
buffer.try_account_ref_mut()?.set_lamports(0);
programdata
.try_account_ref_mut()?
.set_lamports(programdata_balance_required);
ic_logger_msg!(logger, "Upgraded program {:?}", new_program_id);
}
UpgradeableLoaderInstruction::SetAuthority => {
let account = keyed_account_at_index(keyed_accounts, 0)?;
let present_authority = keyed_account_at_index(keyed_accounts, 1)?;
let new_authority = keyed_account_at_index(keyed_accounts, 2)
.ok()
.map(|account| account.unsigned_key());
match account.state()? {
UpgradeableLoaderState::Buffer { authority_address } => {
if new_authority.is_none() {
ic_logger_msg!(logger, "Buffer authority is not optional");
return Err(InstructionError::IncorrectAuthority);
}
if authority_address.is_none() {
ic_logger_msg!(logger, "Buffer is immutable");
return Err(InstructionError::Immutable);
}
if authority_address != Some(*present_authority.unsigned_key()) {
ic_logger_msg!(logger, "Incorrect buffer authority provided");
return Err(InstructionError::IncorrectAuthority);
}
if present_authority.signer_key().is_none() {
ic_logger_msg!(logger, "Buffer authority did not sign");
return Err(InstructionError::MissingRequiredSignature);
}
account.set_state(&UpgradeableLoaderState::Buffer {
authority_address: new_authority.cloned(),
})?;
}
UpgradeableLoaderState::ProgramData {
slot,
upgrade_authority_address,
} => {
if upgrade_authority_address.is_none() {
ic_logger_msg!(logger, "Program not upgradeable");
return Err(InstructionError::Immutable);
}
if upgrade_authority_address != Some(*present_authority.unsigned_key()) {
ic_logger_msg!(logger, "Incorrect upgrade authority provided");
return Err(InstructionError::IncorrectAuthority);
}
if present_authority.signer_key().is_none() {
ic_logger_msg!(logger, "Upgrade authority did not sign");
return Err(InstructionError::MissingRequiredSignature);
}
account.set_state(&UpgradeableLoaderState::ProgramData {
slot,
upgrade_authority_address: new_authority.cloned(),
})?;
}
_ => {
ic_logger_msg!(logger, "Account does not support authorities");
return Err(InstructionError::InvalidArgument);
}
}
ic_logger_msg!(logger, "New authority {:?}", new_authority);
}
UpgradeableLoaderInstruction::Close => {
if !invoke_context.is_feature_active(&upgradeable_close_instruction::id()) {
return Err(InstructionError::InvalidInstructionData);
}
let close_account = keyed_account_at_index(keyed_accounts, 0)?;
let recipient_account = keyed_account_at_index(keyed_accounts, 1)?;
if !invoke_context.is_feature_active(&close_upgradeable_program_accounts::id()) {
let _ = keyed_account_at_index(keyed_accounts, 2)?;
}
if close_account.unsigned_key() == recipient_account.unsigned_key() {
ic_logger_msg!(logger, "Recipient is the same as the account being closed");
return Err(InstructionError::InvalidArgument);
}
if !invoke_context.is_feature_active(&close_upgradeable_program_accounts::id())
&& !matches!(
close_account.state()?,
UpgradeableLoaderState::Buffer {
authority_address: _,
}
)
{
ic_logger_msg!(logger, "Account does not support closing");
return Err(InstructionError::InvalidArgument);
}
match close_account.state()? {
UpgradeableLoaderState::Uninitialized => {
recipient_account
.try_account_ref_mut()?
.checked_add_lamports(close_account.lamports()?)?;
close_account.try_account_ref_mut()?.set_lamports(0);
ic_logger_msg!(
logger,
"Closed Uninitialized {}",
close_account.unsigned_key()
);
}
UpgradeableLoaderState::Buffer { authority_address } => {
let authority = keyed_account_at_index(keyed_accounts, 2)?;
common_close_account(
&authority_address,
authority,
close_account,
recipient_account,
logger.clone(),
!invoke_context
.is_feature_active(&close_upgradeable_program_accounts::id()),
)?;
ic_logger_msg!(logger, "Closed Buffer {}", close_account.unsigned_key());
}
UpgradeableLoaderState::ProgramData {
slot: _,
upgrade_authority_address: authority_address,
} => {
let program_account = keyed_account_at_index(keyed_accounts, 3)?;
if !program_account.is_writable() {
ic_logger_msg!(logger, "Program account is not writable");
return Err(InstructionError::InvalidArgument);
}
if &program_account.owner()? != program_id {
ic_logger_msg!(logger, "Program account not owned by loader");
return Err(InstructionError::IncorrectProgramId);
}
match program_account.state()? {
UpgradeableLoaderState::Program {
programdata_address,
} => {
if programdata_address != *close_account.unsigned_key() {
ic_logger_msg!(
logger,
"ProgramData account does not match ProgramData account"
);
return Err(InstructionError::InvalidArgument);
}
let authority = keyed_account_at_index(keyed_accounts, 2)?;
common_close_account(
&authority_address,
authority,
close_account,
recipient_account,
logger.clone(),
!invoke_context
.is_feature_active(&close_upgradeable_program_accounts::id()),
)?;
}
_ => {
ic_logger_msg!(logger, "Invalid Program account");
return Err(InstructionError::InvalidArgument);
}
}
ic_logger_msg!(logger, "Closed Program {}", program_account.unsigned_key());
}
_ => {
ic_logger_msg!(logger, "Account does not support closing");
return Err(InstructionError::InvalidArgument);
}
}
}
}
Ok(())
}
fn common_close_account(
authority_address: &Option<Pubkey>,
authority_account: &KeyedAccount,
close_account: &KeyedAccount,
recipient_account: &KeyedAccount,
logger: Rc<RefCell<dyn Logger>>,
do_clear_data: bool,
) -> Result<(), InstructionError> {
if authority_address.is_none() {
ic_logger_msg!(logger, "Account is immutable");
return Err(InstructionError::Immutable);
}
if *authority_address != Some(*authority_account.unsigned_key()) {
ic_logger_msg!(logger, "Incorrect authority provided");
return Err(InstructionError::IncorrectAuthority);
}
if authority_account.signer_key().is_none() {
ic_logger_msg!(logger, "Authority did not sign");
return Err(InstructionError::MissingRequiredSignature);
}
recipient_account
.try_account_ref_mut()?
.checked_add_lamports(close_account.lamports()?)?;
close_account.try_account_ref_mut()?.set_lamports(0);
if do_clear_data {
for elt in close_account.try_account_ref_mut()?.data_as_mut_slice() {
*elt = 0;
}
} else {
close_account.set_state(&UpgradeableLoaderState::Uninitialized)?;
}
Ok(())
}
fn process_loader_instruction(
program_id: &Pubkey,
instruction_data: &[u8],
invoke_context: &mut dyn InvokeContext,
use_jit: bool,
) -> Result<(), InstructionError> {
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let program = keyed_account_at_index(keyed_accounts, 0)?;
if program.owner()? != *program_id {
ic_msg!(
invoke_context,
"Executable account not owned by the BPF loader"
);
return Err(InstructionError::IncorrectProgramId);
}
match limited_deserialize(instruction_data)? {
LoaderInstruction::Write { offset, bytes } => {
if program.signer_key().is_none() {
ic_msg!(invoke_context, "Program account did not sign");
return Err(InstructionError::MissingRequiredSignature);
}
write_program_data(0, offset as usize, &bytes, invoke_context)?;
}
LoaderInstruction::Finalize => {
if program.signer_key().is_none() {
ic_msg!(invoke_context, "key[0] did not sign the transaction");
return Err(InstructionError::MissingRequiredSignature);
}
let executor = create_executor(0, 0, invoke_context, use_jit, true)?;
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let program = keyed_account_at_index(keyed_accounts, 0)?;
invoke_context.update_executor(program.unsigned_key(), executor);
program.try_account_ref_mut()?.set_executable(true);
ic_msg!(
invoke_context,
"Finalized account {:?}",
program.unsigned_key()
);
}
}
Ok(())
}
/// Passed to the VM to enforce the compute budget
pub struct ThisInstructionMeter {
pub compute_meter: Rc<RefCell<dyn ComputeMeter>>,
}
impl ThisInstructionMeter {
fn new(compute_meter: Rc<RefCell<dyn ComputeMeter>>) -> Self {
Self { compute_meter }
}
}
impl InstructionMeter for ThisInstructionMeter {
fn consume(&mut self, amount: u64) {
// 1 to 1 instruction to compute unit mapping
// ignore error, Ebpf will bail if exceeded
let _ = self.compute_meter.borrow_mut().consume(amount);
}
fn get_remaining(&self) -> u64 {
self.compute_meter.borrow().get_remaining()
}
}
/// BPF Loader's Executor implementation
pub struct BpfExecutor {
executable: Pin<Box<Executable<BpfError, ThisInstructionMeter>>>,
}
// Well, implement Debug for solana_rbpf::vm::Executable in solana-rbpf...
impl Debug for BpfExecutor {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "BpfExecutor({:p})", self)
}
}
impl Executor for BpfExecutor {
fn execute(
&self,
loader_id: &Pubkey,
program_id: &Pubkey,
instruction_data: &[u8],
invoke_context: &mut dyn InvokeContext,
use_jit: bool,
) -> Result<(), InstructionError> {
let logger = invoke_context.get_logger();
let invoke_depth = invoke_context.invoke_depth();
let add_missing_program_error_mappings =
invoke_context.is_feature_active(&add_missing_program_error_mappings::id());
invoke_context.remove_first_keyed_account()?;
let mut serialize_time = Measure::start("serialize");
let keyed_accounts = invoke_context.get_keyed_accounts()?;
let mut parameter_bytes =
serialize_parameters(loader_id, program_id, keyed_accounts, instruction_data)?;
serialize_time.stop();
let mut create_vm_time = Measure::start("create_vm");
let mut execute_time;
let execution_result = {
let compute_meter = invoke_context.get_compute_meter();
let mut vm = match create_vm(
loader_id,
&self.executable,
parameter_bytes.as_slice_mut(),
invoke_context,
) {
Ok(info) => info,