Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Use `gimli::write::Dwarf::convert_with_filter` for DWARF transform (#12428)

Philip Craigc4a38d67a935
diff --git a/crates/cranelift/src/debug/gc.rs b/crates/cranelift/src/debug/gc.rs
index 0a6673332c..a7c8657421 100644
--- a/crates/cranelift/src/debug/gc.rs
+++ b/crates/cranelift/src/debug/gc.rs
@@ -1,154 +1,25 @@
use crate::debug::Reader;
use crate::debug::transform::AddressTransform;
-use gimli::UnitSectionOffset;
use gimli::constants;
use gimli::read;
-use std::collections::{HashMap, HashSet};
-
-#[derive(Debug)]
-pub struct Dependencies {
- edges: HashMap<UnitSectionOffset, HashSet<UnitSectionOffset>>,
- roots: HashSet<UnitSectionOffset>,
-}
-
-impl Dependencies {
- fn new() -> Dependencies {
- Dependencies {
- edges: HashMap::new(),
- roots: HashSet::new(),
- }
- }
-
- fn add_edge(&mut self, a: UnitSectionOffset, b: UnitSectionOffset) {
- use std::collections::hash_map::Entry;
- match self.edges.entry(a) {
- Entry::Occupied(mut o) => {
- o.get_mut().insert(b);
- }
- Entry::Vacant(v) => {
- let mut set = HashSet::new();
- set.insert(b);
- v.insert(set);
- }
- }
- }
-
- fn add_root(&mut self, root: UnitSectionOffset) {
- self.roots.insert(root);
- }
-
- pub fn get_reachable(&self) -> HashSet<UnitSectionOffset> {
- let mut reachable = self.roots.clone();
- let mut queue = Vec::new();
- for i in self.roots.iter() {
- if let Some(deps) = self.edges.get(i) {
- for j in deps {
- if reachable.contains(j) {
- continue;
- }
- reachable.insert(*j);
- queue.push(*j);
- }
- }
- }
- while let Some(i) = queue.pop() {
- if let Some(deps) = self.edges.get(&i) {
- for j in deps {
- if reachable.contains(j) {
- continue;
- }
- reachable.insert(*j);
- queue.push(*j);
- }
- }
- }
- reachable
- }
-}
+use gimli::write;
pub fn build_dependencies(
- dwarf: &read::Dwarf<Reader<'_>>,
+ filter: &mut write::FilterUnitSection<'_, Reader<'_>>,
at: &AddressTransform,
-) -> read::Result<Dependencies> {
- let mut deps = Dependencies::new();
- let mut units = dwarf.units();
- while let Some(unit) = units.next()? {
- build_unit_dependencies(unit, dwarf, at, &mut deps)?;
+) -> write::ConvertResult<()> {
+ while let Some(mut unit) = filter.read_unit()? {
+ build_die_dependencies(&mut unit, at)?;
}
- Ok(deps)
-}
-
-fn build_unit_dependencies(
- header: read::UnitHeader<Reader<'_>>,
- dwarf: &read::Dwarf<Reader<'_>>,
- at: &AddressTransform,
- deps: &mut Dependencies,
-) -> read::Result<()> {
- let unit = dwarf.unit(header)?;
- let unit = unit.unit_ref(dwarf);
- let mut tree = unit.entries_tree(None)?;
- let root = tree.root()?;
- build_die_dependencies(root, unit, at, deps)?;
Ok(())
}
-fn has_die_back_edge(die: &read::DebuggingInformationEntry<Reader<'_>>) -> read::Result<bool> {
- // DIEs can be broadly divided into three categories:
- // 1. Extensions of their parents; effectively attributes: DW_TAG_variable, DW_TAG_member, etc.
- // 2. Standalone entities referred to by other DIEs via 'reference' class attributes: types.
- // 3. Structural entities that organize how the above relate to each other: namespaces.
- // Here, we must make sure to return 'true' for DIEs in the first category since stripping them,
- // provided their parent is alive, is always wrong. To be conservatively correct in the face
- // of new/vendor tags, we maintain a "(mostly) known good" list of tags of the latter categories.
- let result = match die.tag() {
- constants::DW_TAG_array_type
- | constants::DW_TAG_atomic_type
- | constants::DW_TAG_base_type
- | constants::DW_TAG_class_type
- | constants::DW_TAG_const_type
- | constants::DW_TAG_dwarf_procedure
- | constants::DW_TAG_entry_point
- | constants::DW_TAG_enumeration_type
- | constants::DW_TAG_pointer_type
- | constants::DW_TAG_ptr_to_member_type
- | constants::DW_TAG_reference_type
- | constants::DW_TAG_restrict_type
- | constants::DW_TAG_rvalue_reference_type
- | constants::DW_TAG_string_type
- | constants::DW_TAG_structure_type
- | constants::DW_TAG_typedef
- | constants::DW_TAG_union_type
- | constants::DW_TAG_unspecified_type
- | constants::DW_TAG_volatile_type
- | constants::DW_TAG_coarray_type
- | constants::DW_TAG_common_block
- | constants::DW_TAG_dynamic_type
- | constants::DW_TAG_file_type
- | constants::DW_TAG_immutable_type
- | constants::DW_TAG_interface_type
- | constants::DW_TAG_set_type
- | constants::DW_TAG_shared_type
- | constants::DW_TAG_subroutine_type
- | constants::DW_TAG_packed_type
- | constants::DW_TAG_template_alias
- | constants::DW_TAG_namelist
- | constants::DW_TAG_namespace
- | constants::DW_TAG_imported_unit
- | constants::DW_TAG_imported_declaration
- | constants::DW_TAG_imported_module
- | constants::DW_TAG_module => false,
- constants::DW_TAG_subprogram => die.attr(constants::DW_AT_declaration).is_some(),
- _ => true,
- };
- Ok(result)
-}
-
fn has_valid_code_range(
- die: &read::DebuggingInformationEntry<Reader<'_>>,
- unit: read::UnitRef<Reader<'_>>,
+ die: &write::FilterUnitEntry<'_, Reader<'_>>,
at: &AddressTransform,
) -> read::Result<bool> {
- match die.tag() {
+ let unit = die.read_unit;
+ match die.tag {
constants::DW_TAG_subprogram => {
if let Some(ranges_attr) = die.attr_value(constants::DW_AT_ranges) {
let offset = match ranges_attr {
@@ -215,50 +86,14 @@ fn has_valid_code_range(
}
fn build_die_dependencies(
- die: read::EntriesTreeNode<Reader<'_>>,
- unit: read::UnitRef<Reader<'_>>,
+ unit: &mut write::FilterUnit<'_, Reader<'_>>,
at: &AddressTransform,
- deps: &mut Dependencies,
-) -> read::Result<()> {
- let entry = die.entry();
- let offset = entry.offset().to_unit_section_offset(&unit);
- for attr in entry.attrs() {
- build_attr_dependencies(attr, offset, unit, at, deps)?;
- }
-
- let mut children = die.children();
- while let Some(child) = children.next()? {
- let child_entry = child.entry();
- let child_offset = child_entry.offset().to_unit_section_offset(&unit);
- deps.add_edge(child_offset, offset);
- if has_die_back_edge(child_entry)? {
- deps.add_edge(offset, child_offset);
- }
- if has_valid_code_range(child_entry, unit, at)? {
- deps.add_root(child_offset);
+) -> write::ConvertResult<()> {
+ let mut die = write::FilterUnitEntry::null(unit.read_unit);
+ while unit.read_entry(&mut die)? {
+ if has_valid_code_range(&die, at)? {
+ unit.require_entry(die.offset);
}
- build_die_dependencies(child, unit, at, deps)?;
- }
- Ok(())
-}
-
-fn build_attr_dependencies(
- attr: &read::Attribute<Reader<'_>>,
- offset: UnitSectionOffset,
- unit: read::UnitRef<Reader<'_>>,
- _at: &AddressTransform,
- deps: &mut Dependencies,
-) -> read::Result<()> {
- match attr.value() {
- read::AttributeValue::UnitRef(val) => {
- let ref_offset = val.to_unit_section_offset(&unit);
- deps.add_edge(offset, ref_offset);
- }
- read::AttributeValue::DebugInfoRef(val) => {
- let ref_offset = UnitSectionOffset(val.0);
- deps.add_edge(offset, ref_offset);
- }
- _ => (),
}
Ok(())
}
diff --git a/crates/cranelift/src/debug/transform/attr.rs b/crates/cranelift/src/debug/transform/attr.rs
index 7ac15131a9..6b2cceefb6 100644
--- a/crates/cranelift/src/debug/transform/attr.rs
+++ b/crates/cranelift/src/debug/transform/attr.rs
@@ -2,27 +2,18 @@ use crate::debug::Reader;
use crate::debug::transform::utils::resolve_die_ref;
use super::address_transform::AddressTransform;
+use super::dbi_log;
use super::expression::{CompiledExpression, FunctionFrameInfo, compile_expression};
use super::range_info_builder::RangeInfoBuilder;
-use super::refs::{PendingDebugInfoRefs, PendingUnitRefs};
use super::unit::InheritedAttr;
-use super::{TransformError, dbi_log};
use cranelift_codegen::isa::TargetIsa;
-use gimli::{
- AttributeValue, DebugLineOffset, DebuggingInformationEntry, UnitOffset, UnitRef, write,
-};
-use wasmtime_environ::error::{Error, bail};
+use gimli::{AttributeValue, UnitOffset, write};
+use wasmtime_environ::error::Error;
#[derive(Debug)]
-pub(crate) enum EntryAttributesContext<'a> {
- Root(Option<DebugLineOffset>),
- Children {
- depth: usize,
- subprograms: &'a mut InheritedAttr<SubprogramContext>,
- file_map: &'a [write::FileId],
- file_index_base: u64,
- frame_base: Option<&'a CompiledExpression>,
- },
+pub(crate) struct EntryAttributesContext<'a> {
+ pub subprograms: &'a mut InheritedAttr<SubprogramContext>,
+ pub frame_base: Option<&'a CompiledExpression>,
}
#[derive(Debug)]
@@ -47,20 +38,17 @@ fn is_exprloc_to_loclist_allowed(attr_name: gimli::constants::DwAt) -> bool {
}
pub(crate) fn clone_die_attributes<'a>(
- unit: UnitRef<Reader<'a>>,
- entry: &DebuggingInformationEntry<Reader<'a>>,
+ convert_unit: &mut gimli::write::ConvertUnit<Reader<'a>>,
+ entry: &gimli::write::ConvertUnitEntry<Reader<'a>>,
addr_tr: &AddressTransform,
frame_info: Option<&FunctionFrameInfo>,
- out_unit: &mut write::Unit,
out_entry_id: write::UnitEntryId,
subprogram_range_builder: Option<RangeInfoBuilder>,
scope_ranges: Option<&Vec<(u64, u64)>>,
- out_strings: &mut write::StringTable,
- pending_die_refs: &mut PendingUnitRefs,
- pending_di_refs: &mut PendingDebugInfoRefs,
- mut attr_context: EntryAttributesContext<'_>,
+ mut attr_context: EntryAttributesContext,
isa: &dyn TargetIsa,
) -> Result<(), Error> {
+ let unit = entry.read_unit;
let unit_encoding = unit.encoding();
let range_info = if let Some(subprogram_range_builder) = subprogram_range_builder {
@@ -69,14 +57,14 @@ pub(crate) fn clone_die_attributes<'a>(
// FIXME for CU: currently address_transform operate on a single
// function range, and when CU spans multiple ranges the
// transformation may be incomplete.
- RangeInfoBuilder::from(unit, entry)?
+ RangeInfoBuilder::from(entry)?
};
- range_info.build(addr_tr, out_unit, out_entry_id);
+ range_info.build(addr_tr, convert_unit.unit, out_entry_id);
let mut is_obj_ptr = false;
- prepare_die_context(unit, entry, &mut attr_context, &mut is_obj_ptr)?;
+ prepare_die_context(entry, &mut attr_context, &mut is_obj_ptr)?;
- for attr in entry.attrs() {
+ for attr in &entry.attrs {
match attr.name() {
gimli::DW_AT_low_pc | gimli::DW_AT_high_pc | gimli::DW_AT_ranges => {
// Handled by RangeInfoBuilder.
@@ -87,40 +75,21 @@ pub(crate) fn clone_die_attributes<'a>(
// we translate all pointers to wrapper types), making it unusable.
// To remedy this, we 'strip' instance-ness off of methods by removing
// DW_AT_object_pointer and renaming 'this' to '__this'.
- if let EntryAttributesContext::Children {
- depth,
- ref mut subprograms,
- ..
- } = attr_context
+ if let Some(ref mut subprogram) =
+ attr_context.subprograms.top_with_depth_mut(entry.depth)
{
- if let Some(ref mut subprogram) = subprograms.top_with_depth_mut(depth) {
- // We expect this to reference a child entry in the same unit.
- if let Some(unit_offs) = match attr.value() {
- AttributeValue::DebugInfoRef(di_ref) => {
- di_ref.to_unit_offset(&unit.header)
- }
- AttributeValue::UnitRef(unit_ref) => Some(unit_ref),
- _ => None,
- } {
- subprogram.obj_ptr = unit_offs;
- dbi_log!("Stripped DW_AT_object_pointer");
- continue;
- }
+ // We expect this to reference a child entry in the same unit.
+ if let Some(unit_offs) = match attr.value() {
+ AttributeValue::DebugInfoRef(di_ref) => di_ref.to_unit_offset(&unit.header),
+ AttributeValue::UnitRef(unit_ref) => Some(unit_ref),
+ _ => None,
+ } {
+ subprogram.obj_ptr = unit_offs;
+ dbi_log!("Stripped DW_AT_object_pointer");
+ continue;
}
}
}
- gimli::DW_AT_str_offsets_base
- | gimli::DW_AT_addr_base
- | gimli::DW_AT_rnglists_base
- | gimli::DW_AT_loclists_base
- | gimli::DW_AT_dwo_name
- | gimli::DW_AT_GNU_addr_base
- | gimli::DW_AT_GNU_ranges_base
- | gimli::DW_AT_GNU_dwo_name
- | gimli::DW_AT_GNU_dwo_id => {
- // DWARF encoding details that we don't need to copy.
- continue;
- }
_ => {}
}
@@ -139,8 +108,10 @@ pub(crate) fn clone_die_attributes<'a>(
new_name.as_str()
);
- let attr_value = write::AttributeValue::StringRef(out_strings.add(new_name));
- out_unit
+ let attr_value =
+ write::AttributeValue::StringRef(convert_unit.strings.add(new_name));
+ convert_unit
+ .unit
.get_mut(out_entry_id)
.set(gimli::DW_AT_name, attr_value);
continue;
@@ -160,64 +131,15 @@ pub(crate) fn clone_die_attributes<'a>(
let addr = addr_tr.translate(u).unwrap_or(write::Address::Constant(0));
write::AttributeValue::Address(addr)
}
- AttributeValue::Block(d) => write::AttributeValue::Block(d.to_vec()),
- AttributeValue::Udata(u) => write::AttributeValue::Udata(u),
- AttributeValue::Data1(d) => write::AttributeValue::Data1(d),
- AttributeValue::Data2(d) => write::AttributeValue::Data2(d),
- AttributeValue::Data4(d) => write::AttributeValue::Data4(d),
- AttributeValue::Data8(d) => write::AttributeValue::Data8(d),
- AttributeValue::Sdata(d) => write::AttributeValue::Sdata(d),
- AttributeValue::Flag(f) => write::AttributeValue::Flag(f),
- AttributeValue::DebugLineRef(line_program_offset) => {
- if let EntryAttributesContext::Root(o) = attr_context {
- if o != Some(line_program_offset) {
- return Err(TransformError("invalid debug_line offset").into());
- }
- write::AttributeValue::LineProgramRef
- } else {
- return Err(TransformError("unexpected debug_line index attribute").into());
- }
- }
- AttributeValue::FileIndex(i) => {
- if let EntryAttributesContext::Children {
- file_map,
- file_index_base,
- ..
- } = attr_context
- {
- let index = usize::try_from(i - file_index_base)
- .ok()
- .and_then(|i| file_map.get(i).copied());
- match index {
- Some(index) => write::AttributeValue::FileIndex(Some(index)),
- // This was seen to be invalid in #8884 and #8904 so
- // ignore this seemingly invalid DWARF from LLVM
- None => continue,
- }
- } else {
- return Err(TransformError("unexpected file index attribute").into());
- }
- }
- AttributeValue::String(d) => write::AttributeValue::String(d.to_vec()),
- AttributeValue::DebugStrRef(_) | AttributeValue::DebugStrOffsetsIndex(_) => {
- let s = unit.attr_string(attr_value)?.to_vec();
- write::AttributeValue::StringRef(out_strings.add(s))
- }
AttributeValue::RangeListsRef(_) | AttributeValue::DebugRngListsIndex(_) => {
let r = unit.attr_ranges_offset(attr_value)?.unwrap();
let range_info = RangeInfoBuilder::from_ranges_ref(unit, r)?;
- let range_list_id = range_info.build_ranges(addr_tr, &mut out_unit.ranges);
+ let range_list_id = range_info.build_ranges(addr_tr, &mut convert_unit.unit.ranges);
write::AttributeValue::RangeListRef(range_list_id)
}
AttributeValue::LocationListsRef(_) | AttributeValue::DebugLocListsIndex(_) => {
- let r = unit.attr_locations_offset(attr_value)?.unwrap();
- let mut locs = unit.locations(r)?;
- let frame_base =
- if let EntryAttributesContext::Children { frame_base, .. } = attr_context {
- frame_base
- } else {
- None
- };
+ let mut locs = unit.attr_locations(attr_value)?.unwrap();
+ let frame_base = attr_context.frame_base;
let mut result: Option<Vec<_>> = None;
while let Some(loc) = locs.next()? {
@@ -254,7 +176,10 @@ pub(crate) fn clone_die_attributes<'a>(
if result.is_none() {
continue; // no valid locations
}
- let list_id = out_unit.locations.add(write::LocationList(result.unwrap()));
+ let list_id = convert_unit
+ .unit
+ .locations
+ .add(write::LocationList(result.unwrap()));
write::AttributeValue::LocationListRef(list_id)
}
AttributeValue::Exprloc(_) if attr.name() == gimli::DW_AT_frame_base => {
@@ -265,12 +190,7 @@ pub(crate) fn clone_die_attributes<'a>(
write::AttributeValue::Exprloc(cfa)
}
AttributeValue::Exprloc(ref expr) => {
- let frame_base =
- if let EntryAttributesContext::Children { frame_base, .. } = attr_context {
- frame_base
- } else {
- None
- };
+ let frame_base = attr_context.frame_base;
if let Some(expr) = compile_expression(expr, unit_encoding, frame_base)? {
if expr.is_simple() {
if let Some(expr) = expr.build() {
@@ -319,7 +239,8 @@ pub(crate) fn clone_die_attributes<'a>(
data,
});
}
- let list_id = out_unit.locations.add(write::LocationList(locs));
+ let list_id =
+ convert_unit.unit.locations.add(write::LocationList(locs));
write::AttributeValue::LocationListRef(list_id)
} else {
continue;
@@ -333,53 +254,41 @@ pub(crate) fn clone_die_attributes<'a>(
continue; // ignore attribute
}
}
- AttributeValue::Encoding(e) => write::AttributeValue::Encoding(e),
- AttributeValue::DecimalSign(e) => write::AttributeValue::DecimalSign(e),
- AttributeValue::Endianity(e) => write::AttributeValue::Endianity(e),
- AttributeValue::Accessibility(e) => write::AttributeValue::Accessibility(e),
- AttributeValue::Visibility(e) => write::AttributeValue::Visibility(e),
- AttributeValue::Virtuality(e) => write::AttributeValue::Virtuality(e),
- AttributeValue::Language(e) => write::AttributeValue::Language(e),
- AttributeValue::AddressClass(e) => write::AttributeValue::AddressClass(e),
- AttributeValue::IdentifierCase(e) => write::AttributeValue::IdentifierCase(e),
- AttributeValue::CallingConvention(e) => write::AttributeValue::CallingConvention(e),
- AttributeValue::Inline(e) => write::AttributeValue::Inline(e),
- AttributeValue::Ordering(e) => write::AttributeValue::Ordering(e),
- AttributeValue::UnitRef(offset) => {
- pending_die_refs.insert(out_entry_id, attr.name(), offset);
- continue;
- }
- AttributeValue::DebugInfoRef(offset) => {
- pending_di_refs.insert(out_entry_id, attr.name(), offset);
- continue;
- }
- a => bail!("Unexpected attribute: {a:?}"),
+ // No other attributes contain addresses or address offsets.
+ _ => match convert_unit.convert_attribute_value(unit, attr, &|_| None) {
+ Ok(value) => value,
+ Err(e) => {
+ // Invalid `FileIndex` was seen in #8884 and #8904. In general it's
+ // better to ignore invalid or unknown DWARF rather then failing outright.
+ dbi_log!(
+ "Ignoring entry {:x?} attribute {} = {:x?}: {e}",
+ entry.offset.to_unit_section_offset(&convert_unit.read_unit),
+ attr.name(),
+ attr_value,
+ );
+ continue;
+ }
+ },
};
- let out_entry: &mut write::DebuggingInformationEntry = out_unit.get_mut(out_entry_id);
+ let out_entry = convert_unit.unit.get_mut(out_entry_id);
out_entry.set(attr.name(), out_attr_value);
}
Ok(())
}
fn prepare_die_context<'a>(
- unit: UnitRef<Reader<'a>>,
- entry: &DebuggingInformationEntry<Reader<'a>>,
- attr_context: &mut EntryAttributesContext<'_>,
+ entry: &gimli::write::ConvertUnitEntry<Reader<'a>>,
+ attr_context: &mut EntryAttributesContext,
is_obj_ptr: &mut bool,
) -> Result<(), Error> {
- let EntryAttributesContext::Children {
- depth, subprograms, ..
- } = attr_context
- else {
- return Ok(());
- };
+ let subprograms = &mut attr_context.subprograms;
// Update the current context based on what kind of entry this is.
- match entry.tag() {
+ match entry.tag {
gimli::DW_TAG_subprogram | gimli::DW_TAG_inlined_subroutine | gimli::DW_TAG_entry_point => {
// Push the 'context' of there being no parameters (yet).
subprograms.push(
- *depth,
+ entry.depth,
SubprogramContext {
obj_ptr: UnitOffset { 0: 0 },
param_num: -1,
@@ -390,11 +299,11 @@ fn prepare_die_context<'a>(
// Formal parameter tags can be parented by catch blocks
// and such - not just subprogram DIEs. So we need to check
// that this DIE is indeed a direct child of a subprogram.
- if let Some(subprogram) = subprograms.top_with_depth_mut(*depth - 1) {
+ if let Some(subprogram) = subprograms.top_with_depth_mut(entry.depth - 1) {
subprogram.param_num += 1;
- if subprogram.obj_ptr == entry.offset()
- || is_obj_ptr_param(unit, entry, subprogram.param_num)?
+ if subprogram.obj_ptr == entry.offset
+ || is_obj_ptr_param(entry, subprogram.param_num)?
{
*is_obj_ptr = true;
}
@@ -405,12 +314,12 @@ fn prepare_die_context<'a>(
Ok(())
}
-fn is_obj_ptr_param<'a>(
- unit: UnitRef<Reader<'a>>,
- entry: &DebuggingInformationEntry<Reader<'a>>,
+fn is_obj_ptr_param(
+ entry: &gimli::write::ConvertUnitEntry<Reader<'_>>,
param_num: isize,
) -> Result<bool, Error> {
- debug_assert!(entry.tag() == gimli::DW_TAG_formal_parameter);
+ debug_assert_eq!(entry.tag, gimli::DW_TAG_formal_parameter);
+ let unit = entry.read_unit;
// This logic was taken loosely from LLDB. It is known
// that it is not fully correct (doesn't handle 'deduced
@@ -427,7 +336,7 @@ fn is_obj_ptr_param<'a>(
// Finally, a type check. We expect a pointer.
if let Some(type_attr) = entry.attr_value(gimli::DW_AT_type) {
if let Some(type_die) = resolve_die_ref(unit, &type_attr)? {
- return Ok(type_die.tag() == gimli::DW_TAG_pointer_type);
+ return Ok(type_die.tag == gimli::DW_TAG_pointer_type);
}
}
}
diff --git a/crates/cranelift/src/debug/transform/debug_transform_logging.rs b/crates/cranelift/src/debug/transform/debug_transform_logging.rs
index c967d4904a..47033cdde8 100644
--- a/crates/cranelift/src/debug/transform/debug_transform_logging.rs
+++ b/crates/cranelift/src/debug/transform/debug_transform_logging.rs
@@ -1,7 +1,7 @@
use crate::{debug::Reader, translate::get_vmctx_value_label};
use core::fmt;
use cranelift_codegen::{LabelValueLoc, ValueLabelsRanges, ir::ValueLabel, isa::TargetIsa};
-use gimli::{AttributeValue, DebuggingInformationEntry, LittleEndian, UnitOffset, UnitRef, write};
+use gimli::{AttributeValue, LittleEndian, UnitRef, write};
macro_rules! dbi_log_enabled {
() => {
@@ -45,49 +45,44 @@ pub fn log_get_cu_summary<'a, 'r>(unit: UnitRef<'a, Reader<'r>>) -> CompileUnitS
}
pub struct DieRefSummary<'a, 'r> {
- unit: UnitRef<'a, Reader<'r>>,
- unit_ref: UnitOffset,
+ entry: &'a write::ConvertUnitEntry<'a, Reader<'r>>,
}
impl<'a, 'r> fmt::Debug for DieRefSummary<'a, 'r> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- let section_offs = self.unit_ref.to_unit_section_offset(&self.unit);
+ let section_offs = self
+ .entry
+ .offset
+ .to_unit_section_offset(&self.entry.read_unit);
write!(f, "0x{:08x}", section_offs.0)
}
}
pub fn log_get_die_ref<'a, 'r>(
- unit: UnitRef<'a, Reader<'r>>,
- unit_ref: UnitOffset,
+ entry: &'a write::ConvertUnitEntry<'a, Reader<'r>>,
) -> DieRefSummary<'a, 'r> {
- DieRefSummary { unit, unit_ref }
+ DieRefSummary { entry }
}
struct DieDetailedSummary<'a, 'r> {
- unit: UnitRef<'a, Reader<'r>>,
- die: &'a DebuggingInformationEntry<Reader<'r>>,
+ entry: &'a write::ConvertUnitEntry<'a, Reader<'r>>,
}
-pub fn log_begin_input_die<'r>(
- unit: UnitRef<Reader<'r>>,
- die: &DebuggingInformationEntry<Reader<'r>>,
- depth: isize,
-) {
+pub fn log_begin_input_die<'a, 'r>(entry: &'a write::ConvertUnitEntry<'a, Reader<'r>>) {
dbi_log!(
"=== Begin DIE at {:?} (depth = {}):\n{:?}",
- log_get_die_ref(unit, die.offset()),
- depth,
- DieDetailedSummary { unit, die }
+ log_get_die_ref(entry),
+ entry.depth,
+ DieDetailedSummary { entry }
);
}
impl<'a, 'r> fmt::Debug for DieDetailedSummary<'a, 'r> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- let die = self.die;
- let unit = self.unit;
- write!(f, "{}\n", die.tag())?;
+ let unit = self.entry.read_unit;
+ write!(f, "{}\n", self.entry.tag)?;
- for attr in die.attrs() {
+ for attr in &self.entry.attrs {
write!(f, " {} (", attr.name())?;
let attr_value = attr.value();
match attr_value {
@@ -233,35 +228,27 @@ impl<'a> fmt::Debug for OutDieDetailedSummary<'a> {
}
pub fn log_end_output_die(
- input_die: &DebuggingInformationEntry<Reader<'_>>,
- input_unit: UnitRef<Reader<'_>>,
die_id: write::UnitEntryId,
- unit: &write::Unit,
- strings: &write::StringTable,
- depth: isize,
+ entry: &write::ConvertUnitEntry<'_, Reader<'_>>,
+ unit: &write::ConvertUnit<'_, Reader<'_>>,
) {
dbi_log!(
"=== End DIE at {:?} (depth = {}):\n{:?}",
- log_get_die_ref(input_unit, input_die.offset()),
- depth,
+ log_get_die_ref(entry),
+ entry.depth,
OutDieDetailedSummary {
die_id,
- unit,
- strings
+ unit: &unit.unit,
+ strings: &unit.strings,
}
);
}
-pub fn log_end_output_die_skipped(
- input_die: &DebuggingInformationEntry<Reader<'_>>,
- input_unit: UnitRef<Reader<'_>>,
- reason: &str,
- depth: isize,
-) {
+pub fn log_end_output_die_skipped(entry: &write::ConvertUnitEntry<'_, Reader<'_>>, reason: &str) {
dbi_log!(
"=== End DIE at {:?} (depth = {}):\n Skipped as {}\n",
- log_get_die_ref(input_unit, input_die.offset()),
- depth,
+ log_get_die_ref(entry),
+ entry.depth,
reason
);
}
diff --git a/crates/cranelift/src/debug/transform/line_program.rs b/crates/cranelift/src/debug/transform/line_program.rs
index 18cf56da91..10106123ac 100644
--- a/crates/cranelift/src/debug/transform/line_program.rs
+++ b/crates/cranelift/src/debug/transform/line_program.rs
@@ -1,259 +1,67 @@
-use super::TransformError;
use super::address_transform::AddressTransform;
use crate::debug::Reader;
-use gimli::{DebugLineOffset, LineEncoding, UnitRef, write};
-use wasmtime_environ::DefinedFuncIndex;
-use wasmtime_environ::error::{Error, bail};
-
-#[derive(Debug)]
-enum SavedLineProgramRow {
- Normal {
- address: u64,
- op_index: u64,
- file_index: u64,
- line: u64,
- column: u64,
- discriminator: u64,
- is_stmt: bool,
- basic_block: bool,
- prologue_end: bool,
- epilogue_begin: bool,
- isa: u64,
- },
- EndOfSequence,
-}
-
-#[derive(Debug)]
-struct FuncRows {
- index: DefinedFuncIndex,
- sorted_rows: Vec<(u64, SavedLineProgramRow)>,
-}
-
-#[derive(Debug, Eq, PartialEq)]
-enum ReadLineProgramState {
- SequenceEnded,
- ReadSequence(DefinedFuncIndex),
- IgnoreSequence,
-}
+use gimli::write;
+use wasmtime_environ::error::Error;
pub(crate) fn clone_line_program(
- unit: UnitRef<Reader<'_>>,
- comp_name: Option<Reader<'_>>,
+ mut transform: write::ConvertLineProgram<'_, Reader<'_>>,
addr_tr: &AddressTransform,
- out_encoding: gimli::Encoding,
- out_strings: &mut write::StringTable,
-) -> Result<(write::LineProgram, DebugLineOffset, Vec<write::FileId>, u64), Error> {
- if let Some(program) = unit.line_program.clone() {
- let header = program.header();
- let offset = header.offset();
- let file_index_base = if header.version() < 5 { 1 } else { 0 };
- assert!(header.version() <= 5, "not supported 6");
- let line_encoding = LineEncoding {
- minimum_instruction_length: header.minimum_instruction_length(),
- maximum_operations_per_instruction: header.maximum_operations_per_instruction(),
- default_is_stmt: header.default_is_stmt(),
- line_base: header.line_base(),
- line_range: header.line_range(),
+) -> Result<(write::LineProgram, Vec<write::FileId>), Error> {
+ while let Some(write::ConvertLineSequence {
+ start,
+ rows: saved_rows,
+ ..
+ }) = transform.read_sequence()?
+ {
+ let Some(start) = start else {
+ continue;
};
- let out_comp_dir = match header.directory(0) {
- Some(comp_dir) => clone_line_string(
- unit.attr_string(comp_dir)?,
- gimli::DW_FORM_string,
- out_strings,
- )?,
- None => write::LineString::String(Vec::new()),
+ if start == 0 {
+ continue;
+ }
+ let Some(index) = addr_tr.find_func_index(start) else {
+ // Some non-existent address found.
+ continue;
};
- let out_comp_name = match comp_name {
- Some(comp_name) => clone_line_string(comp_name, gimli::DW_FORM_strp, out_strings)?,
- None => write::LineString::String(Vec::new()),
+ let Some(map) = addr_tr.map().get(index) else {
+ continue; // no code generated
};
-
- let mut out_program = write::LineProgram::new(
- out_encoding,
- line_encoding,
- out_comp_dir,
- None,
- out_comp_name,
- None,
- );
- let mut dirs = Vec::new();
- dirs.push(out_program.default_directory());
- for dir_attr in header.include_directories() {
- let dir_id = out_program.add_directory(clone_line_string(
- unit.attr_string(*dir_attr)?,
- gimli::DW_FORM_string,
- out_strings,
- )?);
- dirs.push(dir_id);
- }
- let mut files = Vec::new();
- // Since we are outputting DWARF-4, perform base change.
- let directory_index_correction = if header.version() >= 5 { 1 } else { 0 };
- for file_entry in header.file_names() {
- let dir_index = file_entry.directory_index() + directory_index_correction;
- let dir_id = dirs[dir_index as usize];
- let file_id = out_program.add_file(
- clone_line_string(
- unit.attr_string(file_entry.path_name())?,
- gimli::DW_FORM_string,
- out_strings,
- )?,
- dir_id,
- None,
- );
- files.push(file_id);
- }
-
- let mut rows = program.rows();
- let mut func_rows = Vec::new();
- let mut saved_rows: Vec<(u64, SavedLineProgramRow)> = Vec::new();
- let mut state = ReadLineProgramState::SequenceEnded;
- while let Some((_header, row)) = rows.next_row()? {
- if state == ReadLineProgramState::IgnoreSequence {
- if row.end_sequence() {
- state = ReadLineProgramState::SequenceEnded;
- }
+ let symbol = map.symbol;
+ let base_addr = map.offset;
+ transform.begin_sequence(Some(write::Address::Symbol { symbol, addend: 0 }));
+ // TODO track and place function declaration line here
+ let mut last_address = None;
+ for addr_map in map.addresses.iter() {
+ let Some(wasm_offset) = addr_map.wasm.checked_sub(start) else {
continue;
- }
- let saved_row = if row.end_sequence() {
- let index = match state {
- ReadLineProgramState::ReadSequence(index) => index,
- _ => panic!(),
- };
- saved_rows.sort_by_key(|r| r.0);
- func_rows.push(FuncRows {
- index,
- sorted_rows: saved_rows,
- });
-
- saved_rows = Vec::new();
- state = ReadLineProgramState::SequenceEnded;
- SavedLineProgramRow::EndOfSequence
- } else {
- if state == ReadLineProgramState::SequenceEnded {
- // Discard sequences for non-existent code.
- if row.address() == 0 {
- state = ReadLineProgramState::IgnoreSequence;
- continue;
- }
- match addr_tr.find_func_index(row.address()) {
- Some(index) => {
- state = ReadLineProgramState::ReadSequence(index);
- }
- None => {
- // Some non-existent address found.
- state = ReadLineProgramState::IgnoreSequence;
- continue;
- }
- }
- }
- SavedLineProgramRow::Normal {
- address: row.address(),
- op_index: row.op_index(),
- file_index: row.file_index(),
- line: row.line().map(|nonzero| nonzero.get()).unwrap_or(0),
- column: match row.column() {
- gimli::ColumnType::LeftEdge => 0,
- gimli::ColumnType::Column(val) => val.get(),
- },
- discriminator: row.discriminator(),
- is_stmt: row.is_stmt(),
- basic_block: row.basic_block(),
- prologue_end: row.prologue_end(),
- epilogue_begin: row.epilogue_begin(),
- isa: row.isa(),
- }
- };
- saved_rows.push((row.address(), saved_row));
- }
-
- for FuncRows {
- index,
- sorted_rows: saved_rows,
- } in func_rows
- {
- let map = match addr_tr.map().get(index) {
- Some(map) if map.len > 0 => map,
- _ => {
- continue; // no code generated
- }
};
- let symbol = map.symbol;
- let base_addr = map.offset;
- out_program.begin_sequence(Some(write::Address::Symbol { symbol, addend: 0 }));
- // TODO track and place function declaration line here
- let mut last_address = None;
- for addr_map in map.addresses.iter() {
- let saved_row = match saved_rows.binary_search_by_key(&addr_map.wasm, |i| i.0) {
- Ok(i) => Some(&saved_rows[i].1),
+ let mut saved_row =
+ match saved_rows.binary_search_by_key(&wasm_offset, |i| i.address_offset) {
+ Ok(i) => saved_rows[i],
Err(i) => {
if i > 0 {
- Some(&saved_rows[i - 1].1)
+ saved_rows[i - 1]
} else {
- None
+ continue;
}
}
};
- if let Some(SavedLineProgramRow::Normal {
- address,
- op_index,
- file_index,
- line,
- column,
- discriminator,
- is_stmt,
- basic_block,
- prologue_end,
- epilogue_begin,
- isa,
- }) = saved_row
- {
- // Ignore duplicates
- if Some(*address) != last_address {
- let address_offset = if last_address.is_none() {
- // Extend first entry to the function declaration
- // TODO use the function declaration line instead
- 0
- } else {
- (addr_map.generated - base_addr) as u64
- };
- out_program.row().address_offset = address_offset;
- out_program.row().op_index = *op_index;
- out_program.row().file = files[(file_index - file_index_base) as usize];
- out_program.row().line = *line;
- out_program.row().column = *column;
- out_program.row().discriminator = *discriminator;
- out_program.row().is_statement = *is_stmt;
- out_program.row().basic_block = *basic_block;
- out_program.row().prologue_end = *prologue_end;
- out_program.row().epilogue_begin = *epilogue_begin;
- out_program.row().isa = *isa;
- out_program.generate_row();
- last_address = Some(*address);
- }
- }
+ // Ignore duplicates
+ if Some(saved_row.address_offset) != last_address {
+ let address_offset = if last_address.is_none() {
+ // Extend first entry to the function declaration
+ // TODO use the function declaration line instead
+ 0
+ } else {
+ (addr_map.generated - base_addr) as u64
+ };
+ last_address = Some(saved_row.address_offset);
+ saved_row.address_offset = address_offset;
+ transform.generate_row(saved_row);
}
- let end_addr = (map.offset + map.len) as u64;
- out_program.end_sequence(end_addr);
}
- Ok((out_program, offset, files, file_index_base))
- } else {
- Err(TransformError("Valid line program not found").into())
+ transform.end_sequence(map.len as u64);
}
-}
-
-fn clone_line_string(
- value: Reader<'_>,
- form: gimli::DwForm,
- out_strings: &mut write::StringTable,
-) -> Result<write::LineString, Error> {
- let content = value.to_vec();
- Ok(match form {
- gimli::DW_FORM_strp => {
- let id = out_strings.add(content);
- write::LineString::StringRef(id)
- }
- gimli::DW_FORM_string => write::LineString::String(content),
- _ => bail!("DW_FORM_line_strp or other not supported"),
- })
+ let (out_program, files) = transform.program();
+ Ok((out_program, files))
}
diff --git a/crates/cranelift/src/debug/transform/mod.rs b/crates/cranelift/src/debug/transform/mod.rs
index 1f73eb7648..9039b404db 100644
--- a/crates/cranelift/src/debug/transform/mod.rs
+++ b/crates/cranelift/src/debug/transform/mod.rs
@@ -1,14 +1,12 @@
use self::debug_transform_logging::dbi_log;
-use self::refs::DebugInfoRefsMap;
use self::simulate::generate_simulated_dwarf;
use self::unit::clone_unit;
+use crate::debug::Compilation;
use crate::debug::gc::build_dependencies;
-use crate::debug::{Compilation, Reader};
use cranelift_codegen::isa::TargetIsa;
-use gimli::{Dwarf, DwarfPackage, LittleEndian, Section, Unit, UnitRef, UnitSectionOffset, write};
-use std::{collections::HashSet, fmt::Debug};
+use gimli::{DwarfPackage, LittleEndian, Section, write};
+use std::collections::HashSet;
use synthetic::ModuleSyntheticUnit;
-use thiserror::Error;
use wasmtime_environ::error::Error;
use wasmtime_environ::{
DefinedFuncIndex, ModuleTranslation, PrimaryMap, StaticModuleIndex, Tunables, prelude::*,
@@ -22,7 +20,6 @@ mod debug_transform_logging;
mod expression;
mod line_program;
mod range_info_builder;
-mod refs;
mod simulate;
mod synthetic;
mod unit;
@@ -43,14 +40,6 @@ impl<'a> Compilation<'a> {
}
}
-#[derive(Error, Debug)]
-#[error("Debug info transform error: {0}")]
-pub struct TransformError(&'static str);
-
-pub(crate) struct DebugInputContext<'a> {
- reachable: &'a HashSet<UnitSectionOffset>,
-}
-
fn load_dwp<'data>(
translation: ModuleTranslation<'data>,
buffer: &'data [u8],
@@ -165,12 +154,8 @@ pub fn transform_dwarf(
version: 4, // TODO: this should be configurable
address_size: isa.pointer_bytes(),
};
- let mut out_strings = write::StringTable::default();
- let mut out_units = write::UnitTable::default();
+ let mut out_dwarf = write::Dwarf::default();
- let out_line_strings = write::LineStringTable::default();
- let mut pending_di_refs = Vec::new();
- let mut di_ref_map = DebugInfoRefsMap::new();
let mut vmctx_ptr_die_refs = PrimaryMap::new();
let mut translated = HashSet::new();
@@ -180,64 +165,58 @@ pub fn transform_dwarf(
let addr_tr = &transforms[module];
let di = &translation.debuginfo;
- let reachable = build_dependencies(&di.dwarf, addr_tr)?.get_reachable();
let out_module_synthetic_unit = ModuleSyntheticUnit::new(
module,
compilation,
out_encoding,
- &mut out_units,
- &mut out_strings,
+ &mut out_dwarf.units,
+ &mut out_dwarf.strings,
);
// TODO-DebugInfo-Cleanup: move the simulation code to be per-module and delete this map.
vmctx_ptr_die_refs.push(out_module_synthetic_unit.vmctx_ptr_die_ref());
- let mut iter = di.dwarf.debug_info.units();
- while let Some(header) = iter.next().unwrap_or(None) {
- let unit = di.dwarf.unit(header)?;
- let unit = unit.unit_ref(&di.dwarf);
-
- let mut split_unit = None;
- let mut split_reachable = None;
-
- if unit.dwo_id.is_some() {
- if let Some(dwarf_package) = &dwarf_package {
- if let Some((fused, fused_dwarf)) =
- replace_unit_from_split_dwarf(unit, dwarf_package)
- {
- split_reachable =
- Some(build_dependencies(&fused_dwarf, addr_tr)?.get_reachable());
- split_unit = Some((fused, fused_dwarf));
- }
- }
- }
- let split_unit = split_unit
- .as_ref()
- .map(|(split_unit, split_dwarf)| split_unit.unit_ref(split_dwarf));
- let context = DebugInputContext {
- reachable: split_reachable.as_ref().unwrap_or(&reachable),
- };
-
- if let Some((id, ref_map, pending_refs)) = clone_unit(
- compilation,
- module,
- unit,
- split_unit,
- &context,
- &addr_tr,
- out_encoding,
- &out_module_synthetic_unit,
- &mut out_units,
- &mut out_strings,
- &mut translated,
- isa,
- )? {
- di_ref_map.insert(&header, id, ref_map);
- pending_di_refs.push((id, pending_refs));
+ let mut filter = write::FilterUnitSection::new(&di.dwarf)?;
+ build_dependencies(&mut filter, addr_tr)?;
+ let mut convert = out_dwarf.convert_with_filter(filter)?;
+ while let Some((mut unit, root_entry)) = convert.read_unit()? {
+ if let Some(dwp) = dwarf_package.as_ref()
+ && let Some(dwo_id) = unit.read_unit.dwo_id
+ && let Ok(Some(split_dwarf)) = dwp.find_cu(dwo_id, unit.read_unit.dwarf)
+ {
+ let mut split_filter =
+ write::FilterUnitSection::new_split(&split_dwarf, unit.read_unit)?;
+ build_dependencies(&mut split_filter, addr_tr)?;
+ let mut convert_split = unit.convert_split_with_filter(split_filter)?;
+ let (mut split_unit, split_root_entry) = convert_split.read_unit()?;
+ split_unit.unit.set_encoding(out_encoding);
+ clone_unit(
+ compilation,
+ module,
+ &mut split_unit,
+ &split_root_entry,
+ Some(&root_entry),
+ &addr_tr,
+ &out_module_synthetic_unit,
+ &mut translated,
+ isa,
+ )?;
+ } else {
+ unit.unit.set_encoding(out_encoding);
+ clone_unit(
+ compilation,
+ module,
+ &mut unit,
+ &root_entry,
+ None,
+ &addr_tr,
+ &out_module_synthetic_unit,
+ &mut translated,
+ isa,
+ )?;
}
}
}
- di_ref_map.patch(pending_di_refs.into_iter(), &mut out_units);
generate_simulated_dwarf(
compilation,
@@ -245,27 +224,10 @@ pub fn transform_dwarf(
&translated,
out_encoding,
&vmctx_ptr_die_refs,
- &mut out_units,
- &mut out_strings,
+ &mut out_dwarf.units,
+ &mut out_dwarf.strings,
isa,
)?;
- Ok(write::Dwarf {
- units: out_units,
- line_programs: vec![],
- line_strings: out_line_strings,
- strings: out_strings,
- })
-}
-
-fn replace_unit_from_split_dwarf<'a>(
- unit: UnitRef<Reader<'a>>,
- dwp: &DwarfPackage<Reader<'a>>,
-) -> Option<(Unit<Reader<'a>>, Dwarf<Reader<'a>>)> {
- let dwo_id = unit.dwo_id?;
- let split_unit_dwarf = dwp.find_cu(dwo_id, unit.dwarf).ok()??;
- let unit_header = split_unit_dwarf.debug_info.units().next().ok()??;
- let mut split_unit = split_unit_dwarf.unit(unit_header).ok()?;
- split_unit.copy_relocated_attributes(&unit);
- Some((split_unit, split_unit_dwarf))
+ Ok(out_dwarf)
}
diff --git a/crates/cranelift/src/debug/transform/range_info_builder.rs b/crates/cranelift/src/debug/transform/range_info_builder.rs
index 052673a970..2799123bf5 100644
--- a/crates/cranelift/src/debug/transform/range_info_builder.rs
+++ b/crates/cranelift/src/debug/transform/range_info_builder.rs
@@ -1,6 +1,6 @@
use super::address_transform::AddressTransform;
use crate::debug::Reader;
-use gimli::{AttributeValue, DebuggingInformationEntry, RangeListsOffset, UnitRef, write};
+use gimli::{AttributeValue, RangeListsOffset, UnitRef, write};
use wasmtime_environ::DefinedFuncIndex;
use wasmtime_environ::error::Error;
@@ -12,13 +12,10 @@ pub(crate) enum RangeInfoBuilder {
}
impl RangeInfoBuilder {
- pub(crate) fn from(
- unit: UnitRef<Reader<'_>>,
- entry: &DebuggingInformationEntry<Reader<'_>>,
- ) -> Result<Self, Error> {
+ pub(crate) fn from(entry: &write::ConvertUnitEntry<Reader<'_>>) -> Result<Self, Error> {
if let Some(AttributeValue::RangeListsRef(r)) = entry.attr_value(gimli::DW_AT_ranges) {
- let r = unit.ranges_offset_from_raw(r);
- return RangeInfoBuilder::from_ranges_ref(unit, r);
+ let r = entry.read_unit.ranges_offset_from_raw(r);
+ return RangeInfoBuilder::from_ranges_ref(entry.read_unit, r);
};
let low_pc = if let Some(AttributeValue::Addr(addr)) = entry.attr_value(gimli::DW_AT_low_pc)
@@ -27,7 +24,7 @@ impl RangeInfoBuilder {
} else if let Some(AttributeValue::DebugAddrIndex(i)) =
entry.attr_value(gimli::DW_AT_low_pc)
{
- unit.address(i)?
+ entry.read_unit.address(i)?
} else {
return Ok(RangeInfoBuilder::Undefined);
};
@@ -42,7 +39,7 @@ impl RangeInfoBuilder {
}
pub(crate) fn from_ranges_ref(
- unit: UnitRef<Reader<'_>>,
+ unit: UnitRef<'_, Reader<'_>>,
ranges: RangeListsOffset,
) -> Result<Self, Error> {
let mut ranges = unit.ranges(ranges)?;
@@ -62,10 +59,10 @@ impl RangeInfoBuilder {
}
pub(crate) fn from_subprogram_die(
- unit: UnitRef<Reader<'_>>,
- entry: &DebuggingInformationEntry<Reader<'_>>,
+ entry: &write::ConvertUnitEntry<Reader<'_>>,
addr_tr: &AddressTransform,
) -> Result<Self, Error> {
+ let unit = entry.read_unit;
let addr = if let Some(AttributeValue::Addr(addr)) = entry.attr_value(gimli::DW_AT_low_pc) {
addr
} else if let Some(AttributeValue::DebugAddrIndex(i)) =
diff --git a/crates/cranelift/src/debug/transform/refs.rs b/crates/cranelift/src/debug/transform/refs.rs
deleted file mode 100644
index ab5b42c86b..0000000000
--- a/crates/cranelift/src/debug/transform/refs.rs
+++ /dev/null
@@ -1,111 +0,0 @@
-//! Helper utils for tracking and patching intra unit or section references.
-
-use gimli::write;
-use gimli::{DebugInfoOffset, Reader, UnitHeader, UnitOffset};
-use std::collections::HashMap;
-
-/// Stores compiled unit references: UnitEntryId+DwAt denotes a patch location
-/// and UnitOffset is a location in original DWARF.
-pub struct PendingUnitRefs {
- refs: Vec<(write::UnitEntryId, gimli::DwAt, UnitOffset)>,
-}
-
-impl PendingUnitRefs {
- pub fn new() -> Self {
- Self { refs: Vec::new() }
- }
- pub fn insert(&mut self, entry_id: write::UnitEntryId, attr: gimli::DwAt, offset: UnitOffset) {
- self.refs.push((entry_id, attr, offset));
- }
-}
-
-/// Stores .debug_info references: UnitEntryId+DwAt denotes a patch location
-/// and DebugInfoOffset is a location in original DWARF.
-pub struct PendingDebugInfoRefs {
- refs: Vec<(write::UnitEntryId, gimli::DwAt, DebugInfoOffset)>,
-}
-
-impl PendingDebugInfoRefs {
- pub fn new() -> Self {
- Self { refs: Vec::new() }
- }
- pub fn insert(
- &mut self,
- entry_id: write::UnitEntryId,
- attr: gimli::DwAt,
- offset: DebugInfoOffset,
- ) {
- self.refs.push((entry_id, attr, offset));
- }
-}
-
-/// Stores map between read and written references of DWARF entries of
-/// a compiled unit.
-pub struct UnitRefsMap {
- map: HashMap<UnitOffset, write::UnitEntryId>,
-}
-
-impl UnitRefsMap {
- pub fn new() -> Self {
- Self {
- map: HashMap::new(),
- }
- }
- pub fn insert(&mut self, offset: UnitOffset, entry_id: write::UnitEntryId) {
- self.map.insert(offset, entry_id);
- }
- pub fn patch(&self, refs: PendingUnitRefs, comp_unit: &mut write::Unit) {
- for (die_id, attr_name, offset) in refs.refs {
- let die = comp_unit.get_mut(die_id);
- if let Some(unit_id) = self.map.get(&offset) {
- die.set(attr_name, write::AttributeValue::UnitRef(*unit_id));
- }
- }
- }
-}
-
-/// Stores map between read and written references of DWARF entries of
-/// the entire .debug_info.
-pub struct DebugInfoRefsMap {
- map: HashMap<DebugInfoOffset, (write::UnitId, write::UnitEntryId)>,
-}
-
-impl DebugInfoRefsMap {
- pub fn new() -> Self {
- Self {
- map: HashMap::new(),
- }
- }
- pub fn insert<R>(&mut self, unit: &UnitHeader<R>, unit_id: write::UnitId, unit_map: UnitRefsMap)
- where
- R: Reader<Offset = usize>,
- {
- self.map
- .extend(unit_map.map.into_iter().map(|(off, entry_id)| {
- let off = off
- .to_debug_info_offset(unit)
- .expect("should be in debug_info section");
- (off, (unit_id, entry_id))
- }));
- }
- pub fn patch(
- &self,
- refs: impl Iterator<Item = (write::UnitId, PendingDebugInfoRefs)>,
- units: &mut write::UnitTable,
- ) {
- for (id, refs) in refs {
- let unit = units.get_mut(id);
- for (die_id, attr_name, offset) in refs.refs {
- let die = unit.get_mut(die_id);
- if let Some((id, entry_id)) = self.map.get(&offset) {
- die.set(
- attr_name,
- write::AttributeValue::DebugInfoRef(write::DebugInfoRef::Entry(
- *id, *entry_id,
- )),
- );
- }
- }
- }
- }
-}
diff --git a/crates/cranelift/src/debug/transform/unit.rs b/crates/cranelift/src/debug/transform/unit.rs
index adda2c5969..726478ce7c 100644
--- a/crates/cranelift/src/debug/transform/unit.rs
+++ b/crates/cranelift/src/debug/transform/unit.rs
@@ -1,4 +1,3 @@
-use super::DebugInputContext;
use super::address_transform::AddressTransform;
use super::attr::{EntryAttributesContext, clone_die_attributes};
use super::debug_transform_logging::{
@@ -8,14 +7,13 @@ use super::debug_transform_logging::{
use super::expression::compile_expression;
use super::line_program::clone_line_program;
use super::range_info_builder::RangeInfoBuilder;
-use super::refs::{PendingDebugInfoRefs, PendingUnitRefs, UnitRefsMap};
use super::synthetic::ModuleSyntheticUnit;
use super::utils::{append_vmctx_info, resolve_die_ref};
use crate::debug::{Compilation, Reader};
use cranelift_codegen::ir::Endianness;
use cranelift_codegen::isa::TargetIsa;
+use gimli::AttributeValue;
use gimli::write;
-use gimli::{AttributeValue, DebuggingInformationEntry, UnitRef};
use std::collections::HashSet;
use wasmtime_environ::StaticModuleIndex;
use wasmtime_environ::error::{Context, Error};
@@ -23,7 +21,7 @@ use wasmtime_versioned_export_macros::versioned_stringify_ident;
#[derive(Debug)]
pub struct InheritedAttr<T> {
- stack: Vec<(usize, T)>,
+ stack: Vec<(isize, T)>,
}
impl<T> InheritedAttr<T> {
@@ -31,13 +29,13 @@ impl<T> InheritedAttr<T> {
InheritedAttr { stack: Vec::new() }
}
- fn update(&mut self, depth: usize) {
+ fn update(&mut self, depth: isize) {
while !self.stack.is_empty() && self.stack.last().unwrap().0 >= depth {
self.stack.pop();
}
}
- pub fn push(&mut self, depth: usize, value: T) {
+ pub fn push(&mut self, depth: isize, value: T) {
self.stack.push((depth, value));
}
@@ -45,7 +43,7 @@ impl<T> InheritedAttr<T> {
self.stack.last().map(|entry| &entry.1)
}
- pub fn top_with_depth_mut(&mut self, depth: usize) -> Option<&mut T> {
+ pub fn top_with_depth_mut(&mut self, depth: isize) -> Option<&mut T> {
self.stack
.last_mut()
.filter(|entry| entry.0 == depth)
@@ -57,28 +55,25 @@ impl<T> InheritedAttr<T> {
}
}
-fn get_base_type_name<'a>(
- type_entry: &DebuggingInformationEntry<Reader<'a>>,
- unit: UnitRef<Reader<'a>>,
-) -> Result<String, Error> {
+fn get_base_type_name(type_entry: &write::ConvertUnitEntry<Reader<'_>>) -> Result<String, Error> {
// FIXME remove recursion.
if let Some(die_ref) = type_entry.attr_value(gimli::DW_AT_type) {
- if let Some(ref die) = resolve_die_ref(unit, &die_ref)? {
+ if let Some(ref die) = resolve_die_ref(type_entry.read_unit, &die_ref)? {
if let Some(value) = die.attr_value(gimli::DW_AT_name) {
- return Ok(String::from(unit.attr_string(value)?.to_string()?));
+ return Ok(String::from(die.read_unit.attr_string(value)?.to_string()?));
}
- match die.tag() {
+ match die.tag {
gimli::DW_TAG_const_type => {
- return Ok(format!("const {}", get_base_type_name(die, unit)?));
+ return Ok(format!("const {}", get_base_type_name(die)?));
}
gimli::DW_TAG_pointer_type => {
- return Ok(format!("{}*", get_base_type_name(die, unit)?));
+ return Ok(format!("{}*", get_base_type_name(die)?));
}
gimli::DW_TAG_reference_type => {
- return Ok(format!("{}&", get_base_type_name(die, unit)?));
+ return Ok(format!("{}&", get_base_type_name(die)?));
}
gimli::DW_TAG_array_type => {
- return Ok(format!("{}[]", get_base_type_name(die, unit)?));
+ return Ok(format!("{}[]", get_base_type_name(die)?));
}
_ => (),
}
@@ -110,22 +105,20 @@ enum WebAssemblyPtrKind {
/// Notice that "resolve_vmctx_memory_ptr" is external/builtin
/// subprogram that is not part of Wasm code.
fn replace_pointer_type<'a>(
+ wrapper_die_id: write::UnitEntryId,
parent_id: write::UnitEntryId,
kind: WebAssemblyPtrKind,
- comp_unit: &mut write::Unit,
wasm_ptr_die_ref: write::DebugInfoRef,
- pointer_type_entry: &DebuggingInformationEntry<Reader<'a>>,
- unit: UnitRef<Reader<'a>>,
- out_strings: &mut write::StringTable,
- pending_die_refs: &mut PendingUnitRefs,
-) -> Result<write::UnitEntryId, Error> {
+ pointer_type_entry: &write::ConvertUnitEntry<Reader<'a>>,
+ unit: &mut write::ConvertUnit<'_, Reader<'a>>,
+) -> Result<(), Error> {
const WASM_PTR_LEN: u8 = 4;
macro_rules! add_tag {
($parent_id:ident, $tag:expr => $die:ident as $die_id:ident { $($a:path = $v:expr),* }) => {
- let $die_id = comp_unit.add($parent_id, $tag);
+ let $die_id = unit.unit.add($parent_id, $tag);
#[allow(unused_variables, reason = "sometimes not used below")]
- let $die = comp_unit.get_mut($die_id);
+ let $die = unit.unit.get_mut($die_id);
$( $die.set($a, $v); )*
};
}
@@ -136,17 +129,24 @@ fn replace_pointer_type<'a>(
let name = match kind {
WebAssemblyPtrKind::Pointer => format!(
"WebAssemblyPtrWrapper<{}>",
- get_base_type_name(pointer_type_entry, unit)?
+ get_base_type_name(pointer_type_entry)?
),
WebAssemblyPtrKind::Reference => format!(
"WebAssemblyRefWrapper<{}>",
- get_base_type_name(pointer_type_entry, unit)?
+ get_base_type_name(pointer_type_entry)?
),
};
- add_tag!(parent_id, gimli::DW_TAG_structure_type => wrapper_die as wrapper_die_id {
- gimli::DW_AT_name = write::AttributeValue::StringRef(out_strings.add(name.as_str())),
- gimli::DW_AT_byte_size = write::AttributeValue::Data1(WASM_PTR_LEN)
- });
+ unit.unit
+ .add_reserved(wrapper_die_id, parent_id, gimli::DW_TAG_structure_type);
+ let wrapper_die = unit.unit.get_mut(wrapper_die_id);
+ wrapper_die.set(
+ gimli::DW_AT_name,
+ write::AttributeValue::StringRef(unit.strings.add(name.as_str())),
+ );
+ wrapper_die.set(
+ gimli::DW_AT_byte_size,
+ write::AttributeValue::Data1(WASM_PTR_LEN),
+ );
// Build DW_TAG_pointer_type for `WebAssemblyPtrWrapper<T>*`:
// .. DW_AT_type = <wrapper_die>
@@ -154,29 +154,44 @@ fn replace_pointer_type<'a>(
gimli::DW_AT_type = write::AttributeValue::UnitRef(wrapper_die_id)
});
- let base_type_id = pointer_type_entry.attr_value(gimli::DW_AT_type);
+ let base_type = pointer_type_entry.attr_value(gimli::DW_AT_type);
+ let base_type_id = if let Some(AttributeValue::UnitRef(offset)) = base_type {
+ unit.convert_unit_ref(offset).ok()
+ } else {
+ None
+ };
+
// Build DW_TAG_reference_type for `T&`:
// .. DW_AT_type = <base_type>
add_tag!(parent_id, gimli::DW_TAG_reference_type => ref_type as ref_type_id {});
- if let Some(AttributeValue::UnitRef(ref offset)) = base_type_id {
- pending_die_refs.insert(ref_type_id, gimli::DW_AT_type, *offset);
+ if let Some(base_type_id) = base_type_id {
+ ref_type.set(
+ gimli::DW_AT_type,
+ write::AttributeValue::UnitRef(base_type_id),
+ );
}
// Build DW_TAG_pointer_type for `T*`:
// .. DW_AT_type = <base_type>
add_tag!(parent_id, gimli::DW_TAG_pointer_type => ptr_type as ptr_type_id {});
- if let Some(AttributeValue::UnitRef(ref offset)) = base_type_id {
- pending_die_refs.insert(ptr_type_id, gimli::DW_AT_type, *offset);
+ if let Some(base_type_id) = base_type_id {
+ ptr_type.set(
+ gimli::DW_AT_type,
+ write::AttributeValue::UnitRef(base_type_id),
+ );
}
// Build wrapper_die's DW_TAG_template_type_parameter:
// .. DW_AT_name = "T"
// .. DW_AT_type = <base_type>
add_tag!(wrapper_die_id, gimli::DW_TAG_template_type_parameter => t_param_die as t_param_die_id {
- gimli::DW_AT_name = write::AttributeValue::StringRef(out_strings.add("T"))
+ gimli::DW_AT_name = write::AttributeValue::StringRef(unit.strings.add("T"))
});
- if let Some(AttributeValue::UnitRef(ref offset)) = base_type_id {
- pending_die_refs.insert(t_param_die_id, gimli::DW_AT_type, *offset);
+ if let Some(base_type_id) = base_type_id {
+ t_param_die.set(
+ gimli::DW_AT_type,
+ write::AttributeValue::UnitRef(base_type_id),
+ );
}
// Build wrapper_die's DW_TAG_member for `__ptr`:
@@ -184,7 +199,7 @@ fn replace_pointer_type<'a>(
// .. DW_AT_type = <wp_die>
// .. DW_AT_location = 0
add_tag!(wrapper_die_id, gimli::DW_TAG_member => m_die as m_die_id {
- gimli::DW_AT_name = write::AttributeValue::StringRef(out_strings.add("__ptr")),
+ gimli::DW_AT_name = write::AttributeValue::StringRef(unit.strings.add("__ptr")),
gimli::DW_AT_type = write::AttributeValue::DebugInfoRef(wasm_ptr_die_ref),
gimli::DW_AT_data_member_location = write::AttributeValue::Data1(0)
});
@@ -197,8 +212,8 @@ fn replace_pointer_type<'a>(
// .. .. DW_AT_type = <wrapper_ptr_type>
// .. .. DW_AT_artificial = 1
add_tag!(wrapper_die_id, gimli::DW_TAG_subprogram => deref_op_die as deref_op_die_id {
- gimli::DW_AT_linkage_name = write::AttributeValue::StringRef(out_strings.add(versioned_stringify_ident!(wasmtime_resolve_vmctx_memory_ptr))),
- gimli::DW_AT_name = write::AttributeValue::StringRef(out_strings.add("ptr")),
+ gimli::DW_AT_linkage_name = write::AttributeValue::StringRef(unit.strings.add(versioned_stringify_ident!(wasmtime_resolve_vmctx_memory_ptr))),
+ gimli::DW_AT_name = write::AttributeValue::StringRef(unit.strings.add("ptr")),
gimli::DW_AT_type = write::AttributeValue::UnitRef(ptr_type_id)
});
add_tag!(deref_op_die_id, gimli::DW_TAG_formal_parameter => deref_op_this_param as deref_op_this_param_id {
@@ -214,8 +229,8 @@ fn replace_pointer_type<'a>(
// .. .. DW_AT_type = <wrapper_ptr_type>
// .. .. DW_AT_artificial = 1
add_tag!(wrapper_die_id, gimli::DW_TAG_subprogram => deref_op_die as deref_op_die_id {
- gimli::DW_AT_linkage_name = write::AttributeValue::StringRef(out_strings.add(versioned_stringify_ident!(wasmtime_resolve_vmctx_memory_ptr))),
- gimli::DW_AT_name = write::AttributeValue::StringRef(out_strings.add("operator*")),
+ gimli::DW_AT_linkage_name = write::AttributeValue::StringRef(unit.strings.add(versioned_stringify_ident!(wasmtime_resolve_vmctx_memory_ptr))),
+ gimli::DW_AT_name = write::AttributeValue::StringRef(unit.strings.add("operator*")),
gimli::DW_AT_type = write::AttributeValue::UnitRef(ref_type_id)
});
add_tag!(deref_op_die_id, gimli::DW_TAG_formal_parameter => deref_op_this_param as deref_op_this_param_id {
@@ -231,8 +246,8 @@ fn replace_pointer_type<'a>(
// .. .. DW_AT_type = <wrapper_ptr_type>
// .. .. DW_AT_artificial = 1
add_tag!(wrapper_die_id, gimli::DW_TAG_subprogram => deref_op_die as deref_op_die_id {
- gimli::DW_AT_linkage_name = write::AttributeValue::StringRef(out_strings.add(versioned_stringify_ident!(wasmtime_resolve_vmctx_memory_ptr))),
- gimli::DW_AT_name = write::AttributeValue::StringRef(out_strings.add("operator->")),
+ gimli::DW_AT_linkage_name = write::AttributeValue::StringRef(unit.strings.add(versioned_stringify_ident!(wasmtime_resolve_vmctx_memory_ptr))),
+ gimli::DW_AT_name = write::AttributeValue::StringRef(unit.strings.add("operator->")),
gimli::DW_AT_type = write::AttributeValue::UnitRef(ptr_type_id)
});
add_tag!(deref_op_die_id, gimli::DW_TAG_formal_parameter => deref_op_this_param as deref_op_this_param_id {
@@ -240,130 +255,91 @@ fn replace_pointer_type<'a>(
gimli::DW_AT_artificial = write::AttributeValue::Flag(true)
});
- Ok(wrapper_die_id)
+ Ok(())
}
pub(crate) fn clone_unit<'a>(
compilation: &mut Compilation<'_>,
module: StaticModuleIndex,
- skeleton_unit: UnitRef<Reader<'a>>,
- split_unit: Option<UnitRef<Reader<'a>>>,
- context: &DebugInputContext,
+ unit: &mut write::ConvertUnit<'_, Reader<'a>>,
+ root_entry: &write::ConvertUnitEntry<Reader<'a>>,
+ skeleton_root_entry: Option<&write::ConvertUnitEntry<Reader<'a>>>,
addr_tr: &AddressTransform,
- out_encoding: gimli::Encoding,
out_module_synthetic_unit: &ModuleSyntheticUnit,
- out_units: &mut write::UnitTable,
- out_strings: &mut write::StringTable,
translated: &mut HashSet<usize>,
isa: &dyn TargetIsa,
-) -> Result<Option<(write::UnitId, UnitRefsMap, PendingDebugInfoRefs)>, Error> {
- let mut die_ref_map = UnitRefsMap::new();
- let mut pending_die_refs = PendingUnitRefs::new();
- let mut pending_di_refs = PendingDebugInfoRefs::new();
- let mut stack = Vec::new();
-
- // Iterate over all of this compilation unit's entries.
- let unit = split_unit.unwrap_or(skeleton_unit);
- let mut entries = unit.entries();
- dbi_log!("Cloning CU {:?}", log_get_cu_summary(unit));
-
- let (mut out_unit, out_unit_id, file_map, file_index_base) =
- if let Some(entry) = entries.next_dfs()? {
- let (out_line_program, debug_line_offset, file_map, file_index_base) =
- clone_line_program(skeleton_unit, unit.name, addr_tr, out_encoding, out_strings)?;
-
- if entry.tag() == gimli::DW_TAG_compile_unit {
- log_begin_input_die(unit, entry, 0);
- let out_unit_id = out_units.add(write::Unit::new(out_encoding, out_line_program));
- let out_unit = out_units.get_mut(out_unit_id);
-
- let out_root_id = out_unit.root();
- die_ref_map.insert(entry.offset(), out_root_id);
-
- clone_die_attributes(
- unit,
- entry,
- addr_tr,
- None,
- out_unit,
- out_root_id,
- None,
- None,
- out_strings,
- &mut pending_die_refs,
- &mut pending_di_refs,
- EntryAttributesContext::Root(Some(debug_line_offset)),
- isa,
- )?;
- if split_unit.is_some() {
- if let Some(skeleton_entry) = skeleton_unit.entries().next_dfs()? {
- clone_die_attributes(
- skeleton_unit,
- skeleton_entry,
- addr_tr,
- None,
- out_unit,
- out_root_id,
- None,
- None,
- out_strings,
- &mut pending_die_refs,
- &mut pending_di_refs,
- EntryAttributesContext::Root(Some(debug_line_offset)),
- isa,
- )?;
- }
- }
-
- log_end_output_die(entry, unit, out_root_id, out_unit, out_strings, 0);
- stack.push(out_root_id);
- (out_unit, out_unit_id, file_map, file_index_base)
- } else {
- // Can happen when the DWARF is split and we dont have the package/dwo files.
- // This is a better user experience than errorring.
- dbi_log!("... skipped: split DW_TAG_compile_unit entry missing");
- return Ok(None); // empty:
- }
- } else {
- dbi_log!("... skipped: empty CU (no DW_TAG_compile_unit entry)");
- return Ok(None); // empty
- };
- let mut skip_at_depth = None;
+) -> Result<(), Error> {
let mut current_frame_base = InheritedAttr::new();
let mut current_value_range = InheritedAttr::new();
let mut current_scope_ranges = InheritedAttr::new();
let mut current_subprogram = InheritedAttr::new();
- while let Some(entry) = entries.next_dfs()? {
- let current_depth = entry.depth();
- log_begin_input_die(unit, entry, current_depth);
-
- // If `skip_at_depth` is `Some` then we previously decided to skip over
- // a node and all it's children.
- if let Some(depth) = skip_at_depth {
- if current_depth > depth {
- log_end_output_die_skipped(entry, unit, "unreachable", current_depth);
- continue;
- }
- skip_at_depth = None;
+
+ dbi_log!("Cloning CU {:?}", log_get_cu_summary(unit.read_unit));
+
+ if let Some(convert_program) = unit.read_line_program(Some(unit.unit.encoding()), None)? {
+ let (program, files) = clone_line_program(convert_program, addr_tr)?;
+ unit.set_line_program(program, files);
+ }
+
+ if root_entry.tag == gimli::DW_TAG_compile_unit {
+ log_begin_input_die(root_entry);
+
+ let out_root_id = unit.unit.root();
+ clone_die_attributes(
+ unit,
+ root_entry,
+ addr_tr,
+ None,
+ out_root_id,
+ None,
+ None,
+ EntryAttributesContext {
+ subprograms: &mut current_subprogram,
+ frame_base: None,
+ },
+ isa,
+ )?;
+
+ if let Some(skeleton_root_entry) = skeleton_root_entry {
+ clone_die_attributes(
+ unit,
+ skeleton_root_entry,
+ addr_tr,
+ None,
+ out_root_id,
+ None,
+ None,
+ EntryAttributesContext {
+ subprograms: &mut current_subprogram,
+ frame_base: None,
+ },
+ isa,
+ )?;
}
- if !context
- .reachable
- .contains(&entry.offset().to_unit_section_offset(&unit))
- {
- // entry is not reachable: discarding all its info.
- skip_at_depth = Some(current_depth);
- log_end_output_die_skipped(entry, unit, "unreachable", current_depth);
+ log_end_output_die(out_root_id, root_entry, unit);
+ } else {
+ // Can happen when the DWARF is split and we dont have the package/dwo files.
+ // This is a better user experience than errorring.
+ dbi_log!("... skipped: split DW_TAG_compile_unit entry missing");
+ return Ok(()); // empty:
+ }
+
+ let mut entry = write::ConvertUnitEntry::null(unit.read_unit);
+ while let Some(entry_id) = unit.read_entry(&mut entry)? {
+ log_begin_input_die(&entry);
+ let (Some(out_die_id), Some(parent)) = (entry_id, entry.parent) else {
+ log_end_output_die_skipped(&entry, "unreachable");
continue;
- }
+ };
- let new_stack_len = current_depth as usize + 1;
+ let new_stack_len = entry.depth;
current_frame_base.update(new_stack_len);
current_scope_ranges.update(new_stack_len);
current_value_range.update(new_stack_len);
current_subprogram.update(new_stack_len);
- let range_builder = if entry.tag() == gimli::DW_TAG_subprogram {
- let range_builder = RangeInfoBuilder::from_subprogram_die(unit, entry, addr_tr)?;
+ let range_builder = if entry.tag == gimli::DW_TAG_subprogram {
+ let range_builder = RangeInfoBuilder::from_subprogram_die(&entry, addr_tr)?;
if let RangeInfoBuilder::Function(func) = range_builder {
let frame_info = compilation.function_frame_info(module, func);
current_value_range.push(new_stack_len, frame_info);
@@ -376,10 +352,8 @@ pub(crate) fn clone_unit<'a>(
None
}
} else {
- let high_pc = entry.attr_value(gimli::DW_AT_high_pc);
- let ranges = entry.attr_value(gimli::DW_AT_ranges);
- if high_pc.is_some() || ranges.is_some() {
- let range_builder = RangeInfoBuilder::from(unit, entry)?;
+ if entry.has_attr(gimli::DW_AT_high_pc) || entry.has_attr(gimli::DW_AT_ranges) {
+ let range_builder = RangeInfoBuilder::from(&entry)?;
current_scope_ranges.push(new_stack_len, range_builder.get_ranges(addr_tr));
Some(range_builder)
} else {
@@ -387,66 +361,43 @@ pub(crate) fn clone_unit<'a>(
}
};
- while stack.len() >= new_stack_len {
- stack.pop();
- }
-
if let Some(AttributeValue::Exprloc(expr)) = entry.attr_value(gimli::DW_AT_frame_base) {
- if let Some(expr) = compile_expression(&expr, unit.encoding(), None)? {
+ if let Some(expr) = compile_expression(&expr, unit.unit.encoding(), None)? {
current_frame_base.push(new_stack_len, expr);
}
}
- let parent = stack.last().unwrap();
-
- if entry.tag() == gimli::DW_TAG_pointer_type || entry.tag() == gimli::DW_TAG_reference_type
- {
+ if entry.tag == gimli::DW_TAG_pointer_type || entry.tag == gimli::DW_TAG_reference_type {
// Wrap pointer types.
- let pointer_kind = match entry.tag() {
+ let pointer_kind = match entry.tag {
gimli::DW_TAG_pointer_type => WebAssemblyPtrKind::Pointer,
gimli::DW_TAG_reference_type => WebAssemblyPtrKind::Reference,
_ => panic!(),
};
- let die_id = replace_pointer_type(
- *parent,
+ replace_pointer_type(
+ out_die_id,
+ parent,
pointer_kind,
- out_unit,
out_module_synthetic_unit.wasm_ptr_die_ref(),
- entry,
+ &entry,
unit,
- out_strings,
- &mut pending_die_refs,
)?;
- stack.push(die_id);
- assert_eq!(stack.len(), new_stack_len);
- die_ref_map.insert(entry.offset(), die_id);
- log_end_output_die(entry, unit, die_id, out_unit, out_strings, current_depth);
+ log_end_output_die(out_die_id, &entry, unit);
continue;
}
- let out_die_id = out_unit.add(*parent, entry.tag());
-
- stack.push(out_die_id);
- assert_eq!(stack.len(), new_stack_len);
- die_ref_map.insert(entry.offset(), out_die_id);
+ unit.unit.add_reserved(out_die_id, parent, entry.tag);
clone_die_attributes(
unit,
- entry,
+ &entry,
addr_tr,
current_value_range.top(),
- &mut out_unit,
out_die_id,
range_builder,
current_scope_ranges.top(),
- out_strings,
- &mut pending_die_refs,
- &mut pending_di_refs,
- EntryAttributesContext::Children {
- depth: current_depth as usize,
+ EntryAttributesContext {
subprograms: &mut current_subprogram,
- file_map: &file_map,
- file_index_base,
frame_base: current_frame_base.top(),
},
isa,
@@ -457,36 +408,28 @@ pub(crate) fn clone_unit<'a>(
// base types used to refer to WebAssembly memory as little-endian
// using the DW_AT_endianity attribute, so that the debugger will
// be able to correctly access them.
- if entry.tag() == gimli::DW_TAG_base_type && isa.endianness() == Endianness::Big {
- let current_scope = out_unit.get_mut(out_die_id);
+ if entry.tag == gimli::DW_TAG_base_type && isa.endianness() == Endianness::Big {
+ let current_scope = unit.unit.get_mut(out_die_id);
current_scope.set(
gimli::DW_AT_endianity,
write::AttributeValue::Endianity(gimli::DW_END_little),
);
}
- if entry.tag() == gimli::DW_TAG_subprogram && !current_scope_ranges.is_empty() {
+ if entry.tag == gimli::DW_TAG_subprogram && !current_scope_ranges.is_empty() {
append_vmctx_info(
- out_unit,
+ unit.unit,
out_die_id,
out_module_synthetic_unit.vmctx_ptr_die_ref(),
addr_tr,
current_value_range.top(),
current_scope_ranges.top().context("range")?,
- out_strings,
+ unit.strings,
isa,
)?;
}
- log_end_output_die(
- entry,
- unit,
- out_die_id,
- out_unit,
- out_strings,
- current_depth,
- );
+ log_end_output_die(out_die_id, &entry, unit);
}
- die_ref_map.patch(pending_die_refs, out_unit);
- Ok(Some((out_unit_id, die_ref_map, pending_di_refs)))
+ Ok(())
}
diff --git a/crates/cranelift/src/debug/transform/utils.rs b/crates/cranelift/src/debug/transform/utils.rs
index 3e25432511..6741bef4ab 100644
--- a/crates/cranelift/src/debug/transform/utils.rs
+++ b/crates/cranelift/src/debug/transform/utils.rs
@@ -3,7 +3,7 @@ use crate::debug::Reader;
use super::address_transform::AddressTransform;
use super::expression::{CompiledExpression, FunctionFrameInfo};
use cranelift_codegen::isa::TargetIsa;
-use gimli::{AttributeValue, DebuggingInformationEntry, UnitRef, write};
+use gimli::{AttributeValue, UnitRef, write};
use wasmtime_environ::error::Error;
pub(crate) fn append_vmctx_info(
@@ -50,10 +50,12 @@ pub(crate) fn append_vmctx_info(
pub fn resolve_die_ref<'a, 'r>(
unit: UnitRef<'a, Reader<'r>>,
- die_ref: &'a AttributeValue<Reader<'r>>,
-) -> Result<Option<DebuggingInformationEntry<Reader<'r>>>, Error> {
+ die_ref: &AttributeValue<Reader<'r>>,
+) -> Result<Option<write::ConvertUnitEntry<'a, Reader<'r>>>, Error> {
let die = match die_ref {
- AttributeValue::UnitRef(unit_offs) => Some(unit.unit.entry(*unit_offs)?),
+ AttributeValue::UnitRef(unit_offs) => {
+ Some(write::ConvertUnitEntry::read(unit, *unit_offs)?)
+ }
// TODO-DebugInfo: support AttributeValue::DebugInfoRef. The trouble is that we don't have
// a fast way to go from a DI offset to a unit offset (which is needed to parse the DIE).
// We would likely need to maintain a cache.