xref: /llvm-project/lldb/source/Plugins/ObjectFile/wasm/ObjectFileWasm.cpp (revision cd9e5c32302cd3b34b796683eedb072c6a1cfdc1)
1 //===-- ObjectFileWasm.cpp ------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ObjectFileWasm.h"
10 #include "lldb/Core/Module.h"
11 #include "lldb/Core/ModuleSpec.h"
12 #include "lldb/Core/PluginManager.h"
13 #include "lldb/Core/Section.h"
14 #include "lldb/Target/Process.h"
15 #include "lldb/Target/SectionLoadList.h"
16 #include "lldb/Target/Target.h"
17 #include "lldb/Utility/DataBufferHeap.h"
18 #include "lldb/Utility/Log.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/BinaryFormat/Magic.h"
23 #include "llvm/BinaryFormat/Wasm.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/Format.h"
26 
27 using namespace lldb;
28 using namespace lldb_private;
29 using namespace lldb_private::wasm;
30 
31 static const uint32_t kWasmHeaderSize =
32     sizeof(llvm::wasm::WasmMagic) + sizeof(llvm::wasm::WasmVersion);
33 
34 /// Checks whether the data buffer starts with a valid Wasm module header.
35 static bool ValidateModuleHeader(const DataBufferSP &data_sp) {
36   if (!data_sp || data_sp->GetByteSize() < kWasmHeaderSize)
37     return false;
38 
39   if (llvm::identify_magic(toStringRef(data_sp->GetData())) !=
40       llvm::file_magic::wasm_object)
41     return false;
42 
43   uint8_t *Ptr = data_sp->GetBytes() + sizeof(llvm::wasm::WasmMagic);
44 
45   uint32_t version = llvm::support::endian::read32le(Ptr);
46   return version == llvm::wasm::WasmVersion;
47 }
48 
49 static llvm::Optional<ConstString>
50 GetWasmString(llvm::DataExtractor &data, llvm::DataExtractor::Cursor &c) {
51   // A Wasm string is encoded as a vector of UTF-8 codes.
52   // Vectors are encoded with their u32 length followed by the element
53   // sequence.
54   uint64_t len = data.getULEB128(c);
55   if (!c) {
56     consumeError(c.takeError());
57     return llvm::None;
58   }
59 
60   if (len >= (uint64_t(1) << 32)) {
61     return llvm::None;
62   }
63 
64   llvm::SmallVector<uint8_t, 32> str_storage;
65   data.getU8(c, str_storage, len);
66   if (!c) {
67     consumeError(c.takeError());
68     return llvm::None;
69   }
70 
71   llvm::StringRef str = toStringRef(makeArrayRef(str_storage));
72   return ConstString(str);
73 }
74 
75 void ObjectFileWasm::Initialize() {
76   PluginManager::RegisterPlugin(GetPluginNameStatic(),
77                                 GetPluginDescriptionStatic(), CreateInstance,
78                                 CreateMemoryInstance, GetModuleSpecifications);
79 }
80 
81 void ObjectFileWasm::Terminate() {
82   PluginManager::UnregisterPlugin(CreateInstance);
83 }
84 
85 ConstString ObjectFileWasm::GetPluginNameStatic() {
86   static ConstString g_name("wasm");
87   return g_name;
88 }
89 
90 ObjectFile *
91 ObjectFileWasm::CreateInstance(const ModuleSP &module_sp, DataBufferSP &data_sp,
92                                offset_t data_offset, const FileSpec *file,
93                                offset_t file_offset, offset_t length) {
94   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
95 
96   if (!data_sp) {
97     data_sp = MapFileData(*file, length, file_offset);
98     if (!data_sp) {
99       LLDB_LOGF(log, "Failed to create ObjectFileWasm instance for file %s",
100                 file->GetPath().c_str());
101       return nullptr;
102     }
103     data_offset = 0;
104   }
105 
106   assert(data_sp);
107   if (!ValidateModuleHeader(data_sp)) {
108     LLDB_LOGF(log,
109               "Failed to create ObjectFileWasm instance: invalid Wasm header");
110     return nullptr;
111   }
112 
113   // Update the data to contain the entire file if it doesn't contain it
114   // already.
115   if (data_sp->GetByteSize() < length) {
116     data_sp = MapFileData(*file, length, file_offset);
117     if (!data_sp) {
118       LLDB_LOGF(log,
119                 "Failed to create ObjectFileWasm instance: cannot read file %s",
120                 file->GetPath().c_str());
121       return nullptr;
122     }
123     data_offset = 0;
124   }
125 
126   std::unique_ptr<ObjectFileWasm> objfile_up(new ObjectFileWasm(
127       module_sp, data_sp, data_offset, file, file_offset, length));
128   ArchSpec spec = objfile_up->GetArchitecture();
129   if (spec && objfile_up->SetModulesArchitecture(spec)) {
130     LLDB_LOGF(log,
131               "%p ObjectFileWasm::CreateInstance() module = %p (%s), file = %s",
132               static_cast<void *>(objfile_up.get()),
133               static_cast<void *>(objfile_up->GetModule().get()),
134               objfile_up->GetModule()->GetSpecificationDescription().c_str(),
135               file ? file->GetPath().c_str() : "<NULL>");
136     return objfile_up.release();
137   }
138 
139   LLDB_LOGF(log, "Failed to create ObjectFileWasm instance");
140   return nullptr;
141 }
142 
143 ObjectFile *ObjectFileWasm::CreateMemoryInstance(const ModuleSP &module_sp,
144                                                  DataBufferSP &data_sp,
145                                                  const ProcessSP &process_sp,
146                                                  addr_t header_addr) {
147   if (!ValidateModuleHeader(data_sp))
148     return nullptr;
149 
150   std::unique_ptr<ObjectFileWasm> objfile_up(
151       new ObjectFileWasm(module_sp, data_sp, process_sp, header_addr));
152   ArchSpec spec = objfile_up->GetArchitecture();
153   if (spec && objfile_up->SetModulesArchitecture(spec))
154     return objfile_up.release();
155   return nullptr;
156 }
157 
158 bool ObjectFileWasm::DecodeNextSection(lldb::offset_t *offset_ptr) {
159   // Buffer sufficient to read a section header and find the pointer to the next
160   // section.
161   const uint32_t kBufferSize = 1024;
162   DataExtractor section_header_data = ReadImageData(*offset_ptr, kBufferSize);
163 
164   llvm::DataExtractor data = section_header_data.GetAsLLVM();
165   llvm::DataExtractor::Cursor c(0);
166 
167   // Each section consists of:
168   // - a one-byte section id,
169   // - the u32 size of the contents, in bytes,
170   // - the actual contents.
171   uint8_t section_id = data.getU8(c);
172   uint64_t payload_len = data.getULEB128(c);
173   if (!c)
174     return !llvm::errorToBool(c.takeError());
175 
176   if (payload_len >= (uint64_t(1) << 32))
177     return false;
178 
179   if (section_id == llvm::wasm::WASM_SEC_CUSTOM) {
180     lldb::offset_t prev_offset = c.tell();
181     llvm::Optional<ConstString> sect_name = GetWasmString(data, c);
182     if (!sect_name)
183       return false;
184 
185     if (payload_len < c.tell() - prev_offset)
186       return false;
187 
188     uint32_t section_length = payload_len - (c.tell() - prev_offset);
189     m_sect_infos.push_back(section_info{*offset_ptr + c.tell(), section_length,
190                                         section_id, *sect_name});
191     *offset_ptr += (c.tell() + section_length);
192   } else if (section_id <= llvm::wasm::WASM_SEC_EVENT) {
193     m_sect_infos.push_back(section_info{*offset_ptr + c.tell(),
194                                         static_cast<uint32_t>(payload_len),
195                                         section_id, ConstString()});
196     *offset_ptr += (c.tell() + payload_len);
197   } else {
198     // Invalid section id.
199     return false;
200   }
201   return true;
202 }
203 
204 bool ObjectFileWasm::DecodeSections() {
205   lldb::offset_t offset = kWasmHeaderSize;
206   if (IsInMemory()) {
207     offset += m_memory_addr;
208   }
209 
210   while (DecodeNextSection(&offset))
211     ;
212   return true;
213 }
214 
215 size_t ObjectFileWasm::GetModuleSpecifications(
216     const FileSpec &file, DataBufferSP &data_sp, offset_t data_offset,
217     offset_t file_offset, offset_t length, ModuleSpecList &specs) {
218   if (!ValidateModuleHeader(data_sp)) {
219     return 0;
220   }
221 
222   ModuleSpec spec(file, ArchSpec("wasm32-unknown-unknown-wasm"));
223   specs.Append(spec);
224   return 1;
225 }
226 
227 ObjectFileWasm::ObjectFileWasm(const ModuleSP &module_sp, DataBufferSP &data_sp,
228                                offset_t data_offset, const FileSpec *file,
229                                offset_t offset, offset_t length)
230     : ObjectFile(module_sp, file, offset, length, data_sp, data_offset),
231       m_arch("wasm32-unknown-unknown-wasm"), m_code_section_offset(0) {
232   m_data.SetAddressByteSize(4);
233 }
234 
235 ObjectFileWasm::ObjectFileWasm(const lldb::ModuleSP &module_sp,
236                                lldb::DataBufferSP &header_data_sp,
237                                const lldb::ProcessSP &process_sp,
238                                lldb::addr_t header_addr)
239     : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
240       m_arch("wasm32-unknown-unknown-wasm"), m_code_section_offset(0) {}
241 
242 bool ObjectFileWasm::ParseHeader() {
243   // We already parsed the header during initialization.
244   return true;
245 }
246 
247 Symtab *ObjectFileWasm::GetSymtab() { return nullptr; }
248 
249 void ObjectFileWasm::CreateSections(SectionList &unified_section_list) {
250   if (m_sections_up)
251     return;
252 
253   m_sections_up = std::make_unique<SectionList>();
254 
255   if (m_sect_infos.empty()) {
256     DecodeSections();
257   }
258 
259   for (const section_info &sect_info : m_sect_infos) {
260     SectionType section_type = eSectionTypeOther;
261     ConstString section_name;
262     offset_t file_offset = 0;
263     addr_t vm_addr = 0;
264     size_t vm_size = 0;
265 
266     if (llvm::wasm::WASM_SEC_CODE == sect_info.id) {
267       section_type = eSectionTypeCode;
268       section_name = ConstString("code");
269       m_code_section_offset = sect_info.offset & 0xffffffff;
270       vm_size = sect_info.size;
271     } else {
272       section_type =
273           llvm::StringSwitch<SectionType>(sect_info.name.GetStringRef())
274               .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev)
275               .Case(".debug_addr", eSectionTypeDWARFDebugAddr)
276               .Case(".debug_aranges", eSectionTypeDWARFDebugAranges)
277               .Case(".debug_cu_index", eSectionTypeDWARFDebugCuIndex)
278               .Case(".debug_frame", eSectionTypeDWARFDebugFrame)
279               .Case(".debug_info", eSectionTypeDWARFDebugInfo)
280               .Case(".debug_line", eSectionTypeDWARFDebugLine)
281               .Case(".debug_line_str", eSectionTypeDWARFDebugLineStr)
282               .Case(".debug_loc", eSectionTypeDWARFDebugLoc)
283               .Case(".debug_loclists", eSectionTypeDWARFDebugLocLists)
284               .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo)
285               .Case(".debug_macro", eSectionTypeDWARFDebugMacro)
286               .Case(".debug_names", eSectionTypeDWARFDebugNames)
287               .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames)
288               .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes)
289               .Case(".debug_ranges", eSectionTypeDWARFDebugRanges)
290               .Case(".debug_rnglists", eSectionTypeDWARFDebugRngLists)
291               .Case(".debug_str", eSectionTypeDWARFDebugStr)
292               .Case(".debug_str_offsets", eSectionTypeDWARFDebugStrOffsets)
293               .Case(".debug_types", eSectionTypeDWARFDebugTypes)
294               .Default(eSectionTypeOther);
295       if (section_type == eSectionTypeOther)
296         continue;
297       section_name = sect_info.name;
298       file_offset = sect_info.offset & 0xffffffff;
299       if (IsInMemory()) {
300         vm_addr = sect_info.offset & 0xffffffff;
301         vm_size = sect_info.size;
302       }
303     }
304 
305     SectionSP section_sp(
306         new Section(GetModule(), // Module to which this section belongs.
307                     this,        // ObjectFile to which this section belongs and
308                                  // should read section data from.
309                     section_type,   // Section ID.
310                     section_name,   // Section name.
311                     section_type,   // Section type.
312                     vm_addr,        // VM address.
313                     vm_size,        // VM size in bytes of this section.
314                     file_offset,    // Offset of this section in the file.
315                     sect_info.size, // Size of the section as found in the file.
316                     0,              // Alignment of the section
317                     0,              // Flags for this section.
318                     1));            // Number of host bytes per target byte
319     m_sections_up->AddSection(section_sp);
320     unified_section_list.AddSection(section_sp);
321   }
322 }
323 
324 bool ObjectFileWasm::SetLoadAddress(Target &target, lldb::addr_t load_address,
325                                     bool value_is_offset) {
326   /// In WebAssembly, linear memory is disjointed from code space. The VM can
327   /// load multiple instances of a module, which logically share the same code.
328   /// We represent a wasm32 code address with 64-bits, like:
329   /// 63            32 31             0
330   /// +---------------+---------------+
331   /// +   module_id   |     offset    |
332   /// +---------------+---------------+
333   /// where the lower 32 bits represent a module offset (relative to the module
334   /// start not to the beginning of the code section) and the higher 32 bits
335   /// uniquely identify the module in the WebAssembly VM.
336   /// In other words, we assume that each WebAssembly module is loaded by the
337   /// engine at a 64-bit address that starts at the boundary of 4GB pages, like
338   /// 0x0000000400000000 for module_id == 4.
339   /// These 64-bit addresses will be used to request code ranges for a specific
340   /// module from the WebAssembly engine.
341   ModuleSP module_sp = GetModule();
342   if (!module_sp)
343     return false;
344 
345   DecodeSections();
346 
347   size_t num_loaded_sections = 0;
348   SectionList *section_list = GetSectionList();
349   if (!section_list)
350     return false;
351 
352   const size_t num_sections = section_list->GetSize();
353   size_t sect_idx = 0;
354 
355   for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
356     SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
357     if (target.GetSectionLoadList().SetSectionLoadAddress(
358             section_sp, load_address | section_sp->GetFileAddress())) {
359       ++num_loaded_sections;
360     }
361   }
362 
363   return num_loaded_sections > 0;
364 }
365 
366 DataExtractor ObjectFileWasm::ReadImageData(uint64_t offset, size_t size) {
367   DataExtractor data;
368   if (m_file) {
369     if (offset < GetByteSize()) {
370       size = std::min(size, (size_t) (GetByteSize() - offset));
371       auto buffer_sp = MapFileData(m_file, size, offset);
372       return DataExtractor(buffer_sp, GetByteOrder(), GetAddressByteSize());
373     }
374   } else {
375     ProcessSP process_sp(m_process_wp.lock());
376     if (process_sp) {
377       auto data_up = std::make_unique<DataBufferHeap>(size, 0);
378       Status readmem_error;
379       size_t bytes_read = process_sp->ReadMemory(
380           offset, data_up->GetBytes(), data_up->GetByteSize(), readmem_error);
381       if (bytes_read > 0) {
382         DataBufferSP buffer_sp(data_up.release());
383         data.SetData(buffer_sp, 0, buffer_sp->GetByteSize());
384       }
385     }
386   }
387 
388   data.SetByteOrder(GetByteOrder());
389   return data;
390 }
391 
392 void ObjectFileWasm::Dump(Stream *s) {
393   ModuleSP module_sp(GetModule());
394   if (!module_sp)
395     return;
396 
397   std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
398 
399   llvm::raw_ostream &ostream = s->AsRawOstream();
400   ostream << static_cast<void *>(this) << ": ";
401   s->Indent();
402   ostream << "ObjectFileWasm, file = '";
403   m_file.Dump(ostream);
404   ostream << "', arch = ";
405   ostream << GetArchitecture().GetArchitectureName() << "\n";
406 
407   SectionList *sections = GetSectionList();
408   if (sections) {
409     sections->Dump(s, nullptr, true, UINT32_MAX);
410   }
411   ostream << "\n";
412   DumpSectionHeaders(ostream);
413   ostream << "\n";
414 }
415 
416 void ObjectFileWasm::DumpSectionHeader(llvm::raw_ostream &ostream,
417                                        const section_info_t &sh) {
418   ostream << llvm::left_justify(sh.name.GetStringRef(), 16) << " "
419           << llvm::format_hex(sh.offset, 10) << " "
420           << llvm::format_hex(sh.size, 10) << " " << llvm::format_hex(sh.id, 6)
421           << "\n";
422 }
423 
424 void ObjectFileWasm::DumpSectionHeaders(llvm::raw_ostream &ostream) {
425   ostream << "Section Headers\n";
426   ostream << "IDX  name             addr       size       id\n";
427   ostream << "==== ---------------- ---------- ---------- ------\n";
428 
429   uint32_t idx = 0;
430   for (auto pos = m_sect_infos.begin(); pos != m_sect_infos.end();
431        ++pos, ++idx) {
432     ostream << "[" << llvm::format_decimal(idx, 2) << "] ";
433     ObjectFileWasm::DumpSectionHeader(ostream, *pos);
434   }
435 }
436