[Go to site: main page, start]

LLDB mainline
ProcessElfCore.cpp
Go to the documentation of this file.
1//===-- ProcessElfCore.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 <algorithm>
10#include <cstdlib>
11
12#include <memory>
13#include <vector>
14
15#include "lldb/Core/Module.h"
18#include "lldb/Core/Section.h"
19#include "lldb/Target/ABI.h"
22#include "lldb/Target/Target.h"
26#include "lldb/Utility/Log.h"
27#include "lldb/Utility/State.h"
28
29#include "llvm/BinaryFormat/ELF.h"
30
36#include "ProcessElfCore.h"
37#include "ThreadElfCore.h"
38
39using namespace lldb_private;
40namespace ELF = llvm::ELF;
41
43
45 return "ELF core dump plug-in.";
46}
47
51
53 lldb::ListenerSP listener_sp,
54 const FileSpec *crash_file,
55 bool can_connect) {
56 lldb::ProcessSP process_sp;
57 if (crash_file && !can_connect) {
58 // Read enough data for an ELF32 header or ELF64 header Note: Here we care
59 // about e_type field only, so it is safe to ignore possible presence of
60 // the header extension.
61 const size_t header_size = sizeof(llvm::ELF::Elf64_Ehdr);
62
64 crash_file->GetPath(), header_size, 0);
65 if (data_sp && data_sp->GetByteSize() == header_size &&
66 elf::ELFHeader::MagicBytesMatch(data_sp->GetBytes())) {
67 elf::ELFHeader elf_header;
68 DataExtractor data(data_sp, lldb::eByteOrderLittle, 4);
69 lldb::offset_t data_offset = 0;
70 if (elf_header.Parse(data, &data_offset)) {
71 // Check whether we're dealing with a raw FreeBSD "full memory dump"
72 // ELF vmcore that needs to be handled via FreeBSDKernel plugin instead.
73 if (elf_header.e_ident[7] == 0xFF && elf_header.e_version == 0)
74 return process_sp;
75 if (elf_header.e_type == llvm::ELF::ET_CORE)
76 process_sp = std::make_shared<ProcessElfCore>(target_sp, listener_sp,
77 *crash_file);
78 }
79 }
80 }
81 return process_sp;
82}
83
85 bool plugin_specified_by_name) {
86 // For now we are just making sure the file exists for a given module
88 ModuleSpec core_module_spec(m_core_file, target_sp->GetArchitecture());
89 core_module_spec.SetTarget(target_sp);
91 nullptr, nullptr));
92 if (m_core_module_sp) {
93 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
94 if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile)
95 return true;
96 }
97 }
98 return false;
99}
100
101// ProcessElfCore constructor
103 lldb::ListenerSP listener_sp,
104 const FileSpec &core_file)
105 : PostMortemProcess(target_sp, listener_sp, core_file), m_uuids() {}
106
107// Destructor
109 Clear();
110 // We need to call finalize on the process before destroying ourselves to
111 // make sure all of the broadcaster cleanup goes as planned. If we destruct
112 // this class, then Process::~Process() might have problems trying to fully
113 // destroy the broadcaster.
114 Finalize(true /* destructing */);
115}
116
118 const elf::ELFProgramHeader &header) {
119 const lldb::addr_t addr = header.p_vaddr;
120 FileRange file_range(header.p_offset, header.p_filesz);
121 VMRangeToFileOffset::Entry range_entry(addr, header.p_memsz, file_range);
122
123 // Only add to m_core_aranges if the file size is non zero. Some core files
124 // have PT_LOAD segments for all address ranges, but set f_filesz to zero for
125 // the .text sections since they can be retrieved from the object files.
126 if (header.p_filesz > 0) {
127 VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
128 if (last_entry && last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
129 last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase() &&
130 last_entry->GetByteSize() == last_entry->data.GetByteSize()) {
131 last_entry->SetRangeEnd(range_entry.GetRangeEnd());
132 last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd());
133 } else {
134 m_core_aranges.Append(range_entry);
135 }
136 }
137 // Keep mapped regions separate from m_core_aranges and uncoalesced so each
138 // PT_LOAD's permissions are preserved.
139 const uint32_t permissions =
140 ((header.p_flags & llvm::ELF::PF_R) ? lldb::ePermissionsReadable : 0u) |
141 ((header.p_flags & llvm::ELF::PF_W) ? lldb::ePermissionsWritable : 0u) |
142 ((header.p_flags & llvm::ELF::PF_X) ? lldb::ePermissionsExecutable : 0u);
143
144 MemoryRegionInfo region_info;
145 region_info.GetRange() = MemoryRegionInfo::RangeType(addr, header.p_memsz);
146 region_info.SetLLDBPermissions(permissions);
147 region_info.SetMapped(eLazyBoolYes);
148 region_info.SetMemoryTagged(eLazyBoolNo);
149 m_core_range_infos.insert(std::move(region_info));
150
151 return addr;
152}
153
155 const elf::ELFProgramHeader &header) {
156 // If lldb understood multiple kinds of tag segments we would record the type
157 // of the segment here also. As long as there is only 1 type lldb looks for,
158 // there is no need.
159 FileRange file_range(header.p_offset, header.p_filesz);
160 m_core_tag_ranges.Append(
161 VMRangeToFileOffset::Entry(header.p_vaddr, header.p_memsz, file_range));
162
163 return header.p_vaddr;
164}
165
166// Process Control
169 if (!m_core_module_sp) {
170 error = Status::FromErrorString("invalid core module");
171 return error;
172 }
173
174 ObjectFileELF *core = (ObjectFileELF *)(m_core_module_sp->GetObjectFile());
175 if (core == nullptr) {
176 error = Status::FromErrorString("invalid core object file");
177 return error;
178 }
179
180 llvm::ArrayRef<elf::ELFProgramHeader> segments = core->ProgramHeaders();
181 if (segments.size() == 0) {
182 error = Status::FromErrorString("core file has no segments");
183 return error;
184 }
185
186 // Even if the architecture is set in the target, we need to override it to
187 // match the core file which is always single arch.
188 ArchSpec arch(m_core_module_sp->GetArchitecture());
189
190 ArchSpec target_arch = GetTarget().GetArchitecture();
191 ArchSpec core_arch(m_core_module_sp->GetArchitecture());
192 target_arch.MergeFrom(core_arch);
193 GetTarget().SetArchitecture(target_arch, /*set_platform*/ true);
194
196
197 SetCanJIT(false);
198
199 m_thread_data_valid = true;
200
201 bool ranges_are_sorted = true;
202 lldb::addr_t vm_addr = 0;
203 lldb::addr_t tag_addr = 0;
204 /// Walk through segments and Thread and Address Map information.
205 /// PT_NOTE - Contains Thread and Register information
206 /// PT_LOAD - Contains a contiguous range of Process Address Space
207 /// PT_AARCH64_MEMTAG_MTE - Contains AArch64 MTE memory tags for a range of
208 /// Process Address Space.
209 for (const elf::ELFProgramHeader &H : segments) {
210
211 // Parse thread contexts and auxv structure
212 if (H.p_type == llvm::ELF::PT_NOTE) {
213 DataExtractor data = core->GetSegmentData(H);
214 if (llvm::Error error = ParseThreadContextsFromNoteSegment(H, data))
215 return Status::FromError(std::move(error));
216 }
217 // PT_LOAD segments contains address map
218 if (H.p_type == llvm::ELF::PT_LOAD) {
220 if (vm_addr > last_addr)
221 ranges_are_sorted = false;
222 vm_addr = last_addr;
223 } else if (H.p_type == llvm::ELF::PT_AARCH64_MEMTAG_MTE) {
225 if (tag_addr > last_addr)
226 ranges_are_sorted = false;
227 tag_addr = last_addr;
228 }
229 }
230
231 if (!ranges_are_sorted) {
232 m_core_aranges.Sort();
233 m_core_tag_ranges.Sort();
234 }
235
237
238 // Ensure we found at least one thread that was stopped on a signal.
239 bool siginfo_signal_found = false;
240 bool prstatus_signal_found = false;
241 // Check we found a signal in a SIGINFO note.
242 for (const auto &thread_data : m_thread_data) {
243 if (!thread_data.siginfo_bytes.empty() || thread_data.signo != 0)
244 siginfo_signal_found = true;
245 if (thread_data.prstatus_sig != 0)
246 prstatus_signal_found = true;
247 }
248 if (!siginfo_signal_found) {
249 // If we don't have signal from SIGINFO use the signal from each threads
250 // PRSTATUS note.
251 if (prstatus_signal_found) {
252 for (auto &thread_data : m_thread_data)
253 thread_data.signo = thread_data.prstatus_sig;
254 } else if (m_thread_data.size() > 0) {
255 // If all else fails force the first thread to be SIGSTOP
256 m_thread_data.begin()->signo =
257 GetUnixSignals()->GetSignalNumberFromName("SIGSTOP");
258 }
259 }
260
261 // Try to find gnu build id before we load the executable.
263
264 // Core files are useless without the main executable. See if we can locate
265 // the main executable using data we found in the core file notes.
266 lldb::ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
267 if (!exe_module_sp) {
268 ModuleSpec exe_module_spec;
269 if (GetMainExecutableModuleSpec(exe_module_spec)) {
270 exe_module_sp =
271 GetTarget().GetOrCreateModule(exe_module_spec, true /* notify */);
272 if (!exe_module_sp) {
273 // Create an ELF file from memory for the main executable. The dynamic
274 // loader requires the main executable so that it can extract the
275 // DT_DEBUG key/value pair from the dynamic section and get the list
276 // of shared libraries.
277 std::optional<NT_FILE_Entry> exe_header =
279 if (exe_header) {
280 if (llvm::Expected<lldb::ModuleSP> module_sp_or_err =
281 ReadModuleFromMemory(exe_module_spec.GetFileSpec(),
282 exe_header->start,
283 exe_header->end - exe_header->start))
284 exe_module_sp = *module_sp_or_err;
285 else
286 llvm::consumeError(module_sp_or_err.takeError());
287 }
288 // Create a placeholder module for the main executable if we failed to
289 // create an ELF module from memory.
290 if (!exe_module_sp) {
291 lldb::addr_t load_addr =
292 exe_header ? exe_header->start : LLDB_INVALID_ADDRESS;
293 lldb::addr_t size =
294 exe_header ? (exe_header->end - exe_header->start) : 0;
295 exe_module_sp =
297 exe_module_spec, load_addr, size);
298 if (exe_module_spec.GetPlatformFileSpec())
299 exe_module_sp->SetPlatformFileSpec(
300 exe_module_spec.GetPlatformFileSpec());
301 }
302 }
303 if (exe_module_sp)
305 }
306 }
307 return error;
308}
309
312 m_uuids.clear();
313 for (NT_FILE_Entry &entry : m_nt_file_entries) {
314 UUID uuid = FindBuidIdInCoreMemory(entry.start);
315 if (uuid.IsValid()) {
316 // Assert that either the path is not in the map or the UUID matches
317 assert(m_uuids.count(entry.path) == 0 || m_uuids[entry.path] == uuid);
318 m_uuids[entry.path] = uuid;
319 LLDB_LOGF(log, "%s found UUID @ %16.16" PRIx64 ": %s \"%s\"",
320 __FUNCTION__, entry.start, uuid.GetAsString().c_str(),
321 entry.path.c_str());
322 }
323 }
324}
325
327 std::set<MemoryRegionInfo, std::less<>> finalized_regions;
328 // Add NT_FILE paths as names to PT_LOAD regions with matching start
329 // addresses, preserving the PT_LOAD ranges and permissions.
330 for (MemoryRegionInfo region_info : m_core_range_infos) {
331 const lldb::addr_t range_base = region_info.GetRange().GetRangeBase();
332 const lldb::addr_t range_end = region_info.GetRange().GetRangeEnd();
333
334 auto file_entry =
335 std::find_if(m_nt_file_entries.begin(), m_nt_file_entries.end(),
336 [range_base](const NT_FILE_Entry &entry) {
337 return entry.start == range_base;
338 });
339 if (file_entry != m_nt_file_entries.end() && !file_entry->path.empty())
340 region_info.SetName(file_entry->path.c_str());
341
342 const VMRangeToFileOffset::Entry *tag_entry =
343 m_core_tag_ranges.FindEntryStartsAt(range_base);
344 if (tag_entry && tag_entry->GetRangeEnd() == range_end)
345 region_info.SetMemoryTagged(eLazyBoolYes);
346
347 finalized_regions.insert(std::move(region_info));
348 }
349
350 // Create mapped regions with unknown permissions for portions of NT_FILE
351 // entries not covered by any PT_LOAD region.
352 for (const NT_FILE_Entry &file_entry : m_nt_file_entries) {
353 if (file_entry.start >= file_entry.end)
354 continue;
355
356 lldb::addr_t cursor = file_entry.start;
357 std::vector<MemoryRegionInfo::RangeType> uncovered_ranges;
358 for (const MemoryRegionInfo &region_info : finalized_regions) {
359 const lldb::addr_t range_base = region_info.GetRange().GetRangeBase();
360 const lldb::addr_t range_end = region_info.GetRange().GetRangeEnd();
361
362 if (range_end <= cursor)
363 continue;
364 if (range_base >= file_entry.end)
365 break;
366
367 if (cursor < range_base)
368 uncovered_ranges.emplace_back(cursor, range_base - cursor);
369
370 cursor = std::max(cursor, range_end);
371 if (cursor >= file_entry.end)
372 break;
373 }
374
375 if (cursor < file_entry.end)
376 uncovered_ranges.emplace_back(cursor, file_entry.end - cursor);
377
378 for (const MemoryRegionInfo::RangeType &range : uncovered_ranges) {
379 MemoryRegionInfo region_info;
380 region_info.GetRange() = range;
381 region_info.SetMapped(eLazyBoolYes);
382 if (!file_entry.path.empty())
383 region_info.SetName(file_entry.path.c_str());
384 finalized_regions.insert(std::move(region_info));
385 }
386 }
387 m_core_range_infos = std::move(finalized_regions);
388}
389
390/// Correctly create a FileSpec from a path found in a core file.
391///
392/// This method will guess the path style more intelligently that specifying
393/// a native path style since core files can contain paths from a different
394/// system than the host system.
395static FileSpec CreateFileSpecFromPath(llvm::StringRef path) {
396 FileSpec::Style path_style = FileSpec::Style::native;
397 if (auto guessed_style = FileSpec::GuessPathStyle(path))
398 path_style = *guessed_style;
399 return FileSpec(path, path_style);
400}
401
403 AuxVector aux_vector(m_auxv);
405
406 // Find the NT_FILE_Entry for the main executable's ELF header.
407 std::optional<NT_FILE_Entry> exe_header =
409 if (exe_header) {
410 exe_spec.GetFileSpec() = CreateFileSpecFromPath(exe_header->path);
411 exe_spec.SetLoadAddress(exe_header->start);
412 }
413
414 // If we failed to find the executable program in the NT_FILE list with the
415 // program header address, then we can read the executable name from the value
416 // of the AUXV_AT_EXECFN in the AUX vector. The reason we don't use this file
417 // all of the time is if the program is launched using a symlink, the value of
418 // the AUXV_AT_EXECFN string will be the symlink itself. The same goes for the
419 // m_executable_name found in the NT_PRPSINFO section, it will be the name of
420 // the symlink. Even if we did find a path above, we want to fill in this path
421 // if it is different from main executable's path in the platform file name
422 // in case someone needs to know how the executable was launched.
423 if (auto execfn = aux_vector.GetAuxValue(AuxVector::AUXV_AT_EXECFN)) {
425 std::string execfn_str;
426 if (ReadCStringFromMemory(*execfn, execfn_str, error)) {
427 // This path can be a symlink path. Set it as the main file spec if one
428 // hasn't been set, else set the platform file spec.
429 FileSpec execfn_spec = CreateFileSpecFromPath(execfn_str);
430 if (exe_spec.GetFileSpec()) {
431 // Fill in the platform file spec if it differs from the main path from
432 // the resolved file info in the NT_FILE note.
433 if (exe_spec.GetFileSpec() != execfn_spec)
434 exe_spec.GetPlatformFileSpec() = execfn_spec;
435 } else {
436 // We don't have an executable file spec yet, lets set it.
437 exe_spec.GetFileSpec() = execfn_spec;
438 }
439 }
440 }
441
442 // If we didn't set the executable file spec yet, lets set it from the info
443 // from the NT_PRPSINFO. This usually is just a basename of the actual path
444 // used to launch the binary, so this can be a symlink basename. But it will
445 // be better than nothing since we will create a placeholder module for any
446 // files that don't exist.
447 if (!exe_spec.GetFileSpec() && !m_executable_name.empty())
449
450 // Try and find the UUID after the module spec was filled in.
451 FindModuleUUID(exe_spec);
452
453 // We succeeded if we got a path.
454 return (bool)exe_spec.GetFileSpec();
455}
456
458 if (spec.GetUUID().IsValid())
459 return true;
460 // Lookup the UUID for the given path in the map.
461 // Note that this could be called by multiple threads so make sure
462 // we access the map in a thread safe way (i.e. don't use operator[]).
463 std::string path;
464 // Sometimes the path to a file or shared library from the dynamic loader,
465 // one of the main clients of this function, is a symlink. The information
466 // in the NT_FILE note contains resolved paths and might not match. The
467 // best way for us to find a module is by load address, so use this trick
468 // if the load address is set in the module specification.
469 if (std::optional<lldb::addr_t> load_addr = spec.GetLoadAddress()) {
470 if (std::optional<NT_FILE_Entry> nt =
472 path = nt->path;
473 }
474 // If we didn't find a file spec from the load address, fall back to using
475 // the file spec.
476 if (path.empty())
477 path = spec.GetFileSpec().GetPath();
478
479 auto it = m_uuids.find(path);
480 if (it != m_uuids.end()) {
482 spec.GetUUID() = it->second;
483 LLDB_LOGF(log, "ProcessElfCore::FindModuleUUID() found UUID for %s: %s",
484 spec.GetFileSpec().GetPath().c_str(),
485 it->second.GetAsString().c_str());
486 }
487 return spec.GetUUID().IsValid();
488}
489
491 if (!m_dyld_up) {
492 llvm::StringRef dyld_name;
493 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::riscv32 &&
494 GetTarget().GetArchitecture().GetTriple().getOS() ==
495 llvm::Triple::UnknownOS)
497 else
499 m_dyld_up.reset(DynamicLoader::FindPlugin(this, dyld_name));
500 }
501 return m_dyld_up.get();
502}
503
505 ThreadList &new_thread_list) {
506 const uint32_t num_threads = GetNumThreadContexts();
508 return false;
509
510 for (lldb::tid_t tid = 0; tid < num_threads; ++tid) {
511 const ThreadData &td = m_thread_data[tid];
512 lldb::ThreadSP thread_sp(new ThreadElfCore(*this, td));
513 new_thread_list.AddThread(thread_sp);
514 }
515 return new_thread_list.GetSize(false) > 0;
516}
517
519
521
522// Process Queries
523
524bool ProcessElfCore::IsAlive() { return true; }
525
526// Process Memory
527size_t ProcessElfCore::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
528 Status &error) {
529 if (lldb::ABISP abi_sp = GetABI())
530 addr = abi_sp->FixAnyAddress(addr);
531
532 // Don't allow the caching that lldb_private::Process::ReadMemory does since
533 // in core files we have it all cached our our core file anyway.
534 return DoReadMemory(addr, buf, size, error);
535}
536
538 MemoryRegionInfo &region_info) {
539 region_info.Clear();
540 auto following = m_core_range_infos.upper_bound(load_addr);
541 // PT_LOAD ranges can overlap, so the immediate predecessor is not
542 // necessarily the range containing load_addr.
543 auto range_entry = std::find_if(m_core_range_infos.begin(), following,
544 [load_addr](const auto &entry) {
545 return entry.GetRange().Contains(load_addr);
546 });
547 if (range_entry != following) {
548 region_info = *range_entry;
549 return Status();
550 }
551
552 region_info.GetRange().SetRangeBase(load_addr);
553 region_info.GetRange().SetRangeEnd(
554 following == m_core_range_infos.end()
556 : following->GetRange().GetRangeBase());
557 region_info.SetReadable(eLazyBoolNo);
558 region_info.SetWritable(eLazyBoolNo);
559 region_info.SetExecutable(eLazyBoolNo);
560 region_info.SetMapped(eLazyBoolNo);
561 region_info.SetMemoryTagged(eLazyBoolNo);
562 return Status();
563}
564
565size_t ProcessElfCore::DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
566 Status &error) {
567 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
568
569 if (core_objfile == nullptr)
570 return 0;
571
572 // Get the address range
573 const VMRangeToFileOffset::Entry *address_range =
574 m_core_aranges.FindEntryThatContains(addr);
575 if (address_range == nullptr || address_range->GetRangeEnd() < addr) {
577 "core file does not contain 0x%" PRIx64, addr);
578 return 0;
579 }
580
581 // Convert the address into core file offset
582 const lldb::addr_t offset = addr - address_range->GetRangeBase();
583 const lldb::addr_t file_start = address_range->data.GetRangeBase();
584 const lldb::addr_t file_end = address_range->data.GetRangeEnd();
585 size_t bytes_to_read = size; // Number of bytes to read from the core file
586 size_t bytes_copied = 0; // Number of bytes actually read from the core file
587 lldb::addr_t bytes_left =
588 0; // Number of bytes available in the core file from the given address
589
590 // Don't proceed if core file doesn't contain the actual data for this
591 // address range.
592 if (file_start == file_end)
593 return 0;
594
595 // Figure out how many on-disk bytes remain in this segment starting at the
596 // given offset
597 if (file_end > file_start + offset)
598 bytes_left = file_end - (file_start + offset);
599
600 if (bytes_to_read > bytes_left)
601 bytes_to_read = bytes_left;
602
603 // If there is data available on the core file read it
604 if (bytes_to_read)
605 bytes_copied =
606 core_objfile->CopyData(offset + file_start, bytes_to_read, buf);
607
608 return bytes_copied;
609}
610
611llvm::Expected<std::vector<lldb::addr_t>>
613 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
614 if (core_objfile == nullptr)
615 return llvm::createStringError(llvm::inconvertibleErrorCode(),
616 "No core object file.");
617
618 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
620 if (!tag_manager_or_err)
621 return tag_manager_or_err.takeError();
622
623 // LLDB only supports AArch64 MTE tag segments so we do not need to worry
624 // about the segment type here. If you got here then you must have a tag
625 // manager (meaning you are debugging AArch64) and all the segments in this
626 // list will have had type PT_AARCH64_MEMTAG_MTE.
627 const VMRangeToFileOffset::Entry *tag_entry =
628 m_core_tag_ranges.FindEntryThatContains(addr);
629 // If we don't have a tag segment or the range asked for extends outside the
630 // segment.
631 if (!tag_entry || (addr + len) >= tag_entry->GetRangeEnd())
632 return llvm::createStringError(llvm::inconvertibleErrorCode(),
633 "No tag segment that covers this range.");
634
635 const MemoryTagManager *tag_manager = *tag_manager_or_err;
636 return tag_manager->UnpackTagsFromCoreFileSegment(
637 [core_objfile](lldb::offset_t offset, size_t length, void *dst) {
638 return core_objfile->CopyData(offset, length, dst);
639 },
640 tag_entry->GetRangeBase(), tag_entry->data.GetRangeBase(), addr, len);
641}
642
644 m_thread_list.Clear();
645
646 SetUnixSignals(std::make_shared<UnixSignals>());
647}
648
653
655 ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile();
656 Address addr = obj_file->GetImageInfoAddress(&GetTarget());
657
658 if (addr.IsValid())
659 return addr.GetLoadAddress(&GetTarget());
661}
662
663// Parse a FreeBSD NT_PRSTATUS note - see FreeBSD sys/procfs.h for details.
664static void ParseFreeBSDPrStatus(ThreadData &thread_data,
665 const DataExtractor &data,
666 bool lp64) {
667 lldb::offset_t offset = 0;
668 int pr_version = data.GetU32(&offset);
669
671 if (pr_version > 1)
672 LLDB_LOGF(log, "FreeBSD PRSTATUS unexpected version %d", pr_version);
673
674 // Skip padding, pr_statussz, pr_gregsetsz, pr_fpregsetsz, pr_osreldate
675 if (lp64)
676 offset += 32;
677 else
678 offset += 16;
679
680 thread_data.signo = data.GetU32(&offset); // pr_cursig
681 thread_data.tid = data.GetU32(&offset); // pr_pid
682 if (lp64)
683 offset += 4;
684
685 size_t len = data.GetByteSize() - offset;
686 thread_data.gpregset = DataExtractor(data, offset, len);
687}
688
689// Parse a FreeBSD NT_PRPSINFO note - see FreeBSD sys/procfs.h for details.
691 const DataExtractor &data,
692 bool lp64) {
693 lldb::offset_t offset = 0;
694 int pr_version = data.GetU32(&offset);
695
697 if (pr_version > 1)
698 LLDB_LOGF(log, "FreeBSD PRPSINFO unexpected version %d", pr_version);
699
700 // Skip pr_psinfosz, pr_fname, pr_psargs
701 offset += 108;
702 if (lp64)
703 offset += 4;
704
705 process.SetID(data.GetU32(&offset)); // pr_pid
706}
707
708static llvm::Error ParseNetBSDProcInfo(const DataExtractor &data,
709 uint32_t &cpi_nlwps,
710 uint32_t &cpi_signo,
711 uint32_t &cpi_siglwp,
712 uint32_t &cpi_pid) {
713 lldb::offset_t offset = 0;
714
715 uint32_t version = data.GetU32(&offset);
716 if (version != 1)
717 return llvm::createStringError(
718 "Error parsing NetBSD core(5) notes: Unsupported procinfo version");
719
720 uint32_t cpisize = data.GetU32(&offset);
721 if (cpisize != NETBSD::NT_PROCINFO_SIZE)
722 return llvm::createStringError(
723 "Error parsing NetBSD core(5) notes: Unsupported procinfo size");
724
725 cpi_signo = data.GetU32(&offset); /* killing signal */
726
732 cpi_pid = data.GetU32(&offset);
742 cpi_nlwps = data.GetU32(&offset); /* number of LWPs */
743
745 cpi_siglwp = data.GetU32(&offset); /* LWP target of killing signal */
746
747 return llvm::Error::success();
748}
749
750static void ParseOpenBSDProcInfo(ThreadData &thread_data,
751 const DataExtractor &data) {
752 lldb::offset_t offset = 0;
753
754 int version = data.GetU32(&offset);
755 if (version != 1)
756 return;
757
758 offset += 4;
759 thread_data.signo = data.GetU32(&offset);
760}
761
762llvm::Expected<std::vector<CoreNote>>
764 lldb::offset_t offset = 0;
765 std::vector<CoreNote> result;
766
767 while (offset < segment.GetByteSize()) {
768 ELFNote note = ELFNote();
769 if (!note.Parse(segment, &offset))
770 return llvm::createStringError("unable to parse note segment");
771
772 size_t note_start = offset;
773 size_t note_size = llvm::alignTo(note.n_descsz, 4);
774
775 result.push_back({note, DataExtractor(segment, note_start, note_size)});
776 offset += note_size;
777 }
778
779 return std::move(result);
780}
781
782llvm::Error ProcessElfCore::parseFreeBSDNotes(llvm::ArrayRef<CoreNote> notes) {
783 ArchSpec arch = GetArchitecture();
784 bool lp64 = (arch.GetMachine() == llvm::Triple::aarch64 ||
785 arch.GetMachine() == llvm::Triple::ppc64 ||
786 arch.GetMachine() == llvm::Triple::x86_64);
787 bool have_prstatus = false;
788 bool have_prpsinfo = false;
789 ThreadData thread_data;
790 for (const auto &note : notes) {
791 if (note.info.n_name != "FreeBSD")
792 continue;
793
794 if ((note.info.n_type == ELF::NT_PRSTATUS && have_prstatus) ||
795 (note.info.n_type == ELF::NT_PRPSINFO && have_prpsinfo)) {
796 assert(thread_data.gpregset.GetByteSize() > 0);
797 // Add the new thread to thread list
798 m_thread_data.push_back(thread_data);
799 thread_data = ThreadData();
800 have_prstatus = false;
801 have_prpsinfo = false;
802 }
803
804 switch (note.info.n_type) {
805 case ELF::NT_PRSTATUS:
806 have_prstatus = true;
807 ParseFreeBSDPrStatus(thread_data, note.data, lp64);
808 break;
809 case ELF::NT_PRPSINFO:
810 have_prpsinfo = true;
811 ParseFreeBSDPrPsInfo(*this, note.data, lp64);
812 break;
813 case ELF::NT_FREEBSD_THRMISC: {
814 lldb::offset_t offset = 0;
815 thread_data.name = note.data.GetCStr(&offset, 20);
816 break;
817 }
818 case ELF::NT_FREEBSD_PROCSTAT_AUXV:
819 // FIXME: FreeBSD sticks an int at the beginning of the note
820 m_auxv = DataExtractor(note.data, 4, note.data.GetByteSize() - 4);
821 break;
822 default:
823 thread_data.notes.push_back(note);
824 break;
825 }
826 }
827 if (!have_prstatus) {
828 return llvm::createStringError(
829 "Could not find NT_PRSTATUS note in core file.");
830 }
831 m_thread_data.push_back(thread_data);
832 return llvm::Error::success();
833}
834
835/// NetBSD specific Thread context from PT_NOTE segment
836///
837/// NetBSD ELF core files use notes to provide information about
838/// the process's state. The note name is "NetBSD-CORE" for
839/// information that is global to the process, and "NetBSD-CORE@nn",
840/// where "nn" is the lwpid of the LWP that the information belongs
841/// to (such as register state).
842///
843/// NetBSD uses the following note identifiers:
844///
845/// ELF_NOTE_NETBSD_CORE_PROCINFO (value 1)
846/// Note is a "netbsd_elfcore_procinfo" structure.
847/// ELF_NOTE_NETBSD_CORE_AUXV (value 2; since NetBSD 8.0)
848/// Note is an array of AuxInfo structures.
849///
850/// NetBSD also uses ptrace(2) request numbers (the ones that exist in
851/// machine-dependent space) to identify register info notes. The
852/// info in such notes is in the same format that ptrace(2) would
853/// export that information.
854///
855/// For more information see /usr/include/sys/exec_elf.h
856///
857llvm::Error ProcessElfCore::parseNetBSDNotes(llvm::ArrayRef<CoreNote> notes) {
858 ThreadData thread_data;
859 bool had_nt_regs = false;
860
861 // To be extracted from struct netbsd_elfcore_procinfo
862 // Used to sanity check of the LWPs of the process
863 uint32_t nlwps = 0;
864 uint32_t signo = 0; // killing signal
865 uint32_t siglwp = 0; // LWP target of killing signal
866 uint32_t pr_pid = 0;
867
868 for (const auto &note : notes) {
869 llvm::StringRef name = note.info.n_name;
870
871 if (name == "NetBSD-CORE") {
872 if (note.info.n_type == NETBSD::NT_PROCINFO) {
873 llvm::Error error = ParseNetBSDProcInfo(note.data, nlwps, signo,
874 siglwp, pr_pid);
875 if (error)
876 return error;
877 SetID(pr_pid);
878 } else if (note.info.n_type == NETBSD::NT_AUXV) {
879 m_auxv = note.data;
880 }
881 } else if (name.consume_front("NetBSD-CORE@")) {
882 lldb::tid_t tid;
883 if (name.getAsInteger(10, tid))
884 return llvm::createStringError(
885 "Error parsing NetBSD core(5) notes: Cannot convert LWP ID "
886 "to integer");
887
888 switch (GetArchitecture().GetMachine()) {
889 case llvm::Triple::aarch64: {
890 // Assume order PT_GETREGS, PT_GETFPREGS
891 if (note.info.n_type == NETBSD::AARCH64::NT_REGS) {
892 // If this is the next thread, push the previous one first.
893 if (had_nt_regs) {
894 m_thread_data.push_back(thread_data);
895 thread_data = ThreadData();
896 had_nt_regs = false;
897 }
898
899 thread_data.gpregset = note.data;
900 thread_data.tid = tid;
901 if (thread_data.gpregset.GetByteSize() == 0)
902 return llvm::createStringError(
903 "Could not find general purpose registers note in core file.");
904 had_nt_regs = true;
905 } else if (note.info.n_type == NETBSD::AARCH64::NT_FPREGS) {
906 if (!had_nt_regs || tid != thread_data.tid)
907 return llvm::createStringError(
908 "Error parsing NetBSD core(5) notes: Unexpected order "
909 "of NOTEs PT_GETFPREG before PT_GETREG");
910 thread_data.notes.push_back(note);
911 }
912 } break;
913 case llvm::Triple::x86: {
914 // Assume order PT_GETREGS, PT_GETFPREGS
915 if (note.info.n_type == NETBSD::I386::NT_REGS) {
916 // If this is the next thread, push the previous one first.
917 if (had_nt_regs) {
918 m_thread_data.push_back(thread_data);
919 thread_data = ThreadData();
920 had_nt_regs = false;
921 }
922
923 thread_data.gpregset = note.data;
924 thread_data.tid = tid;
925 if (thread_data.gpregset.GetByteSize() == 0)
926 return llvm::createStringError(
927 "Could not find general purpose registers note in core file.");
928 had_nt_regs = true;
929 } else if (note.info.n_type == NETBSD::I386::NT_FPREGS) {
930 if (!had_nt_regs || tid != thread_data.tid)
931 return llvm::createStringError(
932 "Error parsing NetBSD core(5) notes: Unexpected order "
933 "of NOTEs PT_GETFPREG before PT_GETREG");
934 thread_data.notes.push_back(note);
935 }
936 } break;
937 case llvm::Triple::x86_64: {
938 // Assume order PT_GETREGS, PT_GETFPREGS
939 if (note.info.n_type == NETBSD::AMD64::NT_REGS) {
940 // If this is the next thread, push the previous one first.
941 if (had_nt_regs) {
942 m_thread_data.push_back(thread_data);
943 thread_data = ThreadData();
944 had_nt_regs = false;
945 }
946
947 thread_data.gpregset = note.data;
948 thread_data.tid = tid;
949 if (thread_data.gpregset.GetByteSize() == 0)
950 return llvm::createStringError(
951 "Could not find general purpose registers note in core file.");
952 had_nt_regs = true;
953 } else if (note.info.n_type == NETBSD::AMD64::NT_FPREGS) {
954 if (!had_nt_regs || tid != thread_data.tid)
955 return llvm::createStringError(
956 "Error parsing NetBSD core(5) notes: Unexpected order "
957 "of NOTEs PT_GETFPREG before PT_GETREG");
958 thread_data.notes.push_back(note);
959 }
960 } break;
961 default:
962 break;
963 }
964 }
965 }
966
967 // Push the last thread.
968 if (had_nt_regs)
969 m_thread_data.push_back(thread_data);
970
971 if (m_thread_data.empty())
972 return llvm::createStringError(
973 "Error parsing NetBSD core(5) notes: No threads information "
974 "specified in notes");
975
976 if (m_thread_data.size() != nlwps)
977 return llvm::createStringError(
978 "Error parsing NetBSD core(5) notes: Mismatch between the number "
979 "of LWPs in netbsd_elfcore_procinfo and the number of LWPs specified "
980 "by MD notes");
981
982 // Signal targeted at the whole process.
983 if (siglwp == 0) {
984 for (auto &data : m_thread_data)
985 data.signo = signo;
986 }
987 // Signal destined for a particular LWP.
988 else {
989 bool passed = false;
990
991 for (auto &data : m_thread_data) {
992 if (data.tid == siglwp) {
993 data.signo = signo;
994 passed = true;
995 break;
996 }
997 }
998
999 if (!passed)
1000 return llvm::createStringError(
1001 "Error parsing NetBSD core(5) notes: Signal passed to unknown LWP");
1002 }
1003
1004 return llvm::Error::success();
1005}
1006
1007llvm::Error ProcessElfCore::parseOpenBSDNotes(llvm::ArrayRef<CoreNote> notes) {
1008 ThreadData thread_data = {};
1009 for (const auto &note : notes) {
1010 // OpenBSD per-thread information is stored in notes named "OpenBSD@nnn" so
1011 // match on the initial part of the string.
1012 if (!llvm::StringRef(note.info.n_name).starts_with("OpenBSD"))
1013 continue;
1014
1015 switch (note.info.n_type) {
1017 ParseOpenBSDProcInfo(thread_data, note.data);
1018 break;
1019 case OPENBSD::NT_AUXV:
1020 m_auxv = note.data;
1021 break;
1022 case OPENBSD::NT_REGS:
1023 thread_data.gpregset = note.data;
1024 break;
1025 default:
1026 thread_data.notes.push_back(note);
1027 break;
1028 }
1029 }
1030 if (thread_data.gpregset.GetByteSize() == 0) {
1031 return llvm::createStringError(
1032 "Could not find general purpose registers note in core file.");
1033 }
1034 m_thread_data.push_back(thread_data);
1035 return llvm::Error::success();
1036}
1037
1038/// A description of a linux process usually contains the following NOTE
1039/// entries:
1040/// - NT_PRPSINFO - General process information like pid, uid, name, ...
1041/// - NT_SIGINFO - Information about the signal that terminated the process
1042/// - NT_AUXV - Process auxiliary vector
1043/// - NT_FILE - Files mapped into memory
1044///
1045/// Additionally, for each thread in the process the core file will contain at
1046/// least the NT_PRSTATUS note, containing the thread id and general purpose
1047/// registers. It may include additional notes for other register sets (floating
1048/// point and vector registers, ...). The tricky part here is that some of these
1049/// notes have "CORE" in their owner fields, while other set it to "LINUX".
1050llvm::Error ProcessElfCore::parseLinuxNotes(llvm::ArrayRef<CoreNote> notes) {
1051 const ArchSpec &arch = GetArchitecture();
1052 bool have_prstatus = false;
1053 bool have_prpsinfo = false;
1054 ThreadData thread_data;
1055 for (const auto &note : notes) {
1056 if (note.info.n_name != "CORE" && note.info.n_name != "LINUX")
1057 continue;
1058
1059 if ((note.info.n_type == ELF::NT_PRSTATUS && have_prstatus) ||
1060 (note.info.n_type == ELF::NT_PRPSINFO && have_prpsinfo)) {
1061 assert(thread_data.gpregset.GetByteSize() > 0);
1062 // Add the new thread to thread list
1063 m_thread_data.push_back(thread_data);
1064 thread_data = ThreadData();
1065 have_prstatus = false;
1066 have_prpsinfo = false;
1067 }
1068
1069 switch (note.info.n_type) {
1070 case ELF::NT_PRSTATUS: {
1071 have_prstatus = true;
1072 ELFLinuxPrStatus prstatus;
1073 Status status = prstatus.Parse(note.data, arch);
1074 if (status.Fail())
1075 return status.ToError();
1076 thread_data.prstatus_sig = prstatus.pr_cursig;
1077 thread_data.tid = prstatus.pr_pid;
1078 uint32_t header_size = ELFLinuxPrStatus::GetSize(arch);
1079 size_t len = note.data.GetByteSize() - header_size;
1080 thread_data.gpregset = DataExtractor(note.data, header_size, len);
1081 break;
1082 }
1083 case ELF::NT_PRPSINFO: {
1084 have_prpsinfo = true;
1085 ELFLinuxPrPsInfo prpsinfo;
1086 Status status = prpsinfo.Parse(note.data, arch);
1087 if (status.Fail())
1088 return status.ToError();
1089 thread_data.name.assign (prpsinfo.pr_fname, strnlen (prpsinfo.pr_fname, sizeof (prpsinfo.pr_fname)));
1090 SetID(prpsinfo.pr_pid);
1091 m_executable_name = thread_data.name;
1092 auto core_arg = llvm::StringRef(prpsinfo.pr_psargs,
1093 strnlen(prpsinfo.pr_psargs,
1094 sizeof(prpsinfo.pr_psargs)))
1095 .str();
1096 // pr_psargs's char array used to represent arguments is only 80 character
1097 // long (\0 included), for a total of 79.
1098 // We set core_arg's m_might_be_truncated = true if its size
1099 // is the maximum (79).
1101 CoreArgs(core_arg, /*might_be_truncated=*/core_arg.size() ==
1102 sizeof(prpsinfo.pr_psargs) - 1);
1103 break;
1104 }
1105 case ELF::NT_SIGINFO: {
1106 lldb::offset_t size = note.data.GetByteSize();
1107 lldb::offset_t offset = 0;
1108 const char *bytes =
1109 static_cast<const char *>(note.data.GetData(&offset, size));
1110 thread_data.siginfo_bytes = llvm::StringRef(bytes, size);
1111 break;
1112 }
1113 case ELF::NT_FILE: {
1114 m_nt_file_entries.clear();
1115 lldb::offset_t offset = 0;
1116 const uint64_t count = note.data.GetAddress(&offset);
1117 note.data.GetAddress(&offset); // Skip page size
1118 for (uint64_t i = 0; i < count; ++i) {
1119 NT_FILE_Entry entry;
1120 entry.start = note.data.GetAddress(&offset);
1121 entry.end = note.data.GetAddress(&offset);
1122 entry.file_ofs = note.data.GetAddress(&offset);
1123 m_nt_file_entries.push_back(entry);
1124 }
1125 for (uint64_t i = 0; i < count; ++i) {
1126 const char *path = note.data.GetCStr(&offset);
1127 if (path && path[0])
1128 m_nt_file_entries[i].path.assign(path);
1129 }
1130 break;
1131 }
1132 case ELF::NT_AUXV:
1133 m_auxv = note.data;
1134 break;
1135 default:
1136 thread_data.notes.push_back(note);
1137 break;
1138 }
1139 }
1140 // Add last entry in the note section
1141 if (have_prstatus)
1142 m_thread_data.push_back(thread_data);
1143 return llvm::Error::success();
1144}
1145
1146/// Parse Thread context from PT_NOTE segment and store it in the thread list
1147/// A note segment consists of one or more NOTE entries, but their types and
1148/// meaning differ depending on the OS.
1150 const elf::ELFProgramHeader &segment_header,
1151 const DataExtractor &segment_data) {
1152 assert(segment_header.p_type == llvm::ELF::PT_NOTE);
1153
1154 auto notes_or_error = parseSegment(segment_data);
1155 if(!notes_or_error)
1156 return notes_or_error.takeError();
1157 switch (GetArchitecture().GetTriple().getOS()) {
1158 case llvm::Triple::FreeBSD:
1159 return parseFreeBSDNotes(*notes_or_error);
1160 case llvm::Triple::Linux:
1161 return parseLinuxNotes(*notes_or_error);
1162 case llvm::Triple::NetBSD:
1163 return parseNetBSDNotes(*notes_or_error);
1164 case llvm::Triple::OpenBSD:
1165 return parseOpenBSDNotes(*notes_or_error);
1166 default:
1167 // Treat bare-metal 32-bit RISC-V like Linux.
1168 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::riscv32 &&
1169 GetTarget().GetArchitecture().GetTriple().getOS() ==
1170 llvm::Triple::UnknownOS)
1171 return parseLinuxNotes(*notes_or_error);
1172 else
1173 return llvm::createStringError(
1174 "don't know how to parse core file: unsupported OS");
1175 }
1176}
1177
1179 UUID invalid_uuid;
1180 const uint32_t addr_size = GetAddressByteSize();
1181 const size_t elf_header_size = addr_size == 4 ? sizeof(llvm::ELF::Elf32_Ehdr)
1182 : sizeof(llvm::ELF::Elf64_Ehdr);
1183
1184 std::vector<uint8_t> elf_header_bytes;
1185 elf_header_bytes.resize(elf_header_size);
1186 Status error;
1187 size_t byte_read =
1188 ReadMemory(address, elf_header_bytes.data(), elf_header_size, error);
1189 if (byte_read != elf_header_size ||
1190 !elf::ELFHeader::MagicBytesMatch(elf_header_bytes.data()))
1191 return invalid_uuid;
1192 DataExtractor elf_header_data(elf_header_bytes.data(), elf_header_size,
1193 GetByteOrder(), addr_size);
1194 lldb::offset_t offset = 0;
1195
1196 elf::ELFHeader elf_header;
1197 elf_header.Parse(elf_header_data, &offset);
1198
1199 const lldb::addr_t ph_addr = address + elf_header.e_phoff;
1200
1201 std::vector<uint8_t> ph_bytes;
1202 ph_bytes.resize(elf_header.e_phentsize);
1203 lldb::addr_t base_addr = 0;
1204 bool found_first_load_segment = false;
1205 for (unsigned int i = 0; i < elf_header.e_phnum; ++i) {
1206 byte_read = ReadMemory(ph_addr + i * elf_header.e_phentsize,
1207 ph_bytes.data(), elf_header.e_phentsize, error);
1208 if (byte_read != elf_header.e_phentsize)
1209 break;
1210 DataExtractor program_header_data(ph_bytes.data(), elf_header.e_phentsize,
1211 GetByteOrder(), addr_size);
1212 offset = 0;
1213 elf::ELFProgramHeader program_header;
1214 program_header.Parse(program_header_data, &offset);
1215 if (program_header.p_type == llvm::ELF::PT_LOAD &&
1216 !found_first_load_segment) {
1217 base_addr = program_header.p_vaddr;
1218 found_first_load_segment = true;
1219 }
1220 if (program_header.p_type != llvm::ELF::PT_NOTE)
1221 continue;
1222
1223 std::vector<uint8_t> note_bytes;
1224 note_bytes.resize(program_header.p_memsz);
1225
1226 // We need to slide the address of the p_vaddr as these values don't get
1227 // relocated in memory.
1228 const lldb::addr_t vaddr = program_header.p_vaddr + address - base_addr;
1229 byte_read =
1230 ReadMemory(vaddr, note_bytes.data(), program_header.p_memsz, error);
1231 if (byte_read != program_header.p_memsz)
1232 continue;
1233 DataExtractor segment_data(note_bytes.data(), note_bytes.size(),
1234 GetByteOrder(), addr_size);
1235 auto notes_or_error = parseSegment(segment_data);
1236 if (!notes_or_error) {
1237 llvm::consumeError(notes_or_error.takeError());
1238 return invalid_uuid;
1239 }
1240 for (const CoreNote &note : *notes_or_error) {
1241 if (note.info.n_namesz == 4 &&
1242 note.info.n_type == llvm::ELF::NT_GNU_BUILD_ID &&
1243 "GNU" == note.info.n_name &&
1244 note.data.ValidOffsetForDataOfSize(0, note.info.n_descsz))
1245 return UUID(note.data.GetData().take_front(note.info.n_descsz));
1246 }
1247 }
1248 return invalid_uuid;
1249}
1250
1253 DoLoadCore();
1254 return m_thread_data.size();
1255}
1256
1258 ArchSpec arch = m_core_module_sp->GetObjectFile()->GetArchitecture();
1259
1260 ArchSpec target_arch = GetTarget().GetArchitecture();
1261 arch.MergeFrom(target_arch);
1262
1263 // On MIPS there is no way to differentiate betwenn 32bit and 64bit core
1264 // files and this information can't be merged in from the target arch so we
1265 // fail back to unconditionally returning the target arch in this config.
1266 if (target_arch.IsMIPS()) {
1267 return target_arch;
1268 }
1269
1270 return arch;
1271}
1272
1274 assert(m_auxv.GetByteSize() == 0 ||
1275 (m_auxv.GetByteOrder() == GetByteOrder() &&
1276 m_auxv.GetAddressByteSize() == GetAddressByteSize()));
1277 return DataExtractor(m_auxv);
1278}
1279std::optional<Process::CoreArgs> ProcessElfCore::GetCoreFileArgs() {
1280 if (m_process_args.empty())
1281 return std::nullopt;
1282 return m_process_args;
1283}
1284
1286 info.Clear();
1287 info.SetProcessID(GetID());
1289 ModuleSpec exe_module_spec;
1290 bool added_executable = false;
1292 const bool add_exe_file_as_first_arg = true;
1293 if (module_sp) {
1294 info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(),
1295 add_exe_file_as_first_arg);
1296 added_executable = true;
1297 } else {
1298 ModuleSpec exe_module_spec;
1299 if (GetMainExecutableModuleSpec(exe_module_spec)) {
1300 if (exe_module_spec.GetFileSpec()) {
1301 info.SetExecutableFile(exe_module_spec.GetFileSpec(),
1302 add_exe_file_as_first_arg);
1303 added_executable = true;
1304 }
1305 }
1306 }
1307 Args process_args = m_process_args.as_args();
1308 bool first_arg_is_executable = true;
1309 if (added_executable) {
1310 // Strip the executable name from the process args as it can be a symlink
1311 // that doesn't match the executable we would have created from a call to
1312 // GetMainExecutableModuleSpec(...).
1313 first_arg_is_executable = false;
1314 info.SetArg0(process_args.GetArgumentAtIndex(0));
1315 process_args.DeleteArgumentAtIndex(0);
1316 }
1317 info.SetArguments(process_args, first_arg_is_executable);
1318 return true;
1319}
1320
1321/// Find the NT_FILE entry that contains an address.
1322std::optional<ProcessElfCore::NT_FILE_Entry>
1324 for (const NT_FILE_Entry &file_entry : m_nt_file_entries) {
1325 if (file_entry.start <= addr && addr < file_entry.end)
1326 return file_entry;
1327 }
1328 return std::nullopt;
1329}
1330
1331std::optional<ProcessElfCore::NT_FILE_Entry>
1333 /// This method will search for the first NT_FILE entry that contains the
1334 /// executable's ELF header. We use the AUXV_AT_PHDR from the aux vector to
1335 /// find the address of the main executable's program headers and then find
1336 /// the NT_FILE entry that contains this address.
1337 ///
1338 /// Previously we would try to find the first NT_FILE entry that had a path
1339 /// that ended with the executable name found in the NT_PRPSINFO note, but
1340 /// this basename can be the name of a symlink and not the actual resolved
1341 /// executable file found in the NT_FILE entry so this could fail for cases
1342 /// where a symlink was used to launch the program, and that symlink's
1343 /// base name was different from the resolved executable file's name in
1344 /// the NT_FILE entry.
1345 if (m_nt_file_entries.empty())
1346 return std::nullopt;
1347 // The AUX vector has the load address of the program headers from the main
1348 // executable as the value for AUXV_AT_PHDR. We can use this value to find
1349 // the NT_FILE entry that contains this address and this will locate the main
1350 // executable's mapping that contains the ELF header.
1351 AuxVector aux_vector(m_auxv);
1352 if (std::optional<uint64_t> opt_value =
1354 if (std::optional<NT_FILE_Entry> nt =
1356 return *nt;
1357 }
1358 // Fall back to trying to find the first NT_FILE entry that contains the entry
1359 // point address.
1360 if (std::optional<uint64_t> opt_value =
1362 if (std::optional<NT_FILE_Entry> nt =
1364 return *nt;
1365 }
1366 return std::nullopt;
1367}
static llvm::raw_ostream & error(Stream &strm)
static llvm::raw_ostream & note(Stream &strm)
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_PLUGIN_DEFINE(PluginName)
static FileSpec CreateFileSpecFromPath(llvm::StringRef path)
Correctly create a FileSpec from a path found in a core file.
static void ParseOpenBSDProcInfo(ThreadData &thread_data, const DataExtractor &data)
static void ParseFreeBSDPrPsInfo(ProcessElfCore &process, const DataExtractor &data, bool lp64)
static void ParseFreeBSDPrStatus(ThreadData &thread_data, const DataExtractor &data, bool lp64)
static llvm::Error ParseNetBSDProcInfo(const DataExtractor &data, uint32_t &cpi_nlwps, uint32_t &cpi_signo, uint32_t &cpi_siglwp, uint32_t &cpi_pid)
@ AUXV_AT_EXECFN
Filename of executable.
Definition AuxVector.h:61
@ AUXV_AT_PHDR
Program headers.
Definition AuxVector.h:30
@ AUXV_AT_ENTRY
Program entry point.
Definition AuxVector.h:36
std::optional< uint64_t > GetAuxValue(enum EntryType entry_type) const
Definition AuxVector.cpp:34
static llvm::StringRef GetPluginNameStatic()
static llvm::StringRef GetPluginNameStatic()
Generic COFF object file reader.
lldb_private::DataExtractor GetSegmentData(const elf::ELFProgramHeader &H)
llvm::ArrayRef< elf::ELFProgramHeader > ProgramHeaders()
std::vector< NT_FILE_Entry > m_nt_file_entries
std::optional< NT_FILE_Entry > GetNTFileEntryForExecutableELFHeader()
Intelligently find the NT_FILE entry for the executable's ELF header.
std::set< lldb_private::MemoryRegionInfo, std::less<> > m_core_range_infos
lldb::addr_t GetImageInfoAddress() override
Get the image information address for the current process.
lldb::addr_t AddAddressRangeFromMemoryTagSegment(const elf::ELFProgramHeader &header)
lldb_private::DataExtractor m_auxv
bool FindModuleUUID(lldb_private::ModuleSpec &spec) override
Given a module spec, try to find the UUID information.
llvm::Error parseLinuxNotes(llvm::ArrayRef< lldb_private::CoreNote > notes)
A description of a linux process usually contains the following NOTE entries:
llvm::Error ParseThreadContextsFromNoteSegment(const elf::ELFProgramHeader &segment_header, const lldb_private::DataExtractor &segment_data)
Parse Thread context from PT_NOTE segment and store it in the thread list A note segment consists of ...
void UpdateBuildIdForNTFileEntries()
std::vector< ThreadData > m_thread_data
lldb_private::Range< lldb::addr_t, lldb::addr_t > FileRange
static void Initialize()
bool DoUpdateThreadList(lldb_private::ThreadList &old_thread_list, lldb_private::ThreadList &new_thread_list) override
Update the thread list following process plug-in's specific logic.
size_t ReadMemory(lldb::addr_t addr, void *buf, size_t size, lldb_private::Status &error) override
Read of memory from a process.
static llvm::StringRef GetPluginDescriptionStatic()
std::unordered_map< std::string, lldb_private::UUID > m_uuids
llvm::Expected< std::vector< lldb_private::CoreNote > > parseSegment(const lldb_private::DataExtractor &segment)
lldb::addr_t AddAddressRangeFromLoadSegment(const elf::ELFProgramHeader &header)
~ProcessElfCore() override
bool GetMainExecutableModuleSpec(lldb_private::ModuleSpec &exe_spec)
llvm::Error parseFreeBSDNotes(llvm::ArrayRef< lldb_private::CoreNote > notes)
lldb_private::UUID FindBuidIdInCoreMemory(lldb::addr_t address)
VMRangeToFileOffset m_core_aranges
lldb_private::Status DoGetMemoryRegionInfo(lldb::addr_t load_addr, lldb_private::MemoryRegionInfo &region_info) override
DoGetMemoryRegionInfo is called by GetMemoryRegionInfo after it has removed non address bits from loa...
Process::CoreArgs m_process_args
size_t DoReadMemory(lldb::addr_t addr, void *buf, size_t size, lldb_private::Status &error) override
Actually do the reading of memory from a process.
VMRangeToFileOffset m_core_tag_ranges
llvm::Error parseNetBSDNotes(llvm::ArrayRef< lldb_private::CoreNote > notes)
NetBSD specific Thread context from PT_NOTE segment.
lldb_private::Status DoLoadCore() override
static void Terminate()
ProcessElfCore(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const lldb_private::FileSpec &core_file)
lldb_private::DynamicLoader * GetDynamicLoader() override
Get the dynamic loader plug-in for this process.
llvm::Expected< std::vector< lldb::addr_t > > ReadMemoryTags(lldb::addr_t addr, size_t len) override
Read memory tags for the range addr to addr+len.
lldb_private::DataExtractor GetAuxvData() override
bool IsAlive() override
Check if a process is still alive.
uint32_t GetNumThreadContexts()
std::string m_executable_name
static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const lldb_private::FileSpec *crash_file_path, bool can_connect)
llvm::Error parseOpenBSDNotes(llvm::ArrayRef< lldb_private::CoreNote > notes)
void RefreshStateAfterStop() override
Currently called as part of ShouldStop.
lldb_private::ArchSpec GetArchitecture()
bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override
Check if a plug-in instance can debug the file in module.
std::optional< Process::CoreArgs > GetCoreFileArgs() override
Provide arguments of a command that triggered a core dump.
bool GetProcessInfo(lldb_private::ProcessInstanceInfo &info) override
static llvm::StringRef GetPluginNameStatic()
void FinalizeMemoryRegionInfos()
lldb::ModuleSP m_core_module_sp
std::optional< NT_FILE_Entry > GetNTFileEntryContainingAddress(lldb::addr_t addr)
Find the NT_FILE entry that contains an address.
lldb_private::Status DoDestroy() override
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:301
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
An architecture specification class.
Definition ArchSpec.h:32
void MergeFrom(const ArchSpec &other)
Merges fields from another ArchSpec into this ArchSpec.
bool IsMIPS() const
if MIPS architecture return true.
Definition ArchSpec.cpp:747
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:881
A command line argument class.
Definition Args.h:33
void DeleteArgumentAtIndex(size_t idx)
Deletes the argument value at index if idx is a valid argument index.
Definition Args.cpp:359
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
An data extractor class.
virtual uint64_t GetByteSize() const
Get the number of bytes contained in this object.
uint32_t GetU32(lldb::offset_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
A plug-in interface definition class for dynamic loaders.
static DynamicLoader * FindPlugin(Process *process, llvm::StringRef plugin_name)
Find a dynamic loader plugin for a given process.
A file utility class.
Definition FileSpec.h:56
static std::optional< Style > GuessPathStyle(llvm::StringRef absolute_path)
Attempt to guess path style for a given path string.
Definition FileSpec.cpp:326
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
llvm::sys::path::Style Style
Definition FileSpec.h:58
static FileSystem & Instance()
std::shared_ptr< DataBuffer > CreateDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
Create memory buffer from path.
MemoryRegionInfo & SetMemoryTagged(LazyBool val)
void SetName(const char *name)
Range< lldb::addr_t, lldb::addr_t > RangeType
void SetLLDBPermissions(uint32_t permissions)
virtual llvm::Expected< std::vector< lldb::addr_t > > UnpackTagsFromCoreFileSegment(CoreReaderFn reader, lldb::addr_t tag_segment_virtual_address, lldb::addr_t tag_segment_data_address, lldb::addr_t addr, size_t len) const =0
static Status GetSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr, bool invoke_locate_callback=true, bool invoke_symbol_locators=true)
void SetLoadAddress(lldb::addr_t addr)
Set the load address of a module in process memory.
Definition ModuleSpec.h:126
FileSpec & GetPlatformFileSpec()
Definition ModuleSpec.h:69
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:93
void SetTarget(lldb::TargetSP target)
Set the target to be used when resolving a module.
Definition ModuleSpec.h:150
std::optional< lldb::addr_t > GetLoadAddress() const
Get the load address of a module in process memory.
Definition ModuleSpec.h:123
static lldb::ModuleSP CreateModuleFromObjectFile(Args &&...args)
Definition Module.h:136
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
virtual lldb_private::Address GetImageInfoAddress(Target *target)
Similar to Process::GetImageInfoAddress().
Definition ObjectFile.h:442
@ eTypeCoreFile
A core file that has a checkpoint of a program's execution state.
Definition ObjectFile.h:53
size_t CopyData(lldb::offset_t offset, size_t length, void *dst) const
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
PostMortemProcess(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec &core_file)
void SetExecutableFile(const FileSpec &exe_file, bool add_exe_file_as_first_arg)
void SetArchitecture(const ArchSpec &arch)
Definition ProcessInfo.h:64
void SetArg0(llvm::StringRef arg)
void SetArguments(const Args &args, bool first_arg_is_executable)
void SetProcessID(lldb::pid_t pid)
Definition ProcessInfo.h:68
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
Definition Process.h:543
void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp)
Definition Process.cpp:3916
size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr, size_t cstr_max_len, Status &error)
Read a NULL terminated C string from memory.
Definition Process.cpp:2337
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2755
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3535
llvm::Expected< const MemoryTagManager * > GetMemoryTagManager()
If this architecture and process supports memory tagging, return a tag manager that can be used to ma...
Definition Process.cpp:6732
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3926
llvm::Expected< lldb::ModuleSP > ReadModuleFromMemory(const FileSpec &file_spec, lldb::addr_t header_addr, size_t size_to_read=512)
Creates and populates a module using an in-memory object file.
Definition Process.cpp:2793
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:548
uint32_t GetAddressByteSize() const
Definition Process.cpp:3930
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
Definition Process.cpp:564
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3508
const lldb::UnixSignalsSP & GetUnixSignals()
Definition Process.cpp:3921
const lldb::ABISP & GetABI()
Definition Process.cpp:1492
friend class ThreadList
Definition Process.h:366
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1258
RangeData< lldb::addr_t, lldb::addr_t, FileRange > Entry
Definition RangeMap.h:462
An error handling class.
Definition Status.h:118
llvm::Error ToError() const
FIXME: Replace all uses with takeError() instead.
Definition Status.cpp:138
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify, Status *error_ptr=nullptr)
Find a binary on the system and return its Module, or return an existing Module that is already in th...
Definition Target.cpp:2449
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1786
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1624
const ArchSpec & GetArchitecture() const
Definition Target.h:1289
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1657
void AddThread(const lldb::ThreadSP &thread_sp)
uint32_t GetSize(bool can_update=true)
Represents UUID's of various sizes.
Definition UUID.h:27
std::string GetAsString(llvm::StringRef separator="-") const
Definition UUID.cpp:54
bool IsValid() const
Definition UUID.h:69
static lldb::UnixSignalsSP Create(const ArchSpec &arch)
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::Thread > ThreadSP
uint64_t offset_t
Definition lldb-types.h:86
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Listener > ListenerSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
uint64_t tid_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Module > ModuleSP
lldb_private::Status Parse(const lldb_private::DataExtractor &data, const lldb_private::ArchSpec &arch)
static size_t GetSize(const lldb_private::ArchSpec &arch)
lldb_private::Status Parse(const lldb_private::DataExtractor &data, const lldb_private::ArchSpec &arch)
lldb::addr_t file_ofs
lldb::addr_t end
lldb::addr_t start
llvm::StringRef siginfo_bytes
lldb::tid_t tid
std::string name
lldb_private::DataExtractor gpregset
std::vector< lldb_private::CoreNote > notes
Generic representation of an ELF file header.
Definition ELFHeader.h:56
elf_off e_phoff
File offset of program header table.
Definition ELFHeader.h:59
elf_half e_phentsize
Size of a program header table entry.
Definition ELFHeader.h:66
static bool MagicBytesMatch(const uint8_t *magic)
Examines at most EI_NIDENT bytes starting from the given pointer and determines if the magic ELF iden...
bool Parse(lldb_private::DataExtractor &data, lldb::offset_t *offset)
Parse an ELFHeader entry starting at position offset and update the data extractor with the address s...
elf_word e_phnum
Number of program header entries.
Definition ELFHeader.h:75
elf_word e_version
Version of object file (always 1).
Definition ELFHeader.h:62
unsigned char e_ident[llvm::ELF::EI_NIDENT]
ELF file identification.
Definition ELFHeader.h:57
elf_half e_type
Object file type.
Definition ELFHeader.h:63
Generic representation of an ELF program header.
Definition ELFHeader.h:192
bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset)
Parse an ELFProgramHeader entry from the given DataExtractor starting at position offset.
elf_word p_flags
Segment attributes.
Definition ELFHeader.h:194
elf_xword p_filesz
Byte size of the segment in file.
Definition ELFHeader.h:198
elf_off p_offset
Start of segment from beginning of file.
Definition ELFHeader.h:195
elf_addr p_vaddr
Virtual address of segment in memory.
Definition ELFHeader.h:196
elf_xword p_memsz
Byte size of the segment in memory.
Definition ELFHeader.h:199
elf_word p_type
Type of program segment.
Definition ELFHeader.h:193
BaseType GetRangeBase() const
Definition RangeMap.h:45
void SetRangeEnd(BaseType end)
Definition RangeMap.h:80
SizeType GetByteSize() const
Definition RangeMap.h:87
void SetRangeBase(BaseType b)
Set the start value for the range, and keep the same size.
Definition RangeMap.h:48
BaseType GetRangeEnd() const
Definition RangeMap.h:78