wasmtime/compile/code_builder/compile_time_builtins.rs
1use super::*;
2use crate::ToWasmtimeResult as _;
3use wasm_compose::graph::{CompositionGraph, EncodeOptions, ImportIndex, InstanceId};
4
5/// Returns the instance imports of `component`, in declaration order.
6fn instance_imports<'c>(
7 component: &'c wasm_compose::graph::Component<'_>,
8) -> impl Iterator<Item = (ImportIndex, &'c str)> {
9 component.imports().filter_map(|(index, name, ty)| {
10 matches!(ty, wasmparser::ComponentTypeRef::Instance(_)).then_some((index, name))
11 })
12}
13
14/// A composition of the main Wasm with compile-time builtins.
15struct Composition<'b> {
16 builtins: &'b HashMap<Cow<'b, str>, Cow<'b, [u8]>>,
17 validator: wasmparser::Validator,
18 graph: CompositionGraph<'b>,
19 /// The builtins instantiated so far.
20 instances: Vec<(&'b str, InstanceId)>,
21 /// The builtins whose imports are being connected, outermost first.
22 stack: Vec<&'b str>,
23}
24
25impl<'b> Composition<'b> {
26 /// Connects each instance import of `target` that names a builtin to that
27 /// builtin, in declaration order, so the output is deterministic.
28 fn connect_builtins(&mut self, target: InstanceId) -> Result<()> {
29 // Look up the builtins first, since instantiating them needs the graph
30 // mutably.
31 let (_, component) = self.graph.get_component_of_instance(target).unwrap();
32 let builtins = self.builtins;
33 let imports: Vec<(ImportIndex, &'b str)> = instance_imports(component)
34 .filter_map(|(import, name)| Some((import, &**builtins.get_key_value(name)?.0)))
35 .collect();
36
37 for (import, name) in imports {
38 let source = self.instantiate(name)?;
39
40 // If the builtin exports an instance named after the import, use
41 // that instead of the builtin's instance itself.
42 let (_, source_component) = self.graph.get_component_of_instance(source).unwrap();
43 let export = source_component
44 .export_by_name(name)
45 .filter(|(_, kind, _)| *kind == wasmparser::ComponentExternalKind::Instance)
46 .map(|(index, _, _)| index);
47
48 // wasm-compose's errors name the import but not the importer, which
49 // is the builtin on top of the stack, if any.
50 self.graph
51 .connect(source, export, target, import)
52 .to_wasmtime_result()
53 .with_context(|| match self.stack.last() {
54 Some(importer) => format!(
55 "failed to link compile-time builtin `{name}` into compile-time \
56 builtin `{importer}`"
57 ),
58 None => {
59 format!("failed to link compile-time builtin `{name}` into the main Wasm")
60 }
61 })?;
62 }
63
64 Ok(())
65 }
66
67 /// Returns the instance of the builtin `name`, instantiating it and
68 /// connecting its builtin imports the first time.
69 fn instantiate(&mut self, name: &'b str) -> Result<InstanceId> {
70 // wasm-compose would only report a cycle by label, so name the
71 // builtins here.
72 if let Some(start) = self.stack.iter().position(|&builtin| builtin == name) {
73 let cycle: Vec<String> = self.stack[start..]
74 .iter()
75 .chain([&name])
76 .map(|builtin| format!("`{builtin}`"))
77 .collect();
78 bail!(
79 "compile-time builtins form an import cycle: {}",
80 cycle.join(" -> ")
81 );
82 }
83
84 if let Some(&(_, instance)) = self.instances.iter().find(|&&(builtin, _)| builtin == name) {
85 return Ok(instance);
86 }
87
88 // Graph labels must be unique and valid but aren't encoded, so number
89 // them rather than reuse import names, which could clash with `main`.
90 let label = format!("builtin{}", self.instances.len());
91
92 // wasm-compose's errors use the label, so name the builtin here.
93 let component = wasm_compose::graph::Component::from_bytes(
94 &mut self.validator,
95 label,
96 &*self.builtins[name],
97 )
98 .to_wasmtime_result()
99 .with_context(|| format!("invalid compile-time builtin `{name}`"))?;
100 let component = self.graph.add_component(component).to_wasmtime_result()?;
101 let instance = self.graph.instantiate(component).to_wasmtime_result()?;
102 self.instances.push((name, instance));
103
104 self.stack.push(name);
105 self.connect_builtins(instance)?;
106 self.stack.pop();
107
108 Ok(instance)
109 }
110}
111
112/// Composes `main_wasm` with the compile-time builtins it imports, directly or
113/// through other builtins. Other imports, such as the unsafe intrinsics,
114/// remain imports, merged by name.
115fn compose<'b>(
116 main_wasm: &'b [u8],
117 builtins: &'b HashMap<Cow<'b, str>, Cow<'b, [u8]>>,
118 features: wasmparser::WasmFeatures,
119) -> Result<Vec<u8>> {
120 let mut composition = Composition {
121 builtins,
122 validator: wasmparser::Validator::new_with_features(features),
123 graph: CompositionGraph::new(),
124 instances: Vec::new(),
125 stack: Vec::new(),
126 };
127
128 let main =
129 wasm_compose::graph::Component::from_bytes(&mut composition.validator, "main", main_wasm)
130 .to_wasmtime_result()?;
131 let main = composition.graph.add_component(main).to_wasmtime_result()?;
132 let main = composition.graph.instantiate(main).to_wasmtime_result()?;
133 composition.connect_builtins(main)?;
134
135 composition
136 .graph
137 .encode(EncodeOptions {
138 define_components: true,
139 export: Some(main),
140 validate: false,
141 })
142 .to_wasmtime_result()
143}
144
145impl<'a> CodeBuilder<'a> {
146 pub(crate) fn get_compile_time_builtins(&self) -> &HashMap<Cow<'a, str>, Cow<'a, [u8]>> {
147 &self.compile_time_builtins
148 }
149
150 pub(super) fn compose_compile_time_builtins<'b>(
151 &self,
152 main_wasm: &'b [u8],
153 ) -> Result<Cow<'b, [u8]>> {
154 if self.get_compile_time_builtins().is_empty() {
155 return Ok(main_wasm.into());
156 }
157
158 let imports = self.check_imports_for_compile_time_builtins(&main_wasm)?;
159 let builtins = self.get_compile_time_builtins();
160
161 // Nothing to compose if the main Wasm imports none of the builtins.
162 if !imports.iter().any(|import| builtins.contains_key(*import)) {
163 drop(imports);
164 return Ok(main_wasm.into());
165 }
166
167 Ok(compose(main_wasm, builtins, self.engine.features())?.into())
168 }
169
170 /// Check that the main Wasm doesn't import unsafe intrinsics, keeping the
171 /// TCB to just the compile-time builtins' implementation.
172 ///
173 /// Returns the Wasm's top-level instance imports, so that composition can
174 /// be skipped when none of them is a compile-time builtin.
175 fn check_imports_for_compile_time_builtins<'b>(
176 &self,
177 main_wasm: &'b [u8],
178 ) -> Result<crate::hash_set::HashSet<&'b str>, Error> {
179 let intrinsics_import = self.unsafe_intrinsics_import.as_deref().ok_or_else(|| {
180 format_err!(
181 "must configure the unsafe-intrinsics import when using compile-time builtins"
182 )
183 })?;
184
185 let mut instance_imports = crate::hash_set::HashSet::new();
186 let parser = wasmparser::Parser::new(0);
187 let mut level = 0;
188
189 for payload in parser.parse_all(main_wasm) {
190 match payload? {
191 wasmparser::Payload::Version { .. } => {
192 level += 1;
193 }
194 wasmparser::Payload::End(_) => {
195 level -= 1;
196 }
197 wasmparser::Payload::ComponentImportSection(imports) if level == 1 => {
198 for imp in imports.into_iter() {
199 let imp = imp?;
200 // Ideally we would simply choose a new import name that
201 // doesn't conflict with the main Wasm's imports and
202 // plumb that through to the compile-time builtins
203 // regardless of the import name that they use, but
204 // unfortunately the `wasm-compose` API is not powerful
205 // enough for us to do all that.
206 ensure!(
207 imp.name.name != intrinsics_import,
208 "main Wasm cannot import the unsafe intrinsics (`{intrinsics_import}`) \
209 when using compile-time builtins"
210 );
211
212 if let wasmparser::ComponentTypeRef::Instance(_) = imp.ty {
213 instance_imports.insert(imp.name.name);
214 }
215 }
216 }
217 _ => {}
218 }
219 }
220
221 Ok(instance_imports)
222 }
223
224 /// Define a compile-time builtin component, via its Wasm bytes.
225 ///
226 /// Compile-time builtins enable you to build safe, zero-copy, and (with
227 /// [inlining][crate::Config::compiler_inlining])
228 /// zero-function-call-overhead Wasm APIs for accessing host data, buffers,
229 /// and objects.
230 ///
231 /// A compile-time builtin is a component that is
232 ///
233 /// * authored by the host (Wasmtime embedder),
234 ///
235 /// * whose implementation (though not necessarily its interface!) is
236 /// host-specific,
237 ///
238 /// * has access to unsafe intrinsics (and is therefore part of the host's
239 /// [trusted compute base]), and
240 ///
241 /// * is linked into guest Wasm programs at compile-time.
242 ///
243 /// Compile-time builtins may import other compile-time builtins, but not
244 /// in a cycle. Wasmtime links in every builtin that the main Wasm imports,
245 /// directly or through other builtins. It instantiates each builtin once,
246 /// and every import with the builtin's name shares that instance.
247 ///
248 /// Any imports satisfied by a compile-time builtin during compilation will
249 /// not show up in the resulting component's
250 /// [imports][crate::component::types::Component::imports], and they can no
251 /// longer be customized by a [`Linker`][crate::component::Linker]
252 /// definition at instantiation time.[^0]
253 ///
254 /// [^0]: If linking compile-time builtins into a component at compile-time
255 /// reminds you of [component composition], that is not a coincidence:
256 /// component composition is used under the covers as part of compile-time
257 /// builtins' implementation.
258 ///
259 /// Comparing compile-time builtins with
260 /// [`Linker`][crate::component::Linker]s is informative:
261 ///
262 /// * Both mechanisms define APIs to satisfy a Wasm program's imports.
263 ///
264 /// * A `Linker` satisfies those imports at instantiation-time, while
265 /// compile-time builtins do it during compilation.
266 ///
267 /// * APIs defined by a `Linker` are implemented in Rust, and hosts can
268 /// build safe, sandboxed Wasm APIs on top of raw, un-sandboxed primitives
269 /// via Rust's `unsafe`. APIs defined by compile-time builtins are
270 /// implemented as Wasm components, and hosts can build safe, sandboxed
271 /// Wasm APIs on top of raw, un-sandboxed primitives via [unsafe
272 /// intrinsics][CodeBuilder::expose_unsafe_intrinsics].
273 ///
274 /// * Imports satisfied via `Linker`-defined APIs are implemented with
275 /// [PLT/GOT]-style function table lookups and indirect calls in the
276 /// Wasm's compiled native code. On the other hand, Wasmtime implements
277 /// calls to imports satisfied via compile-time builtins with direct calls
278 /// in the Wasm's compiled native code. Wasmtime's compiler can also
279 /// [inline][crate::Config::compiler_inlining] these direct calls,
280 /// removing function call overheads and enabling further, cascading
281 /// compiler optimizations.
282 ///
283 /// If you are familiar with Wasm on the Web, you can think of compile-time
284 /// builtins as the rough equivalent of [the `js-string-builtins` proposal]
285 /// but for arbitrary host-defined APIs in a Wasmtime embedding environment
286 /// rather than JS string APIs in a Web browser environment.
287 ///
288 /// [trusted compute base]: https://en.wikipedia.org/wiki/Trusted_computing_base
289 /// [the `js-string-builtins` proposal]: https://github.com/WebAssembly/js-string-builtins/blob/main/proposals/js-string-builtins/Overview.md
290 /// [component composition]: https://component-model.bytecodealliance.org/composing-and-distributing/composing.html
291 /// [PLT/GOT]: https://reverseengineering.stackexchange.com/a/1993
292 ///
293 /// # Safety
294 ///
295 /// Compile-time builtins are part of your [trusted compute base] and should
296 /// be authored by trusted, first-party developers with extreme care. You
297 /// should never use compile-time builtins authored by untrusted,
298 /// third-party developers.
299 ///
300 /// Compile-time builtins are given access to Wasmtime's [unsafe
301 /// intrinsics][CodeBuilder::expose_unsafe_intrinsics], and the same safety
302 /// invariants and portability concerns apply. However, when compile-time
303 /// builtins are defined on a `CodeBuilder`, unsafe intrinsics are *only*
304 /// exposed to the compile-time builtins, and they are *not* exposed to the
305 /// main guest Wasm program. This means that — assuming your compile-time
306 /// builtins only exposing safe APIs, encapsulating the intrinsics'
307 /// unsafety, and modulo bugs in your implementation of those safe APIs —
308 /// that the main guest Wasm program is not part of your trusted compute
309 /// base.
310 ///
311 /// # Example
312 ///
313 /// See the example in [CodeBuilder::expose_unsafe_intrinsics].
314 pub unsafe fn compile_time_builtins_binary(
315 &mut self,
316 name: impl Into<Cow<'a, str>>,
317 wasm_bytes: impl Into<Cow<'a, [u8]>>,
318 ) -> &mut Self {
319 self.compile_time_builtins
320 .insert(name.into(), wasm_bytes.into());
321 self
322 }
323
324 /// Equivalent of [`CodeBuilder::compile_time_builtins_binary`] that also
325 /// accepts the WebAssembly text format.
326 ///
327 /// This method will configure the WebAssembly binary to be compiled and
328 /// used to satisfy the `name` instance import. The input `wasm_bytes` may
329 /// either be the wasm text format or the binary format. If the `wat` crate
330 /// feature is enabled, which is enabled by default, then the text format
331 /// will automatically be converted to the binary format.
332 ///
333 /// # Errors
334 ///
335 /// This method will also return an error if `wasm_bytes` is the wasm text
336 /// format and the text syntax is not valid.
337 ///
338 /// # Safety
339 ///
340 /// See [`CodeBuilder::compile_time_builtins_binary`].
341 ///
342 /// # Example
343 ///
344 /// See the example in [CodeBuilder::expose_unsafe_intrinsics], which uses
345 /// compile-time builtins.
346 #[allow(unused_variables, reason = "`wasm_path` only used with `wat` feature")]
347 pub unsafe fn compile_time_builtins_binary_or_text(
348 &mut self,
349 name: impl Into<Cow<'a, str>>,
350 wasm_bytes: impl Into<Cow<'a, [u8]>>,
351 wasm_path: Option<&Path>,
352 ) -> Result<&mut Self> {
353 let wasm_bytes = wasm_bytes.into();
354
355 #[cfg(feature = "wat")]
356 if let Cow::Owned(wasm_bytes) = wat::parse_bytes(&wasm_bytes).map_err(|mut e| {
357 if let Some(path) = wasm_path {
358 e.set_path(path);
359 }
360 e
361 })? {
362 // SAFETY: Same as our unsafe contract.
363 return Ok(unsafe { self.compile_time_builtins_binary(name, wasm_bytes) });
364 }
365
366 // SAFETY: Same as our unsafe contract.
367 Ok(unsafe { self.compile_time_builtins_binary(name, wasm_bytes) })
368 }
369
370 /// Like [`CodeBuilder::compile_time_builtins_binary`], but reads the `file`
371 /// specified for the bytes that will define the compile-time builtin.
372 ///
373 /// # Safety
374 ///
375 /// See [`CodeBuilder::compile_time_builtins_binary`].
376 ///
377 /// # Example
378 ///
379 /// See the example in [CodeBuilder::expose_unsafe_intrinsics], which uses
380 /// compile-time builtins.
381 pub unsafe fn compile_time_builtins_binary_file(
382 &mut self,
383 name: impl Into<Cow<'a, str>>,
384 file: &Path,
385 ) -> Result<&mut Self> {
386 let wasm_bytes = std::fs::read(file)
387 .with_context(|| format!("failed to read file: {}", file.display()))?;
388 // SAFETY: Same as our unsafe contract.
389 Ok(unsafe { self.compile_time_builtins_binary(name, wasm_bytes) })
390 }
391
392 /// Equivalent of [`CodeBuilder::compile_time_builtins_binary_file`] that
393 /// also accepts the WebAssembly text format.
394 ///
395 /// This method is will read the file at the given path and interpret the
396 /// contents to determine if it's the Wasm text format or binary format. The
397 /// file extension is not consulted. The text format is automatically
398 /// converted to the binary format if the crate feature `wat` is active.
399 ///
400 /// # Errors
401 ///
402 /// In addition to the errors returned by
403 /// [`CodeBuilder::compile_time_builtins_binary_file`] this may also fail if
404 /// the text format is read and the syntax is invalid.
405 ///
406 /// # Safety
407 ///
408 /// See [`CodeBuilder::compile_time_builtins_binary`].
409 ///
410 /// # Example
411 ///
412 /// See the example in [CodeBuilder::expose_unsafe_intrinsics], which uses
413 /// compile-time builtins.
414 pub unsafe fn compile_time_builtins_binary_or_text_file(
415 &mut self,
416 name: impl Into<Cow<'a, str>>,
417 file: &Path,
418 ) -> Result<&mut Self> {
419 #[cfg(feature = "wat")]
420 {
421 let wasm = wat::parse_file(file)
422 .with_context(|| format!("error parsing file: {}", file.display()))?;
423 // SAFETY: Same as our unsafe contract.
424 Ok(unsafe { self.compile_time_builtins_binary(name, wasm) })
425 }
426
427 #[cfg(not(feature = "wat"))]
428 {
429 // SAFETY: Same as our unsafe contract.
430 unsafe { self.compile_time_builtins_binary_file(name, file) }
431 }
432 }
433}