Debian Codegraph @

crates/wit-component/src/linking/metadata.rs

raw
1 //! Support for parsing and analyzing [dynamic
2 //! library](https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md) modules.
3
4 use {
5 anyhow::{Context, Error, Result, bail},
6 std::{
7 collections::{BTreeSet, HashMap, HashSet},
8 fmt,
9 },
10 wasmparser::{
11 Dylink0Subsection, ExternalKind, FuncType, KnownCustom, MemInfo, Parser, Payload, RefType,
12 SymbolFlags, TableType, TypeRef, ValType,
13 },
14 };
15
16 /// Represents a core Wasm value type (not including V128 or reference types, which are not yet supported)
17 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
18 pub enum ValueType {
19 I32,
20 I64,
21 F32,
22 F64,
23 }
24
25 impl TryFrom<ValType> for ValueType {
26 type Error = Error;
27
28 fn try_from(value: ValType) -> Result<Self> {
29 Ok(match value {
30 ValType::I32 => Self::I32,
31 ValType::I64 => Self::I64,
32 ValType::F32 => Self::F32,
33 ValType::F64 => Self::F64,
34 _ => bail!("{value:?} not yet supported"),
35 })
36 }
37 }
38
39 impl From<ValueType> for wasm_encoder::ValType {
40 fn from(value: ValueType) -> Self {
41 match value {
42 ValueType::I32 => Self::I32,
43 ValueType::I64 => Self::I64,
44 ValueType::F32 => Self::F32,
45 ValueType::F64 => Self::F64,
46 }
47 }
48 }
49
50 /// Represents a core Wasm function type
51 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
52 pub struct FunctionType {
53 pub parameters: Vec<ValueType>,
54 pub results: Vec<ValueType>,
55 }
56
57 impl fmt::Display for FunctionType {
58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
59 write!(f, "{:?} -> {:?}", self.parameters, self.results)
60 }
61 }
62
63 impl TryFrom<&FuncType> for FunctionType {
64 type Error = Error;
65
66 fn try_from(value: &FuncType) -> Result<Self> {
67 Ok(Self {
68 parameters: value
69 .params()
70 .iter()
71 .map(|&v| ValueType::try_from(v))
72 .collect::<Result<_>>()?,
73 results: value
74 .results()
75 .iter()
76 .map(|&v| ValueType::try_from(v))
77 .collect::<Result<_>>()?,
78 })
79 }
80 }
81
82 /// Represents a core Wasm global variable type
83 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
84 pub struct GlobalType {
85 pub ty: ValueType,
86 pub mutable: bool,
87 pub shared: bool,
88 }
89
90 impl fmt::Display for GlobalType {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 if self.mutable {
93 write!(f, "mut ")?;
94 }
95 write!(f, "{:?}", self.ty)
96 }
97 }
98
99 /// Represents a core Wasm export or import type
100 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
101 pub enum Type {
102 Function(FunctionType),
103 Global(GlobalType),
104 }
105
106 impl fmt::Display for Type {
107 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
108 match self {
109 Self::Function(ty) => write!(f, "function {ty}"),
110 Self::Global(ty) => write!(f, "global {ty}"),
111 }
112 }
113 }
114
115 impl From<&Type> for wasm_encoder::ExportKind {
116 fn from(value: &Type) -> Self {
117 match value {
118 Type::Function(_) => wasm_encoder::ExportKind::Func,
119 Type::Global(_) => wasm_encoder::ExportKind::Global,
120 }
121 }
122 }
123
124 /// Represents a core Wasm import
125 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
126 pub struct Import<'a> {
127 pub module: &'a str,
128 pub name: &'a str,
129 pub ty: Type,
130 pub flags: SymbolFlags,
131 }
132
133 /// Represents a core Wasm export
134 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
135 pub struct ExportKey<'a> {
136 pub name: &'a str,
137 pub ty: Type,
138 }
139
140 impl<'a> fmt::Display for ExportKey<'a> {
141 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
142 write!(f, "{} ({})", self.name, self.ty)
143 }
144 }
145
146 /// Represents a core Wasm export, including dylink.0 flags
147 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
148 pub struct Export<'a> {
149 pub key: ExportKey<'a>,
150 pub flags: SymbolFlags,
151 }
152
153 /// Metadata extracted from a dynamic library module
154 #[derive(Debug)]
155 pub struct Metadata<'a> {
156 /// The name of the module
157 ///
158 /// This is currently not part of the file itself and must be provided separately, but the plan is to add
159 /// something like a `WASM_DYLINK_SO_NAME` field to the dynamic linking tool convention so we can parse it
160 /// along with everything else.
161 pub name: &'a str,
162
163 /// Whether this module should be resolvable via `dlopen`
164 pub dl_openable: bool,
165
166 /// The `WASM_DYLINK_MEM_INFO` value (or all zeros if not found)
167 pub mem_info: MemInfo,
168
169 /// The `WASM_DYLINK_NEEDED` values, if any
170 pub needed_libs: Vec<&'a str>,
171
172 /// The `WASM_DYLINK_RUNTIME_PATH` values, if any
173 pub runtime_path: Vec<&'a str>,
174
175 /// Whether this module exports `__wasm_apply_data_relocs`
176 pub has_data_relocs: bool,
177
178 /// Whether this module exports `__wasm_call_ctors`
179 pub has_ctors: bool,
180
181 /// Whether this module exports `_initialize`
182 pub has_initialize: bool,
183
184 /// Whether this module exports `_start`
185 pub has_wasi_start: bool,
186
187 /// Whether this module exports `__wasm_set_libraries`
188 pub has_set_libraries: bool,
189
190 /// Whether this module includes any `component-type*` custom sections which include exports
191 pub has_component_exports: bool,
192
193 /// Whether this module imports `__asyncify_state` or `__asyncify_data`, indicating that it is
194 /// asyncified with `--pass-arg=asyncify-relocatable` option.
195 pub is_asyncified: bool,
196
197 /// The functions imported from the `env` module, if any
198 pub env_imports: BTreeSet<(&'a str, (FunctionType, SymbolFlags))>,
199
200 /// The memory addresses imported from `GOT.mem`, if any
201 pub memory_address_imports: BTreeSet<&'a str>,
202
203 /// The table addresses imported from `GOT.func`, if any
204 pub table_address_imports: BTreeSet<&'a str>,
205
206 /// The symbols exported by this module, if any
207 pub exports: BTreeSet<Export<'a>>,
208
209 /// The symbols imported by this module (and not accounted for in the above fields), if any
210 pub imports: BTreeSet<Import<'a>>,
211 }
212
213 impl<'a> Metadata<'a> {
214 /// Parse the specified module and extract its metadata.
215 pub fn try_new(
216 name: &'a str,
217 dl_openable: bool,
218 module: &'a [u8],
219 adapter_names: &HashSet<&str>,
220 ) -> Result<Self> {
221 let bindgen = crate::metadata::decode(module)?.1;
222 let has_component_exports = !bindgen.resolve.worlds[bindgen.world].exports.is_empty();
223
224 let mut result = Self {
225 name,
226 dl_openable,
227 mem_info: MemInfo {
228 memory_size: 0,
229 memory_alignment: 1,
230 table_size: 0,
231 table_alignment: 1,
232 },
233 needed_libs: Vec::new(),
234 runtime_path: Vec::new(),
235 has_data_relocs: false,
236 has_ctors: false,
237 has_initialize: false,
238 has_wasi_start: false,
239 has_set_libraries: false,
240 has_component_exports,
241 is_asyncified: false,
242 env_imports: BTreeSet::new(),
243 memory_address_imports: BTreeSet::new(),
244 table_address_imports: BTreeSet::new(),
245 exports: BTreeSet::new(),
246 imports: BTreeSet::new(),
247 };
248 let mut types = Vec::new();
249 let mut function_types = Vec::new();
250 let mut global_types = Vec::new();
251 let mut import_info = HashMap::new();
252 let mut export_info = HashMap::new();
253
254 for payload in Parser::new(0).parse_all(module) {
255 match payload? {
256 Payload::CustomSection(section) => {
257 if let KnownCustom::Dylink0(reader) = section.as_known() {
258 for subsection in reader {
259 match subsection.context("failed to parse `dylink.0` subsection")? {
260 Dylink0Subsection::MemInfo(info) => result.mem_info = info,
261 Dylink0Subsection::Needed(needed) => {
262 result.needed_libs = needed.clone()
263 }
264 Dylink0Subsection::ExportInfo(info) => {
265 export_info
266 .extend(info.iter().map(|info| (info.name, info.flags)));
267 }
268 Dylink0Subsection::ImportInfo(info) => {
269 import_info.extend(
270 info.iter()
271 .map(|info| ((info.module, info.field), info.flags)),
272 );
273 }
274 Dylink0Subsection::RuntimePath(runtime_path) => {
275 result.runtime_path.extend(runtime_path.iter());
276 }
277 Dylink0Subsection::Unknown { ty, .. } => {
278 bail!("unrecognized `dylink.0` subsection: {ty}")
279 }
280 }
281 }
282 }
283 }
284
285 Payload::TypeSection(reader) => {
286 types = reader
287 .into_iter_err_on_gc_types()
288 .collect::<Result<Vec<_>, _>>()?;
289 }
290
291 Payload::ImportSection(reader) => {
292 for import in reader {
293 let import = import?;
294
295 match import.ty {
296 TypeRef::Func(ty) => function_types.push(usize::try_from(ty).unwrap()),
297 TypeRef::Global(ty) => global_types.push(ty),
298 _ => (),
299 }
300
301 let type_error = || {
302 bail!(
303 "unexpected type for {}:{}: {:?}",
304 import.module,
305 import.name,
306 import.ty
307 )
308 };
309
310 match (import.module, import.name) {
311 ("env", "memory") => {
312 if !matches!(import.ty, TypeRef::Memory(_)) {
313 return type_error();
314 }
315 }
316 ("env", "__asyncify_data" | "__asyncify_state") => {
317 result.is_asyncified = true;
318 if !matches!(
319 import.ty,
320 TypeRef::Global(wasmparser::GlobalType {
321 content_type: ValType::I32,
322 ..
323 })
324 ) {
325 return type_error();
326 }
327 }
328 ("env", "__memory_base" | "__table_base" | "__stack_pointer") => {
329 if !matches!(
330 import.ty,
331 TypeRef::Global(wasmparser::GlobalType {
332 content_type: ValType::I32,
333 ..
334 })
335 ) {
336 return type_error();
337 }
338 }
339 ("env", "__indirect_function_table") => {
340 if let TypeRef::Table(TableType {
341 element_type,
342 maximum: None,
343 ..
344 }) = import.ty
345 {
346 if element_type != RefType::FUNCREF {
347 return type_error();
348 }
349 } else {
350 return type_error();
351 }
352 }
353 ("env", name) => {
354 if let TypeRef::Func(ty) = import.ty {
355 result.env_imports.insert((
356 name,
357 (
358 FunctionType::try_from(
359 &types[usize::try_from(ty).unwrap()],
360 )?,
361 import_info
362 .get(&("env", name))
363 .copied()
364 .unwrap_or_default(),
365 ),
366 ));
367 } else {
368 return type_error();
369 }
370 }
371 ("GOT.mem", name) => {
372 if let TypeRef::Global(wasmparser::GlobalType {
373 content_type: ValType::I32,
374 ..
375 }) = import.ty
376 {
377 match name {
378 "__heap_base" | "__heap_end" => (),
379 _ => {
380 result.memory_address_imports.insert(name);
381 }
382 }
383 } else {
384 return type_error();
385 }
386 }
387 ("GOT.func", name) => {
388 if let TypeRef::Global(wasmparser::GlobalType {
389 content_type: ValType::I32,
390 ..
391 }) = import.ty
392 {
393 result.table_address_imports.insert(name);
394 } else {
395 return type_error();
396 }
397 }
398 (module, name) if adapter_names.contains(module) => {
399 let ty = match import.ty {
400 TypeRef::Global(wasmparser::GlobalType {
401 content_type,
402 mutable,
403 shared,
404 }) => Type::Global(GlobalType {
405 ty: content_type.try_into()?,
406 mutable,
407 shared,
408 }),
409 TypeRef::Func(ty) => Type::Function(FunctionType::try_from(
410 &types[usize::try_from(ty).unwrap()],
411 )?),
412 ty => {
413 bail!("unsupported import kind for {module}.{name}: {ty:?}",)
414 }
415 };
416 let flags = import_info
417 .get(&(module, name))
418 .copied()
419 .unwrap_or_default();
420 result.imports.insert(Import {
421 module,
422 name,
423 ty,
424 flags,
425 });
426 }
427 _ => {
428 if !matches!(import.ty, TypeRef::Func(_) | TypeRef::Global(_)) {
429 return type_error();
430 }
431 }
432 }
433 }
434 }
435
436 Payload::FunctionSection(reader) => {
437 for function in reader {
438 function_types.push(usize::try_from(function?).unwrap());
439 }
440 }
441
442 Payload::GlobalSection(reader) => {
443 for global in reader {
444 global_types.push(global?.ty);
445 }
446 }
447
448 Payload::ExportSection(reader) => {
449 for export in reader {
450 let export = export?;
451
452 match export.name {
453 "__wasm_apply_data_relocs" => result.has_data_relocs = true,
454 "__wasm_call_ctors" => result.has_ctors = true,
455 "_initialize" => result.has_initialize = true,
456 "_start" => result.has_wasi_start = true,
457 "__wasm_set_libraries" => result.has_set_libraries = true,
458 _ => {
459 let ty = match export.kind {
460 ExternalKind::Func => Type::Function(FunctionType::try_from(
461 &types[function_types
462 [usize::try_from(export.index).unwrap()]],
463 )?),
464 ExternalKind::Global => {
465 let ty =
466 global_types[usize::try_from(export.index).unwrap()];
467 Type::Global(GlobalType {
468 ty: ValueType::try_from(ty.content_type)?,
469 mutable: ty.mutable,
470 shared: ty.shared,
471 })
472 }
473 kind => {
474 bail!(
475 "unsupported export kind for {}: {kind:?}",
476 export.name
477 )
478 }
479 };
480 let flags =
481 export_info.get(&export.name).copied().unwrap_or_default();
482 result.exports.insert(Export {
483 key: ExportKey {
484 name: export.name,
485 ty,
486 },
487 flags,
488 });
489 }
490 }
491 }
492 }
493
494 _ => {}
495 }
496 }
497
498 Ok(result)
499 }
500 }