[Lldb-commits] [lldb] [lldb] Create data symbols from the Wasm export section (PR #236504)

Felipe de Azevedo Piovezan via lldb-commits lldb-commits at lists.llvm.org
Thu Oct 29 06:31:24 PDT 2026


https://github.com/felipepiovezan updated https://github.com/llvm/llvm-project/pull/236504

>From a8840f22e65b553f1b90872333aac4aefc0cb66e Mon Sep 17 00:00:00 2001
From: Felipe de Azevedo Piovezan <fpiovezan at apple.com>
Date: Thu, 15 Oct 2026 15:59:19 +0100
Subject: [PATCH] [lldb] Create data symbols from the Wasm export section

When targeting Wasm, the global variables in C or Swift programs are
placed in linear memory, which means they get no entry in the name
section of the binary and therefore no Symbol in LLDB. In other words,
they can't be found by name without debug info.

There is a mechanism to somewhat remedy that: a program can make such a
variable findable with the `__attribute__((export_name))` attribute in C
and C++ or `@_expose(wasm)` in Swift. The Swift concurrency runtime
exports the debug variables that debuggers look up by name this way, for
example _swift_concurrency_debug_internal_layout_version.

These attributes cause the creation on an _extra_ immutable global whose
value is the annotated variable's address. This fake global has an entry
in the "globals" section, as well as entry in the "export" section of
the binary.

With this commit, LLDB now parses the export section, and follows the
extra level of indirection to create a Symbol whose address is the
address of the annotated variable.

There is no size information in the object file, so we arbitrarily give
the symbol a size of one. The alternative of using size zero was
considered, but this makes LLDB infer the size based on "the symbol
whose address is closest to this symbol's address". This is wrong for
WASM, where both code and data sections start at 0. Fixing this LLDB
limitation is outside the scope of this patch. For now, we can let
consumers of these symbols figure out what size to read.
---
 .../ObjectFile/wasm/ObjectFileWasm.cpp        | 109 +++++++++++-
 .../SymbolFile/DWARF/SymbolFileWasm.cpp       |  31 +++-
 .../wasm/wasm-export-data-symbols.yaml        | 163 ++++++++++++++++++
 .../DWARF/wasm-exported-data-symbol.yaml      |  89 ++++++++++
 4 files changed, 387 insertions(+), 5 deletions(-)
 create mode 100644 lldb/test/Shell/ObjectFile/wasm/wasm-export-data-symbols.yaml
 create mode 100644 lldb/test/Shell/SymbolFile/DWARF/wasm-exported-data-symbol.yaml

diff --git a/lldb/source/Plugins/ObjectFile/wasm/ObjectFileWasm.cpp b/lldb/source/Plugins/ObjectFile/wasm/ObjectFileWasm.cpp
index 4b89e44a18d9da..aa5b1e405c26e7 100644
--- a/lldb/source/Plugins/ObjectFile/wasm/ObjectFileWasm.cpp
+++ b/lldb/source/Plugins/ObjectFile/wasm/ObjectFileWasm.cpp
@@ -18,6 +18,7 @@
 #include "lldb/Utility/LLDBLog.h"
 #include "lldb/Utility/Log.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringSwitch.h"
@@ -756,6 +757,88 @@ ParseNames(SectionSP code_section_sp, SectionSP global_section_sp,
   return symbols;
 }
 
+struct WasmExport {
+  std::string name;
+  uint8_t kind = 0;
+  uint32_t index = 0;
+};
+
+static llvm::Expected<std::vector<WasmExport>>
+ParseExports(DataExtractor &export_data) {
+  llvm::DataExtractor data = export_data.GetAsLLVM();
+  llvm::DataExtractor::Cursor c(0);
+
+  llvm::Expected<uint32_t> count = GetULEB32(data, c);
+  if (!count)
+    return count.takeError();
+
+  std::vector<WasmExport> exports;
+  for (uint32_t i = 0; c && i < *count; ++i) {
+    llvm::Expected<std::string> name = GetWasmString(data, c);
+    if (!name)
+      return name.takeError();
+    const uint8_t kind = data.getU8(c);
+    llvm::Expected<uint32_t> index = GetULEB32(data, c);
+    if (!index)
+      return index.takeError();
+    exports.push_back({std::move(*name), kind, *index});
+  }
+
+  if (!c)
+    return c.takeError();
+
+  return exports;
+}
+
+/// Adds to \p symbols a data symbol for each export that stands for a variable
+/// in linear memory. Such an export refers to an immutable Wasm global that
+/// holds the variable's address, not the variable's value. Wasm globals listed
+/// in the name section already have a symbol and are skipped.
+static void AddExportedDataSymbols(llvm::ArrayRef<WasmExport> exports,
+                                   llvm::ArrayRef<WasmGlobal> globals,
+                                   uint32_t num_imported_globals,
+                                   const SectionSP &global_section_sp,
+                                   llvm::ArrayRef<SectionSP> memory_sections,
+                                   std::vector<Symbol> &symbols) {
+  llvm::DenseSet<uint32_t> named_globals;
+  if (global_section_sp)
+    for (const Symbol &symbol : symbols)
+      if (symbol.GetAddressRef().GetSection() == global_section_sp)
+        named_globals.insert(symbol.GetAddressRef().GetOffset());
+
+  for (const WasmExport &exp : exports) {
+    if (exp.kind != llvm::wasm::WASM_EXTERNAL_GLOBAL ||
+        exp.index < num_imported_globals || named_globals.contains(exp.index))
+      continue;
+    const uint32_t global_idx = exp.index - num_imported_globals;
+    if (global_idx >= globals.size())
+      continue;
+
+    const WasmGlobal &global = globals[global_idx];
+    if (global.is_mutable || !global.init_expr_value ||
+        (global.value_type != llvm::wasm::WASM_TYPE_I32 &&
+         global.value_type != llvm::wasm::WASM_TYPE_I64))
+      continue;
+
+    const addr_t addr = *global.init_expr_value;
+    const SectionSP *section_sp =
+        llvm::find_if(memory_sections, [addr](const SectionSP &section) {
+          return section->ContainsFileAddress(addr);
+        });
+    if (section_sp == memory_sections.end())
+      continue;
+
+    // The module does not record the variable's size. Symtab would size a
+    // symbol without one up to the next symbol, across unnamed variables.
+    symbols.emplace_back(symbols.size(), exp.name, lldb::eSymbolTypeData,
+                         /*external=*/true, /*is_debug=*/false,
+                         /*is_trampoline=*/false, /*is_artificial=*/false,
+                         *section_sp, addr - (*section_sp)->GetFileAddress(),
+                         /*size=*/1, /*size_is_valid=*/true,
+                         /*contains_linker_annotations=*/false, /*flags=*/0);
+  }
+}
+
 void ObjectFileWasm::ParseSymtab(Symtab &symtab) {
   for (const Symbol &symbol : m_symbols)
     symtab.AddSymbol(symbol);
@@ -877,6 +960,7 @@ void ObjectFileWasm::CreateSections(SectionList &unified_section_list) {
 
   // Parse the import section. The counts are needed because the function and
   // global index spaces used in the name section include imports.
+  bool imports_parsed = true;
   if (std::optional<section_info> info =
           GetSectionInfo(llvm::wasm::WASM_SEC_IMPORT)) {
     DataExtractor import_data = ReadImageData(info->offset, info->size);
@@ -884,6 +968,7 @@ void ObjectFileWasm::CreateSections(SectionList &unified_section_list) {
     if (!imports) {
       LLDB_LOG_ERROR(log, imports.takeError(),
                      "Failed to parse Wasm import section: {0}");
+      imports_parsed = false;
     } else {
       m_num_imported_functions = imports->functions;
       m_num_imported_globals = imports->globals;
@@ -951,6 +1036,7 @@ void ObjectFileWasm::CreateSections(SectionList &unified_section_list) {
 
   lldb::user_id_t segment_id = 0;
   lldb::addr_t static_data_end = 0;
+  std::vector<SectionSP> memory_sections;
   for (const WasmSegment &segment : segments) {
     if (segment.type == WasmSegment::Active) {
       // FIXME: Support segments with a memory index.
@@ -989,8 +1075,10 @@ void ObjectFileWasm::CreateSections(SectionList &unified_section_list) {
     m_sections_up->AddSection(segment_sp);
     GetModule()->GetSectionList()->AddSection(segment_sp);
 
-    if (segment.type == WasmSegment::Active)
+    if (segment.type == WasmSegment::Active) {
+      memory_sections.push_back(segment_sp);
       static_data_end = std::max(static_data_end, file_vm_addr + segment.size);
+    }
   }
 
   // Zero-initialized globals (BSS) have no data segment, so the loop above
@@ -1016,6 +1104,25 @@ void ObjectFileWasm::CreateSections(SectionList &unified_section_list) {
           /*log2align=*/0, /*flags=*/0);
       m_sections_up->AddSection(bss_sp);
       GetModule()->GetSectionList()->AddSection(bss_sp);
+      memory_sections.push_back(bss_sp);
+    }
+  }
+
+  // The global index of an export counts imported globals, so it can be mapped
+  // to a global of this module only if the import section parsed.
+  if (!imports_parsed)
+    return;
+
+  if (std::optional<section_info> info =
+          GetSectionInfo(llvm::wasm::WASM_SEC_EXPORT)) {
+    DataExtractor export_data = ReadImageData(info->offset, info->size);
+    llvm::Expected<std::vector<WasmExport>> exports = ParseExports(export_data);
+    if (!exports) {
+      LLDB_LOG_ERROR(log, exports.takeError(),
+                     "Failed to parse Wasm export section: {0}");
+    } else {
+      AddExportedDataSymbols(*exports, m_globals, m_num_imported_globals,
+                             global_section_sp, memory_sections, m_symbols);
     }
   }
 }
diff --git a/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileWasm.cpp b/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileWasm.cpp
index de660d58682cca..af3e6daea22198 100644
--- a/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileWasm.cpp
+++ b/lldb/source/Plugins/SymbolFile/DWARF/SymbolFileWasm.cpp
@@ -21,7 +21,10 @@
 #include "lldb/Utility/ConstString.h"
 #include "lldb/Utility/LLDBLog.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
 #include <optional>
+#include <utility>
+#include <vector>
 
 using namespace lldb;
 using namespace lldb_private;
@@ -69,6 +72,20 @@ void SymbolFileWasm::AddSymbols(Symtab &symtab) {
   // Built on demand to recover a mangled name from a declaration-only DIE.
   std::optional<llvm::DenseMap<ConstString, uint32_t>> demangled_index;
 
+  // The object file already has data symbols for exported variables. A
+  // variable that DWARF describes too must not get a second symbol.
+  llvm::DenseSet<std::pair<ConstString, addr_t>> existing_data_symbols;
+  for (size_t i = 0, n = symtab.GetNumSymbols(); i < n; ++i) {
+    Symbol *symbol = symtab.SymbolAtIndex(i);
+    if (!symbol || symbol->GetType() != eSymbolTypeData ||
+        !symbol->ValueIsAddress())
+      continue;
+    existing_data_symbols.insert(
+        {symbol->GetMangled().GetName(Mangled::ePreferMangled),
+         symbol->GetAddressRef().GetFileAddress()});
+  }
+
+  std::vector<Symbol> data_symbols;
   DWARFDebugInfo &debug_info = DebugInfo();
   const size_t num_units = debug_info.GetNumUnits();
   for (size_t i = 0; i < num_units; ++i) {
@@ -148,12 +165,12 @@ void SymbolFileWasm::AddSymbols(Symtab &symtab) {
       Address addr(*file_addr, section_list);
       if (!addr.IsSectionOffset())
         continue;
+      if (existing_data_symbols.contains({ConstString(name), *file_addr}))
+        continue;
 
       // Leave the size unset for Symtab to compute from the gap to the next
-      // symbol. Don't look the address up in the symtab here. That would build
-      // the address index before the remaining vtables are added, mis-sizing
-      // them.
-      symtab.AddSymbol(Symbol(
+      // symbol.
+      data_symbols.push_back(Symbol(
           /*symID=*/0, Mangled(ConstString(name)), eSymbolTypeData,
           /*external=*/true, /*is_debug=*/false, /*is_trampoline=*/false,
           /*is_artificial=*/false, AddressRange(addr, 0),
@@ -161,6 +178,12 @@ void SymbolFileWasm::AddSymbols(Symtab &symtab) {
           /*flags=*/0));
     }
   }
+
+  // Added after the loop: FindSymbolAtFileAddress above sizes the symbols
+  // without a size from the gap to the next symbol, and Symtab keeps those
+  // sizes.
+  for (const Symbol &symbol : data_symbols)
+    symtab.AddSymbol(symbol);
 }
 
 lldb::offset_t
diff --git a/lldb/test/Shell/ObjectFile/wasm/wasm-export-data-symbols.yaml b/lldb/test/Shell/ObjectFile/wasm/wasm-export-data-symbols.yaml
new file mode 100644
index 00000000000000..f64a4a318cfc46
--- /dev/null
+++ b/lldb/test/Shell/ObjectFile/wasm/wasm-export-data-symbols.yaml
@@ -0,0 +1,163 @@
+# REQUIRES: webassembly
+
+# An export cannot name a location in linear memory, so a variable in linear
+# memory is exported as an immutable global that holds its address. Such an
+# export becomes a data symbol at that address.
+
+# RUN: yaml2obj %s -o %t.wasm
+# RUN: %lldb %t.wasm \
+# RUN:   -o "target modules dump symtab" \
+# RUN:   -o "image lookup -s g_data" \
+# RUN:   -o "image lookup -s g_bss" \
+# RUN:   -o "image lookup -s g_data64" \
+# RUN:   -o exit 2>&1 | FileCheck %s \
+# RUN:   --implicit-check-not=g_mutable --implicit-check-not=g_named_export \
+# RUN:   --implicit-check-not=g_outside --implicit-check-not=g_float \
+# RUN:   --implicit-check-not=g_imported
+
+# CHECK: Dumping symbol table
+# CHECK: Code {{.*}}get_42
+# CHECK: Data 0x8000000000000004 0x0000000000000001 {{.*}}g_named
+# CHECK: Data 0x0000000000000400 0x0000000000000001 {{.*}}g_data
+# CHECK: Data 0x0000000000000800 0x0000000000000001 {{.*}}g_bss
+# CHECK: Data 0x0000000000000404 0x0000000000000001 {{.*}}g_data64
+
+# CHECK: 1 symbols match 'g_data'
+# CHECK: (wasm-export-data-symbols.yaml.tmp.wasm..data + 0)
+# CHECK: 1 symbols match 'g_bss'
+# CHECK: (wasm-export-data-symbols.yaml.tmp.wasm..bss + 1016)
+# CHECK: 1 symbols match 'g_data64'
+# CHECK: (wasm-export-data-symbols.yaml.tmp.wasm..data + 4)
+
+--- !WASM
+FileHeader:
+  Version: 0x1
+Sections:
+  - Type: TYPE
+    Signatures:
+      - Index: 0
+        ParamTypes: []
+        ReturnTypes:
+          - I32
+  - Type: IMPORT
+    Imports:
+      # Not a variable of this module. Global indices count it, so the globals
+      # below start at index 1.
+      - Module: env
+        Field: g_imp
+        Kind: GLOBAL
+        GlobalType: I32
+        GlobalMutable: false
+  - Type: FUNCTION
+    FunctionTypes: [ 0 ]
+  - Type: MEMORY
+    Memories:
+      - Minimum: 0x1
+  - Type: GLOBAL
+    Globals:
+      # In the data segment.
+      - Index: 1
+        Type: I32
+        Mutable: false
+        InitExpr:
+          Opcode: I32_CONST
+          Value: 1024
+      # Past the data segment, in the zero-fill rest of linear memory.
+      - Index: 2
+        Type: I32
+        Mutable: false
+        InitExpr:
+          Opcode: I32_CONST
+          Value: 2048
+      # A global the program writes to does not hold an address.
+      - Index: 3
+        Type: I32
+        Mutable: true
+        InitExpr:
+          Opcode: I32_CONST
+          Value: 1024
+      # Named by the name section, so a wasm global in its own right.
+      - Index: 4
+        Type: I32
+        Mutable: false
+        InitExpr:
+          Opcode: I32_CONST
+          Value: 1028
+      # Outside linear memory.
+      - Index: 5
+        Type: I32
+        Mutable: false
+        InitExpr:
+          Opcode: I32_CONST
+          Value: 131072
+      # The bits of a float, not an address.
+      - Index: 6
+        Type: F32
+        Mutable: false
+        InitExpr:
+          Opcode: F32_CONST
+          Value: 1024
+      # An address can be an i64 value too.
+      - Index: 7
+        Type: I64
+        Mutable: false
+        InitExpr:
+          Opcode: I64_CONST
+          Value: 1028
+  - Type: EXPORT
+    Exports:
+      - Name: memory
+        Kind: MEMORY
+        Index: 0
+      - Name: get_42
+        Kind: FUNCTION
+        Index: 0
+      - Name: g_imported
+        Kind: GLOBAL
+        Index: 0
+      - Name: g_data
+        Kind: GLOBAL
+        Index: 1
+      - Name: g_bss
+        Kind: GLOBAL
+        Index: 2
+      - Name: g_mutable
+        Kind: GLOBAL
+        Index: 3
+      - Name: g_named_export
+        Kind: GLOBAL
+        Index: 4
+      - Name: g_outside
+        Kind: GLOBAL
+        Index: 5
+      - Name: g_float
+        Kind: GLOBAL
+        Index: 6
+      - Name: g_data64
+        Kind: GLOBAL
+        Index: 7
+  - Type: CODE
+    Functions:
+      - Index: 0
+        Locals: []
+        Body: 412A0F0B
+  - Type: DATA
+    Segments:
+      - SectionOffset: 6
+        InitFlags: 0
+        Offset:
+          Opcode: I32_CONST
+          Value: 1024
+        Content: 'DEADBEEFCAFEF00D'
+  - Type: CUSTOM
+    Name: name
+    FunctionNames:
+      - Index: 0
+        Name: get_42
+    GlobalNames:
+      - Index: 4
+        Name: g_named
+    DataSegmentNames:
+      - Index: 0
+        Name: .data
+...
diff --git a/lldb/test/Shell/SymbolFile/DWARF/wasm-exported-data-symbol.yaml b/lldb/test/Shell/SymbolFile/DWARF/wasm-exported-data-symbol.yaml
new file mode 100644
index 00000000000000..00c62f5f9035f5
--- /dev/null
+++ b/lldb/test/Shell/SymbolFile/DWARF/wasm-exported-data-symbol.yaml
@@ -0,0 +1,89 @@
+# g_global is exported, so the object file already has a data symbol for it,
+# and DWARF describes it too. It must get only one symbol, which must not cover
+# g_keep: g_global lives at linear-memory address 0x10000 and g_keep, which only
+# DWARF describes, at 0x10004.
+
+# RUN: yaml2obj %s -o %t
+# RUN: %lldb %t \
+# RUN:   -o "image lookup -s g_global" \
+# RUN:   -o "image lookup -a 0x10006" \
+# RUN:   -o exit 2>&1 | FileCheck %s
+
+# CHECK-LABEL: image lookup -s g_global
+# CHECK: 1 symbols match 'g_global'
+# CHECK-LABEL: image lookup -a 0x10006
+# CHECK: Summary: {{.*}}g_keep + 2
+
+--- !WASM
+FileHeader:
+  Version:         0x1
+Sections:
+  - Type:            TYPE
+    Signatures:
+      - Index:           0
+        ParamTypes:      []
+        ReturnTypes:     []
+  - Type:            FUNCTION
+    FunctionTypes:   [ 0 ]
+  - Type:            MEMORY
+    Memories:
+      - Minimum:         0x2
+  - Type:            GLOBAL
+    Globals:
+      - Index:           0
+        Type:            I32
+        Mutable:         true
+        InitExpr:
+          Opcode:          I32_CONST
+          Value:           65536
+      - Index:           1
+        Type:            I32
+        Mutable:         false
+        InitExpr:
+          Opcode:          I32_CONST
+          Value:           65536
+  - Type:            EXPORT
+    Exports:
+      - Name:            g_global
+        Kind:            GLOBAL
+        Index:           1
+      - Name:            memory
+        Kind:            MEMORY
+        Index:           0
+  - Type:            CODE
+    Functions:
+      - Index:           0
+        Locals:          []
+        Body:            0B
+  - Type:            DATA
+    Segments:
+      - SectionOffset:   8
+        InitFlags:       0
+        Offset:
+          Opcode:          I32_CONST
+          Value:           65536
+        Content:         2A00000000000100
+  - Type:            CUSTOM
+    Name:            .debug_abbrev
+    Payload:         011101250E1305030E10171B0E0000023400030E49133F193A0B3B0B02180000032400030E3E0B0B0B0000040F004913000000
+  - Type:            CUSTOM
+    Name:            .debug_info
+    Payload:         4900000004000000000004012A0000001D0023000000000000000B000000021A0000002F0000000101050300000100030000000005040204000000470000000102050304000100042F00000000
+  - Type:            CUSTOM
+    Name:            .debug_str
+    Payload:         696E7400675F6B656570002F746D702F7761736D726570726F00675F676C6F62616C00676C6F622E6300636C616E672076657273696F6E2032322E312E302D776173692D73646B202868747470733A2F2F6769746875622E636F6D2F6C6C766D2F6C6C766D2D70726F6A65637420343433346461626236393931363835366238323466363861363462303239633637313735653533322900
+  - Type:            CUSTOM
+    Name:            .debug_line
+    Payload:         2400000004001E000000010101FB0E0D00010101010000000100000100676C6F622E630000000000
+  - Type:            CUSTOM
+    Name:            name
+    FunctionNames:
+      - Index:           0
+        Name:            __wasm_call_ctors
+    GlobalNames:
+      - Index:           0
+        Name:            __stack_pointer
+    DataSegmentNames:
+      - Index:           0
+        Name:            .data
+...



More information about the lldb-commits mailing list