Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit dcec6fd

Browse files
committed
Add comments and refactor Sandbox module
1 parent 7217ab6 commit dcec6fd

File tree

1 file changed

+33
-16
lines changed

1 file changed

+33
-16
lines changed

client/executor/common/src/sandbox.rs

Lines changed: 33 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -44,33 +44,44 @@ impl From<SupervisorFuncIndex> for usize {
4444

4545
/// Index of a function within guest index space.
4646
///
47-
/// This index is supposed to be used with as index for `Externals`.
47+
/// This index is supposed to be used as index for `Externals`.
4848
#[derive(Copy, Clone, Debug, PartialEq)]
4949
struct GuestFuncIndex(usize);
5050

5151
/// This struct holds a mapping from guest index space to supervisor.
5252
struct GuestToSupervisorFunctionMapping {
53+
/// Position of elements in this vector are interpreted
54+
/// as indices of guest functions and are mappeed to
55+
/// corresponding supervisor function indices.
5356
funcs: Vec<SupervisorFuncIndex>,
5457
}
5558

5659
impl GuestToSupervisorFunctionMapping {
60+
/// Create an empty function mapping
5761
fn new() -> GuestToSupervisorFunctionMapping {
5862
GuestToSupervisorFunctionMapping { funcs: Vec::new() }
5963
}
6064

65+
/// Add a new supervisor function to the mapping.
66+
/// Returns a newly assigned guest function index.
6167
fn define(&mut self, supervisor_func: SupervisorFuncIndex) -> GuestFuncIndex {
6268
let idx = self.funcs.len();
6369
self.funcs.push(supervisor_func);
6470
GuestFuncIndex(idx)
6571
}
6672

73+
/// Find supervisor function index by its corresponding guest function index
6774
fn func_by_guest_index(&self, guest_func_idx: GuestFuncIndex) -> Option<SupervisorFuncIndex> {
6875
self.funcs.get(guest_func_idx.0).cloned()
6976
}
7077
}
7178

79+
/// Holds sandbox function and memory imports and performs name resolution
7280
struct Imports {
81+
/// Maps qualified function name to its guest function index
7382
func_map: HashMap<(Vec<u8>, Vec<u8>), GuestFuncIndex>,
83+
84+
/// Maps qualified field name to its memory reference
7485
memories_map: HashMap<(Vec<u8>, Vec<u8>), MemoryRef>,
7586
}
7687

@@ -146,14 +157,15 @@ impl ImportResolver for Imports {
146157
/// Note that this functions are only called in the `supervisor` context.
147158
pub trait SandboxCapabilities: FunctionContext {
148159
/// Represents a function reference into the supervisor environment.
160+
/// Provides an abstraction over execution environment.
149161
type SupervisorFuncRef;
150162

151163
/// Invoke a function in the supervisor environment.
152164
///
153165
/// This first invokes the dispatch_thunk function, passing in the function index of the
154166
/// desired function to call and serialized arguments. The thunk calls the desired function
155167
/// with the deserialized arguments, then serializes the result into memory and returns
156-
/// reference. The pointer to and length of the result in linear memory is encoded into an i64,
168+
/// reference. The pointer to and length of the result in linear memory is encoded into an `i64`,
157169
/// with the upper 32 bits representing the pointer and the lower 32 bits representing the
158170
/// length.
159171
///
@@ -176,15 +188,22 @@ pub trait SandboxCapabilities: FunctionContext {
176188
///
177189
/// [`Externals`]: ../wasmi/trait.Externals.html
178190
pub struct GuestExternals<'a, FE: SandboxCapabilities + 'a> {
191+
/// Supervisor function environment
179192
supervisor_externals: &'a mut FE,
193+
194+
/// Instance of sandboxed module to be dispatched
180195
sandbox_instance: &'a SandboxInstance<FE::SupervisorFuncRef>,
196+
197+
/// Opaque pointer to outer context, see the `instantiate` function
181198
state: u32,
182199
}
183200

201+
/// Construct trap error from specified message
184202
fn trap(msg: &'static str) -> Trap {
185203
TrapKind::Host(Box::new(Error::Other(msg.into()))).into()
186204
}
187205

206+
/// Deserialize bytes into `Result`
188207
fn deserialize_result(serialized_result: &[u8]) -> std::result::Result<Option<RuntimeValue>, Trap> {
189208
use self::sandbox_primitives::HostError;
190209
use sp_wasm_interface::ReturnValue;
@@ -209,6 +228,7 @@ impl<'a, FE: SandboxCapabilities + 'a> Externals for GuestExternals<'a, FE> {
209228
// Make `index` typesafe again.
210229
let index = GuestFuncIndex(index);
211230

231+
// Convert function index from guest to supervisor space
212232
let func_idx = self.sandbox_instance
213233
.guest_to_supervisor_mapping
214234
.func_by_guest_index(index)
@@ -229,7 +249,7 @@ impl<'a, FE: SandboxCapabilities + 'a> Externals for GuestExternals<'a, FE> {
229249

230250
let state = self.state;
231251

232-
// Move serialized arguments inside the memory and invoke dispatch thunk and
252+
// Move serialized arguments inside the memory, invoke dispatch thunk and
233253
// then free allocated memory.
234254
let invoke_args_len = invoke_args_data.len() as WordSize;
235255
let invoke_args_ptr = self
@@ -408,7 +428,10 @@ fn decode_environment_definition(
408428

409429
/// An environment in which the guest module is instantiated.
410430
pub struct GuestEnvironment {
431+
/// Function and memory imports of the guest module
411432
imports: Imports,
433+
434+
/// Supervisor functinons mapped to guest index space
412435
guest_to_supervisor_mapping: GuestToSupervisorFunctionMapping,
413436
}
414437

@@ -449,26 +472,20 @@ impl<FR> UnregisteredInstance<FR> {
449472
/// Instantiate a guest module and return it's index in the store.
450473
///
451474
/// The guest module's code is specified in `wasm`. Environment that will be available to
452-
/// guest module is specified in `raw_env_def` (serialized version of [`EnvironmentDefinition`]).
453-
/// `dispatch_thunk` is used as function that handle calls from guests.
454-
///
455-
/// # Errors
456-
///
457-
/// Returns `Err` if any of the following conditions happens:
458-
///
459-
/// - `raw_env_def` can't be deserialized as a [`EnvironmentDefinition`].
460-
/// - Module in `wasm` is invalid or couldn't be instantiated.
475+
/// guest module is specified in `guest_env`, `dispatch_thunk` is used as function that
476+
/// handle calls from guests. `state` is an opaque pointer to caller's arbitrary context
477+
/// normally created by `sp_sandbox::Instance` primitive.
461478
///
462-
/// [`EnvironmentDefinition`]: ../sandbox/struct.EnvironmentDefinition.html
479+
/// Returns uninitialized sandboxed module instance or an instantiation error.
463480
pub fn instantiate<'a, FE: SandboxCapabilities>(
464481
supervisor_externals: &mut FE,
465482
dispatch_thunk: FE::SupervisorFuncRef,
466483
wasm: &[u8],
467-
host_env: GuestEnvironment,
484+
guest_env: GuestEnvironment,
468485
state: u32,
469486
) -> std::result::Result<UnregisteredInstance<FE::SupervisorFuncRef>, InstantiationError> {
470487
let module = Module::from_buffer(wasm).map_err(|_| InstantiationError::ModuleDecoding)?;
471-
let instance = ModuleInstance::new(&module, &host_env.imports)
488+
let instance = ModuleInstance::new(&module, &guest_env.imports)
472489
.map_err(|_| InstantiationError::Instantiation)?;
473490

474491
let sandbox_instance = Rc::new(SandboxInstance {
@@ -477,7 +494,7 @@ pub fn instantiate<'a, FE: SandboxCapabilities>(
477494
// for the purpose of running `start` function which should be ok.
478495
instance: instance.not_started_instance().clone(),
479496
dispatch_thunk,
480-
guest_to_supervisor_mapping: host_env.guest_to_supervisor_mapping,
497+
guest_to_supervisor_mapping: guest_env.guest_to_supervisor_mapping,
481498
});
482499

483500
with_guest_externals(

0 commit comments

Comments
 (0)