LLDB mainline
ProcessMachCore.cpp
Go to the documentation of this file.
1//===-- ProcessMachCore.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 <cerrno>
10#include <cstdlib>
11
12#include "llvm/Support/MathExtras.h"
13#include "llvm/Support/Threading.h"
14
15#include "lldb/Core/Debugger.h"
16#include "lldb/Core/Module.h"
19#include "lldb/Core/Section.h"
20#include "lldb/Host/Host.h"
24#include "lldb/Target/Target.h"
25#include "lldb/Target/Thread.h"
29#include "lldb/Utility/Log.h"
30#include "lldb/Utility/State.h"
31#include "lldb/Utility/UUID.h"
32
33#include "ProcessMachCore.h"
35#include "ThreadMachCore.h"
36
37// Needed for the plug-in names for the dynamic loaders.
38#include "lldb/Host/SafeMachO.h"
39
45
46#include <memory>
47#include <mutex>
48
49using namespace lldb;
50using namespace lldb_private;
51
53
55 return "Mach-O core file debugging plug-in.";
56}
57
61
63 ListenerSP listener_sp,
64 const FileSpec *crash_file,
65 bool can_connect) {
66 lldb::ProcessSP process_sp;
67 if (crash_file && !can_connect) {
68 const size_t header_size = sizeof(llvm::MachO::mach_header);
70 crash_file->GetPath(), header_size, 0);
71 if (data_sp && data_sp->GetByteSize() == header_size) {
72 DataExtractorSP extractor_sp =
73 std::make_shared<DataExtractor>(data_sp, lldb::eByteOrderLittle, 4);
74
75 lldb::offset_t data_offset = 0;
76 llvm::MachO::mach_header mach_header;
77 if (ObjectFileMachO::ParseHeader(extractor_sp, &data_offset,
78 mach_header)) {
79 if (mach_header.filetype == llvm::MachO::MH_CORE)
80 process_sp = std::make_shared<ProcessMachCore>(target_sp, listener_sp,
81 *crash_file);
82 }
83 }
84 }
85 return process_sp;
86}
87
89 bool plugin_specified_by_name) {
90 if (plugin_specified_by_name)
91 return true;
92
93 // For now we are just making sure the file exists for a given module
95 // Don't add the Target's architecture to the ModuleSpec - we may be
96 // working with a core file that doesn't have the correct cpusubtype in the
97 // header but we should still try to use it -
98 // ModuleSpecList::FindMatchingModuleSpec enforces a strict arch mach.
99 ModuleSpec core_module_spec(m_core_file);
100 core_module_spec.SetTarget(target_sp);
102 nullptr, nullptr));
103
104 if (m_core_module_sp) {
105 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
106 if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile)
107 return true;
108 }
109 }
110 return false;
111}
112
113// ProcessMachCore constructor
122
123// Destructor
125 Clear();
126 // We need to call finalize on the process before destroying ourselves to
127 // make sure all of the broadcaster cleanup goes as planned. If we destruct
128 // this class, then Process::~Process() might have problems trying to fully
129 // destroy the broadcaster.
130 Finalize(true /* destructing */);
131}
132
134 addr_t &dyld,
135 addr_t &kernel) {
137 llvm::MachO::mach_header header;
139 dyld = kernel = LLDB_INVALID_ADDRESS;
140 if (DoReadMemory(addr, &header, sizeof(header), error) != sizeof(header))
141 return false;
142 if (header.magic == llvm::MachO::MH_CIGAM ||
143 header.magic == llvm::MachO::MH_CIGAM_64) {
144 header.magic = llvm::byteswap<uint32_t>(header.magic);
145 header.cputype = llvm::byteswap<uint32_t>(header.cputype);
146 header.cpusubtype = llvm::byteswap<uint32_t>(header.cpusubtype);
147 header.filetype = llvm::byteswap<uint32_t>(header.filetype);
148 header.ncmds = llvm::byteswap<uint32_t>(header.ncmds);
149 header.sizeofcmds = llvm::byteswap<uint32_t>(header.sizeofcmds);
150 header.flags = llvm::byteswap<uint32_t>(header.flags);
151 }
152
153 if (header.magic == llvm::MachO::MH_MAGIC ||
154 header.magic == llvm::MachO::MH_MAGIC_64) {
155 // Check MH_EXECUTABLE to see if we can find the mach image that contains
156 // the shared library list. The dynamic loader (dyld) is what contains the
157 // list for user applications, and the mach kernel contains a global that
158 // has the list of kexts to load
159 switch (header.filetype) {
160 case llvm::MachO::MH_DYLINKER:
161 LLDB_LOGF(log,
162 "ProcessMachCore::%s found a user "
163 "process dyld binary image at 0x%" PRIx64,
164 __FUNCTION__, addr);
165 dyld = addr;
166 return true;
167
168 case llvm::MachO::MH_EXECUTE:
169 // Check MH_EXECUTABLE file types to see if the dynamic link object flag
170 // is NOT set. If it isn't, then we have a mach_kernel.
171 if ((header.flags & llvm::MachO::MH_DYLDLINK) == 0) {
172 LLDB_LOGF(log,
173 "ProcessMachCore::%s found a mach "
174 "kernel binary image at 0x%" PRIx64,
175 __FUNCTION__, addr);
176 // Address of the mach kernel "struct mach_header" in the core file.
177 kernel = addr;
178 return true;
179 }
180 break;
181 }
182 }
183 return false;
184}
185
187 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
188 SectionList *section_list = core_objfile->GetSectionList();
189 const uint32_t num_sections = section_list->GetNumSections(0);
190
191 bool ranges_are_sorted = true;
192 addr_t vm_addr = 0;
193 for (uint32_t i = 0; i < num_sections; ++i) {
194 Section *section = section_list->GetSectionAtIndex(i).get();
195 if (section && section->GetFileSize() > 0) {
196 lldb::addr_t section_vm_addr = section->GetFileAddress();
197 FileRange file_range(section->GetFileOffset(), section->GetFileSize());
198 VMRangeToFileOffset::Entry range_entry(
199 section_vm_addr, section->GetByteSize(), file_range);
200
201 if (vm_addr > section_vm_addr)
202 ranges_are_sorted = false;
203 vm_addr = section->GetFileAddress();
204 VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
205
206 if (last_entry &&
207 last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
208 last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase()) {
209 last_entry->SetRangeEnd(range_entry.GetRangeEnd());
210 last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd());
211 } else {
212 m_core_aranges.Append(range_entry);
213 }
214 // Some core files don't fill in the permissions correctly. If that is
215 // the case assume read + execute so clients don't think the memory is
216 // not readable, or executable. The memory isn't writable since this
217 // plug-in doesn't implement DoWriteMemory.
218 uint32_t permissions = section->GetPermissions();
219 if (permissions == 0)
220 permissions = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
222 section_vm_addr, section->GetByteSize(), permissions));
223 }
224 }
225 if (!ranges_are_sorted) {
226 m_core_aranges.Sort();
227 m_core_range_infos.Sort();
228 }
229}
230
231// Some corefiles have a UUID stored in a low memory
232// address. We inspect a set list of addresses for
233// the characters 'uuid' and 16 bytes later there will
234// be a uuid_t UUID. If we can find a binary that
235// matches the UUID, it is loaded with no slide in the target.
238 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
239
240 uint64_t lowmem_uuid_addresses[] = {0x2000204, 0x1000204, 0x1000020, 0x4204,
241 0x1204, 0x1020, 0x4020, 0xc00,
242 0xC0, 0};
243
244 for (uint64_t addr : lowmem_uuid_addresses) {
245 const VMRangeToFileOffset::Entry *core_memory_entry =
246 m_core_aranges.FindEntryThatContains(addr);
247 if (core_memory_entry) {
248 const addr_t offset = addr - core_memory_entry->GetRangeBase();
249 const addr_t bytes_left = core_memory_entry->GetRangeEnd() - addr;
250 // (4-bytes 'uuid' + 12 bytes pad for align + 16 bytes uuid_t) == 32 bytes
251 if (bytes_left >= 32) {
252 char strbuf[4];
253 if (core_objfile->CopyData(
254 core_memory_entry->data.GetRangeBase() + offset, 4, &strbuf) &&
255 strncmp("uuid", (char *)&strbuf, 4) == 0) {
256 uuid_t uuid_bytes;
257 if (core_objfile->CopyData(core_memory_entry->data.GetRangeBase() +
258 offset + 16,
259 sizeof(uuid_t), uuid_bytes)) {
260 UUID uuid(uuid_bytes, sizeof(uuid_t));
261 if (uuid.IsValid()) {
262 LLDB_LOGF(log,
263 "ProcessMachCore::LoadBinaryViaLowmemUUID: found "
264 "binary uuid %s at low memory address 0x%" PRIx64,
265 uuid.GetAsString().c_str(), addr);
266 // We have no address specified, only a UUID. Load it at the file
267 // address.
268 const bool value_is_offset = true;
269 const bool force_symbol_search = true;
270 const bool notify = true;
271 const bool set_address_in_target = true;
272 const bool allow_memory_image_last_resort = false;
274 this, llvm::StringRef(), uuid, 0, value_is_offset,
275 force_symbol_search, notify, set_address_in_target,
276 allow_memory_image_last_resort)) {
278 }
279 // We found metadata saying which binary should be loaded; don't
280 // try an exhaustive search.
281 return true;
282 }
283 }
284 }
285 }
286 }
287 }
288 return false;
289}
290
293 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
294
295 addr_t objfile_binary_value;
296 bool objfile_binary_value_is_offset;
297 UUID objfile_binary_uuid;
299
300 // This will be set to true if we had a metadata hint
301 // specifying a UUID or address -- and we should not fall back
302 // to doing an exhaustive search.
303 bool found_binary_spec_in_metadata = false;
304
305 if (core_objfile->GetCorefileMainBinaryInfo(objfile_binary_value,
306 objfile_binary_value_is_offset,
307 objfile_binary_uuid, type)) {
308 if (log) {
309 log->Printf("ProcessMachCore::LoadBinariesViaMetadata: using binary hint "
310 "from 'main bin spec' "
311 "LC_NOTE with UUID %s value 0x%" PRIx64
312 " value is offset %d and type %d",
313 objfile_binary_uuid.GetAsString().c_str(),
314 objfile_binary_value, objfile_binary_value_is_offset, type);
315 }
316 found_binary_spec_in_metadata = true;
317
318 // If this is the xnu kernel, don't load it now. Note the correct
319 // DynamicLoader plugin to use, and the address of the kernel, and
320 // let the DynamicLoader handle the finding & loading of the binary.
321 if (type == ObjectFile::eBinaryTypeKernel) {
322 m_mach_kernel_addr = objfile_binary_value;
324 } else if (type == ObjectFile::eBinaryTypeUser) {
325 m_dyld_addr = objfile_binary_value;
327 } else if (type == ObjectFile::eBinaryTypeUserAllImageInfos) {
328 m_dyld_all_image_infos_addr = objfile_binary_value;
330 } else {
331 const bool force_symbol_search = true;
332 const bool notify = true;
333 const bool set_address_in_target = true;
334 const bool allow_memory_image_last_resort = false;
336 this, llvm::StringRef(), objfile_binary_uuid,
337 objfile_binary_value, objfile_binary_value_is_offset,
338 force_symbol_search, notify, set_address_in_target,
339 allow_memory_image_last_resort)) {
341 }
342 }
343 }
344
345 // This checks for the presence of an LC_IDENT string in a core file;
346 // LC_IDENT is very obsolete and should not be used in new code, but if the
347 // load command is present, let's use the contents.
348 UUID ident_uuid;
349 addr_t ident_binary_addr = LLDB_INVALID_ADDRESS;
350 std::string corefile_identifier = core_objfile->GetIdentifierString();
351
352 // Search for UUID= and stext= strings in the identifier str.
353 if (corefile_identifier.find("UUID=") != std::string::npos) {
354 size_t p = corefile_identifier.find("UUID=") + strlen("UUID=");
355 std::string uuid_str = corefile_identifier.substr(p, 36);
356 ident_uuid.SetFromStringRef(uuid_str);
357 if (log)
358 log->Printf("Got a UUID from LC_IDENT/kern ver str LC_NOTE: %s",
359 ident_uuid.GetAsString().c_str());
360 found_binary_spec_in_metadata = true;
361 }
362 if (corefile_identifier.find("stext=") != std::string::npos) {
363 size_t p = corefile_identifier.find("stext=") + strlen("stext=");
364 if (corefile_identifier[p] == '0' && corefile_identifier[p + 1] == 'x') {
365 ident_binary_addr =
366 ::strtoul(corefile_identifier.c_str() + p, nullptr, 16);
367 if (log)
368 log->Printf("Got a load address from LC_IDENT/kern ver str "
369 "LC_NOTE: 0x%" PRIx64,
370 ident_binary_addr);
371 found_binary_spec_in_metadata = true;
372 }
373 }
374
375 // Search for a "Darwin Kernel" str indicating kernel; else treat as
376 // standalone
377 if (corefile_identifier.find("Darwin Kernel") != std::string::npos &&
378 ident_uuid.IsValid() && ident_binary_addr != LLDB_INVALID_ADDRESS) {
379 if (log)
380 log->Printf(
381 "ProcessMachCore::LoadBinariesViaMetadata: Found kernel binary via "
382 "LC_IDENT/kern ver str LC_NOTE");
383 m_mach_kernel_addr = ident_binary_addr;
384 found_binary_spec_in_metadata = true;
385 } else if (ident_uuid.IsValid()) {
386 // We have no address specified, only a UUID. Load it at the file
387 // address.
388 const bool value_is_offset = false;
389 const bool force_symbol_search = true;
390 const bool notify = true;
391 const bool set_address_in_target = true;
392 const bool allow_memory_image_last_resort = false;
394 this, llvm::StringRef(), ident_uuid, ident_binary_addr,
395 value_is_offset, force_symbol_search, notify,
396 set_address_in_target, allow_memory_image_last_resort)) {
397 found_binary_spec_in_metadata = true;
399 }
400 }
401
402 // Finally, load any binaries noted by "load binary" LC_NOTEs in the
403 // corefile
404 if (core_objfile->LoadCoreFileImages(*this)) {
405 found_binary_spec_in_metadata = true;
407 }
408
409 if (!found_binary_spec_in_metadata && LoadBinaryViaLowmemUUID())
410 found_binary_spec_in_metadata = true;
411
412 // LoadCoreFileImges may have set the dynamic loader, e.g. in
413 // PlatformDarwinKernel::LoadPlatformBinaryAndSetup().
414 // If we now have a dynamic loader, save its name so we don't
415 // un-set it later.
416 if (m_dyld_up)
418
419 return found_binary_spec_in_metadata;
420}
421
424
425 // Search the pages of the corefile for dyld or mach kernel
426 // binaries. There may be multiple things that look like a kernel
427 // in the corefile; disambiguating to the correct one can be difficult.
428
429 std::vector<addr_t> dylds_found;
430 std::vector<addr_t> kernels_found;
431
432 // To do an exhaustive search, we'll need to create data extractors
433 // to get correctly sized/endianness fields. If we had a main binary
434 // already, we would have set the Target to that - so here we'll use
435 // the corefile's cputype/cpusubtype as the best guess.
436 if (!GetTarget().GetArchitecture().IsValid()) {
437 // The corefile's architecture is our best starting point.
438 ArchSpec arch(m_core_module_sp->GetArchitecture());
439 if (arch.IsValid()) {
440 LLDB_LOGF(log,
441 "ProcessMachCore::%s: Setting target ArchSpec based on "
442 "corefile mach-o cputype/cpusubtype",
443 __FUNCTION__);
445 }
446 }
447
448 const size_t num_core_aranges = m_core_aranges.GetSize();
449 for (size_t i = 0; i < num_core_aranges; ++i) {
450 const VMRangeToFileOffset::Entry *entry = m_core_aranges.GetEntryAtIndex(i);
451 lldb::addr_t section_vm_addr_start = entry->GetRangeBase();
452 lldb::addr_t section_vm_addr_end = entry->GetRangeEnd();
453 for (lldb::addr_t section_vm_addr = section_vm_addr_start;
454 section_vm_addr < section_vm_addr_end; section_vm_addr += 0x1000) {
455 addr_t dyld, kernel;
456 if (CheckAddressForDyldOrKernel(section_vm_addr, dyld, kernel)) {
457 if (dyld != LLDB_INVALID_ADDRESS)
458 dylds_found.push_back(dyld);
459 if (kernel != LLDB_INVALID_ADDRESS)
460 kernels_found.push_back(kernel);
461 }
462 }
463 }
464
465 // If we found more than one dyld mach-o header in the corefile,
466 // pick the first one.
467 if (dylds_found.size() > 0)
468 m_dyld_addr = dylds_found[0];
469 if (kernels_found.size() > 0)
470 m_mach_kernel_addr = kernels_found[0];
471
472 // Zero or one kernels found, we're done.
473 if (kernels_found.size() < 2)
474 return;
475
476 // In the case of multiple kernel images found in the core file via
477 // exhaustive search, we may not pick the correct one. See if the
478 // DynamicLoaderDarwinKernel's search heuristics might identify the correct
479 // one.
480
481 // SearchForDarwinKernel will call this class' GetImageInfoAddress method
482 // which will give it the addresses we already have.
483 // Save those aside and set
484 // m_mach_kernel_addr/m_dyld_addr to an invalid address temporarily so
485 // DynamicLoaderDarwinKernel does a real search for the kernel using its
486 // own heuristics.
487
488 addr_t saved_mach_kernel_addr = m_mach_kernel_addr;
489 addr_t saved_user_dyld_addr = m_dyld_addr;
493
494 addr_t better_kernel_address =
496
497 m_mach_kernel_addr = saved_mach_kernel_addr;
498 m_dyld_addr = saved_user_dyld_addr;
499
500 if (better_kernel_address != LLDB_INVALID_ADDRESS) {
501 LLDB_LOGF(log,
502 "ProcessMachCore::%s: Using "
503 "the kernel address "
504 "from DynamicLoaderDarwinKernel",
505 __FUNCTION__);
506 m_mach_kernel_addr = better_kernel_address;
507 }
508}
509
512
513 bool found_binary_spec_in_metadata = LoadBinariesViaMetadata();
514 if (!found_binary_spec_in_metadata)
516
517 if (m_dyld_plugin_name.empty()) {
518 // If we found both a user-process dyld and a kernel binary, we need to
519 // decide which to prefer.
522 LLDB_LOGF(log,
523 "ProcessMachCore::%s: Using kernel "
524 "corefile image "
525 "at 0x%" PRIx64,
526 __FUNCTION__, m_mach_kernel_addr);
528 } else if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
529 LLDB_LOGF(log,
530 "ProcessMachCore::%s: Using user process dyld "
531 "image at 0x%" PRIx64,
532 __FUNCTION__, m_dyld_addr);
535 LLDB_LOGF(log,
536 "ProcessMachCore::%s: Using user process dyld "
537 "dyld_all_image_infos at 0x%" PRIx64,
538 __FUNCTION__, m_dyld_all_image_infos_addr);
540 }
541 } else {
543 LLDB_LOGF(log,
544 "ProcessMachCore::%s: Using user process dyld "
545 "image at 0x%" PRIx64,
546 __FUNCTION__, m_dyld_addr);
549 LLDB_LOGF(log,
550 "ProcessMachCore::%s: Using user process dyld "
551 "dyld_all_image_infos at 0x%" PRIx64,
552 __FUNCTION__, m_dyld_all_image_infos_addr);
554 LLDB_LOGF(log,
555 "ProcessMachCore::%s: Using kernel "
556 "corefile image "
557 "at 0x%" PRIx64,
558 __FUNCTION__, m_mach_kernel_addr);
560 }
561 }
562 }
563}
564
567 // For non-user process core files, the permissions on the core file
568 // segments are usually meaningless, they may be just "read", because we're
569 // dealing with kernel coredumps or early startup coredumps and the dumper
570 // is grabbing pages of memory without knowing what they are. If they
571 // aren't marked as "executable", that can break the unwinder which will
572 // check a pc value to see if it is in an executable segment and stop the
573 // backtrace early if it is not ("executable" and "unknown" would both be
574 // fine, but "not executable" will break the unwinder).
575 size_t core_range_infos_size = m_core_range_infos.GetSize();
576 for (size_t i = 0; i < core_range_infos_size; i++) {
578 m_core_range_infos.GetMutableEntryAtIndex(i);
579 ent->data = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
580 }
581 }
582}
583
584// Process Control
587 if (!m_core_module_sp) {
588 error = Status::FromErrorString("invalid core module");
589 return error;
590 }
592
593 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
594 if (core_objfile == nullptr) {
595 error = Status::FromErrorString("invalid core object file");
596 return error;
597 }
598
599 SetCanJIT(false);
600
601 // If we have an executable binary in the Target already,
602 // use that to set the Target's ArchSpec.
603 //
604 // Don't initialize the ArchSpec based on the corefile's cputype/cpusubtype
605 // here, the corefile creator may not know the correct subtype of the code
606 // that is executing, initialize the Target to that, and if the
607 // main binary has Python code which initializes based on the Target arch,
608 // get the wrong subtype value.
609 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
610 if (exe_module_sp && exe_module_sp->GetArchitecture().IsValid()) {
611 LLDB_LOGF(log,
612 "ProcessMachCore::%s: Was given binary + corefile, setting "
613 "target ArchSpec to binary to start",
614 __FUNCTION__);
615 GetTarget().SetArchitecture(exe_module_sp->GetArchitecture());
616 }
617
619
621
623
624 exe_module_sp = GetTarget().GetExecutableModule();
625 if (exe_module_sp && exe_module_sp->GetArchitecture().IsValid()) {
626 LLDB_LOGF(log,
627 "ProcessMachCore::%s: have executable binary in the Target "
628 "after metadata/scan. Setting Target's ArchSpec based on "
629 "that.",
630 __FUNCTION__);
631 GetTarget().SetArchitecture(exe_module_sp->GetArchitecture());
632 } else {
633 // The corefile's architecture is our best starting point.
634 ArchSpec arch(m_core_module_sp->GetArchitecture());
635 if (arch.IsValid()) {
636 LLDB_LOGF(log,
637 "ProcessMachCore::%s: Setting target ArchSpec based on "
638 "corefile mach-o cputype/cpusubtype",
639 __FUNCTION__);
641 }
642 }
643
644 AddressableBits addressable_bits = core_objfile->GetAddressableBits();
645 SetAddressableBitMasks(addressable_bits);
646
647 return error;
648}
649
655
657 ThreadList &new_thread_list) {
658 if (old_thread_list.GetSize(false) == 0) {
659 // Make up the thread the first time this is called so we can setup our one
660 // and only core thread state.
661 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
662
663 if (core_objfile) {
664 const uint32_t num_threads = core_objfile->GetNumThreadContexts();
665 std::vector<lldb::tid_t> tids;
666 if (core_objfile->GetCorefileThreadExtraInfos(tids)) {
667 assert(tids.size() == num_threads);
668
669 // Find highest tid value.
670 lldb::tid_t highest_tid = 0;
671 for (uint32_t i = 0; i < num_threads; i++) {
672 if (tids[i] != LLDB_INVALID_THREAD_ID && tids[i] > highest_tid)
673 highest_tid = tids[i];
674 }
675 lldb::tid_t current_unused_tid = highest_tid + 1;
676 for (uint32_t i = 0; i < num_threads; i++) {
677 if (tids[i] == LLDB_INVALID_THREAD_ID) {
678 tids[i] = current_unused_tid++;
679 }
680 }
681 } else {
682 // No metadata, insert numbers sequentially from 0.
683 for (uint32_t i = 0; i < num_threads; i++) {
684 tids.push_back(i);
685 }
686 }
687
688 for (uint32_t i = 0; i < num_threads; i++) {
689 ThreadSP thread_sp =
690 std::make_shared<ThreadMachCore>(*this, tids[i], i);
691 new_thread_list.AddThread(thread_sp);
692 }
693 }
694 } else {
695 const uint32_t num_threads = old_thread_list.GetSize(false);
696 for (uint32_t i = 0; i < num_threads; ++i)
697 new_thread_list.AddThread(old_thread_list.GetThreadAtIndex(i, false));
698 }
699 return new_thread_list.GetSize(false) > 0;
700}
701
703 // Let all threads recover from stopping and do any clean up based on the
704 // previous thread state (if any).
705 m_thread_list.RefreshStateAfterStop();
706 // SetThreadStopInfo (m_last_stop_packet);
707}
708
710
711// Process Queries
712
713bool ProcessMachCore::IsAlive() { return true; }
714
715bool ProcessMachCore::WarnBeforeDetach() const { return false; }
716
717// Process Memory
718size_t ProcessMachCore::ReadMemory(addr_t addr, void *buf, size_t size,
719 Status &error) {
720 // Don't allow the caching that lldb_private::Process::ReadMemory does since
721 // in core files we have it all cached our our core file anyway.
722 return DoReadMemory(FixAnyAddress(addr), buf, size, error);
723}
724
725size_t ProcessMachCore::DoReadMemory(addr_t addr, void *buf, size_t size,
726 Status &error) {
727 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
728 size_t bytes_read = 0;
729
730 if (core_objfile) {
731 // Segments are not always contiguous in mach-o core files. We have core
732 // files that have segments like:
733 // Address Size File off File size
734 // ---------- ---------- ---------- ----------
735 // LC_SEGMENT 0x000f6000 0x00001000 0x1d509ee8 0x00001000 --- --- 0
736 // 0x00000000 __TEXT LC_SEGMENT 0x0f600000 0x00100000 0x1d50aee8 0x00100000
737 // --- --- 0 0x00000000 __TEXT LC_SEGMENT 0x000f7000 0x00001000
738 // 0x1d60aee8 0x00001000 --- --- 0 0x00000000 __TEXT
739 //
740 // Any if the user executes the following command:
741 //
742 // (lldb) mem read 0xf6ff0
743 //
744 // We would attempt to read 32 bytes from 0xf6ff0 but would only get 16
745 // unless we loop through consecutive memory ranges that are contiguous in
746 // the address space, but not in the file data.
747 while (bytes_read < size) {
748 const addr_t curr_addr = addr + bytes_read;
749 const VMRangeToFileOffset::Entry *core_memory_entry =
750 m_core_aranges.FindEntryThatContains(curr_addr);
751
752 if (core_memory_entry) {
753 const addr_t offset = curr_addr - core_memory_entry->GetRangeBase();
754 const addr_t bytes_left = core_memory_entry->GetRangeEnd() - curr_addr;
755 const size_t bytes_to_read =
756 std::min(size - bytes_read, (size_t)bytes_left);
757 const size_t curr_bytes_read = core_objfile->CopyData(
758 core_memory_entry->data.GetRangeBase() + offset, bytes_to_read,
759 (char *)buf + bytes_read);
760 if (curr_bytes_read == 0)
761 break;
762 bytes_read += curr_bytes_read;
763 } else {
764 // Only set the error if we didn't read any bytes
765 if (bytes_read == 0)
767 "core file does not contain 0x%" PRIx64, curr_addr);
768 break;
769 }
770 }
771 }
772
773 return bytes_read;
774}
775
777 MemoryRegionInfo &region_info) {
778 region_info.Clear();
779 const VMRangeToPermissions::Entry *permission_entry =
780 m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
781 if (permission_entry) {
782 if (permission_entry->Contains(load_addr)) {
783 region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
784 region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
785 const Flags permissions(permission_entry->data);
786 region_info.SetReadable(permissions.Test(ePermissionsReadable)
789 region_info.SetWritable(permissions.Test(ePermissionsWritable)
792 region_info.SetExecutable(permissions.Test(ePermissionsExecutable)
796 } else if (load_addr < permission_entry->GetRangeBase()) {
797 region_info.GetRange().SetRangeBase(load_addr);
798 region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
802 region_info.SetMapped(MemoryRegionInfo::eNo);
803 }
804 return Status();
805 } else {
806 // The corefile has no LC_SEGMENT at this virtual address,
807 // but see if there is a binary whose Section has been
808 // loaded at that address in the current Target.
809 Address addr;
810 if (GetTarget().ResolveLoadAddress(load_addr, addr)) {
811 SectionSP section_sp(addr.GetSection());
812 if (section_sp) {
813 region_info.GetRange().SetRangeBase(
814 section_sp->GetLoadBaseAddress(&GetTarget()));
815 region_info.GetRange().SetByteSize(section_sp->GetByteSize());
816 if (region_info.GetRange().Contains(load_addr)) {
817 region_info.SetLLDBPermissions(section_sp->GetPermissions());
818 return Status();
819 }
820 }
821 }
822 }
823
824 region_info.GetRange().SetRangeBase(load_addr);
829 region_info.SetMapped(MemoryRegionInfo::eNo);
830 return Status();
831}
832
834
836 static llvm::once_flag g_once_flag;
837
838 llvm::call_once(g_once_flag, []() {
841 });
842}
843
845 // The DynamicLoader plugin will call back in to this Process
846 // method to find the virtual address of one of these:
847 // 1. The xnu mach kernel binary Mach-O header
848 // 2. The dyld binary Mach-O header
849 // 3. dyld's dyld_all_image_infos object
850 //
851 // DynamicLoaderMacOSX will accept either the dyld Mach-O header
852 // address or the dyld_all_image_infos interchangably, no need
853 // to distinguish between them. It disambiguates by the Mach-O
854 // file magic number at the start.
857 return m_mach_kernel_addr;
859 return m_dyld_addr;
860 } else {
862 return m_dyld_addr;
864 return m_mach_kernel_addr;
865 }
866
867 // m_dyld_addr and m_mach_kernel_addr both
868 // invalid, return m_dyld_all_image_infos_addr
869 // in case it has a useful value.
871}
872
unsigned char uuid_t[16]
static llvm::raw_ostream & error(Stream &strm)
static llvm::Expected< lldb::addr_t > ResolveLoadAddress(ExecutionContext *exe_ctx, lldb::ModuleSP &module_sp, const char *dw_op_type, lldb::addr_t file_addr, Address &so_addr, bool check_sectionoffset=false)
Helper function to move common code used to resolve a file address and turn into a load address.
#define LLDB_LOGF(log,...)
Definition Log.h:376
#define LLDB_PLUGIN_DEFINE(PluginName)
static llvm::StringRef GetPluginNameStatic()
static lldb::addr_t SearchForDarwinKernel(lldb_private::Process *process)
static llvm::StringRef GetPluginNameStatic()
static llvm::StringRef GetPluginNameStatic()
bool ParseHeader() override
Attempts to parse the object header.
lldb::addr_t m_dyld_addr
bool WarnBeforeDetach() const override
Before lldb detaches from a process, it warns the user that they are about to lose their debug sessio...
static llvm::StringRef GetPluginDescriptionStatic()
static void Initialize()
size_t ReadMemory(lldb::addr_t addr, void *buf, size_t size, lldb_private::Status &error) override
Read of memory from a process.
VMRangeToFileOffset m_core_aranges
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.
CorefilePreference GetCorefilePreference()
If a core file can be interpreted multiple ways, this establishes which style wins.
bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override
Check if a plug-in instance can debug the file in module.
void CleanupMemoryRegionPermissions()
lldb_private::ObjectFile * GetCoreObjectFile()
ProcessMachCore(lldb::TargetSP target_sp, lldb::ListenerSP listener, const lldb_private::FileSpec &core_file)
llvm::StringRef m_dyld_plugin_name
lldb_private::DynamicLoader * GetDynamicLoader() override
Get the dynamic loader plug-in for this process.
lldb_private::Status DoDestroy() override
static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener, const lldb_private::FileSpec *crash_file_path, bool can_connect)
lldb::addr_t m_dyld_all_image_infos_addr
void RefreshStateAfterStop() override
Currently called as part of ShouldStop.
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 GetPluginNameStatic()
bool IsAlive() override
Check if a process is still alive.
bool CheckAddressForDyldOrKernel(lldb::addr_t addr, lldb::addr_t &dyld, lldb::addr_t &kernel)
lldb_private::Range< lldb::addr_t, lldb::addr_t > FileRange
VMRangeToPermissions m_core_range_infos
lldb_private::Status DoLoadCore() override
void LoadBinariesViaExhaustiveSearch()
lldb::addr_t m_mach_kernel_addr
lldb::addr_t GetImageInfoAddress() override
Get the image information address for the current process.
~ProcessMachCore() override
lldb::ModuleSP m_core_module_sp
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...
static void Terminate()
A section + offset based address class.
Definition Address.h:62
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition Address.h:432
A class which holds the metadata from a remote stub/corefile note about how many bits are used for ad...
An architecture specification class.
Definition ArchSpec.h:31
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:366
A plug-in interface definition class for dynamic loaders.
static lldb::ModuleSP LoadBinaryWithUUIDAndAddress(Process *process, llvm::StringRef name, UUID uuid, lldb::addr_t value, bool value_is_offset, bool force_symbol_search, bool notify, bool set_address_in_target, bool allow_memory_image_last_resort)
Find/load a binary into lldb given a UUID and the address where it is loaded in memory,...
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:57
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
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.
A class to manage flags.
Definition Flags.h:22
bool Test(ValueType bit) const
Test a single flag bit.
Definition Flags.h:96
void void Printf(const char *format,...) __attribute__((format(printf
Prefer using LLDB_LOGF whenever possible.
Definition Log.cpp:156
void SetMapped(OptionalBool val)
void SetReadable(OptionalBool val)
void SetExecutable(OptionalBool val)
void SetWritable(OptionalBool val)
void SetLLDBPermissions(uint32_t permissions)
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)
void SetTarget(lldb::TargetSP target)
Set the target to be used when resolving a module.
Definition ModuleSpec.h:141
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
virtual bool GetCorefileThreadExtraInfos(std::vector< lldb::tid_t > &tids)
Get metadata about thread ids from the corefile.
Definition ObjectFile.h:546
virtual std::string GetIdentifierString()
Some object files may have an identifier string embedded in them, e.g.
Definition ObjectFile.h:477
virtual uint32_t GetNumThreadContexts()
Definition ObjectFile.h:468
virtual bool LoadCoreFileImages(lldb_private::Process &process)
Load binaries listed in a corefile.
Definition ObjectFile.h:735
@ eTypeCoreFile
A core file that has a checkpoint of a program's execution state.
Definition ObjectFile.h:53
virtual lldb_private::AddressableBits GetAddressableBits()
Some object files may have the number of bits used for addressing embedded in them,...
Definition ObjectFile.h:489
size_t CopyData(lldb::offset_t offset, size_t length, void *dst) const
virtual SectionList * GetSectionList(bool update_module_section_list=true)
Gets the section list for the currently selected architecture (and object for archives).
virtual bool GetCorefileMainBinaryInfo(lldb::addr_t &value, bool &value_is_offset, UUID &uuid, ObjectFile::BinaryType &type)
When the ObjectFile is a core file, lldb needs to locate the "binary" in the core file.
Definition ObjectFile.h:517
BinaryType
If we have a corefile binary hint, this enum specifies the binary type which we can use to select the...
Definition ObjectFile.h:83
@ eBinaryTypeKernel
kernel binary
Definition ObjectFile.h:87
@ eBinaryTypeUser
user process binary, dyld addr
Definition ObjectFile.h:89
@ eBinaryTypeUserAllImageInfos
user process binary, dyld_all_image_infos addr
Definition ObjectFile.h:91
virtual llvm::StringRef GetPluginName()=0
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 SetAddressableBitMasks(AddressableBits bit_masks)
Definition Process.cpp:6905
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2586
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3247
lldb::addr_t FixAnyAddress(lldb::addr_t pc)
Use this method when you do not know, or do not care what kind of address you are fixing.
Definition Process.cpp:6069
bool IsValid() const
Return whether this object is valid (i.e.
Definition Process.h:588
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
Definition Process.cpp:538
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3220
friend class ThreadList
Definition Process.h:361
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1267
RangeData< lldb::addr_t, lldb::addr_t, FileRange > Entry
Definition RangeMap.h:462
size_t GetNumSections(uint32_t depth) const
Definition Section.cpp:546
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:557
uint32_t GetPermissions() const
Get the permissions as OR'ed bits from lldb::Permissions.
Definition Section.cpp:363
lldb::offset_t GetFileOffset() const
Definition Section.h:183
lldb::addr_t GetFileAddress() const
Definition Section.cpp:198
lldb::addr_t GetByteSize() const
Definition Section.h:199
lldb::offset_t GetFileSize() const
Definition Section.h:189
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1704
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1524
void AddThread(const lldb::ThreadSP &thread_sp)
uint32_t GetSize(bool can_update=true)
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
Represents UUID's of various sizes.
Definition UUID.h:27
bool SetFromStringRef(llvm::StringRef str)
Definition UUID.cpp:101
std::string GetAsString(llvm::StringRef separator="-") const
Definition UUID.cpp:54
bool IsValid() const
Definition UUID.h:69
#define LLDB_INVALID_THREAD_ID
#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:332
std::shared_ptr< lldb_private::Thread > ThreadSP
uint64_t offset_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Listener > ListenerSP
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
uint64_t tid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::Module > ModuleSP
bool Contains(BaseType r) const
Definition RangeMap.h:93
BaseType GetRangeBase() const
Definition RangeMap.h:45
void SetRangeEnd(BaseType end)
Definition RangeMap.h:80
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
void SetByteSize(SizeType s)
Definition RangeMap.h:89