Commit Graph

28 Commits

Author SHA1 Message Date
behzad nouri 4ec5ea6f7b
replaces assert!(matches!(...)) with assert_matches!(...) (#33068)
assert_matches!(...) provides more informative error message when it
fails and it is part of nightly rust:
https://doc.rust-lang.org/std/assert_matches/macro.assert_matches.html
2023-08-30 13:48:27 -04:00
Alessandro Decina 0f41719918
direct mapping: misc fixes (#32649)
* transaction_context: update make_data_mut comment

* bpf_loader: cpi: pass SerializeAccountMetadata to CallerAccount::from*

We now have a way to provide CallerAccount with trusted values coming
from our internal serialization code and not from untrusted vm space

* bpf_loader: direct_mapping: enforce account info pointers to be immutable

When direct mapping is enabled, we might need to update account data
memory regions across CPI calls. Since the only way we have to retrieve
the regions is based on their vm addresses, we enforce vm addresses to
be stable.  Accounts can still be mutated and resized of course, but it
must be done in place.

This also locks all other AccountInfo pointers, since there's no legitimate
reason to make them point to anything else.

* bpf_loader: cpi: access ref_to_len_in_vm through VmValue

Direct mapping needs to translate vm values at each access since
permissions of the underlying memory might have changed.

* direct mapping: improve memory permission tracking across CPI calls

Ensure that the data and realloc regions of an account always track the
account's permissions. In order to do this, we also need to split
realloc regions in their own self contained regions, where before we
had:

[account fields][account data][account realloc + more account fields + next account fields][next account data][...]

we now have:

[account fields][account data][account realloc][more account fields + next account fields][next account data][...]

Tested in TEST_[FORBID|ALLOW]_WRITE_AFTER_OWNERSHIP_CHANGE*

Additionally when direct mapping is on, we must update all perms at once before
doing account data updates. Otherwise, updating an account might write into
another account whose perms we haven't updated yet. Tested in
TEST_FORBID_LEN_UPDATE_AFTER_OWNERSHIP_CHANGE.

* bpf_loader: serialization: address review comment don't return vm_addr from push_account_region

* bpf_loader: rename push_account_region to push_account_data_region

* cpi: fix slow edge case zeroing extra account capacity after shrinking an account

When returning from CPI we need to zero all the account memory up to the
original length only if we know we're potentially dealing with uninitialized
memory.

When we know that the spare capacity has deterministic content, we only need to
zero new_len..prev_len.

This fixes a slow edge case that was triggerable by the following scenario:

- load a large account (say 10MB) into the vm
- shrink to 10 bytes - would memset 10..10MB
- shrink to 9 bytes - would memset 9..10MB
- shrink to 8 bytes - would memset 8..10MB
- ...

Now instead in the scenario above the following will happen:

- load a large account (say 10MB) into the vm
- shrink to 10 bytes - memsets 10..10MB
- shrink to 9 bytes - memsets 9..10
- shrink to 8 bytes - memset 8..9
- ...

* bpf_loader: add account_data_region_memory_state helper

Shared between serialization and CPI to figure out the MemoryState of an
account.

* cpi: direct_mapping: error out if ref_to_len_in_vm points to account memory

If ref_to_len_in_vm is allowed to be in account memory, calles could mutate it,
essentially letting callees directly mutate callers memory.

* bpf_loader: direct_mapping: map AccessViolation -> InstructionError

Return the proper ReadonlyDataModified / ExecutableDataModified /
ExternalAccountDataModified depending on where the violation occurs

* bpf_loader: cpi: remove unnecessary infallible slice::get call
2023-08-30 16:57:24 +07:00
Alexander Meißner 150a798d32
Fix - Upcoming `arithmetic_side_effects` lints (#33000)
* dereplicode address alignment check

* Uses `checked_div` and `checked_rem` in built-in loaders.

* Uses `checked_div` and `checked_rem`.

* sdk: replace sub() with saturating_sub()

* eliminate `String` "arithmetic"

* allow arithmetic side-effects in tests and benches and on types we don't control

---------

Co-authored-by: Trent Nelson <trent@solana.com>
2023-08-29 20:58:53 +02:00
Alessandro Decina e3f253d559
introduce SerializedAccountMetadata (#32644)
* bpf_loader: move computing original account lengths inside serialize_paramters_(aligned|unaligned)

This is in preparation of returning more than just the original length

* bpf_loader: deserialize*: take original lens as an iterator instead of a slice

This is in preparation of extracting account lenghts from a larger
context

* bpf_loader: introduce SerializedAccountMetadata

Instead of passing original_account_lengths around as Vec<usize>,
introduce an explicit type that includes the length and soon more.
2023-07-28 18:34:27 +07:00
Alessandro Decina 6f88587652
cpi: change unnecessary &mut MemoryMapping to &MemoryMapping (#32643) 2023-07-28 14:11:17 +07:00
Alexander Meißner 9731331be4
Bump solana_rbpf to v0.6.0 (#32313) 2023-07-05 19:46:21 +02:00
Alessandro Decina 117a194b73
Account data direct mapping (#28053)
* AccountSharedData: make data_mut() private

This ensures that the inner Vec is never handed out. This is in
preparation of enforcing that the capacity of the inner vec never
shrinks, which is required for direct mapping.

* Adds the feature bpf_account_data_direct_mapping.

* Remaps EbpfError::AccessViolation into InstructionError::ReadonlyDataModified.

* WIP: Memory regions for each instruction account in create_vm().

* Fix serialization benches, run both copy and !copy variants

* rbpf-cli: fix build

* BorrowedAccount: ensure that account capacity is never reduced

Accounts can be directly mapped in address space. Their capacity can't
be reduced mid transaction as that would create holes in vm address
space that point to invalid host memory.

* bpf_load: run serialization tests for both copy and !copy account data

* bpf_loader: add Serializer::write_account

* fix lints

* BorrowedAccount: make_data_mut is host only

* Fix unused import warning

* Fix lints

* cpi: add explicit direct_mapping arg to update_(callee|caller)_account

* cpi: rename account_data_or_only_realloc_padding to serialized_data

* cpi: add CallerAccount::original_data_len comment

* cpi: add update_callee_account direct_mapping test

* cpi: add test_update_caller_account_data_direct_mapping and fix bug

We used to have a bug in zeroing data when shrinking account, where we zeroed
the spare account capacity but not the realloc padding.

* cpi: add tests for mutated readonly accounts

* cpi: update_caller_account doesn't need to change .serialized_data when direct_mapping is on

* cpi: update_caller_account: ensure that account capacity is always enough

Introduce a better way to ensure that account capacity never goes below what
might be mapped in memory regions.

* cpi: zero account capacity using the newly introduced BorrowedAccount::spare_data_capacity_mut()

Before we were using BorrowedAccount::get_data_mut() to get the base pointer to
the account data, then we were slicing the spare capacity from it. Calling
get_data_mut() doesn't work if an account has been closed tho, since the
current program doesn't own the account anymore and therefore get_data_mut()
errors out.

* bpf_loader: fix same lint for the umpteenth time

* bpf_loader: map AccessViolation to ReadonlyDataModified only for account region violations

* programs/sbf: realloc: add test for large write after realloc

Add a test that after a realloc does a large write that spans the
original account length and the realloc area. This ensures that memory
mapping works correctly across the boundary.

* programs/sbf: run test_program_sbf_realloc with both direct_mapping on and off

By default test banks test with all features on. This ensures we keep
testing the existing code until the new feature is enabled.

* bpf_loader: tweak memcmp syscall

Split the actual memcmp code in a separate function. Remove check
indexing the slices since the slices are guaranteed to have the correct
length by construction.

* bpf_loader: tweak the memset syscall

Use slice::fill, which is effectively memset.

* bpf_loader: syscalls: update mem syscalls to work with non contiguous memory

With direct mapping enabled, accounts can now span multiple memory
regions.

* fix lint, rebase mem_ops

* Implement CoW for writable accounts

* Fix CI

* Move CoW to the MemoryMapping level

* Update after rbpf API change

* Fix merge screwup

* Add create_vm macro. Fix benches.

* cpi: simplify update_caller_account

Simplify the logic to update a caller's memory region when a callee
causes an account data pointer to change (eg during CoW)

* benches/bpf_loader: move serialization out of  create_vm bench

* benches/bpf_loader: don't copy accounts when direct mapping is on

* Fix review nits

* bpf_loader: mem_ops: handle u64 overflow in MemoryChunkIterator::new

When starting at u64::MAX, the chunk iterator would always return the
empty sequence (None on the first next()) call, instead of returning a
memory access violation.

Use checked instead of saturating arithmetic to detect the condition and
error out.

This commit also adds more tests around boundary conditions.

* Fix loader-v3 tests: data_mut => data_as_mut_slice

* Fix CI

* bpf_loader: fix tuner bench: account must be writable

With direct mapping on, invalid writes are caught early meaning the
tuner would fail on the first store and not consume the whole budget
like the benchmark expects.

---------

Co-authored-by: Alexander Meißner <AlexanderMeissner@gmx.net>
2023-04-29 06:54:39 +10:00
Alexander Meißner 8eb31f6cfd
Refactor - Syscalls in RBPF CLI (#31109)
* Makes members of SyscallContext public.
Removes check_aligned and check_size from SyscallContext.

* Replaces InvokeContext::set_syscall_context() in tests with mock_create_vm!().

* Passes SyscallContext directly to InvokeContext::set_syscall_context().

* Merges TraceLogStackFrame into SyscallContext.

* Removes the create_vm!() macro.

* Moves BpfAllocator from bpf_loader into program_runtime.

* Frees BpfAllocator from Rc<RefCell<>>.

* Removes unused code from BpfAllocator.

* Consume CUs for heap before doing the allocation.

* Exposes syscalls in rbpf-cli.

* Adds debugging_features parameter to load_program_from_bytes() and load_program_from_account().

* Removes test_bpf_loader_non_terminating_program() as that is already tested in RBPF.

* Moves stack and heap allocation back onto the program runtime stack.
2023-04-14 15:20:08 +02:00
Alexander Meißner 24a87f33a8
Refactor - Cleanup error handling in program runtime (#30693)
* Moves stable_log::program_invoke(), stable_log::program_success() and stable_log::program_failure() calls from bpf_loader into InvokeContext::process_executable_chain().

* Turns result of ProcessInstructionWithContext from InstructionError into Box<dyn std::error::Error>.

* Bump to solana_rbpf v0.3.0

* Removes Result from return type of EbpfVm::new().

* Turns EbpfError into Box<dyn std::error::Error>.

* Removes BpfError.

* Removes SyscallError::InstructionError.

* Adds a type alias for Box<dyn std::error::Error> in syscalls.
2023-04-05 15:50:34 +02:00
Alexander Meißner a0c7fde90e
Cleanup - mock InvokeContext (#31007)
* Turns with_mock_invoke_context() into a macro.

* Removes prepare_mock_invoke_context().

* Replaces InvokeContext::new_mock() with with_mock_invoke_context().

* Removes InvokeContext::new_mock().

* Removes Cow from InvokeContext::sysvar_cache.

* Removes override parameters from mock_process_instruction().

* cargo fmt
2023-04-03 17:23:24 +02:00
Alessandro Decina 0335ea7249
Bump solana_rbpf to v0.2.40 (#30668)
Update to solana_rbpf v0.2.40
2023-03-10 19:05:29 +01:00
Brooks 0c36e4c82d
Adds stable layout types to pass to the runtime (#30192) 2023-02-16 08:16:25 -05:00
Trent Nelson 61e2da45f8
fix: synchronize cpi error prioritization with v1.14 (fp #29593) (#29621)
* Revert "Removes `serialized_len_ptr` from `CallerAccount`. (#26737)"

36cfa78fa0

Co-authored-by: Alexander Meißner <AlexanderMeissner@gmx.net>
2023-01-10 14:28:38 -07:00
Alessandro Decina bee24a81b8
Refactor CPI, add tests and sprinkle some comments (#28544)
* bpf_loader: cpi: split account update code to update_caller_account and add tests

* bpf_loader: cpi: set CallerAccount::original_data_len earlier

* cpi: add CallerAccount::from_account_info and CallerAccount::from_sol_account_info

* cpi: refactor common account info translation code in translate_account_infos

* update_caller docs

* cpi: rename translate_accounts to translate_and_update_accounts

* cpi: refactor pre-cpi account update code into update_callee_account

* cpi: add tests for CallerAccount::from_account_info

* cpi: add test for SyscallInvokeSignedRust::translate_accounts

* cpi: fix lints

* cpi: add test for translate_instruction()

* cpi: add test for translate_signers

* cpi: fix lint

* cpi: review fixups round 1

* cpi: more review fixups

Replace ugly MockInvokeContext with a macro

* cpi: more review fixes

replace get_callee with macro

* cpi: more review fixes

Add MockAccountInfo::new

* Fix rebase mistake
2022-11-23 23:22:50 +11:00
Alessandro Decina 1f40cb3d37
The syscall_saturated_math feature was activated, remove checks (#28605) 2022-11-23 20:42:59 +11:00
Alexander Meißner ff1ff587d1
Bump solana_rbpf to 0.2.36 (#28794)
* Bumps solana_rbpf to v0.2.36

* Removes ThisInstructionMeter.

* Removes one "unsafe" expression.

* Removes redundant call to solana_rbpf:🧝:register_bpf_function().

* Adjusts SyscallFunction and SyscallRegistry.

* Inlines ProgramEnvironment into EbpfVm.

* Refactors trait SyscallConsume into fn consume_compute_meter().

* Inlines ComputeMeter into InvokeContext.

* Removes solana-metrics dependency from bpf_loader.

* Replaces RBPF tracer functionality by the debugger.

* Take compute_units_consumed from execute_program().

* Merges execute_program_interpreted() and execute_program_jit().
2022-11-15 15:21:11 +01:00
Brooks Prumo d1ba42180d
clippy for rust 1.65.0 (#28765) 2022-11-09 19:39:38 +00:00
0xripleys 5de4dd8f9b
Add SetAuthorityChecked instruction to bpf loader (#28424)
* SetAuthorityChecked

* restore old logic for loader

* add more upgrade authority checked test cases

* setBufferAuthority checked tests

* format

* add set_buffer_authority_checked instruction to sdk

* Update transaction-status/src/parse_bpf_loader.rs

Co-authored-by: Justin Starry <justin.m.starry@gmail.com>

* add is_set_authority_checked function

* fix set_buffer_authority_checked sdk instruction

* feature gate setAuthorityChecked

* add bpf loader tests for setAuthorityChecked ixs

* test that you can set to same authority

* allow set_authority_checked to be called via cpi (if feature is enabled)

* fix ci

* fmt

Co-authored-by: Justin Starry <justin.m.starry@gmail.com>
Co-authored-by: Justin Starry <justin@solana.com>
2022-11-01 08:34:04 +00:00
Alexander Meißner 30b0a13ba9
Bump solana_rbpf to 0.2.34 (#28198)
* Bumps solana_rbpf to 0.2.34

* Removes generic UserError from EbpfError.

* Uses ProgramResult for syscalls.
Removes use sites of the question_mark! macro by wrapping the call method of SyscallObjects.

* Uses InvokeContext as syscall context object directly.

* Replaces bind_syscall_context_object() by a parameter in the constructor.

* Inlines bind_syscall_context_objects() at its only call site.
2022-10-06 20:31:58 +02:00
Alessandro Decina b9f4c8e3c0
BorrowedAccount: add set_data_from_slice(), make set_data() take owned values (#27836)
* BorrowedAccount: add set_data_from_slice(), make set_data() take owned values

set_data() used to take a slice and would force alloc+copy if the caller
has owned values (eg account creation, account lookup table).

Expose set_data_from_slice() for callers that have slices, and switch
set_data() to taking an owned Vec.

* BorrowAccount: refactor common accounts_update_delta code in helper method

* BorrowedAccount: add extend_from_slice()

This allows avoiding copies appending entries to account lookup tables.

* BorrowedAccount: remove unnecessary ifs around update_accounts_resize_delta
2022-09-24 01:37:02 +01:00
Justin Starry b9700244b5
Increase transaction account lock limit from 64 to 128 (#27242)
* Increase transaction account lock limit from 64 to 256

* fix bpf test

* Reduce lock limit from 256 to 128
2022-09-15 13:50:14 -04:00
Alexander Meißner 12d2147efa
Adds `IndexOfAccount` type (#27599)
Adds the type `IndexOfAccount`.
2022-09-06 11:31:40 +02:00
Justin Starry 7d765e3d67
clean feature: `prevent_calling_precompiles_as_programs` (#27100)
* clean feature: prevent_calling_precompiles_as_programs

* fix tests

* fix test

* remove comment

* fix test

* feedback
2022-08-18 05:21:16 +00:00
Alexander Meißner 85a679b098
Feature: disable CPI setting `is_executable` and `rent_epoch` (#26987)
* Adds the feature disable_cpi_setting_executable_and_rent_epoch.

* Adds the feature gate for disable_cpi_setting_executable_and_rent_epoch.

* Removes TEST_EXECUTABLE_LAMPORTS.

* Test that is_executable and rent_epoch are ignored.
2022-08-10 00:22:23 +02:00
Justin Starry 2335f6908a
Loosen CPI restrictions and charge compute for ix data len (#26653)
* Loosen CPI restrictions and charge compute for ix data len

* Address feedback

* use explicit casting

* more feedback
2022-07-24 20:20:16 +02:00
Alexander Meißner 36cfa78fa0
Removes `serialized_len_ptr` from `CallerAccount`. (#26737)
Removes serialized_len_ptr from CallerAccount.
2022-07-22 16:10:14 +02:00
Justin Starry ca4d917081 Fix clippy warning 2022-07-17 12:23:03 +02:00
Justin Starry 07d7c938b9
Refactor: split up syscalls module (#26637)
* Refactor: split up syscalls module

* fix ci script

* fix visibility
2022-07-16 19:33:57 +02:00