Debian Codegraph @

third_party/rust/object/src/read/wasm.rs

raw
1 //! Support for reading Wasm files.
2 //!
3 //! [`WasmFile`] implements the [`Object`] trait for Wasm files.
4 use alloc::boxed::Box;
5 use alloc::vec::Vec;
6 use core::marker::PhantomData;
7 use core::ops::Range;
8 use core::{slice, str};
9 use wasmparser as wp;
10
11 use crate::read::{
12 self, Architecture, ComdatKind, CompressedData, CompressedFileRange, Error, Export, FileFlags,
13 Import, NoDynamicRelocationIterator, Object, ObjectComdat, ObjectKind, ObjectSection,
14 ObjectSegment, ObjectSymbol, ObjectSymbolTable, ReadError, ReadRef, Relocation, RelocationMap,
15 Result, SectionFlags, SectionIndex, SectionKind, SegmentFlags, SymbolFlags, SymbolIndex,
16 SymbolKind, SymbolScope, SymbolSection,
17 };
18
19 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
20 #[repr(usize)]
21 enum SectionId {
22 Custom = 0,
23 Type = 1,
24 Import = 2,
25 Function = 3,
26 Table = 4,
27 Memory = 5,
28 Global = 6,
29 Export = 7,
30 Start = 8,
31 Element = 9,
32 Code = 10,
33 Data = 11,
34 DataCount = 12,
35 Tag = 13,
36 }
37 // Update this constant when adding new section id:
38 const MAX_SECTION_ID: usize = SectionId::Tag as usize;
39
40 /// A WebAssembly object file.
41 #[derive(Debug)]
42 pub struct WasmFile<'data, R = &'data [u8]> {
43 data: &'data [u8],
44 has_memory64: bool,
45 // All sections, including custom sections.
46 sections: Vec<SectionHeader<'data>>,
47 // Indices into `sections` of sections with a non-zero id.
48 id_sections: Box<[Option<usize>; MAX_SECTION_ID + 1]>,
49 // Whether the file has DWARF information.
50 has_debug_symbols: bool,
51 // Symbols collected from imports, exports, code and name sections.
52 symbols: Vec<WasmSymbolInternal<'data>>,
53 // Address of the function body for the entry point.
54 entry: u64,
55 marker: PhantomData<R>,
56 }
57
58 #[derive(Debug)]
59 struct SectionHeader<'data> {
60 id: SectionId,
61 range: Range<usize>,
62 name: &'data str,
63 }
64
65 #[derive(Clone)]
66 enum LocalFunctionKind {
67 Unknown,
68 Exported { symbol_ids: Vec<u32> },
69 Local { symbol_id: u32 },
70 }
71
72 impl<T> ReadError<T> for wasmparser::Result<T> {
73 fn read_error(self, error: &'static str) -> Result<T> {
74 self.map_err(|_| Error(error))
75 }
76 }
77
78 impl<'data, R: ReadRef<'data>> WasmFile<'data, R> {
79 /// Parse the raw wasm data.
80 pub fn parse(data: R) -> Result<Self> {
81 let len = data.len().read_error("Unknown Wasm file size")?;
82 let data = data.read_bytes_at(0, len).read_error("Wasm read failed")?;
83 let parser = wp::Parser::new(0).parse_all(data);
84
85 let mut file = WasmFile {
86 data,
87 has_memory64: false,
88 sections: Vec::new(),
89 id_sections: Default::default(),
90 has_debug_symbols: false,
91 symbols: Vec::new(),
92 entry: 0,
93 marker: PhantomData,
94 };
95
96 let mut main_file_symbol = Some(WasmSymbolInternal {
97 name: "",
98 address: 0,
99 size: 0,
100 kind: SymbolKind::File,
101 section: SymbolSection::None,
102 scope: SymbolScope::Compilation,
103 });
104
105 let mut imported_funcs_count = 0;
106 let mut local_func_kinds = Vec::new();
107 let mut entry_func_id = None;
108 let mut code_range_start = 0;
109 let mut code_func_index = 0;
110 // One-to-one mapping of globals to their value (if the global is a constant integer).
111 let mut global_values = Vec::new();
112
113 for payload in parser {
114 let payload = payload.read_error("Invalid Wasm section header")?;
115
116 match payload {
117 wp::Payload::Version { encoding, .. } => {
118 if encoding != wp::Encoding::Module {
119 return Err(Error("Unsupported Wasm encoding"));
120 }
121 }
122 wp::Payload::TypeSection(section) => {
123 file.add_section(SectionId::Type, section.range(), "");
124 }
125 wp::Payload::ImportSection(section) => {
126 file.add_section(SectionId::Import, section.range(), "");
127 let mut last_module_name = None;
128
129 for import in section {
130 let import = import.read_error("Couldn't read an import item")?;
131 let module_name = import.module;
132
133 if last_module_name != Some(module_name) {
134 file.symbols.push(WasmSymbolInternal {
135 name: module_name,
136 address: 0,
137 size: 0,
138 kind: SymbolKind::File,
139 section: SymbolSection::None,
140 scope: SymbolScope::Dynamic,
141 });
142 last_module_name = Some(module_name);
143 }
144
145 let kind = match import.ty {
146 wp::TypeRef::Func(_) => {
147 imported_funcs_count += 1;
148 SymbolKind::Text
149 }
150 wp::TypeRef::Memory(memory) => {
151 file.has_memory64 |= memory.memory64;
152 SymbolKind::Data
153 }
154 wp::TypeRef::Table(_) | wp::TypeRef::Global(_) => SymbolKind::Data,
155 wp::TypeRef::Tag(_) => SymbolKind::Unknown,
156 };
157
158 file.symbols.push(WasmSymbolInternal {
159 name: import.name,
160 address: 0,
161 size: 0,
162 kind,
163 section: SymbolSection::Undefined,
164 scope: SymbolScope::Dynamic,
165 });
166 }
167 }
168 wp::Payload::FunctionSection(section) => {
169 file.add_section(SectionId::Function, section.range(), "");
170 local_func_kinds =
171 vec![LocalFunctionKind::Unknown; section.into_iter().count()];
172 }
173 wp::Payload::TableSection(section) => {
174 file.add_section(SectionId::Table, section.range(), "");
175 }
176 wp::Payload::MemorySection(section) => {
177 file.add_section(SectionId::Memory, section.range(), "");
178 for memory in section {
179 let memory = memory.read_error("Couldn't read a memory item")?;
180 file.has_memory64 |= memory.memory64;
181 }
182 }
183 wp::Payload::GlobalSection(section) => {
184 file.add_section(SectionId::Global, section.range(), "");
185 for global in section {
186 let global = global.read_error("Couldn't read a global item")?;
187 let mut address = None;
188 if !global.ty.mutable {
189 // There should be exactly one instruction.
190 let init = global.init_expr.get_operators_reader().read();
191 address = match init.read_error("Couldn't read a global init expr")? {
192 wp::Operator::I32Const { value } => Some(value as u64),
193 wp::Operator::I64Const { value } => Some(value as u64),
194 _ => None,
195 };
196 }
197 global_values.push(address);
198 }
199 }
200 wp::Payload::ExportSection(section) => {
201 file.add_section(SectionId::Export, section.range(), "");
202 if let Some(main_file_symbol) = main_file_symbol.take() {
203 file.symbols.push(main_file_symbol);
204 }
205
206 for export in section {
207 let export = export.read_error("Couldn't read an export item")?;
208
209 let (kind, section_idx) = match export.kind {
210 wp::ExternalKind::Func => {
211 if let Some(local_func_id) =
212 export.index.checked_sub(imported_funcs_count)
213 {
214 let local_func_kind = local_func_kinds
215 .get_mut(local_func_id as usize)
216 .read_error("Invalid Wasm export index")?;
217 if let LocalFunctionKind::Unknown = local_func_kind {
218 *local_func_kind = LocalFunctionKind::Exported {
219 symbol_ids: Vec::new(),
220 };
221 }
222 let symbol_ids = match local_func_kind {
223 LocalFunctionKind::Exported { symbol_ids } => symbol_ids,
224 _ => unreachable!(),
225 };
226 symbol_ids.push(file.symbols.len() as u32);
227 }
228 (SymbolKind::Text, SectionId::Code)
229 }
230 wp::ExternalKind::Table
231 | wp::ExternalKind::Memory
232 | wp::ExternalKind::Global => (SymbolKind::Data, SectionId::Data),
233 // TODO
234 wp::ExternalKind::Tag => continue,
235 };
236
237 // Try to guess the symbol address. Rust and C export a global containing
238 // the address in linear memory of the symbol.
239 let mut address = 0;
240 if export.kind == wp::ExternalKind::Global {
241 if let Some(&Some(x)) = global_values.get(export.index as usize) {
242 address = x;
243 }
244 }
245
246 file.symbols.push(WasmSymbolInternal {
247 name: export.name,
248 address,
249 size: 0,
250 kind,
251 section: SymbolSection::Section(SectionIndex(section_idx as usize)),
252 scope: SymbolScope::Dynamic,
253 });
254 }
255 }
256 wp::Payload::StartSection { func, range, .. } => {
257 file.add_section(SectionId::Start, range, "");
258 entry_func_id = Some(func);
259 }
260 wp::Payload::ElementSection(section) => {
261 file.add_section(SectionId::Element, section.range(), "");
262 }
263 wp::Payload::CodeSectionStart { range, .. } => {
264 code_range_start = range.start;
265 file.add_section(SectionId::Code, range, "");
266 if let Some(main_file_symbol) = main_file_symbol.take() {
267 file.symbols.push(main_file_symbol);
268 }
269 }
270 wp::Payload::CodeSectionEntry(body) => {
271 let i = code_func_index;
272 code_func_index += 1;
273
274 let range = body.range();
275
276 let address = range.start as u64 - code_range_start as u64;
277 let size = (range.end - range.start) as u64;
278
279 if entry_func_id == Some(i as u32) {
280 file.entry = address;
281 }
282
283 let local_func_kind = local_func_kinds
284 .get_mut(i)
285 .read_error("Invalid Wasm code section index")?;
286 match local_func_kind {
287 LocalFunctionKind::Unknown => {
288 *local_func_kind = LocalFunctionKind::Local {
289 symbol_id: file.symbols.len() as u32,
290 };
291 file.symbols.push(WasmSymbolInternal {
292 name: "",
293 address,
294 size,
295 kind: SymbolKind::Text,
296 section: SymbolSection::Section(SectionIndex(
297 SectionId::Code as usize,
298 )),
299 scope: SymbolScope::Compilation,
300 });
301 }
302 LocalFunctionKind::Exported { symbol_ids } => {
303 for symbol_id in core::mem::take(symbol_ids) {
304 let export_symbol = &mut file.symbols[symbol_id as usize];
305 export_symbol.address = address;
306 export_symbol.size = size;
307 }
308 }
309 _ => unreachable!(),
310 }
311 }
312 wp::Payload::DataSection(section) => {
313 file.add_section(SectionId::Data, section.range(), "");
314 }
315 wp::Payload::DataCountSection { range, .. } => {
316 file.add_section(SectionId::DataCount, range, "");
317 }
318 wp::Payload::TagSection(section) => {
319 file.add_section(SectionId::Tag, section.range(), "");
320 }
321 wp::Payload::CustomSection(section) => {
322 let name = section.name();
323 let size = section.data().len();
324 let mut range = section.range();
325 range.start = range.end - size;
326 file.add_section(SectionId::Custom, range, name);
327 if name == "name" {
328 let reader = wp::BinaryReader::new(
329 section.data(),
330 section.data_offset(),
331 wp::WasmFeatures::all(),
332 );
333 for name in wp::NameSectionReader::new(reader) {
334 // TODO: Right now, ill-formed name subsections
335 // are silently ignored in order to maintain
336 // compatibility with extended name sections, which
337 // are not yet supported by the version of
338 // `wasmparser` currently used.
339 // A better fix would be to update `wasmparser` to
340 // the newest version, but this requires
341 // a major rewrite of this file.
342 if let Ok(wp::Name::Function(name_map)) = name {
343 for naming in name_map {
344 let naming =
345 naming.read_error("Couldn't read a function name")?;
346 if let Some(local_index) =
347 naming.index.checked_sub(imported_funcs_count)
348 {
349 if let LocalFunctionKind::Local { symbol_id } =
350 local_func_kinds[local_index as usize]
351 {
352 file.symbols[symbol_id as usize].name = naming.name;
353 }
354 }
355 }
356 }
357 }
358 } else if name.starts_with(".debug_") {
359 file.has_debug_symbols = true;
360 }
361 }
362 _ => {}
363 }
364 }
365
366 Ok(file)
367 }
368
369 fn add_section(&mut self, id: SectionId, range: Range<usize>, name: &'data str) {
370 let section = SectionHeader { id, range, name };
371 self.id_sections[id as usize] = Some(self.sections.len());
372 self.sections.push(section);
373 }
374 }
375
376 impl<'data, R> read::private::Sealed for WasmFile<'data, R> {}
377
378 impl<'data, R: ReadRef<'data>> Object<'data> for WasmFile<'data, R> {
379 type Segment<'file> = WasmSegment<'data, 'file, R> where Self: 'file, 'data: 'file;
380 type SegmentIterator<'file> = WasmSegmentIterator<'data, 'file, R> where Self: 'file, 'data: 'file;
381 type Section<'file> = WasmSection<'data, 'file, R> where Self: 'file, 'data: 'file;
382 type SectionIterator<'file> = WasmSectionIterator<'data, 'file, R> where Self: 'file, 'data: 'file;
383 type Comdat<'file> = WasmComdat<'data, 'file, R> where Self: 'file, 'data: 'file;
384 type ComdatIterator<'file> = WasmComdatIterator<'data, 'file, R> where Self: 'file, 'data: 'file;
385 type Symbol<'file> = WasmSymbol<'data, 'file> where Self: 'file, 'data: 'file;
386 type SymbolIterator<'file> = WasmSymbolIterator<'data, 'file> where Self: 'file, 'data: 'file;
387 type SymbolTable<'file> = WasmSymbolTable<'data, 'file> where Self: 'file, 'data: 'file;
388 type DynamicRelocationIterator<'file> = NoDynamicRelocationIterator where Self: 'file, 'data: 'file;
389
390 #[inline]
391 fn architecture(&self) -> Architecture {
392 if self.has_memory64 {
393 Architecture::Wasm64
394 } else {
395 Architecture::Wasm32
396 }
397 }
398
399 #[inline]
400 fn is_little_endian(&self) -> bool {
401 true
402 }
403
404 #[inline]
405 fn is_64(&self) -> bool {
406 self.has_memory64
407 }
408
409 fn kind(&self) -> ObjectKind {
410 // TODO: check for `linking` custom section
411 ObjectKind::Unknown
412 }
413
414 fn segments(&self) -> Self::SegmentIterator<'_> {
415 WasmSegmentIterator { file: self }
416 }
417
418 fn section_by_name_bytes<'file>(
419 &'file self,
420 section_name: &[u8],
421 ) -> Option<WasmSection<'data, 'file, R>> {
422 self.sections()
423 .find(|section| section.name_bytes() == Ok(section_name))
424 }
425
426 fn section_by_index(&self, index: SectionIndex) -> Result<WasmSection<'data, '_, R>> {
427 // TODO: Missing sections should return an empty section.
428 let id_section = self
429 .id_sections
430 .get(index.0)
431 .and_then(|x| *x)
432 .read_error("Invalid Wasm section index")?;
433 let section = self.sections.get(id_section).unwrap();
434 Ok(WasmSection {
435 file: self,
436 section,
437 })
438 }
439
440 fn sections(&self) -> Self::SectionIterator<'_> {
441 WasmSectionIterator {
442 file: self,
443 sections: self.sections.iter(),
444 }
445 }
446
447 fn comdats(&self) -> Self::ComdatIterator<'_> {
448 WasmComdatIterator { file: self }
449 }
450
451 #[inline]
452 fn symbol_by_index(&self, index: SymbolIndex) -> Result<WasmSymbol<'data, '_>> {
453 let symbol = self
454 .symbols
455 .get(index.0)
456 .read_error("Invalid Wasm symbol index")?;
457 Ok(WasmSymbol { index, symbol })
458 }
459
460 fn symbols(&self) -> Self::SymbolIterator<'_> {
461 WasmSymbolIterator {
462 symbols: self.symbols.iter().enumerate(),
463 }
464 }
465
466 fn symbol_table(&self) -> Option<WasmSymbolTable<'data, '_>> {
467 Some(WasmSymbolTable {
468 symbols: &self.symbols,
469 })
470 }
471
472 fn dynamic_symbols(&self) -> Self::SymbolIterator<'_> {
473 WasmSymbolIterator {
474 symbols: [].iter().enumerate(),
475 }
476 }
477
478 #[inline]
479 fn dynamic_symbol_table(&self) -> Option<WasmSymbolTable<'data, '_>> {
480 None
481 }
482
483 #[inline]
484 fn dynamic_relocations(&self) -> Option<NoDynamicRelocationIterator> {
485 None
486 }
487
488 fn imports(&self) -> Result<Vec<Import<'data>>> {
489 // TODO: return entries in the import section
490 Ok(Vec::new())
491 }
492
493 fn exports(&self) -> Result<Vec<Export<'data>>> {
494 // TODO: return entries in the export section
495 Ok(Vec::new())
496 }
497
498 fn has_debug_symbols(&self) -> bool {
499 self.has_debug_symbols
500 }
501
502 fn relative_address_base(&self) -> u64 {
503 0
504 }
505
506 #[inline]
507 fn entry(&self) -> u64 {
508 self.entry
509 }
510
511 #[inline]
512 fn flags(&self) -> FileFlags {
513 FileFlags::None
514 }
515 }
516
517 /// An iterator for the segments in a [`WasmFile`].
518 ///
519 /// This is a stub that doesn't implement any functionality.
520 #[derive(Debug)]
521 pub struct WasmSegmentIterator<'data, 'file, R = &'data [u8]> {
522 #[allow(unused)]
523 file: &'file WasmFile<'data, R>,
524 }
525
526 impl<'data, 'file, R> Iterator for WasmSegmentIterator<'data, 'file, R> {
527 type Item = WasmSegment<'data, 'file, R>;
528
529 #[inline]
530 fn next(&mut self) -> Option<Self::Item> {
531 None
532 }
533 }
534
535 /// A segment in a [`WasmFile`].
536 ///
537 /// This is a stub that doesn't implement any functionality.
538 #[derive(Debug)]
539 pub struct WasmSegment<'data, 'file, R = &'data [u8]> {
540 #[allow(unused)]
541 file: &'file WasmFile<'data, R>,
542 }
543
544 impl<'data, 'file, R> read::private::Sealed for WasmSegment<'data, 'file, R> {}
545
546 impl<'data, 'file, R> ObjectSegment<'data> for WasmSegment<'data, 'file, R> {
547 #[inline]
548 fn address(&self) -> u64 {
549 unreachable!()
550 }
551
552 #[inline]
553 fn size(&self) -> u64 {
554 unreachable!()
555 }
556
557 #[inline]
558 fn align(&self) -> u64 {
559 unreachable!()
560 }
561
562 #[inline]
563 fn file_range(&self) -> (u64, u64) {
564 unreachable!()
565 }
566
567 fn data(&self) -> Result<&'data [u8]> {
568 unreachable!()
569 }
570
571 fn data_range(&self, _address: u64, _size: u64) -> Result<Option<&'data [u8]>> {
572 unreachable!()
573 }
574
575 #[inline]
576 fn name_bytes(&self) -> Result<Option<&[u8]>> {
577 unreachable!()
578 }
579
580 #[inline]
581 fn name(&self) -> Result<Option<&str>> {
582 unreachable!()
583 }
584
585 #[inline]
586 fn flags(&self) -> SegmentFlags {
587 unreachable!()
588 }
589 }
590
591 /// An iterator for the sections in a [`WasmFile`].
592 #[derive(Debug)]
593 pub struct WasmSectionIterator<'data, 'file, R = &'data [u8]> {
594 file: &'file WasmFile<'data, R>,
595 sections: slice::Iter<'file, SectionHeader<'data>>,
596 }
597
598 impl<'data, 'file, R> Iterator for WasmSectionIterator<'data, 'file, R> {
599 type Item = WasmSection<'data, 'file, R>;
600
601 fn next(&mut self) -> Option<Self::Item> {
602 let section = self.sections.next()?;
603 Some(WasmSection {
604 file: self.file,
605 section,
606 })
607 }
608 }
609
610 /// A section in a [`WasmFile`].
611 ///
612 /// Most functionality is provided by the [`ObjectSection`] trait implementation.
613 #[derive(Debug)]
614 pub struct WasmSection<'data, 'file, R = &'data [u8]> {
615 file: &'file WasmFile<'data, R>,
616 section: &'file SectionHeader<'data>,
617 }
618
619 impl<'data, 'file, R> read::private::Sealed for WasmSection<'data, 'file, R> {}
620
621 impl<'data, 'file, R: ReadRef<'data>> ObjectSection<'data> for WasmSection<'data, 'file, R> {
622 type RelocationIterator = WasmRelocationIterator<'data, 'file, R>;
623
624 #[inline]
625 fn index(&self) -> SectionIndex {
626 // Note that we treat all custom sections as index 0.
627 // This is ok because they are never looked up by index.
628 SectionIndex(self.section.id as usize)
629 }
630
631 #[inline]
632 fn address(&self) -> u64 {
633 0
634 }
635
636 #[inline]
637 fn size(&self) -> u64 {
638 let range = &self.section.range;
639 (range.end - range.start) as u64
640 }
641
642 #[inline]
643 fn align(&self) -> u64 {
644 1
645 }
646
647 #[inline]
648 fn file_range(&self) -> Option<(u64, u64)> {
649 let range = &self.section.range;
650 Some((range.start as _, range.end as _))
651 }
652
653 #[inline]
654 fn data(&self) -> Result<&'data [u8]> {
655 let range = &self.section.range;
656 self.file
657 .data
658 .read_bytes_at(range.start as u64, range.end as u64 - range.start as u64)
659 .read_error("Invalid Wasm section size or offset")
660 }
661
662 fn data_range(&self, _address: u64, _size: u64) -> Result<Option<&'data [u8]>> {
663 unimplemented!()
664 }
665
666 #[inline]
667 fn compressed_file_range(&self) -> Result<CompressedFileRange> {
668 Ok(CompressedFileRange::none(self.file_range()))
669 }
670
671 #[inline]
672 fn compressed_data(&self) -> Result<CompressedData<'data>> {
673 self.data().map(CompressedData::none)
674 }
675
676 #[inline]
677 fn name_bytes(&self) -> Result<&'data [u8]> {
678 self.name().map(str::as_bytes)
679 }
680
681 #[inline]
682 fn name(&self) -> Result<&'data str> {
683 Ok(match self.section.id {
684 SectionId::Custom => self.section.name,
685 SectionId::Type => "<type>",
686 SectionId::Import => "<import>",
687 SectionId::Function => "<function>",
688 SectionId::Table => "<table>",
689 SectionId::Memory => "<memory>",
690 SectionId::Global => "<global>",
691 SectionId::Export => "<export>",
692 SectionId::Start => "<start>",
693 SectionId::Element => "<element>",
694 SectionId::Code => "<code>",
695 SectionId::Data => "<data>",
696 SectionId::DataCount => "<data_count>",
697 SectionId::Tag => "<tag>",
698 })
699 }
700
701 #[inline]
702 fn segment_name_bytes(&self) -> Result<Option<&[u8]>> {
703 Ok(None)
704 }
705
706 #[inline]
707 fn segment_name(&self) -> Result<Option<&str>> {
708 Ok(None)
709 }
710
711 #[inline]
712 fn kind(&self) -> SectionKind {
713 match self.section.id {
714 SectionId::Custom => match self.section.name {
715 "reloc." | "linking" => SectionKind::Linker,
716 _ => SectionKind::Other,
717 },
718 SectionId::Type => SectionKind::Metadata,
719 SectionId::Import => SectionKind::Linker,
720 SectionId::Function => SectionKind::Metadata,
721 SectionId::Table => SectionKind::UninitializedData,
722 SectionId::Memory => SectionKind::UninitializedData,
723 SectionId::Global => SectionKind::Data,
724 SectionId::Export => SectionKind::Linker,
725 SectionId::Start => SectionKind::Linker,
726 SectionId::Element => SectionKind::Data,
727 SectionId::Code => SectionKind::Text,
728 SectionId::Data => SectionKind::Data,
729 SectionId::DataCount => SectionKind::UninitializedData,
730 SectionId::Tag => SectionKind::Data,
731 }
732 }
733
734 #[inline]
735 fn relocations(&self) -> WasmRelocationIterator<'data, 'file, R> {
736 WasmRelocationIterator(PhantomData)
737 }
738
739 fn relocation_map(&self) -> read::Result<RelocationMap> {
740 RelocationMap::new(self.file, self)
741 }
742
743 #[inline]
744 fn flags(&self) -> SectionFlags {
745 SectionFlags::None
746 }
747 }
748
749 /// An iterator for the COMDAT section groups in a [`WasmFile`].
750 ///
751 /// This is a stub that doesn't implement any functionality.
752 #[derive(Debug)]
753 pub struct WasmComdatIterator<'data, 'file, R = &'data [u8]> {
754 #[allow(unused)]
755 file: &'file WasmFile<'data, R>,
756 }
757
758 impl<'data, 'file, R> Iterator for WasmComdatIterator<'data, 'file, R> {
759 type Item = WasmComdat<'data, 'file, R>;
760
761 #[inline]
762 fn next(&mut self) -> Option<Self::Item> {
763 None
764 }
765 }
766
767 /// A COMDAT section group in a [`WasmFile`].
768 ///
769 /// This is a stub that doesn't implement any functionality.
770 #[derive(Debug)]
771 pub struct WasmComdat<'data, 'file, R = &'data [u8]> {
772 #[allow(unused)]
773 file: &'file WasmFile<'data, R>,
774 }
775
776 impl<'data, 'file, R> read::private::Sealed for WasmComdat<'data, 'file, R> {}
777
778 impl<'data, 'file, R> ObjectComdat<'data> for WasmComdat<'data, 'file, R> {
779 type SectionIterator = WasmComdatSectionIterator<'data, 'file, R>;
780
781 #[inline]
782 fn kind(&self) -> ComdatKind {
783 unreachable!();
784 }
785
786 #[inline]
787 fn symbol(&self) -> SymbolIndex {
788 unreachable!();
789 }
790
791 #[inline]
792 fn name_bytes(&self) -> Result<&'data [u8]> {
793 unreachable!();
794 }
795
796 #[inline]
797 fn name(&self) -> Result<&'data str> {
798 unreachable!();
799 }
800
801 #[inline]
802 fn sections(&self) -> Self::SectionIterator {
803 unreachable!();
804 }
805 }
806
807 /// An iterator for the sections in a COMDAT section group in a [`WasmFile`].
808 ///
809 /// This is a stub that doesn't implement any functionality.
810 #[derive(Debug)]
811 pub struct WasmComdatSectionIterator<'data, 'file, R = &'data [u8]> {
812 #[allow(unused)]
813 file: &'file WasmFile<'data, R>,
814 }
815
816 impl<'data, 'file, R> Iterator for WasmComdatSectionIterator<'data, 'file, R> {
817 type Item = SectionIndex;
818
819 fn next(&mut self) -> Option<Self::Item> {
820 None
821 }
822 }
823
824 /// A symbol table in a [`WasmFile`].
825 #[derive(Debug)]
826 pub struct WasmSymbolTable<'data, 'file> {
827 symbols: &'file [WasmSymbolInternal<'data>],
828 }
829
830 impl<'data, 'file> read::private::Sealed for WasmSymbolTable<'data, 'file> {}
831
832 impl<'data, 'file> ObjectSymbolTable<'data> for WasmSymbolTable<'data, 'file> {
833 type Symbol = WasmSymbol<'data, 'file>;
834 type SymbolIterator = WasmSymbolIterator<'data, 'file>;
835
836 fn symbols(&self) -> Self::SymbolIterator {
837 WasmSymbolIterator {
838 symbols: self.symbols.iter().enumerate(),
839 }
840 }
841
842 fn symbol_by_index(&self, index: SymbolIndex) -> Result<Self::Symbol> {
843 let symbol = self
844 .symbols
845 .get(index.0)
846 .read_error("Invalid Wasm symbol index")?;
847 Ok(WasmSymbol { index, symbol })
848 }
849 }
850
851 /// An iterator for the symbols in a [`WasmFile`].
852 #[derive(Debug)]
853 pub struct WasmSymbolIterator<'data, 'file> {
854 symbols: core::iter::Enumerate<slice::Iter<'file, WasmSymbolInternal<'data>>>,
855 }
856
857 impl<'data, 'file> Iterator for WasmSymbolIterator<'data, 'file> {
858 type Item = WasmSymbol<'data, 'file>;
859
860 fn next(&mut self) -> Option<Self::Item> {
861 let (index, symbol) = self.symbols.next()?;
862 Some(WasmSymbol {
863 index: SymbolIndex(index),
864 symbol,
865 })
866 }
867 }
868
869 /// A symbol in a [`WasmFile`].
870 ///
871 /// Most functionality is provided by the [`ObjectSymbol`] trait implementation.
872 #[derive(Clone, Copy, Debug)]
873 pub struct WasmSymbol<'data, 'file> {
874 index: SymbolIndex,
875 symbol: &'file WasmSymbolInternal<'data>,
876 }
877
878 #[derive(Clone, Debug)]
879 struct WasmSymbolInternal<'data> {
880 name: &'data str,
881 address: u64,
882 size: u64,
883 kind: SymbolKind,
884 section: SymbolSection,
885 scope: SymbolScope,
886 }
887
888 impl<'data, 'file> read::private::Sealed for WasmSymbol<'data, 'file> {}
889
890 impl<'data, 'file> ObjectSymbol<'data> for WasmSymbol<'data, 'file> {
891 #[inline]
892 fn index(&self) -> SymbolIndex {
893 self.index
894 }
895
896 #[inline]
897 fn name_bytes(&self) -> read::Result<&'data [u8]> {
898 Ok(self.symbol.name.as_bytes())
899 }
900
901 #[inline]
902 fn name(&self) -> read::Result<&'data str> {
903 Ok(self.symbol.name)
904 }
905
906 #[inline]
907 fn address(&self) -> u64 {
908 self.symbol.address
909 }
910
911 #[inline]
912 fn size(&self) -> u64 {
913 self.symbol.size
914 }
915
916 #[inline]
917 fn kind(&self) -> SymbolKind {
918 self.symbol.kind
919 }
920
921 #[inline]
922 fn section(&self) -> SymbolSection {
923 self.symbol.section
924 }
925
926 #[inline]
927 fn is_undefined(&self) -> bool {
928 self.symbol.section == SymbolSection::Undefined
929 }
930
931 #[inline]
932 fn is_definition(&self) -> bool {
933 (self.symbol.kind == SymbolKind::Text || self.symbol.kind == SymbolKind::Data)
934 && self.symbol.section != SymbolSection::Undefined
935 }
936
937 #[inline]
938 fn is_common(&self) -> bool {
939 self.symbol.section == SymbolSection::Common
940 }
941
942 #[inline]
943 fn is_weak(&self) -> bool {
944 false
945 }
946
947 #[inline]
948 fn scope(&self) -> SymbolScope {
949 self.symbol.scope
950 }
951
952 #[inline]
953 fn is_global(&self) -> bool {
954 self.symbol.scope != SymbolScope::Compilation
955 }
956
957 #[inline]
958 fn is_local(&self) -> bool {
959 self.symbol.scope == SymbolScope::Compilation
960 }
961
962 #[inline]
963 fn flags(&self) -> SymbolFlags<SectionIndex, SymbolIndex> {
964 SymbolFlags::None
965 }
966 }
967
968 /// An iterator for the relocations for a [`WasmSection`].
969 ///
970 /// This is a stub that doesn't implement any functionality.
971 #[derive(Debug)]
972 pub struct WasmRelocationIterator<'data, 'file, R = &'data [u8]>(
973 PhantomData<(&'data (), &'file (), R)>,
974 );
975
976 impl<'data, 'file, R> Iterator for WasmRelocationIterator<'data, 'file, R> {
977 type Item = (u64, Relocation);
978
979 #[inline]
980 fn next(&mut self) -> Option<Self::Item> {
981 None
982 }
983 }