Commit Graph

330 Commits

Author SHA1 Message Date
Alexander Meißner 9e703f85de
Upgrades Rust to 1.72.0 & nightly-2023-08-25 (#32961)
* allow pedantic invalid cast lint

* allow lint with false-positive triggered by `test-case` crate

* nightly `fmt` correction

* adapt to rust layout changes

* remove dubious test

* Use transmute instead of pointer cast and de/ref when check_aligned is false.

* Renames clippy::integer_arithmetic to clippy::arithmetic_side_effects.

* bump rust nightly to 2023-08-25

* Upgrades Rust to 1.72.0

---------

Co-authored-by: Trent Nelson <trent@solana.com>
2023-09-01 07:26:13 +00:00
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
Alexander Meißner 67d6d688cc
Refactor - Demotes `Arc` to `Rc`. (#32982)
Demotes `Arc` to `Rc`.
2023-08-25 00:54:06 +02:00
Alexander Meißner a8be70fa7a
General cleanup (#32980)
* Fixes `cargo::` in build.rs

* Fixes overshadowing reexports.

* Removes unnecessary `as *const u8`.

* Removes unnecessary `.into_iter()`.

* cargo clippy
2023-08-24 21:44:19 +02:00
Jon Cinque 0fe902ced7
Bump rand to 0.8, rand_chacha to 0.3, getrandom to 0.2 (#32871)
* sdk: Add concurrent support for rand 0.7 and 0.8

* Update rand, rand_chacha, and getrandom versions

* Run command to replace `gen_range`

Run `git grep -l gen_range | xargs sed -i'' -e 's/gen_range(\(\S*\), /gen_range(\1../'

* sdk: Fix users of older `gen_range`

* Replace `hash::new_rand` with `hash::new_with_thread_rng`

Run:
```
git grep -l hash::new_rand | xargs sed -i'' -e 's/hash::new_rand([^)]*/hash::new_with_thread_rng(/'
```

* perf: Use `Keypair::new()` instead of `generate`

* Use older rand version in zk-token-sdk

* program-runtime: Inline random key generation

* bloom: Fix clippy warnings in tests

* streamer: Scope rng usage correctly

* perf: Fix clippy warning

* accounts-db: Map to char to generate a random string

* Remove `from_secret_key_bytes`, it's just `keypair_from_seed`

* ledger: Generate keypairs by hand

* ed25519-tests: Use new rand

* runtime: Use new rand in all tests

* gossip: Clean up clippy and inline keypair generators

* core: Inline keypair generation for tests

* Push sbf lockfile change

* sdk: Sort dependencies correctly

* Remove `hash::new_with_thread_rng`, use `Hash::new_unique()`

* Use Keypair::new where chacha isn't used

* sdk: Fix build by marking rand 0.7 optional

* Hardcode secret key length, add static assertion

* Unify `getrandom` crate usage to fix linking errors

* bloom: Fix tests that require a random hash

* Remove some dependencies, try to unify others

* Remove unnecessary uses of rand and rand_core

* Update lockfiles

* Add back some dependencies to reduce rebuilds

* Increase max rebuilds from 14 to 15

* frozen-abi: Remove `getrandom`

* Bump rebuilds to 17

* Remove getrandom from zk-token-proof
2023-08-21 19:11:21 +02:00
Pankaj Garg c17b938204
Integrate program loader-v4 with bank (#32832)
* Integrate program loader-v4 with bank

* fix tests

* new struct for ProgramRuntimeEnvironments

* remove environment from program_runtime_environment_v

* move find_program_in_cache() to invoke_context

* cleanup
2023-08-16 10:50:23 -07:00
Pankaj Garg a1a0829a8b
Initialize and store PRv2 environment in cache (#32812)
* Initialize and store PRv2 environment in cache

* address review comments
2023-08-11 18:58:22 +00:00
Alexander Meißner b5a80a72f0
Fix - Adds missing "Executable account not owned by the BPF loader" error to `remove_bpf_loader_incorrect_program_id` (#32695)
Adds missing "Executable account not owned by the BPF loader" error.
2023-08-03 15:26:02 +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
Pankaj Garg fc35b13365
Cleanup load_program() in bank.rs (#32146) 2023-07-21 13:43:46 -07:00
Alexander Meißner 9731331be4
Bump solana_rbpf to v0.6.0 (#32313) 2023-07-05 19:46:21 +02:00
Pankaj Garg c86e160438
Add runtime environment to FailedVerification tombstones (#31991)
* Add runtime environment to FailedVerification tombstones

* modify default variant

* prune update

* add DelayVisibility in prune_feature_set_transition
2023-06-06 22:24:39 +00:00
Pankaj Garg 1b30de4f32
Retain runtime environment config for unloaded programs (#31953)
* Retain runtime environment config for unloaded programs
2023-06-03 09:38:11 +02:00
Pankaj Garg 37ebb709e6
Evict program cache using transaction usage counter (#31927)
* Evict program cache using tx usage counter

* address review feedback

* address review feedback
2023-06-02 11:26:56 -07:00
Tao Zhu 10995f66c0
use one definition of builtin program cost in runtime and banking stage (#31930)
* use one definition of builtin program cost in runtime and banking stage
* add loader_v4
2023-06-02 10:22:22 -05:00
Alexander Meißner 3792204598
Bump solana_rbpf to v0.5.0 (#31943)
* Renames RBPF BuiltIn to Builtin.

* Bump solana_rbpf to v0.5.0
2023-06-02 16:34:01 +02:00
Pankaj Garg 449f92e32c
Reverify programs that are extended using ExtendProgram (#31886) 2023-06-01 06:17:42 -07:00
Pankaj Garg 595eb31277
Set deployment slot for non-upgradeable programs (#31792)
* Set deployment slot for non-upgradeable programs

* fix sbf programs test
2023-05-24 16:15:47 +00:00
Alexander Meißner 83f692ce67
Refactor - Share RBPF config and syscall registry globally (#31727)
* Adds LoadedPrograms::program_runtime_environment_v1.

* No need to explicitly remove precompiles from program_accounts_map.
2023-05-20 20:28:00 +02:00
Alexander Meißner 520c647918
Refactor - Merges `BuiltinPrograms` into `LoadedPrograms` (#31654)
* Merges BuiltinPrograms into LoadedPrograms.

* Prevents built-ins from being pruned.
2023-05-18 22:18:28 +02:00
Pankaj Garg b03422968b
Remove Rc and RefCell to carry program cache in invoke_context (#31684) 2023-05-17 06:10:50 -07:00
Alexander Meißner 5c8b5a2a68
Bump solana_rbpf to v0.4.0 (#31594)
* Moves "disable_deploy_of_alloc_free_syscall" parameter inside create_loader().

* Removes the "is_abi_v2" flag.

* Bumps solana_rbpf to v0.4.0
2023-05-12 18:07:13 +02:00
Pankaj Garg 04425b81ce
Add stats for LoadedPrograms (#31577) 2023-05-10 12:08:55 -07:00
Pankaj Garg 2210af60ee
Replace executor cache usage with LoadedPrograms cache (#31462)
* Replace executor cache usage with LoadedPrograms cache

* clippy fixes

* update cache with updated programs

* fixes

* more cleanup

* update tx batch cache with the tx results

* address review comments

* handle program closing backward compatibility

* handle unloaded programs during extraction
2023-05-09 15:44:38 -07:00
Pankaj Garg ba6f7e80e8
Remove obsolete code for lazily loading programs (#31395) 2023-05-02 14:39:27 -07: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 c05d1d5c51
Refactor - Moves bpf_loader registration into the runtime (#31345)
* Moves the registration of bpf_loader built-ins from the ledger into the runtime.

* Removes bpf_loader built-ins registration in tests and benchmarks.

* Removes declare_builtin!() of bpf_loader built-ins.

* Removes built-ins from the SDK.

* Adjusts tests.
2023-04-26 14:44:19 +02:00
Alexander Meißner 7002c568fb
Cleanup - Removes the CLI option "no-bpf-jit" (#31329)
* Enables JIT everywhere by default.

* Removes the CLI argument "no-bpf-jit" and its plumbering through out the validator code base.

* Removes with_jit bpf_loader variants.

* Removes the to_builtin!() macro.
2023-04-25 19:04:11 +02:00
Alexander Meißner e5490b8d09
Refactor - Use builtin function interface from rbpf (#31221)
* Removes test_program_entry_debug().

* Uses declare_process_instruction!() in all tests and benchmarks.

* Replaces with ProcessInstructionWithContext with solana_rbpf::BuiltInFunction.
2023-04-21 18:08:32 +02: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
Pankaj Garg fb6e02c46c
Retain usage counter on program upgrade (#31142)
* Retain usage counter on program upgrade

* cleanup as per feedback

* fix clippy
2023-04-11 09:43:42 -07:00
Alexander Meißner 0cd57addcf
Cleanup - mock_process_instruction() (#31088)
* Uses declare_process_instruction!() in all tests.

* Adds post_adjustments to mock_process_instruction().
Removes "solana_sbf_rust_external_spend" from assert_instruction_count() as it panics.
2023-04-07 12:53:19 +02:00
Pankaj Garg 83e17d8e44
Add expiration slot to loaded program cache entry (#31034) 2023-04-05 09:26:28 -07: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
Pankaj Garg f198d7426a
Use feature gate to set effective slot of loaded programs (#30950) 2023-03-29 04:47:49 -07:00
Pankaj Garg aebc191c38
Stop loading program accounts if program exists in cache (#30703)
* Stop loading program accounts if program exists in cache

* load accounts for upgradeable programs

* revert loader change to conditionally use program data account

* load instruction accounts

* generate TransactionExecutorCache from loaded programs

* cleanup account_found_and_dep_index variable

* address review comments

* handle tombstones in loader

* unify tombstone constructor

* handle multiple tombstones
2023-03-28 11:49:56 -07:00
Pankaj Garg cbf70430a5
Fix deployment slot for upgraded programs (#30902) 2023-03-27 06:48:26 -07:00
Pankaj Garg 0df28f6d51
Increment usage count for loaded programs and call eviction (#30900) 2023-03-27 06:48:05 -07:00
Tao Zhu 3e500d9e92
Feature gate builtin consumes static units during processing instruction (#30702)
* add feature gate
* builtins consume statically defined units at beginning of process_instruction()
* Add new instructionError; return error if builtin did not consume units to enforce builtin to consume units;
* updated related tests
* updated ProgramTest with deactivated native_programs_consume_cu feature to continue support existing mock/test programs that do not consume units
2023-03-24 11:31:01 -05:00
Alexander Meißner c10f337f85
Feature - Loader built-in program v3 (#30464)
* Adds loader-v3 in SDK.

* Adds loader-v3 built-in program.

* Adds tests.
2023-03-23 18:13:47 +01:00
Alexander Meißner 66da71fa7a
Fix - Revert and feature gate incorrect error message in BPF loader (#30748)
* Revert to old behavior.

* Adds feature gate.
2023-03-21 11:08:41 +01:00
Tao Zhu 17ba051e1f
Revert "add default_cost as mandatory field for Builtin (#30639)" (#30749)
This reverts commit 7b95c8e698.
2023-03-16 11:21:06 -05:00
Tao Zhu a4ad0c75fc
fix heap cost calculation rounding error (#30673)
* add test for refaction heap size, fix size truncating by div op
* add feature gate
* checked result of consume_checked() if feature is activated
2023-03-15 12:03:04 -05:00
Tao Zhu 7b95c8e698
add default_cost as mandatory field for Builtin (#30639)
* add default_cost as mandatory field for Builtin

* updated tests

* set zkp program default to VerifyTransfer CUs

---------

Co-authored-by: Jon Cinque <joncinque@pm.me>
2023-03-10 14:02:24 -06: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
Alexander Meißner d2fc2e5f62
Refactor - Remove `first_instruction_account` in `bpf_loader` (#30614)
* Removes first_instruction_account from process_loader_upgradeable_instruction(), process_loader_instruction() and write_program_data().

* Removes first_instruction_account from process_instruction_common().

* Removes get_index_in_transaction() and try_borrow_account().
2023-03-08 16:54:19 +01:00
Alexander Meißner 38e74325e3
Refactor - Remove `process_instruction` parameter `first_instruction_account` (#30579)
* Stops using first_instruction_account parameter in bpf_loader.

* Removes first_instruction_account parameter from process_instruction().
2023-03-06 17:37:37 +01:00