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(const ProcessAddress &process_addr, void *buf,
528 size_t size, Status &error) {
529 lldb::addr_t addr = process_addr.GetValue();
530 if (lldb::ABISP abi_sp = GetABI())
531 addr = abi_sp->FixAnyAddress(addr);
532
533 // Don't allow the caching that lldb_private::Process::ReadMemory does since
534 // in core files we have it all cached our our core file anyway.
535 return DoReadMemory(addr, buf, size, error);
536}
537
539 MemoryRegionInfo &region_info) {
540 region_info.Clear();
541 auto following = m_core_range_infos.upper_bound(load_addr);
542 // PT_LOAD ranges can overlap, so the immediate predecessor is not
543 // necessarily the range containing load_addr.
544 auto range_entry = std::find_if(m_core_range_infos.begin(), following,
545 [load_addr](const auto &entry) {
546 return entry.GetRange().Contains(load_addr);
547 });
548 if (range_entry != following) {
549 region_info = *range_entry;
550 return Status();
551 }
552
553 region_info.GetRange().SetRangeBase(load_addr);
554 region_info.GetRange().SetRangeEnd(
555 following == m_core_range_infos.end()
557 : following->GetRange().GetRangeBase());
558 region_info.SetReadable(eLazyBoolNo);
559 region_info.SetWritable(eLazyBoolNo);
560 region_info.SetExecutable(eLazyBoolNo);
561 region_info.SetMapped(eLazyBoolNo);
562 region_info.SetMemoryTagged(eLazyBoolNo);
563 return Status();
564}
565
567 void *buf, size_t size, Status &error) {
568 lldb::addr_t addr = process_addr.GetValue();
569 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
570
571 if (core_objfile == nullptr)
572 return 0;
573
574 // Get the address range
575 const VMRangeToFileOffset::Entry *address_range =
576 m_core_aranges.FindEntryThatContains(addr);
577 if (address_range == nullptr || address_range->GetRangeEnd() < addr) {
579 "core file does not contain 0x%" PRIx64, addr);
580 return 0;
581 }
582
583 // Convert the address into core file offset
584 const lldb::addr_t offset = addr - address_range->GetRangeBase();
585 const lldb::addr_t file_start = address_range->data.GetRangeBase();
586 const lldb::addr_t file_end = address_range->data.GetRangeEnd();
587 size_t bytes_to_read = size; // Number of bytes to read from the core file
588 size_t bytes_copied = 0; // Number of bytes actually read from the core file
589 lldb::addr_t bytes_left =
590 0; // Number of bytes available in the core file from the given address
591
592 // Don't proceed if core file doesn't contain the actual data for this
593 // address range.
594 if (file_start == file_end)
595 return 0;
596
597 // Figure out how many on-disk bytes remain in this segment starting at the
598 // given offset
599 if (file_end > file_start + offset)
600 bytes_left = file_end - (file_start + offset);
601
602 if (bytes_to_read > bytes_left)
603 bytes_to_read = bytes_left;
604
605 // If there is data available on the core file read it
606 if (bytes_to_read)
607 bytes_copied =
608 core_objfile->CopyData(offset + file_start, bytes_to_read, buf);
609
610 return bytes_copied;
611}
612
613llvm::Expected<std::vector<lldb::addr_t>>
615 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
616 if (core_objfile == nullptr)
617 return llvm::createStringError(llvm::inconvertibleErrorCode(),
618 "No core object file.");
619
620 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
622 if (!tag_manager_or_err)
623 return tag_manager_or_err.takeError();
624
625 // LLDB only supports AArch64 MTE tag segments so we do not need to worry
626 // about the segment type here. If you got here then you must have a tag
627 // manager (meaning you are debugging AArch64) and all the segments in this
628 // list will have had type PT_AARCH64_MEMTAG_MTE.
629 const VMRangeToFileOffset::Entry *tag_entry =
630 m_core_tag_ranges.FindEntryThatContains(addr);
631 // If we don't have a tag segment or the range asked for extends outside the
632 // segment.
633 if (!tag_entry || (addr + len) >= tag_entry->GetRangeEnd())
634 return llvm::createStringError(llvm::inconvertibleErrorCode(),
635 "No tag segment that covers this range.");
636
637 const MemoryTagManager *tag_manager = *tag_manager_or_err;
638 return tag_manager->UnpackTagsFromCoreFileSegment(
639 [core_objfile](lldb::offset_t offset, size_t length, void *dst) {
640 return core_objfile->CopyData(offset, length, dst);
641 },
642 tag_entry->GetRangeBase(), tag_entry->data.GetRangeBase(), addr, len);
643}
644
646 m_thread_list.Clear();
647
648 SetUnixSignals(std::make_shared<UnixSignals>());
649}
650
655
657 ObjectFile *obj_file = GetTarget().GetExecutableModule()->GetObjectFile();
658 Address addr = obj_file->GetImageInfoAddress(&GetTarget());
659
660 if (addr.IsValid())
661 return addr.GetLoadAddress(&GetTarget());
663}
664
665// Parse a FreeBSD NT_PRSTATUS note - see FreeBSD sys/procfs.h for details.
666static void ParseFreeBSDPrStatus(ThreadData &thread_data,
667 const DataExtractor &data,
668 bool lp64) {
669 lldb::offset_t offset = 0;
670 int pr_version = data.GetU32(&offset);
671
673 if (pr_version > 1)
674 LLDB_LOGF(log, "FreeBSD PRSTATUS unexpected version %d", pr_version);
675
676 // Skip padding, pr_statussz, pr_gregsetsz, pr_fpregsetsz, pr_osreldate
677 if (lp64)
678 offset += 32;
679 else
680 offset += 16;
681
682 thread_data.signo = data.GetU32(&offset); // pr_cursig
683 thread_data.tid = data.GetU32(&offset); // pr_pid
684 if (lp64)
685 offset += 4;
686
687 size_t len = data.GetByteSize() - offset;
688 thread_data.gpregset = DataExtractor(data, offset, len);
689}
690
691// Parse a FreeBSD NT_PRPSINFO note - see FreeBSD sys/procfs.h for details.
693 const DataExtractor &data,
694 bool lp64) {
695 lldb::offset_t offset = 0;
696 int pr_version = data.GetU32(&offset);
697
699 if (pr_version > 1)
700 LLDB_LOGF(log, "FreeBSD PRPSINFO unexpected version %d", pr_version);
701
702 // Skip pr_psinfosz, pr_fname, pr_psargs
703 offset += 108;
704 if (lp64)
705 offset += 4;
706
707 process.SetID(data.GetU32(&offset)); // pr_pid
708}
709
710static llvm::Error ParseNetBSDProcInfo(const DataExtractor &data,
711 uint32_t &cpi_nlwps,
712 uint32_t &cpi_signo,
713 uint32_t &cpi_siglwp,
714 uint32_t &cpi_pid) {
715 lldb::offset_t offset = 0;
716
717 uint32_t version = data.GetU32(&offset);
718 if (version != 1)
719 return llvm::createStringError(
720 "Error parsing NetBSD core(5) notes: Unsupported procinfo version");
721
722 uint32_t cpisize = data.GetU32(&offset);
723 if (cpisize != NETBSD::NT_PROCINFO_SIZE)
724 return llvm::createStringError(
725 "Error parsing NetBSD core(5) notes: Unsupported procinfo size");
726
727 cpi_signo = data.GetU32(&offset); /* killing signal */
728
734 cpi_pid = data.GetU32(&offset);
744 cpi_nlwps = data.GetU32(&offset); /* number of LWPs */
745
747 cpi_siglwp = data.GetU32(&offset); /* LWP target of killing signal */
748
749 return llvm::Error::success();
750}
751
752static void ParseOpenBSDProcInfo(ThreadData &thread_data,
753 const DataExtractor &data) {
754 lldb::offset_t offset = 0;
755
756 int version = data.GetU32(&offset);
757 if (version != 1)
758 return;
759
760 offset += 4;
761 thread_data.signo = data.GetU32(&offset);
762}
763
764llvm::Expected<std::vector<CoreNote>>
766 lldb::offset_t offset = 0;
767 std::vector<CoreNote> result;
768
769 while (offset < segment.GetByteSize()) {
770 ELFNote note = ELFNote();
771 if (!note.Parse(segment, &offset))
772 return llvm::createStringError("unable to parse note segment");
773
774 size_t note_start = offset;
775 size_t note_size = llvm::alignTo(note.n_descsz, 4);
776
777 result.push_back({note, DataExtractor(segment, note_start, note_size)});
778 offset += note_size;
779 }
780
781 return std::move(result);
782}
783
784llvm::Error ProcessElfCore::parseFreeBSDNotes(llvm::ArrayRef<CoreNote> notes) {
785 ArchSpec arch = GetArchitecture();
786 bool lp64 = (arch.GetMachine() == llvm::Triple::aarch64 ||
787 arch.GetMachine() == llvm::Triple::ppc64 ||
788 arch.GetMachine() == llvm::Triple::x86_64);
789 bool have_prstatus = false;
790 bool have_prpsinfo = false;
791 ThreadData thread_data;
792 for (const auto &note : notes) {
793 if (note.info.n_name != "FreeBSD")
794 continue;
795
796 if ((note.info.n_type == ELF::NT_PRSTATUS && have_prstatus) ||
797 (note.info.n_type == ELF::NT_PRPSINFO && have_prpsinfo)) {
798 assert(thread_data.gpregset.GetByteSize() > 0);
799 // Add the new thread to thread list
800 m_thread_data.push_back(thread_data);
801 thread_data = ThreadData();
802 have_prstatus = false;
803 have_prpsinfo = false;
804 }
805
806 switch (note.info.n_type) {
807 case ELF::NT_PRSTATUS:
808 have_prstatus = true;
809 ParseFreeBSDPrStatus(thread_data, note.data, lp64);
810 break;
811 case ELF::NT_PRPSINFO:
812 have_prpsinfo = true;
813 ParseFreeBSDPrPsInfo(*this, note.data, lp64);
814 break;
815 case ELF::NT_FREEBSD_THRMISC: {
816 lldb::offset_t offset = 0;
817 thread_data.name = note.data.GetCStr(&offset, 20);
818 break;
819 }
820 case ELF::NT_FREEBSD_PROCSTAT_AUXV:
821 // FIXME: FreeBSD sticks an int at the beginning of the note
822 m_auxv = DataExtractor(note.data, 4, note.data.GetByteSize() - 4);
823 break;
824 default:
825 thread_data.notes.push_back(note);
826 break;
827 }
828 }
829 if (!have_prstatus) {
830 return llvm::createStringError(
831 "Could not find NT_PRSTATUS note in core file.");
832 }
833 m_thread_data.push_back(thread_data);
834 return llvm::Error::success();
835}
836
837/// NetBSD specific Thread context from PT_NOTE segment
838///
839/// NetBSD ELF core files use notes to provide information about
840/// the process's state. The note name is "NetBSD-CORE" for
841/// information that is global to the process, and "NetBSD-CORE@nn",
842/// where "nn" is the lwpid of the LWP that the information belongs
843/// to (such as register state).
844///
845/// NetBSD uses the following note identifiers:
846///
847/// ELF_NOTE_NETBSD_CORE_PROCINFO (value 1)
848/// Note is a "netbsd_elfcore_procinfo" structure.
849/// ELF_NOTE_NETBSD_CORE_AUXV (value 2; since NetBSD 8.0)
850/// Note is an array of AuxInfo structures.
851///
852/// NetBSD also uses ptrace(2) request numbers (the ones that exist in
853/// machine-dependent space) to identify register info notes. The
854/// info in such notes is in the same format that ptrace(2) would
855/// export that information.
856///
857/// For more information see /usr/include/sys/exec_elf.h
858///
859llvm::Error ProcessElfCore::parseNetBSDNotes(llvm::ArrayRef<CoreNote> notes) {
860 ThreadData thread_data;
861 bool had_nt_regs = false;
862
863 // To be extracted from struct netbsd_elfcore_procinfo
864 // Used to sanity check of the LWPs of the process
865 uint32_t nlwps = 0;
866 uint32_t signo = 0; // killing signal
867 uint32_t siglwp = 0; // LWP target of killing signal
868 uint32_t pr_pid = 0;
869
870 for (const auto &note : notes) {
871 llvm::StringRef name = note.info.n_name;
872
873 if (name == "NetBSD-CORE") {
874 if (note.info.n_type == NETBSD::NT_PROCINFO) {
875 llvm::Error error = ParseNetBSDProcInfo(note.data, nlwps, signo,
876 siglwp, pr_pid);
877 if (error)
878 return error;
879 SetID(pr_pid);
880 } else if (note.info.n_type == NETBSD::NT_AUXV) {
881 m_auxv = note.data;
882 }
883 } else if (name.consume_front("NetBSD-CORE@")) {
884 lldb::tid_t tid;
885 if (name.getAsInteger(10, tid))
886 return llvm::createStringError(
887 "Error parsing NetBSD core(5) notes: Cannot convert LWP ID "
888 "to integer");
889
890 switch (GetArchitecture().GetMachine()) {
891 case llvm::Triple::aarch64: {
892 // Assume order PT_GETREGS, PT_GETFPREGS
893 if (note.info.n_type == NETBSD::AARCH64::NT_REGS) {
894 // If this is the next thread, push the previous one first.
895 if (had_nt_regs) {
896 m_thread_data.push_back(thread_data);
897 thread_data = ThreadData();
898 had_nt_regs = false;
899 }
900
901 thread_data.gpregset = note.data;
902 thread_data.tid = tid;
903 if (thread_data.gpregset.GetByteSize() == 0)
904 return llvm::createStringError(
905 "Could not find general purpose registers note in core file.");
906 had_nt_regs = true;
907 } else if (note.info.n_type == NETBSD::AARCH64::NT_FPREGS) {
908 if (!had_nt_regs || tid != thread_data.tid)
909 return llvm::createStringError(
910 "Error parsing NetBSD core(5) notes: Unexpected order "
911 "of NOTEs PT_GETFPREG before PT_GETREG");
912 thread_data.notes.push_back(note);
913 }
914 } break;
915 case llvm::Triple::x86: {
916 // Assume order PT_GETREGS, PT_GETFPREGS
917 if (note.info.n_type == NETBSD::I386::NT_REGS) {
918 // If this is the next thread, push the previous one first.
919 if (had_nt_regs) {
920 m_thread_data.push_back(thread_data);
921 thread_data = ThreadData();
922 had_nt_regs = false;
923 }
924
925 thread_data.gpregset = note.data;
926 thread_data.tid = tid;
927 if (thread_data.gpregset.GetByteSize() == 0)
928 return llvm::createStringError(
929 "Could not find general purpose registers note in core file.");
930 had_nt_regs = true;
931 } else if (note.info.n_type == NETBSD::I386::NT_FPREGS) {
932 if (!had_nt_regs || tid != thread_data.tid)
933 return llvm::createStringError(
934 "Error parsing NetBSD core(5) notes: Unexpected order "
935 "of NOTEs PT_GETFPREG before PT_GETREG");
936 thread_data.notes.push_back(note);
937 }
938 } break;
939 case llvm::Triple::x86_64: {
940 // Assume order PT_GETREGS, PT_GETFPREGS
941 if (note.info.n_type == NETBSD::AMD64::NT_REGS) {
942 // If this is the next thread, push the previous one first.
943 if (had_nt_regs) {
944 m_thread_data.push_back(thread_data);
945 thread_data = ThreadData();
946 had_nt_regs = false;
947 }
948
949 thread_data.gpregset = note.data;
950 thread_data.tid = tid;
951 if (thread_data.gpregset.GetByteSize() == 0)
952 return llvm::createStringError(
953 "Could not find general purpose registers note in core file.");
954 had_nt_regs = true;
955 } else if (note.info.n_type == NETBSD::AMD64::NT_FPREGS) {
956 if (!had_nt_regs || tid != thread_data.tid)
957 return llvm::createStringError(
958 "Error parsing NetBSD core(5) notes: Unexpected order "
959 "of NOTEs PT_GETFPREG before PT_GETREG");
960 thread_data.notes.push_back(note);
961 }
962 } break;
963 default:
964 break;
965 }
966 }
967 }
968
969 // Push the last thread.
970 if (had_nt_regs)
971 m_thread_data.push_back(thread_data);
972
973 if (m_thread_data.empty())
974 return llvm::createStringError(
975 "Error parsing NetBSD core(5) notes: No threads information "
976 "specified in notes");
977
978 if (m_thread_data.size() != nlwps)
979 return llvm::createStringError(
980 "Error parsing NetBSD core(5) notes: Mismatch between the number "
981 "of LWPs in netbsd_elfcore_procinfo and the number of LWPs specified "
982 "by MD notes");
983
984 // Signal targeted at the whole process.
985 if (siglwp == 0) {
986 for (auto &data : m_thread_data)
987 data.signo = signo;
988 }
989 // Signal destined for a particular LWP.
990 else {
991 bool passed = false;
992
993 for (auto &data : m_thread_data) {
994 if (data.tid == siglwp) {
995 data.signo = signo;
996 passed = true;
997 break;
998 }
999 }
1000
1001 if (!passed)
1002 return llvm::createStringError(
1003 "Error parsing NetBSD core(5) notes: Signal passed to unknown LWP");
1004 }
1005
1006 return llvm::Error::success();
1007}
1008
1009llvm::Error ProcessElfCore::parseOpenBSDNotes(llvm::ArrayRef<CoreNote> notes) {
1010 ThreadData thread_data = {};
1011 for (const auto &note : notes) {
1012 // OpenBSD per-thread information is stored in notes named "OpenBSD@nnn" so
1013 // match on the initial part of the string.
1014 if (!llvm::StringRef(note.info.n_name).starts_with("OpenBSD"))
1015 continue;
1016
1017 switch (note.info.n_type) {
1019 ParseOpenBSDProcInfo(thread_data, note.data);
1020 break;
1021 case OPENBSD::NT_AUXV:
1022 m_auxv = note.data;
1023 break;
1024 case OPENBSD::NT_REGS:
1025 thread_data.gpregset = note.data;
1026 break;
1027 default:
1028 thread_data.notes.push_back(note);
1029 break;
1030 }
1031 }
1032 if (thread_data.gpregset.GetByteSize() == 0) {
1033 return llvm::createStringError(
1034 "Could not find general purpose registers note in core file.");
1035 }
1036 m_thread_data.push_back(thread_data);
1037 return llvm::Error::success();
1038}
1039
1040/// A description of a linux process usually contains the following NOTE
1041/// entries:
1042/// - NT_PRPSINFO - General process information like pid, uid, name, ...
1043/// - NT_SIGINFO - Information about the signal that terminated the process
1044/// - NT_AUXV - Process auxiliary vector
1045/// - NT_FILE - Files mapped into memory
1046///
1047/// Additionally, for each thread in the process the core file will contain at
1048/// least the NT_PRSTATUS note, containing the thread id and general purpose
1049/// registers. It may include additional notes for other register sets (floating
1050/// point and vector registers, ...). The tricky part here is that some of these
1051/// notes have "CORE" in their owner fields, while other set it to "LINUX".
1052llvm::Error ProcessElfCore::parseLinuxNotes(llvm::ArrayRef<CoreNote> notes) {
1053 const ArchSpec &arch = GetArchitecture();
1054 bool have_prstatus = false;
1055 bool have_prpsinfo = false;
1056 ThreadData thread_data;
1057 for (const auto &note : notes) {
1058 if (note.info.n_name != "CORE" && note.info.n_name != "LINUX")
1059 continue;
1060
1061 if ((note.info.n_type == ELF::NT_PRSTATUS && have_prstatus) ||
1062 (note.info.n_type == ELF::NT_PRPSINFO && have_prpsinfo)) {
1063 assert(thread_data.gpregset.GetByteSize() > 0);
1064 // Add the new thread to thread list
1065 m_thread_data.push_back(thread_data);
1066 thread_data = ThreadData();
1067 have_prstatus = false;
1068 have_prpsinfo = false;
1069 }
1070
1071 switch (note.info.n_type) {
1072 case ELF::NT_PRSTATUS: {
1073 have_prstatus = true;
1074 ELFLinuxPrStatus prstatus;
1075 Status status = prstatus.Parse(note.data, arch);
1076 if (status.Fail())
1077 return status.ToError();
1078 thread_data.prstatus_sig = prstatus.pr_cursig;
1079 thread_data.tid = prstatus.pr_pid;
1080 uint32_t header_size = ELFLinuxPrStatus::GetSize(arch);
1081 size_t len = note.data.GetByteSize() - header_size;
1082 thread_data.gpregset = DataExtractor(note.data, header_size, len);
1083 break;
1084 }
1085 case ELF::NT_PRPSINFO: {
1086 have_prpsinfo = true;
1087 ELFLinuxPrPsInfo prpsinfo;
1088 Status status = prpsinfo.Parse(note.data, arch);
1089 if (status.Fail())
1090 return status.ToError();
1091 thread_data.name.assign (prpsinfo.pr_fname, strnlen (prpsinfo.pr_fname, sizeof (prpsinfo.pr_fname)));
1092 SetID(prpsinfo.pr_pid);
1093 m_executable_name = thread_data.name;
1094 auto core_arg = llvm::StringRef(prpsinfo.pr_psargs,
1095 strnlen(prpsinfo.pr_psargs,
1096 sizeof(prpsinfo.pr_psargs)))
1097 .str();
1098 // pr_psargs's char array used to represent arguments is only 80 character
1099 // long (\0 included), for a total of 79.
1100 // We set core_arg's m_might_be_truncated = true if its size
1101 // is the maximum (79).
1103 CoreArgs(core_arg, /*might_be_truncated=*/core_arg.size() ==
1104 sizeof(prpsinfo.pr_psargs) - 1);
1105 break;
1106 }
1107 case ELF::NT_SIGINFO: {
1108 lldb::offset_t size = note.data.GetByteSize();
1109 lldb::offset_t offset = 0;
1110 const char *bytes =
1111 static_cast<const char *>(note.data.GetData(&offset, size));
1112 thread_data.siginfo_bytes = llvm::StringRef(bytes, size);
1113 break;
1114 }
1115 case ELF::NT_FILE: {
1116 m_nt_file_entries.clear();
1117 lldb::offset_t offset = 0;
1118 const uint64_t count = note.data.GetAddress(&offset);
1119 note.data.GetAddress(&offset); // Skip page size
1120 for (uint64_t i = 0; i < count; ++i) {
1121 NT_FILE_Entry entry;
1122 entry.start = note.data.GetAddress(&offset);
1123 entry.end = note.data.GetAddress(&offset);
1124 entry.file_ofs = note.data.GetAddress(&offset);
1125 m_nt_file_entries.push_back(entry);
1126 }
1127 for (uint64_t i = 0; i < count; ++i) {
1128 const char *path = note.data.GetCStr(&offset);
1129 if (path && path[0])
1130 m_nt_file_entries[i].path.assign(path);
1131 }
1132 break;
1133 }
1134 case ELF::NT_AUXV:
1135 m_auxv = note.data;
1136 break;
1137 default:
1138 thread_data.notes.push_back(note);
1139 break;
1140 }
1141 }
1142 // Add last entry in the note section
1143 if (have_prstatus)
1144 m_thread_data.push_back(thread_data);
1145 return llvm::Error::success();
1146}
1147
1148/// Parse Thread context from PT_NOTE segment and store it in the thread list
1149/// A note segment consists of one or more NOTE entries, but their types and
1150/// meaning differ depending on the OS.
1152 const elf::ELFProgramHeader &segment_header,
1153 const DataExtractor &segment_data) {
1154 assert(segment_header.p_type == llvm::ELF::PT_NOTE);
1155
1156 auto notes_or_error = parseSegment(segment_data);
1157 if(!notes_or_error)
1158 return notes_or_error.takeError();
1159 switch (GetArchitecture().GetTriple().getOS()) {
1160 case llvm::Triple::FreeBSD:
1161 return parseFreeBSDNotes(*notes_or_error);
1162 case llvm::Triple::Linux:
1163 return parseLinuxNotes(*notes_or_error);
1164 case llvm::Triple::NetBSD:
1165 return parseNetBSDNotes(*notes_or_error);
1166 case llvm::Triple::OpenBSD:
1167 return parseOpenBSDNotes(*notes_or_error);
1168 default:
1169 // Treat bare-metal 32-bit RISC-V like Linux.
1170 if (GetTarget().GetArchitecture().GetMachine() == llvm::Triple::riscv32 &&
1171 GetTarget().GetArchitecture().GetTriple().getOS() ==
1172 llvm::Triple::UnknownOS)
1173 return parseLinuxNotes(*notes_or_error);
1174 else
1175 return llvm::createStringError(
1176 "don't know how to parse core file: unsupported OS");
1177 }
1178}
1179
1181 UUID invalid_uuid;
1182 const uint32_t addr_size = GetAddressByteSize();
1183 const size_t elf_header_size = addr_size == 4 ? sizeof(llvm::ELF::Elf32_Ehdr)
1184 : sizeof(llvm::ELF::Elf64_Ehdr);
1185
1186 std::vector<uint8_t> elf_header_bytes;
1187 elf_header_bytes.resize(elf_header_size);
1188 Status error;
1189 size_t byte_read =
1190 ReadMemory(address, elf_header_bytes.data(), elf_header_size, error);
1191 if (byte_read != elf_header_size ||
1192 !elf::ELFHeader::MagicBytesMatch(elf_header_bytes.data()))
1193 return invalid_uuid;
1194 DataExtractor elf_header_data(elf_header_bytes.data(), elf_header_size,
1195 GetByteOrder(), addr_size);
1196 lldb::offset_t offset = 0;
1197
1198 elf::ELFHeader elf_header;
1199 elf_header.Parse(elf_header_data, &offset);
1200
1201 const lldb::addr_t ph_addr = address + elf_header.e_phoff;
1202
1203 std::vector<uint8_t> ph_bytes;
1204 ph_bytes.resize(elf_header.e_phentsize);
1205 lldb::addr_t base_addr = 0;
1206 bool found_first_load_segment = false;
1207 for (unsigned int i = 0; i < elf_header.e_phnum; ++i) {
1208 byte_read = ReadMemory(ph_addr + i * elf_header.e_phentsize,
1209 ph_bytes.data(), elf_header.e_phentsize, error);
1210 if (byte_read != elf_header.e_phentsize)
1211 break;
1212 DataExtractor program_header_data(ph_bytes.data(), elf_header.e_phentsize,
1213 GetByteOrder(), addr_size);
1214 offset = 0;
1215 elf::ELFProgramHeader program_header;
1216 program_header.Parse(program_header_data, &offset);
1217 if (program_header.p_type == llvm::ELF::PT_LOAD &&
1218 !found_first_load_segment) {
1219 base_addr = program_header.p_vaddr;
1220 found_first_load_segment = true;
1221 }
1222 if (program_header.p_type != llvm::ELF::PT_NOTE)
1223 continue;
1224
1225 std::vector<uint8_t> note_bytes;
1226 note_bytes.resize(program_header.p_memsz);
1227
1228 // We need to slide the address of the p_vaddr as these values don't get
1229 // relocated in memory.
1230 const lldb::addr_t vaddr = program_header.p_vaddr + address - base_addr;
1231 byte_read =
1232 ReadMemory(vaddr, note_bytes.data(), program_header.p_memsz, error);
1233 if (byte_read != program_header.p_memsz)
1234 continue;
1235 DataExtractor segment_data(note_bytes.data(), note_bytes.size(),
1236 GetByteOrder(), addr_size);
1237 auto notes_or_error = parseSegment(segment_data);
1238 if (!notes_or_error) {
1239 llvm::consumeError(notes_or_error.takeError());
1240 return invalid_uuid;
1241 }
1242 for (const CoreNote &note : *notes_or_error) {
1243 if (note.info.n_namesz == 4 &&
1244 note.info.n_type == llvm::ELF::NT_GNU_BUILD_ID &&
1245 "GNU" == note.info.n_name &&
1246 note.data.ValidOffsetForDataOfSize(0, note.info.n_descsz))
1247 return UUID(note.data.GetData().take_front(note.info.n_descsz));
1248 }
1249 }
1250 return invalid_uuid;
1251}
1252
1255 DoLoadCore();
1256 return m_thread_data.size();
1257}
1258
1260 ArchSpec arch = m_core_module_sp->GetObjectFile()->GetArchitecture();
1261
1262 ArchSpec target_arch = GetTarget().GetArchitecture();
1263 arch.MergeFrom(target_arch);
1264
1265 // On MIPS there is no way to differentiate betwenn 32bit and 64bit core
1266 // files and this information can't be merged in from the target arch so we
1267 // fail back to unconditionally returning the target arch in this config.
1268 if (target_arch.IsMIPS()) {
1269 return target_arch;
1270 }
1271
1272 return arch;
1273}
1274
1276 assert(m_auxv.GetByteSize() == 0 ||
1277 (m_auxv.GetByteOrder() == GetByteOrder() &&
1278 m_auxv.GetAddressByteSize() == GetAddressByteSize()));
1279 return DataExtractor(m_auxv);
1280}
1281std::optional<Process::CoreArgs> ProcessElfCore::GetCoreFileArgs() {
1282 if (m_process_args.empty())
1283 return std::nullopt;
1284 return m_process_args;
1285}
1286
1288 info.Clear();
1289 info.SetProcessID(GetID());
1291 ModuleSpec exe_module_spec;
1292 bool added_executable = false;
1294 const bool add_exe_file_as_first_arg = true;
1295 if (module_sp) {
1296 info.SetExecutableFile(GetTarget().GetExecutableModule()->GetFileSpec(),
1297 add_exe_file_as_first_arg);
1298 added_executable = true;
1299 } else {
1300 ModuleSpec exe_module_spec;
1301 if (GetMainExecutableModuleSpec(exe_module_spec)) {
1302 if (exe_module_spec.GetFileSpec()) {
1303 info.SetExecutableFile(exe_module_spec.GetFileSpec(),
1304 add_exe_file_as_first_arg);
1305 added_executable = true;
1306 }
1307 }
1308 }
1309 Args process_args = m_process_args.as_args();
1310 bool first_arg_is_executable = true;
1311 if (added_executable) {
1312 // Strip the executable name from the process args as it can be a symlink
1313 // that doesn't match the executable we would have created from a call to
1314 // GetMainExecutableModuleSpec(...).
1315 first_arg_is_executable = false;
1316 info.SetArg0(process_args.GetArgumentAtIndex(0));
1317 process_args.DeleteArgumentAtIndex(0);
1318 }
1319 info.SetArguments(process_args, first_arg_is_executable);
1320 return true;
1321}
1322
1323/// Find the NT_FILE entry that contains an address.
1324std::optional<ProcessElfCore::NT_FILE_Entry>
1326 for (const NT_FILE_Entry &file_entry : m_nt_file_entries) {
1327 if (file_entry.start <= addr && addr < file_entry.end)
1328 return file_entry;
1329 }
1330 return std::nullopt;
1331}
1332
1333std::optional<ProcessElfCore::NT_FILE_Entry>
1335 /// This method will search for the first NT_FILE entry that contains the
1336 /// executable's ELF header. We use the AUXV_AT_PHDR from the aux vector to
1337 /// find the address of the main executable's program headers and then find
1338 /// the NT_FILE entry that contains this address.
1339 ///
1340 /// Previously we would try to find the first NT_FILE entry that had a path
1341 /// that ended with the executable name found in the NT_PRPSINFO note, but
1342 /// this basename can be the name of a symlink and not the actual resolved
1343 /// executable file found in the NT_FILE entry so this could fail for cases
1344 /// where a symlink was used to launch the program, and that symlink's
1345 /// base name was different from the resolved executable file's name in
1346 /// the NT_FILE entry.
1347 if (m_nt_file_entries.empty())
1348 return std::nullopt;
1349 // The AUX vector has the load address of the program headers from the main
1350 // executable as the value for AUXV_AT_PHDR. We can use this value to find
1351 // the NT_FILE entry that contains this address and this will locate the main
1352 // executable's mapping that contains the ELF header.
1353 AuxVector aux_vector(m_auxv);
1354 if (std::optional<uint64_t> opt_value =
1356 if (std::optional<NT_FILE_Entry> nt =
1358 return *nt;
1359 }
1360 // Fall back to trying to find the first NT_FILE entry that contains the entry
1361 // point address.
1362 if (std::optional<uint64_t> opt_value =
1364 if (std::optional<NT_FILE_Entry> nt =
1366 return *nt;
1367 }
1368 return std::nullopt;
1369}
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.
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)
size_t DoReadMemory(const lldb_private::ProcessAddress &addr, void *buf, size_t size, lldb_private::Status &error) override
Actually do the reading of memory from a process.
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 ReadMemory(const lldb_private::ProcessAddress &addr, void *buf, size_t size, lldb_private::Status &error) override
Read 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)
An address in a process, qualified by an address space.
lldb::addr_t GetValue() const
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:544
void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp)
Definition Process.cpp:3918
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:2339
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2757
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3536
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:6734
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3928
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:2795
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:549
uint32_t GetAddressByteSize() const
Definition Process.cpp:3932
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:3509
const lldb::UnixSignalsSP & GetUnixSignals()
Definition Process.cpp:3923
const lldb::ABISP & GetABI()
Definition Process.cpp:1492
friend class ThreadList
Definition Process.h:367
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1259
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:2450
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1787
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1625
const ArchSpec & GetArchitecture() const
Definition Target.h:1296
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1658
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