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 "lldb/Core/Debugger.h"
13#include "lldb/Core/Module.h"
16#include "lldb/Core/Section.h"
17#include "lldb/Host/Host.h"
21#include "lldb/Target/Target.h"
22#include "lldb/Target/Thread.h"
26#include "lldb/Utility/Log.h"
27#include "lldb/Utility/State.h"
28#include "lldb/Utility/UUID.h"
29#include "llvm/Support/MathExtras.h"
30
31#include "ProcessMachCore.h"
33#include "ThreadMachCore.h"
34
35// Needed for the plug-in names for the dynamic loaders.
36#include "lldb/Host/SafeMachO.h"
37
43
44#include <memory>
45
46using namespace lldb;
47using namespace lldb_private;
48
50
52 return "Mach-O core file debugging plug-in.";
53}
54
58
60 ListenerSP listener_sp,
61 const FileSpec *crash_file,
62 bool can_connect) {
63 lldb::ProcessSP process_sp;
64 if (crash_file && !can_connect) {
65 const size_t header_size = sizeof(llvm::MachO::mach_header);
67 crash_file->GetPath(), header_size, 0);
68 if (data_sp && data_sp->GetByteSize() == header_size) {
69 DataExtractorSP extractor_sp =
70 std::make_shared<DataExtractor>(data_sp, lldb::eByteOrderLittle, 4);
71
72 lldb::offset_t data_offset = 0;
73 llvm::MachO::mach_header mach_header;
74 if (ObjectFileMachO::ParseHeader(extractor_sp, &data_offset,
75 mach_header)) {
76 if (mach_header.filetype == llvm::MachO::MH_CORE)
77 process_sp = std::make_shared<ProcessMachCore>(target_sp, listener_sp,
78 *crash_file);
79 }
80 }
81 }
82 return process_sp;
83}
84
86 bool plugin_specified_by_name) {
87 if (plugin_specified_by_name)
88 return true;
89
90 // For now we are just making sure the file exists for a given module
92 // Don't add the Target's architecture to the ModuleSpec - we may be
93 // working with a core file that doesn't have the correct cpusubtype in the
94 // header but we should still try to use it -
95 // ModuleSpecList::FindMatchingModuleSpec enforces a strict arch mach.
96 ModuleSpec core_module_spec(m_core_file);
97 core_module_spec.SetTarget(target_sp);
99 nullptr, nullptr));
100
101 if (m_core_module_sp) {
102 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
103 if (core_objfile && core_objfile->GetType() == ObjectFile::eTypeCoreFile)
104 return true;
105 }
106 }
107 return false;
108}
109
110// ProcessMachCore constructor
119
120// Destructor
122 Clear();
123 // We need to call finalize on the process before destroying ourselves to
124 // make sure all of the broadcaster cleanup goes as planned. If we destruct
125 // this class, then Process::~Process() might have problems trying to fully
126 // destroy the broadcaster.
127 Finalize(true /* destructing */);
128}
129
131 addr_t &dyld,
132 addr_t &kernel) {
134 llvm::MachO::mach_header header;
136 dyld = kernel = LLDB_INVALID_ADDRESS;
137 if (DoReadMemory(addr, &header, sizeof(header), error) != sizeof(header))
138 return false;
139 if (header.magic == llvm::MachO::MH_CIGAM ||
140 header.magic == llvm::MachO::MH_CIGAM_64) {
141 header.magic = llvm::byteswap<uint32_t>(header.magic);
142 header.cputype = llvm::byteswap<uint32_t>(header.cputype);
143 header.cpusubtype = llvm::byteswap<uint32_t>(header.cpusubtype);
144 header.filetype = llvm::byteswap<uint32_t>(header.filetype);
145 header.ncmds = llvm::byteswap<uint32_t>(header.ncmds);
146 header.sizeofcmds = llvm::byteswap<uint32_t>(header.sizeofcmds);
147 header.flags = llvm::byteswap<uint32_t>(header.flags);
148 }
149
150 if (header.magic == llvm::MachO::MH_MAGIC ||
151 header.magic == llvm::MachO::MH_MAGIC_64) {
152 // Check MH_EXECUTABLE to see if we can find the mach image that contains
153 // the shared library list. The dynamic loader (dyld) is what contains the
154 // list for user applications, and the mach kernel contains a global that
155 // has the list of kexts to load
156 switch (header.filetype) {
157 case llvm::MachO::MH_DYLINKER:
158 LLDB_LOGF(log,
159 "ProcessMachCore::%s found a user "
160 "process dyld binary image at 0x%" PRIx64,
161 __FUNCTION__, addr);
162 dyld = addr;
163 return true;
164
165 case llvm::MachO::MH_EXECUTE:
166 // Check MH_EXECUTABLE file types to see if the dynamic link object flag
167 // is NOT set. If it isn't, then we have a mach_kernel.
168 if ((header.flags & llvm::MachO::MH_DYLDLINK) == 0) {
169 LLDB_LOGF(log,
170 "ProcessMachCore::%s found a mach "
171 "kernel binary image at 0x%" PRIx64,
172 __FUNCTION__, addr);
173 // Address of the mach kernel "struct mach_header" in the core file.
174 kernel = addr;
175 return true;
176 }
177 break;
178 }
179 }
180 return false;
181}
182
184 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
185 SectionList *section_list = core_objfile->GetSectionList();
186 const uint32_t num_sections = section_list->GetNumSections(0);
187
188 bool ranges_are_sorted = true;
189 addr_t vm_addr = 0;
190 for (uint32_t i = 0; i < num_sections; ++i) {
191 Section *section = section_list->GetSectionAtIndex(i).get();
192 if (section && section->GetFileSize() > 0) {
193 lldb::addr_t section_vm_addr = section->GetFileAddress();
194 FileRange file_range(section->GetFileOffset(), section->GetFileSize());
195 VMRangeToFileOffset::Entry range_entry(
196 section_vm_addr, section->GetByteSize(), file_range);
197
198 if (vm_addr > section_vm_addr)
199 ranges_are_sorted = false;
200 vm_addr = section->GetFileAddress();
201 VMRangeToFileOffset::Entry *last_entry = m_core_aranges.Back();
202
203 if (last_entry &&
204 last_entry->GetRangeEnd() == range_entry.GetRangeBase() &&
205 last_entry->data.GetRangeEnd() == range_entry.data.GetRangeBase()) {
206 last_entry->SetRangeEnd(range_entry.GetRangeEnd());
207 last_entry->data.SetRangeEnd(range_entry.data.GetRangeEnd());
208 } else {
209 m_core_aranges.Append(range_entry);
210 }
211 // Some core files don't fill in the permissions correctly. If that is
212 // the case assume read + execute so clients don't think the memory is
213 // not readable, or executable. The memory isn't writable since this
214 // plug-in doesn't implement DoWriteMemory.
215 uint32_t permissions = section->GetPermissions();
216 if (permissions == 0)
217 permissions = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
219 section_vm_addr, section->GetByteSize(), permissions));
220 }
221 }
222 if (!ranges_are_sorted) {
223 m_core_aranges.Sort();
224 m_core_range_infos.Sort();
225 }
226}
227
228// Some corefiles have a UUID stored in a low memory
229// address. We inspect a set list of addresses for
230// the characters 'uuid' and 16 bytes later there will
231// be a uuid_t UUID. If we can find a binary that
232// matches the UUID, it is loaded with no slide in the target.
235 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
236
237 uint64_t lowmem_uuid_addresses[] = {0x2000204, 0x1000204, 0x1000020, 0x4204,
238 0x1204, 0x1020, 0x4020, 0xc00,
239 0xC0, 0};
240
241 for (uint64_t addr : lowmem_uuid_addresses) {
242 const VMRangeToFileOffset::Entry *core_memory_entry =
243 m_core_aranges.FindEntryThatContains(addr);
244 if (core_memory_entry) {
245 const addr_t offset = addr - core_memory_entry->GetRangeBase();
246 const addr_t bytes_left = core_memory_entry->GetRangeEnd() - addr;
247 // (4-bytes 'uuid' + 12 bytes pad for align + 16 bytes uuid_t) == 32 bytes
248 if (bytes_left >= 32) {
249 char strbuf[4];
250 if (core_objfile->CopyData(
251 core_memory_entry->data.GetRangeBase() + offset, 4, &strbuf) &&
252 strncmp("uuid", (char *)&strbuf, 4) == 0) {
253 uuid_t uuid_bytes;
254 if (core_objfile->CopyData(core_memory_entry->data.GetRangeBase() +
255 offset + 16,
256 sizeof(uuid_t), uuid_bytes)) {
257 UUID uuid(uuid_bytes, sizeof(uuid_t));
258 if (uuid.IsValid()) {
259 LLDB_LOGF(log,
260 "ProcessMachCore::LoadBinaryViaLowmemUUID: found "
261 "binary uuid %s at low memory address 0x%" PRIx64,
262 uuid.GetAsString().c_str(), addr);
263 // We have no address specified, only a UUID. Load it at the file
264 // address.
266 bin_spec.uuid = uuid;
267 bin_spec.value = 0;
268 bin_spec.value_is_offset = true;
269 bin_spec.force_symbol_search = true;
270 bin_spec.notify = true;
271 bin_spec.set_address_in_target = true;
272 bin_spec.is_main_executable = true;
273 llvm::Expected<ModuleSP> module =
275 if (module)
277 else
279 << llvm::toString(module.takeError()) << "\n";
280 // We found metadata saying which binary should be loaded; don't
281 // try an exhaustive search.
282 return true;
283 }
284 }
285 }
286 }
287 }
288 }
289 return false;
290}
291
294 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
295
296 addr_t objfile_binary_value;
297 bool objfile_binary_value_is_offset;
298 UUID objfile_binary_uuid;
300
301 // This will be set to true if we had a metadata hint
302 // specifying a UUID or address -- and we should not fall back
303 // to doing an exhaustive search.
304 bool found_binary_spec_in_metadata = false;
305
306 if (core_objfile->GetCorefileMainBinaryInfo(objfile_binary_value,
307 objfile_binary_value_is_offset,
308 objfile_binary_uuid, type)) {
309 if (log) {
310 log->Printf("ProcessMachCore::LoadBinariesViaMetadata: using binary hint "
311 "from 'main bin spec' "
312 "LC_NOTE with UUID %s value 0x%" PRIx64
313 " value is offset %d and type %d",
314 objfile_binary_uuid.GetAsString().c_str(),
315 objfile_binary_value, objfile_binary_value_is_offset, type);
316 }
317 found_binary_spec_in_metadata = true;
318
319 // If this is the xnu kernel, don't load it now. Note the correct
320 // DynamicLoader plugin to use, and the address of the kernel, and
321 // let the DynamicLoader handle the finding & loading of the binary.
322 if (type == ObjectFile::eBinaryTypeKernel) {
323 m_mach_kernel_addr = objfile_binary_value;
325 } else if (type == ObjectFile::eBinaryTypeUser) {
326 m_dyld_addr = objfile_binary_value;
328 } else if (type == ObjectFile::eBinaryTypeUserAllImageInfos) {
329 m_dyld_all_image_infos_addr = objfile_binary_value;
331 } else {
333 bin_spec.uuid = objfile_binary_uuid;
334 bin_spec.value = objfile_binary_value;
335 bin_spec.value_is_offset = objfile_binary_value_is_offset;
336 bin_spec.force_symbol_search = true;
337 bin_spec.notify = true;
338 bin_spec.set_address_in_target = true;
339 bin_spec.is_main_executable = true;
340 llvm::Expected<ModuleSP> module =
342 if (module)
344 else
346 << llvm::toString(module.takeError()) << "\n";
347 }
348 }
349
350 // This checks for the presence of an LC_IDENT string in a core file;
351 // LC_IDENT is very obsolete and should not be used in new code, but if the
352 // load command is present, let's use the contents.
353 UUID ident_uuid;
354 addr_t ident_binary_addr = LLDB_INVALID_ADDRESS;
355 std::string corefile_identifier = core_objfile->GetIdentifierString();
356
357 // Search for UUID= and stext= strings in the identifier str.
358 if (corefile_identifier.find("UUID=") != std::string::npos) {
359 size_t p = corefile_identifier.find("UUID=") + strlen("UUID=");
360 std::string uuid_str = corefile_identifier.substr(p, 36);
361 ident_uuid.SetFromStringRef(uuid_str);
362 if (log)
363 log->Printf("Got a UUID from LC_IDENT/kern ver str LC_NOTE: %s",
364 ident_uuid.GetAsString().c_str());
365 found_binary_spec_in_metadata = true;
366 }
367 if (corefile_identifier.find("stext=") != std::string::npos) {
368 size_t p = corefile_identifier.find("stext=") + strlen("stext=");
369 if (corefile_identifier[p] == '0' && corefile_identifier[p + 1] == 'x') {
370 ident_binary_addr =
371 ::strtoul(corefile_identifier.c_str() + p, nullptr, 16);
372 if (log)
373 log->Printf("Got a load address from LC_IDENT/kern ver str "
374 "LC_NOTE: 0x%" PRIx64,
375 ident_binary_addr);
376 found_binary_spec_in_metadata = true;
377 }
378 }
379
380 // Search for a "Darwin Kernel" str indicating kernel; else treat as
381 // standalone
382 if (corefile_identifier.find("Darwin Kernel") != std::string::npos &&
383 ident_uuid.IsValid() && ident_binary_addr != LLDB_INVALID_ADDRESS) {
384 if (log)
385 log->Printf(
386 "ProcessMachCore::LoadBinariesViaMetadata: Found kernel binary via "
387 "LC_IDENT/kern ver str LC_NOTE");
388 m_mach_kernel_addr = ident_binary_addr;
389 found_binary_spec_in_metadata = true;
390 } else if (ident_uuid.IsValid()) {
391 // We have no address specified, only a UUID. Load it at the file
392 // address.
394 bin_spec.uuid = ident_uuid;
395 bin_spec.value = ident_binary_addr;
396 bin_spec.force_symbol_search = true;
397 bin_spec.notify = true;
398 bin_spec.set_address_in_target = true;
399 bin_spec.is_main_executable = true;
400 llvm::Expected<ModuleSP> module =
402 if (module) {
403 found_binary_spec_in_metadata = true;
405 } else {
407 << llvm::toString(module.takeError()) << "\n";
408 }
409 }
410
411 // Finally, load any binaries noted by "load binary" LC_NOTEs in the
412 // corefile
413 if (core_objfile->LoadCoreFileImages(*this)) {
414 found_binary_spec_in_metadata = true;
416 }
417
418 if (!found_binary_spec_in_metadata && LoadBinaryViaLowmemUUID())
419 found_binary_spec_in_metadata = true;
420
421 // LoadCoreFileImges may have set the dynamic loader, e.g. in
422 // PlatformDarwinKernel::LoadPlatformBinaryAndSetup().
423 // If we now have a dynamic loader, save its name so we don't
424 // un-set it later.
425 if (m_dyld_up)
427
428 return found_binary_spec_in_metadata;
429}
430
433
434 // Search the pages of the corefile for dyld or mach kernel
435 // binaries. There may be multiple things that look like a kernel
436 // in the corefile; disambiguating to the correct one can be difficult.
437
438 std::vector<addr_t> dylds_found;
439 std::vector<addr_t> kernels_found;
440
441 // To do an exhaustive search, we'll need to create data extractors
442 // to get correctly sized/endianness fields. If we had a main binary
443 // already, we would have set the Target to that - so here we'll use
444 // the corefile's cputype/cpusubtype as the best guess.
445 if (!GetTarget().GetArchitecture().IsValid()) {
446 // The corefile's architecture is our best starting point.
447 ArchSpec arch(m_core_module_sp->GetArchitecture());
448 if (arch.IsValid()) {
449 LLDB_LOGF(log,
450 "ProcessMachCore::%s: Setting target ArchSpec based on "
451 "corefile mach-o cputype/cpusubtype",
452 __FUNCTION__);
454 }
455 }
456
457 const size_t num_core_aranges = m_core_aranges.GetSize();
458 for (size_t i = 0; i < num_core_aranges; ++i) {
459 const VMRangeToFileOffset::Entry *entry = m_core_aranges.GetEntryAtIndex(i);
460 lldb::addr_t section_vm_addr_start = entry->GetRangeBase();
461 lldb::addr_t section_vm_addr_end = entry->GetRangeEnd();
462 for (lldb::addr_t section_vm_addr = section_vm_addr_start;
463 section_vm_addr < section_vm_addr_end; section_vm_addr += 0x1000) {
464 addr_t dyld, kernel;
465 if (CheckAddressForDyldOrKernel(section_vm_addr, dyld, kernel)) {
466 if (dyld != LLDB_INVALID_ADDRESS)
467 dylds_found.push_back(dyld);
468 if (kernel != LLDB_INVALID_ADDRESS)
469 kernels_found.push_back(kernel);
470 }
471 }
472 }
473
474 // If we found more than one dyld mach-o header in the corefile,
475 // pick the first one.
476 if (dylds_found.size() > 0)
477 m_dyld_addr = dylds_found[0];
478 if (kernels_found.size() > 0)
479 m_mach_kernel_addr = kernels_found[0];
480
481 // Zero or one kernels found, we're done.
482 if (kernels_found.size() < 2)
483 return;
484
485 // In the case of multiple kernel images found in the core file via
486 // exhaustive search, we may not pick the correct one. See if the
487 // DynamicLoaderDarwinKernel's search heuristics might identify the correct
488 // one.
489
490 // SearchForDarwinKernel will call this class' GetImageInfoAddress method
491 // which will give it the addresses we already have.
492 // Save those aside and set
493 // m_mach_kernel_addr/m_dyld_addr to an invalid address temporarily so
494 // DynamicLoaderDarwinKernel does a real search for the kernel using its
495 // own heuristics.
496
497 addr_t saved_mach_kernel_addr = m_mach_kernel_addr;
498 addr_t saved_user_dyld_addr = m_dyld_addr;
502
503 addr_t better_kernel_address =
505
506 m_mach_kernel_addr = saved_mach_kernel_addr;
507 m_dyld_addr = saved_user_dyld_addr;
508
509 if (better_kernel_address != LLDB_INVALID_ADDRESS) {
510 LLDB_LOGF(log,
511 "ProcessMachCore::%s: Using "
512 "the kernel address "
513 "from DynamicLoaderDarwinKernel",
514 __FUNCTION__);
515 m_mach_kernel_addr = better_kernel_address;
516 }
517}
518
521
522 bool found_binary_spec_in_metadata = LoadBinariesViaMetadata();
523 if (!found_binary_spec_in_metadata)
525
526 if (m_dyld_plugin_name.empty()) {
527 // If we found both a user-process dyld and a kernel binary, we need to
528 // decide which to prefer.
531 LLDB_LOGF(log,
532 "ProcessMachCore::%s: Using kernel "
533 "corefile image "
534 "at 0x%" PRIx64,
535 __FUNCTION__, m_mach_kernel_addr);
537 } else if (m_dyld_addr != LLDB_INVALID_ADDRESS) {
538 LLDB_LOGF(log,
539 "ProcessMachCore::%s: Using user process dyld "
540 "image at 0x%" PRIx64,
541 __FUNCTION__, m_dyld_addr);
544 LLDB_LOGF(log,
545 "ProcessMachCore::%s: Using user process dyld "
546 "dyld_all_image_infos at 0x%" PRIx64,
547 __FUNCTION__, m_dyld_all_image_infos_addr);
549 }
550 } else {
552 LLDB_LOGF(log,
553 "ProcessMachCore::%s: Using user process dyld "
554 "image at 0x%" PRIx64,
555 __FUNCTION__, m_dyld_addr);
558 LLDB_LOGF(log,
559 "ProcessMachCore::%s: Using user process dyld "
560 "dyld_all_image_infos at 0x%" PRIx64,
561 __FUNCTION__, m_dyld_all_image_infos_addr);
563 LLDB_LOGF(log,
564 "ProcessMachCore::%s: Using kernel "
565 "corefile image "
566 "at 0x%" PRIx64,
567 __FUNCTION__, m_mach_kernel_addr);
569 }
570 }
571 }
572}
573
576 // For non-user process core files, the permissions on the core file
577 // segments are usually meaningless, they may be just "read", because we're
578 // dealing with kernel coredumps or early startup coredumps and the dumper
579 // is grabbing pages of memory without knowing what they are. If they
580 // aren't marked as "executable", that can break the unwinder which will
581 // check a pc value to see if it is in an executable segment and stop the
582 // backtrace early if it is not ("executable" and "unknown" would both be
583 // fine, but "not executable" will break the unwinder).
584 size_t core_range_infos_size = m_core_range_infos.GetSize();
585 for (size_t i = 0; i < core_range_infos_size; i++) {
587 m_core_range_infos.GetMutableEntryAtIndex(i);
588 ent->data = lldb::ePermissionsReadable | lldb::ePermissionsExecutable;
589 }
590 }
591}
592
593// Process Control
596 if (!m_core_module_sp) {
597 error = Status::FromErrorString("invalid core module");
598 return error;
599 }
601
602 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
603 if (core_objfile == nullptr) {
604 error = Status::FromErrorString("invalid core object file");
605 return error;
606 }
607
608 SetCanJIT(false);
609
610 // If we have an executable binary in the Target already,
611 // use that to set the Target's ArchSpec.
612 //
613 // Don't initialize the ArchSpec based on the corefile's cputype/cpusubtype
614 // here, the corefile creator may not know the correct subtype of the code
615 // that is executing, initialize the Target to that, and if the
616 // main binary has Python code which initializes based on the Target arch,
617 // get the wrong subtype value.
618 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
619 if (exe_module_sp && exe_module_sp->GetArchitecture().IsValid()) {
620 LLDB_LOGF(log,
621 "ProcessMachCore::%s: Was given binary + corefile, setting "
622 "target ArchSpec to binary to start",
623 __FUNCTION__);
624 GetTarget().SetArchitecture(exe_module_sp->GetArchitecture());
625 }
626
628
630
632
633 exe_module_sp = GetTarget().GetExecutableModule();
634 if (exe_module_sp && exe_module_sp->GetArchitecture().IsValid()) {
635 LLDB_LOGF(log,
636 "ProcessMachCore::%s: have executable binary in the Target "
637 "after metadata/scan. Setting Target's ArchSpec based on "
638 "that.",
639 __FUNCTION__);
640 GetTarget().SetArchitecture(exe_module_sp->GetArchitecture());
641 } else {
642 // The corefile's architecture is our best starting point.
643 ArchSpec arch(m_core_module_sp->GetArchitecture());
644 if (arch.IsValid()) {
645 LLDB_LOGF(log,
646 "ProcessMachCore::%s: Setting target ArchSpec based on "
647 "corefile mach-o cputype/cpusubtype",
648 __FUNCTION__);
650 }
651 }
652
653 AddressableBits addressable_bits = core_objfile->GetAddressableBits();
654 SetAddressableBitMasks(addressable_bits);
655
656 return error;
657}
658
664
666 ThreadList &new_thread_list) {
667 if (old_thread_list.GetSize(false) == 0) {
668 // Make up the thread the first time this is called so we can setup our one
669 // and only core thread state.
670 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
671
672 if (core_objfile) {
673 const uint32_t num_threads = core_objfile->GetNumThreadContexts();
674 std::vector<lldb::tid_t> tids;
675 if (core_objfile->GetCorefileThreadExtraInfos(tids)) {
676 assert(tids.size() == num_threads);
677
678 // Find highest tid value.
679 lldb::tid_t highest_tid = 0;
680 for (uint32_t i = 0; i < num_threads; i++) {
681 if (tids[i] != LLDB_INVALID_THREAD_ID && tids[i] > highest_tid)
682 highest_tid = tids[i];
683 }
684 lldb::tid_t current_unused_tid = highest_tid + 1;
685 for (uint32_t i = 0; i < num_threads; i++) {
686 if (tids[i] == LLDB_INVALID_THREAD_ID) {
687 tids[i] = current_unused_tid++;
688 }
689 }
690 } else {
691 // No metadata, insert numbers sequentially from 0.
692 for (uint32_t i = 0; i < num_threads; i++) {
693 tids.push_back(i);
694 }
695 }
696
697 for (uint32_t i = 0; i < num_threads; i++) {
698 ThreadSP thread_sp =
699 std::make_shared<ThreadMachCore>(*this, tids[i], i);
700 new_thread_list.AddThread(thread_sp);
701 }
702 }
703 } else {
704 const uint32_t num_threads = old_thread_list.GetSize(false);
705 for (uint32_t i = 0; i < num_threads; ++i)
706 new_thread_list.AddThread(old_thread_list.GetThreadAtIndex(i, false));
707 }
708 return new_thread_list.GetSize(false) > 0;
709}
710
712 // Let all threads recover from stopping and do any clean up based on the
713 // previous thread state (if any).
714 m_thread_list.RefreshStateAfterStop();
715 // SetThreadStopInfo (m_last_stop_packet);
716}
717
719
720// Process Queries
721
722bool ProcessMachCore::IsAlive() { return true; }
723
724bool ProcessMachCore::WarnBeforeDetach() const { return false; }
725
726// Process Memory
728 void *buf, size_t size, Status &error) {
729 lldb::addr_t addr = process_addr.GetValue();
730 // Don't allow the caching that lldb_private::Process::ReadMemory does since
731 // in core files we have it all cached our our core file anyway.
732 return DoReadMemory(FixAnyAddress(addr), buf, size, error);
733}
734
736 void *buf, size_t size, Status &error) {
737 lldb::addr_t addr = process_addr.GetValue();
738 ObjectFile *core_objfile = m_core_module_sp->GetObjectFile();
739 size_t bytes_read = 0;
740
741 if (core_objfile) {
742 // Segments are not always contiguous in mach-o core files. We have core
743 // files that have segments like:
744 // Address Size File off File size
745 // ---------- ---------- ---------- ----------
746 // LC_SEGMENT 0x000f6000 0x00001000 0x1d509ee8 0x00001000 --- --- 0
747 // 0x00000000 __TEXT LC_SEGMENT 0x0f600000 0x00100000 0x1d50aee8 0x00100000
748 // --- --- 0 0x00000000 __TEXT LC_SEGMENT 0x000f7000 0x00001000
749 // 0x1d60aee8 0x00001000 --- --- 0 0x00000000 __TEXT
750 //
751 // Any if the user executes the following command:
752 //
753 // (lldb) mem read 0xf6ff0
754 //
755 // We would attempt to read 32 bytes from 0xf6ff0 but would only get 16
756 // unless we loop through consecutive memory ranges that are contiguous in
757 // the address space, but not in the file data.
758 while (bytes_read < size) {
759 const addr_t curr_addr = addr + bytes_read;
760 const VMRangeToFileOffset::Entry *core_memory_entry =
761 m_core_aranges.FindEntryThatContains(curr_addr);
762
763 if (core_memory_entry) {
764 const addr_t offset = curr_addr - core_memory_entry->GetRangeBase();
765 const addr_t bytes_left = core_memory_entry->GetRangeEnd() - curr_addr;
766 const size_t bytes_to_read =
767 std::min(size - bytes_read, (size_t)bytes_left);
768 const size_t curr_bytes_read = core_objfile->CopyData(
769 core_memory_entry->data.GetRangeBase() + offset, bytes_to_read,
770 (char *)buf + bytes_read);
771 if (curr_bytes_read == 0)
772 break;
773 bytes_read += curr_bytes_read;
774 } else {
775 // Only set the error if we didn't read any bytes
776 if (bytes_read == 0)
778 "core file does not contain 0x%" PRIx64, curr_addr);
779 break;
780 }
781 }
782 }
783
784 return bytes_read;
785}
786
788 MemoryRegionInfo &region_info) {
789 region_info.Clear();
790 const VMRangeToPermissions::Entry *permission_entry =
791 m_core_range_infos.FindEntryThatContainsOrFollows(load_addr);
792 if (permission_entry) {
793 if (permission_entry->Contains(load_addr)) {
794 region_info.GetRange().SetRangeBase(permission_entry->GetRangeBase());
795 region_info.GetRange().SetRangeEnd(permission_entry->GetRangeEnd());
796 const Flags permissions(permission_entry->data);
797 region_info.SetReadable(
798 permissions.Test(ePermissionsReadable) ? eLazyBoolYes : eLazyBoolNo);
799 region_info.SetWritable(
800 permissions.Test(ePermissionsWritable) ? eLazyBoolYes : eLazyBoolNo);
801 region_info.SetExecutable(permissions.Test(ePermissionsExecutable)
803 : eLazyBoolNo);
804 region_info.SetMapped(eLazyBoolYes);
805 } else if (load_addr < permission_entry->GetRangeBase()) {
806 region_info.GetRange().SetRangeBase(load_addr);
807 region_info.GetRange().SetRangeEnd(permission_entry->GetRangeBase());
808 region_info.SetReadable(eLazyBoolNo);
809 region_info.SetWritable(eLazyBoolNo);
810 region_info.SetExecutable(eLazyBoolNo);
811 region_info.SetMapped(eLazyBoolNo);
812 }
813 return Status();
814 } else {
815 // The corefile has no LC_SEGMENT at this virtual address,
816 // but see if there is a binary whose Section has been
817 // loaded at that address in the current Target.
818 Address addr;
819 if (GetTarget().ResolveLoadAddress(load_addr, addr)) {
820 SectionSP section_sp(addr.GetSection());
821 if (section_sp) {
822 region_info.GetRange().SetRangeBase(
823 section_sp->GetLoadBaseAddress(&GetTarget()));
824 region_info.GetRange().SetByteSize(section_sp->GetByteSize());
825 if (region_info.GetRange().Contains(load_addr)) {
826 region_info.SetLLDBPermissions(section_sp->GetPermissions());
827 return Status();
828 }
829 }
830 }
831 }
832
833 region_info.GetRange().SetRangeBase(load_addr);
835 region_info.SetReadable(eLazyBoolNo);
836 region_info.SetWritable(eLazyBoolNo);
837 region_info.SetExecutable(eLazyBoolNo);
838 region_info.SetMapped(eLazyBoolNo);
839 return Status();
840}
841
843
848
850 // The DynamicLoader plugin will call back in to this Process
851 // method to find the virtual address of one of these:
852 // 1. The xnu mach kernel binary Mach-O header
853 // 2. The dyld binary Mach-O header
854 // 3. dyld's dyld_all_image_infos object
855 //
856 // DynamicLoaderMacOSX will accept either the dyld Mach-O header
857 // address or the dyld_all_image_infos interchangably, no need
858 // to distinguish between them. It disambiguates by the Mach-O
859 // file magic number at the start.
862 return m_mach_kernel_addr;
864 return m_dyld_addr;
865 } else {
867 return m_dyld_addr;
869 return m_mach_kernel_addr;
870 }
871
872 // m_dyld_addr and m_mach_kernel_addr both
873 // invalid, return m_dyld_all_image_infos_addr
874 // in case it has a useful value.
876}
877
unsigned char uuid_t[16]
static llvm::raw_ostream & error(Stream &strm)
static llvm::Expected< lldb::addr_t > ResolveLoadAddress(EvalContext &eval_ctx, 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:389
#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 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.
VMRangeToFileOffset m_core_aranges
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.
size_t ReadMemory(const lldb_private::ProcessAddress &addr, void *buf, size_t size, lldb_private::Status &error) override
Read of memory from a process.
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:426
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:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:453
lldb::StreamUP GetAsyncErrorStream()
A plug-in interface definition class for dynamic loaders.
static llvm::Expected< lldb::ModuleSP > LocateAndLoadBinary(Process *process, BinarySpec &bin_spec)
Find a binary and load it into a Target.
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
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
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:177
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, bool invoke_symbol_locators=true)
void SetTarget(lldb::TargetSP target)
Set the target to be used when resolving a module.
Definition ModuleSpec.h:150
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:550
virtual std::string GetIdentifierString()
Some object files may have an identifier string embedded in them, e.g.
Definition ObjectFile.h:481
virtual uint32_t GetNumThreadContexts()
Definition ObjectFile.h:472
virtual bool LoadCoreFileImages(lldb_private::Process &process)
Load binaries listed in a corefile.
Definition ObjectFile.h:739
@ 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:493
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:521
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)
An address in a process, qualified by an address space.
lldb::addr_t GetValue() const
void SetAddressableBitMasks(AddressableBits bit_masks)
Definition Process.cpp:7129
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2769
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3511
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:6283
bool IsValid() const
Return whether this object is valid (i.e.
Definition Process.h:587
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
Definition Process.cpp:596
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3481
friend class ThreadList
Definition Process.h:375
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:544
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:555
uint32_t GetPermissions() const
Get the permissions as OR'ed bits from lldb::Permissions.
Definition Section.cpp:357
lldb::offset_t GetFileOffset() const
Definition Section.h:180
lldb::addr_t GetFileAddress() const
Definition Section.cpp:194
lldb::addr_t GetByteSize() const
Definition Section.h:196
lldb::offset_t GetFileSize() const
Definition Section.h:186
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
Debugger & GetDebugger() const
Definition Target.h:1356
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1807
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1630
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:338
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
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:85
std::shared_ptr< lldb_private::Module > ModuleSP
A binary to find and load into a Target.
lldb::addr_t value
Address where the binary should be loaded, or read out of memory.
UUID uuid
UUID of the binary to be loaded.
bool is_main_executable
Whether this is the process' main executable.
bool force_symbol_search
Allow the search to do a possibly expensive external search for the ObjectFile and/or SymbolFile.
bool set_address_in_target
Whether the address of the binary should be set in the Target if it is added.
bool notify
Whether ModulesDidLoad should be called once the binary has been added to the Target.
bool value_is_offset
A flag indicating that value is an address, or an offset to be applied to the file addresses.
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