Skip to content

Commit 9f82644

Browse files
authored
Some minor cleanups/refactorings in components (#4582)
This is a collection of some minor renamings, refactorings, sharing of code, etc. This was all discovered during my addition of string support to adapter functions and I figured it'd be best to frontload this and land it ahead of the full patch since it's getting complex.
1 parent 0a6baed commit 9f82644

File tree

5 files changed

+67
-77
lines changed

5 files changed

+67
-77
lines changed

crates/cranelift/src/compiler/component.rs

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@ use cranelift_codegen::ir::{self, InstBuilder, MemFlags};
88
use cranelift_frontend::FunctionBuilder;
99
use object::write::Object;
1010
use std::any::Any;
11+
use std::ops::Range;
1112
use wasmtime_environ::component::{
12-
AlwaysTrapInfo, CanonicalOptions, Component, ComponentCompiler, ComponentTypes, LowerImport,
13-
LoweredIndex, LoweringInfo, RuntimeAlwaysTrapIndex, VMComponentOffsets,
13+
AlwaysTrapInfo, CanonicalOptions, Component, ComponentCompiler, ComponentTypes, FunctionInfo,
14+
LowerImport, LoweredIndex, RuntimeAlwaysTrapIndex, VMComponentOffsets,
1415
};
1516
use wasmtime_environ::{PrimaryMap, SignatureIndex, Trampoline, TrapCode, WasmFuncType};
1617

@@ -187,28 +188,29 @@ impl ComponentCompiler for Compiler {
187188
trampolines: Vec<(SignatureIndex, Box<dyn Any + Send>)>,
188189
obj: &mut Object<'static>,
189190
) -> Result<(
190-
PrimaryMap<LoweredIndex, LoweringInfo>,
191+
PrimaryMap<LoweredIndex, FunctionInfo>,
191192
PrimaryMap<RuntimeAlwaysTrapIndex, AlwaysTrapInfo>,
192193
Vec<Trampoline>,
193194
)> {
194195
let module = Default::default();
195196
let mut text = ModuleTextBuilder::new(obj, &module, &*self.isa);
196-
let mut ret = PrimaryMap::new();
197-
for (idx, lowering) in lowerings.iter() {
198-
let lowering = lowering.downcast_ref::<CompiledFunction>().unwrap();
199-
assert!(lowering.traps.is_empty());
200-
let (_symbol, range) = text.append_func(
201-
false,
202-
format!("_wasm_component_lowering_trampoline{}", idx.as_u32()).into_bytes(),
203-
&lowering,
204-
);
205-
206-
let i = ret.push(LoweringInfo {
207-
start: u32::try_from(range.start).unwrap(),
208-
length: u32::try_from(range.end - range.start).unwrap(),
209-
});
210-
assert_eq!(i, idx);
211-
}
197+
198+
let range2info = |range: Range<u64>| FunctionInfo {
199+
start: u32::try_from(range.start).unwrap(),
200+
length: u32::try_from(range.end - range.start).unwrap(),
201+
};
202+
let ret_lowerings = lowerings
203+
.iter()
204+
.map(|(i, lowering)| {
205+
let lowering = lowering.downcast_ref::<CompiledFunction>().unwrap();
206+
assert!(lowering.traps.is_empty());
207+
let range = text.named_func(
208+
&format!("_wasm_component_lowering_trampoline{}", i.as_u32()),
209+
&lowering,
210+
);
211+
range2info(range)
212+
})
213+
.collect();
212214
let ret_always_trap = always_trap
213215
.iter()
214216
.map(|(i, func)| {
@@ -217,11 +219,8 @@ impl ComponentCompiler for Compiler {
217219
assert_eq!(func.traps[0].trap_code, TrapCode::AlwaysTrapAdapter);
218220
let name = format!("_wasmtime_always_trap{}", i.as_u32());
219221
let range = text.named_func(&name, func);
220-
let start = u32::try_from(range.start).unwrap();
221-
let end = u32::try_from(range.end).unwrap();
222222
AlwaysTrapInfo {
223-
start: start,
224-
length: end - start,
223+
info: range2info(range),
225224
trap_offset: func.traps[0].code_offset,
226225
}
227226
})
@@ -238,6 +237,6 @@ impl ComponentCompiler for Compiler {
238237

239238
text.finish()?;
240239

241-
Ok((ret, ret_always_trap, ret_trampolines))
240+
Ok((ret_lowerings, ret_always_trap, ret_trampolines))
242241
}
243242
}

crates/environ/src/component/compiler.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use std::any::Any;
1010
/// Description of where a trampoline is located in the text section of a
1111
/// compiled image.
1212
#[derive(Serialize, Deserialize)]
13-
pub struct LoweringInfo {
13+
pub struct FunctionInfo {
1414
/// The byte offset from the start of the text section where this trampoline
1515
/// starts.
1616
pub start: u32,
@@ -22,11 +22,8 @@ pub struct LoweringInfo {
2222
/// `ComponentCompiler::compile_always_trap`.
2323
#[derive(Serialize, Deserialize)]
2424
pub struct AlwaysTrapInfo {
25-
/// The byte offset from the start of the text section where this trampoline
26-
/// starts.
27-
pub start: u32,
28-
/// The byte length of this trampoline's function body.
29-
pub length: u32,
25+
/// Information about the extent of this generated function.
26+
pub info: FunctionInfo,
3027
/// The offset from `start` of where the trapping instruction is located.
3128
pub trap_offset: u32,
3229
}
@@ -79,7 +76,7 @@ pub trait ComponentCompiler: Send + Sync {
7976
tramplines: Vec<(SignatureIndex, Box<dyn Any + Send>)>,
8077
obj: &mut Object<'static>,
8178
) -> Result<(
82-
PrimaryMap<LoweredIndex, LoweringInfo>,
79+
PrimaryMap<LoweredIndex, FunctionInfo>,
8380
PrimaryMap<RuntimeAlwaysTrapIndex, AlwaysTrapInfo>,
8481
Vec<Trampoline>,
8582
)>;

crates/runtime/src/component.rs

Lines changed: 30 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -244,27 +244,22 @@ impl ComponentInstance {
244244
/// This can only be called after `idx` has been initialized at runtime
245245
/// during the instantiation process of a component.
246246
pub fn lowering_anyfunc(&self, idx: LoweredIndex) -> NonNull<VMCallerCheckedAnyfunc> {
247-
unsafe {
248-
let ret = self
249-
.vmctx_plus_offset::<VMCallerCheckedAnyfunc>(self.offsets.lowering_anyfunc(idx));
250-
debug_assert!((*ret).func_ptr.as_ptr() as usize != INVALID_PTR);
251-
debug_assert!((*ret).vmctx as usize != INVALID_PTR);
252-
NonNull::new(ret).unwrap()
253-
}
247+
unsafe { self.anyfunc(self.offsets.lowering_anyfunc(idx)) }
254248
}
255249

256250
/// Same as `lowering_anyfunc` except for the functions that always trap.
257251
pub fn always_trap_anyfunc(
258252
&self,
259253
idx: RuntimeAlwaysTrapIndex,
260254
) -> NonNull<VMCallerCheckedAnyfunc> {
261-
unsafe {
262-
let ret = self
263-
.vmctx_plus_offset::<VMCallerCheckedAnyfunc>(self.offsets.always_trap_anyfunc(idx));
264-
debug_assert!((*ret).func_ptr.as_ptr() as usize != INVALID_PTR);
265-
debug_assert!((*ret).vmctx as usize != INVALID_PTR);
266-
NonNull::new(ret).unwrap()
267-
}
255+
unsafe { self.anyfunc(self.offsets.always_trap_anyfunc(idx)) }
256+
}
257+
258+
unsafe fn anyfunc(&self, offset: u32) -> NonNull<VMCallerCheckedAnyfunc> {
259+
let ret = self.vmctx_plus_offset::<VMCallerCheckedAnyfunc>(offset);
260+
debug_assert!((*ret).func_ptr.as_ptr() as usize != INVALID_PTR);
261+
debug_assert!((*ret).vmctx as usize != INVALID_PTR);
262+
NonNull::new(ret).unwrap()
268263
}
269264

270265
/// Stores the runtime memory pointer at the index specified.
@@ -335,16 +330,12 @@ impl ComponentInstance {
335330
debug_assert!(
336331
*self.vmctx_plus_offset::<usize>(self.offsets.lowering_data(idx)) == INVALID_PTR
337332
);
338-
debug_assert!(
339-
*self.vmctx_plus_offset::<usize>(self.offsets.lowering_anyfunc(idx)) == INVALID_PTR
340-
);
341333
*self.vmctx_plus_offset(self.offsets.lowering(idx)) = lowering;
342-
let vmctx = self.vmctx();
343-
*self.vmctx_plus_offset(self.offsets.lowering_anyfunc(idx)) = VMCallerCheckedAnyfunc {
344-
func_ptr: anyfunc_func_ptr,
345-
type_index: anyfunc_type_index,
346-
vmctx: VMOpaqueContext::from_vmcomponent(vmctx),
347-
};
334+
self.set_anyfunc(
335+
self.offsets.lowering_anyfunc(idx),
336+
anyfunc_func_ptr,
337+
anyfunc_type_index,
338+
);
348339
}
349340
}
350341

@@ -355,19 +346,22 @@ impl ComponentInstance {
355346
func_ptr: NonNull<VMFunctionBody>,
356347
type_index: VMSharedSignatureIndex,
357348
) {
358-
unsafe {
359-
debug_assert!(
360-
*self.vmctx_plus_offset::<usize>(self.offsets.always_trap_anyfunc(idx))
361-
== INVALID_PTR
362-
);
363-
let vmctx = self.vmctx();
364-
*self.vmctx_plus_offset(self.offsets.always_trap_anyfunc(idx)) =
365-
VMCallerCheckedAnyfunc {
366-
func_ptr,
367-
type_index,
368-
vmctx: VMOpaqueContext::from_vmcomponent(vmctx),
369-
};
370-
}
349+
unsafe { self.set_anyfunc(self.offsets.always_trap_anyfunc(idx), func_ptr, type_index) }
350+
}
351+
352+
unsafe fn set_anyfunc(
353+
&mut self,
354+
offset: u32,
355+
func_ptr: NonNull<VMFunctionBody>,
356+
type_index: VMSharedSignatureIndex,
357+
) {
358+
debug_assert!(*self.vmctx_plus_offset::<usize>(offset) == INVALID_PTR);
359+
let vmctx = self.vmctx();
360+
*self.vmctx_plus_offset(offset) = VMCallerCheckedAnyfunc {
361+
func_ptr,
362+
type_index,
363+
vmctx: VMOpaqueContext::from_vmcomponent(vmctx),
364+
};
371365
}
372366

373367
unsafe fn initialize_vmctx(&mut self, store: *mut dyn Store) {

crates/wasmtime/src/component/component.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use std::path::Path;
1010
use std::ptr::NonNull;
1111
use std::sync::Arc;
1212
use wasmtime_environ::component::{
13-
AlwaysTrapInfo, ComponentTypes, GlobalInitializer, LoweredIndex, LoweringInfo,
13+
AlwaysTrapInfo, ComponentTypes, FunctionInfo, GlobalInitializer, LoweredIndex,
1414
RuntimeAlwaysTrapIndex, StaticModuleIndex, Translator,
1515
};
1616
use wasmtime_environ::{PrimaryMap, ScopeVec, SignatureIndex, Trampoline, TrapCode};
@@ -56,7 +56,7 @@ struct ComponentInner {
5656
/// These trampolines are the function pointer within the
5757
/// `VMCallerCheckedAnyfunc` and will delegate indirectly to a host function
5858
/// pointer when called.
59-
lowerings: PrimaryMap<LoweredIndex, LoweringInfo>,
59+
lowerings: PrimaryMap<LoweredIndex, FunctionInfo>,
6060

6161
/// Where the "always trap" functions are located within the `text` section
6262
/// of `trampoline_obj`.
@@ -205,7 +205,7 @@ impl Component {
205205
.values()
206206
.as_slice()
207207
.windows(2)
208-
.all(|window| { window[0].start < window[1].start }));
208+
.all(|window| { window[0].info.start < window[1].info.start }));
209209

210210
crate::module::register_component(code.text, &always_trap);
211211
Ok(Component {
@@ -229,7 +229,7 @@ impl Component {
229229
types: &ComponentTypes,
230230
provided_trampolines: &HashSet<SignatureIndex>,
231231
) -> Result<(
232-
PrimaryMap<LoweredIndex, LoweringInfo>,
232+
PrimaryMap<LoweredIndex, FunctionInfo>,
233233
PrimaryMap<RuntimeAlwaysTrapIndex, AlwaysTrapInfo>,
234234
Vec<Trampoline>,
235235
wasmtime_runtime::MmapVec,
@@ -368,17 +368,17 @@ impl Component {
368368

369369
pub(crate) fn lowering_ptr(&self, index: LoweredIndex) -> NonNull<VMFunctionBody> {
370370
let info = &self.inner.lowerings[index];
371-
self.func(info.start, info.length)
371+
self.func(info)
372372
}
373373

374374
pub(crate) fn always_trap_ptr(&self, index: RuntimeAlwaysTrapIndex) -> NonNull<VMFunctionBody> {
375375
let info = &self.inner.always_trap[index];
376-
self.func(info.start, info.length)
376+
self.func(&info.info)
377377
}
378378

379-
fn func(&self, start: u32, len: u32) -> NonNull<VMFunctionBody> {
379+
fn func(&self, info: &FunctionInfo) -> NonNull<VMFunctionBody> {
380380
let text = self.text();
381-
let trampoline = &text[start as usize..][..len as usize];
381+
let trampoline = &text[info.start as usize..][..info.length as usize];
382382
NonNull::new(trampoline.as_ptr() as *mut VMFunctionBody).unwrap()
383383
}
384384

@@ -393,7 +393,7 @@ impl Component {
393393
.always_trap
394394
.values()
395395
.as_slice()
396-
.binary_search_by_key(&offset, |info| info.start + info.trap_offset)
396+
.binary_search_by_key(&offset, |info| info.info.start + info.trap_offset)
397397
{
398398
Ok(_) => Some(TrapCode::AlwaysTrapAdapter),
399399
Err(_) => None,

crates/wasmtime/src/module/registry.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -287,7 +287,7 @@ pub fn register_component(text: &[u8], traps: &PrimaryMap<RuntimeAlwaysTrapIndex
287287
let info = Arc::new(
288288
traps
289289
.iter()
290-
.map(|(_, info)| info.start + info.trap_offset)
290+
.map(|(_, info)| info.info.start + info.trap_offset)
291291
.collect::<Vec<_>>(),
292292
);
293293
let prev = GLOBAL_MODULES

0 commit comments

Comments
 (0)