LLDB mainline
ObjectFileMachO.cpp
Go to the documentation of this file.
1//===-- ObjectFileMachO.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 "llvm/ADT/ScopeExit.h"
10#include "llvm/ADT/StringRef.h"
11
12#include <algorithm>
13
18#include "lldb/Core/Debugger.h"
19#include "lldb/Core/Module.h"
22#include "lldb/Core/Progress.h"
23#include "lldb/Core/Section.h"
24#include "lldb/Host/Host.h"
25#include "lldb/Host/HostInfo.h"
31#include "lldb/Target/Process.h"
33#include "lldb/Target/Target.h"
34#include "lldb/Target/Thread.h"
41#include "lldb/Utility/Log.h"
44#include "lldb/Utility/Status.h"
46#include "lldb/Utility/Timer.h"
47#include "lldb/Utility/UUID.h"
48
49#include "lldb/Host/SafeMachO.h"
50
51#include "llvm/ADT/DenseSet.h"
52#include "llvm/Support/Compression.h"
53#include "llvm/Support/Endian.h"
54#include "llvm/Support/FormatVariadic.h"
55#include "llvm/Support/MemoryBuffer.h"
56
57#include "MachOTrie.h"
58#include "ObjectFileMachO.h"
59
60#if defined(__APPLE__)
61#include <TargetConditionals.h>
62// GetLLDBSharedCacheUUID() needs to call dlsym()
63#include <dlfcn.h>
64#include <mach/mach_init.h>
65#include <mach/vm_map.h>
66#include <lldb/Host/SafeMachO.h>
67#endif
68
69#ifndef __APPLE__
71#else
72#include <uuid/uuid.h>
73#endif
74
75#include <bitset>
76#include <memory>
77#include <optional>
78
79// Unfortunately the signpost header pulls in the system MachO header, too.
80#ifdef CPU_TYPE_ARM
81#undef CPU_TYPE_ARM
82#endif
83#ifdef CPU_TYPE_ARM64
84#undef CPU_TYPE_ARM64
85#endif
86#ifdef CPU_TYPE_ARM64_32
87#undef CPU_TYPE_ARM64_32
88#endif
89#ifdef CPU_TYPE_X86_64
90#undef CPU_TYPE_X86_64
91#endif
92#ifdef MH_DYLINKER
93#undef MH_DYLINKER
94#endif
95#ifdef MH_OBJECT
96#undef MH_OBJECT
97#endif
98#ifdef LC_VERSION_MIN_MACOSX
99#undef LC_VERSION_MIN_MACOSX
100#endif
101#ifdef LC_VERSION_MIN_IPHONEOS
102#undef LC_VERSION_MIN_IPHONEOS
103#endif
104#ifdef LC_VERSION_MIN_TVOS
105#undef LC_VERSION_MIN_TVOS
106#endif
107#ifdef LC_VERSION_MIN_WATCHOS
108#undef LC_VERSION_MIN_WATCHOS
109#endif
110#ifdef LC_BUILD_VERSION
111#undef LC_BUILD_VERSION
112#endif
113#ifdef PLATFORM_MACOS
114#undef PLATFORM_MACOS
115#endif
116#ifdef PLATFORM_MACCATALYST
117#undef PLATFORM_MACCATALYST
118#endif
119#ifdef PLATFORM_IOS
120#undef PLATFORM_IOS
121#endif
122#ifdef PLATFORM_IOSSIMULATOR
123#undef PLATFORM_IOSSIMULATOR
124#endif
125#ifdef PLATFORM_TVOS
126#undef PLATFORM_TVOS
127#endif
128#ifdef PLATFORM_TVOSSIMULATOR
129#undef PLATFORM_TVOSSIMULATOR
130#endif
131#ifdef PLATFORM_WATCHOS
132#undef PLATFORM_WATCHOS
133#endif
134#ifdef PLATFORM_WATCHOSSIMULATOR
135#undef PLATFORM_WATCHOSSIMULATOR
136#endif
137
138using namespace lldb;
139using namespace lldb_private;
140using namespace llvm::MachO;
141
142static constexpr llvm::StringLiteral g_loader_path = "@loader_path";
143static constexpr llvm::StringLiteral g_executable_path = "@executable_path";
144
146
147/// Read a Mach-O load-command header (cmd + cmdsize) from \p data at
148/// \p offset into \p cmd, advancing \p offset by 8 bytes. \p T may be
149/// \c llvm::MachO::load_command or any of its richer variants
150/// (\c thread_command, \c dylib_command, \c encryption_info_command, ...);
151/// only the leading cmd/cmdsize fields are touched by this read. Returns
152/// false on EOF or on a cmdsize smaller than sizeof(load_command), in which
153/// case callers should break out of their load-command loop to avoid spinning
154/// on malformed input.
155template <typename T>
156static bool ReadMachOCommand(const DataExtractor &data, lldb::offset_t &offset,
157 T &cmd) {
158 static_assert(offsetof(T, cmd) == 0, "T::cmd must be the first field");
159 static_assert(offsetof(T, cmdsize) == sizeof(uint32_t),
160 "T::cmdsize must immediately follow T::cmd");
161 static_assert(std::is_same<decltype(T::cmd), uint32_t>::value,
162 "T::cmd must be uint32_t");
163 static_assert(std::is_same<decltype(T::cmdsize), uint32_t>::value,
164 "T::cmdsize must be uint32_t");
165 if (data.GetU32(&offset, &cmd, 2) == nullptr)
166 return false;
167 if (cmd.cmdsize < sizeof(load_command))
168 return false;
169 return true;
170}
171
172static void PrintRegisterValue(RegisterContext *reg_ctx, const char *name,
173 const char *alt_name, size_t reg_byte_size,
174 Stream &data) {
175 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(name);
176 if (reg_info == nullptr)
177 reg_info = reg_ctx->GetRegisterInfoByName(alt_name);
178 if (reg_info) {
180 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
181 if (reg_info->byte_size >= reg_byte_size)
182 data.Write(reg_value.GetBytes(), reg_byte_size);
183 else {
184 data.Write(reg_value.GetBytes(), reg_info->byte_size);
185 for (size_t i = 0, n = reg_byte_size - reg_info->byte_size; i < n; ++i)
186 data.PutChar(0);
187 }
188 return;
189 }
190 }
191 // Just write zeros if all else fails
192 for (size_t i = 0; i < reg_byte_size; ++i)
193 data.PutChar(0);
194}
195
197public:
203
204 void InvalidateAllRegisters() override {
205 // Do nothing... registers are always valid...
206 }
207
209 lldb::offset_t offset = 0;
210 SetError(GPRRegSet, Read, -1);
211 SetError(FPURegSet, Read, -1);
212 SetError(EXCRegSet, Read, -1);
213
214 while (offset < data.GetByteSize()) {
215 int flavor = data.GetU32(&offset);
216 if (flavor == 0)
217 break;
218 uint32_t count = data.GetU32(&offset);
219 switch (flavor) {
220 case GPRRegSet: {
221 uint32_t *gpr_data = reinterpret_cast<uint32_t *>(&gpr.rax);
222 for (uint32_t i = 0; i < count && offset < data.GetByteSize(); ++i)
223 gpr_data[i] = data.GetU32(&offset);
225 } break;
226 case FPURegSet:
227 // TODO: fill in FPU regs....
228 SetError(FPURegSet, Read, -1);
229 break;
230 case EXCRegSet:
231 exc.trapno = data.GetU32(&offset);
232 exc.err = data.GetU32(&offset);
233 exc.faultvaddr = data.GetU64(&offset);
235 break;
236 default:
237 offset += count * 4;
238 break;
239 }
240 }
241 }
242
243 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
244 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
245 if (reg_ctx_sp) {
246 RegisterContext *reg_ctx = reg_ctx_sp.get();
247
248 data.PutHex32(GPRRegSet); // Flavor
250 PrintRegisterValue(reg_ctx, "rax", nullptr, 8, data);
251 PrintRegisterValue(reg_ctx, "rbx", nullptr, 8, data);
252 PrintRegisterValue(reg_ctx, "rcx", nullptr, 8, data);
253 PrintRegisterValue(reg_ctx, "rdx", nullptr, 8, data);
254 PrintRegisterValue(reg_ctx, "rdi", nullptr, 8, data);
255 PrintRegisterValue(reg_ctx, "rsi", nullptr, 8, data);
256 PrintRegisterValue(reg_ctx, "rbp", nullptr, 8, data);
257 PrintRegisterValue(reg_ctx, "rsp", nullptr, 8, data);
258 PrintRegisterValue(reg_ctx, "r8", nullptr, 8, data);
259 PrintRegisterValue(reg_ctx, "r9", nullptr, 8, data);
260 PrintRegisterValue(reg_ctx, "r10", nullptr, 8, data);
261 PrintRegisterValue(reg_ctx, "r11", nullptr, 8, data);
262 PrintRegisterValue(reg_ctx, "r12", nullptr, 8, data);
263 PrintRegisterValue(reg_ctx, "r13", nullptr, 8, data);
264 PrintRegisterValue(reg_ctx, "r14", nullptr, 8, data);
265 PrintRegisterValue(reg_ctx, "r15", nullptr, 8, data);
266 PrintRegisterValue(reg_ctx, "rip", nullptr, 8, data);
267 PrintRegisterValue(reg_ctx, "rflags", nullptr, 8, data);
268 PrintRegisterValue(reg_ctx, "cs", nullptr, 8, data);
269 PrintRegisterValue(reg_ctx, "fs", nullptr, 8, data);
270 PrintRegisterValue(reg_ctx, "gs", nullptr, 8, data);
271
272 // // Write out the FPU registers
273 // const size_t fpu_byte_size = sizeof(FPU);
274 // size_t bytes_written = 0;
275 // data.PutHex32 (FPURegSet);
276 // data.PutHex32 (fpu_byte_size/sizeof(uint64_t));
277 // bytes_written += data.PutHex32(0); // uint32_t pad[0]
278 // bytes_written += data.PutHex32(0); // uint32_t pad[1]
279 // bytes_written += WriteRegister (reg_ctx, "fcw", "fctrl", 2,
280 // data); // uint16_t fcw; // "fctrl"
281 // bytes_written += WriteRegister (reg_ctx, "fsw" , "fstat", 2,
282 // data); // uint16_t fsw; // "fstat"
283 // bytes_written += WriteRegister (reg_ctx, "ftw" , "ftag", 1,
284 // data); // uint8_t ftw; // "ftag"
285 // bytes_written += data.PutHex8 (0); // uint8_t pad1;
286 // bytes_written += WriteRegister (reg_ctx, "fop" , NULL, 2,
287 // data); // uint16_t fop; // "fop"
288 // bytes_written += WriteRegister (reg_ctx, "fioff", "ip", 4,
289 // data); // uint32_t ip; // "fioff"
290 // bytes_written += WriteRegister (reg_ctx, "fiseg", NULL, 2,
291 // data); // uint16_t cs; // "fiseg"
292 // bytes_written += data.PutHex16 (0); // uint16_t pad2;
293 // bytes_written += WriteRegister (reg_ctx, "dp", "fooff" , 4,
294 // data); // uint32_t dp; // "fooff"
295 // bytes_written += WriteRegister (reg_ctx, "foseg", NULL, 2,
296 // data); // uint16_t ds; // "foseg"
297 // bytes_written += data.PutHex16 (0); // uint16_t pad3;
298 // bytes_written += WriteRegister (reg_ctx, "mxcsr", NULL, 4,
299 // data); // uint32_t mxcsr;
300 // bytes_written += WriteRegister (reg_ctx, "mxcsrmask", NULL,
301 // 4, data);// uint32_t mxcsrmask;
302 // bytes_written += WriteRegister (reg_ctx, "stmm0", NULL,
303 // sizeof(MMSReg), data);
304 // bytes_written += WriteRegister (reg_ctx, "stmm1", NULL,
305 // sizeof(MMSReg), data);
306 // bytes_written += WriteRegister (reg_ctx, "stmm2", NULL,
307 // sizeof(MMSReg), data);
308 // bytes_written += WriteRegister (reg_ctx, "stmm3", NULL,
309 // sizeof(MMSReg), data);
310 // bytes_written += WriteRegister (reg_ctx, "stmm4", NULL,
311 // sizeof(MMSReg), data);
312 // bytes_written += WriteRegister (reg_ctx, "stmm5", NULL,
313 // sizeof(MMSReg), data);
314 // bytes_written += WriteRegister (reg_ctx, "stmm6", NULL,
315 // sizeof(MMSReg), data);
316 // bytes_written += WriteRegister (reg_ctx, "stmm7", NULL,
317 // sizeof(MMSReg), data);
318 // bytes_written += WriteRegister (reg_ctx, "xmm0" , NULL,
319 // sizeof(XMMReg), data);
320 // bytes_written += WriteRegister (reg_ctx, "xmm1" , NULL,
321 // sizeof(XMMReg), data);
322 // bytes_written += WriteRegister (reg_ctx, "xmm2" , NULL,
323 // sizeof(XMMReg), data);
324 // bytes_written += WriteRegister (reg_ctx, "xmm3" , NULL,
325 // sizeof(XMMReg), data);
326 // bytes_written += WriteRegister (reg_ctx, "xmm4" , NULL,
327 // sizeof(XMMReg), data);
328 // bytes_written += WriteRegister (reg_ctx, "xmm5" , NULL,
329 // sizeof(XMMReg), data);
330 // bytes_written += WriteRegister (reg_ctx, "xmm6" , NULL,
331 // sizeof(XMMReg), data);
332 // bytes_written += WriteRegister (reg_ctx, "xmm7" , NULL,
333 // sizeof(XMMReg), data);
334 // bytes_written += WriteRegister (reg_ctx, "xmm8" , NULL,
335 // sizeof(XMMReg), data);
336 // bytes_written += WriteRegister (reg_ctx, "xmm9" , NULL,
337 // sizeof(XMMReg), data);
338 // bytes_written += WriteRegister (reg_ctx, "xmm10", NULL,
339 // sizeof(XMMReg), data);
340 // bytes_written += WriteRegister (reg_ctx, "xmm11", NULL,
341 // sizeof(XMMReg), data);
342 // bytes_written += WriteRegister (reg_ctx, "xmm12", NULL,
343 // sizeof(XMMReg), data);
344 // bytes_written += WriteRegister (reg_ctx, "xmm13", NULL,
345 // sizeof(XMMReg), data);
346 // bytes_written += WriteRegister (reg_ctx, "xmm14", NULL,
347 // sizeof(XMMReg), data);
348 // bytes_written += WriteRegister (reg_ctx, "xmm15", NULL,
349 // sizeof(XMMReg), data);
350 //
351 // // Fill rest with zeros
352 // for (size_t i=0, n = fpu_byte_size - bytes_written; i<n; ++
353 // i)
354 // data.PutChar(0);
355
356 // Write out the EXC registers
357 data.PutHex32(EXCRegSet);
359 PrintRegisterValue(reg_ctx, "trapno", nullptr, 4, data);
360 PrintRegisterValue(reg_ctx, "err", nullptr, 4, data);
361 PrintRegisterValue(reg_ctx, "faultvaddr", nullptr, 8, data);
362 return true;
363 }
364 return false;
365 }
366
367protected:
368 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
369
370 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
371
372 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
373
374 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
375 return 0;
376 }
377
378 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
379 return 0;
380 }
381
382 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
383 return 0;
384 }
385};
386
388public:
394
395 void InvalidateAllRegisters() override {
396 // Do nothing... registers are always valid...
397 }
398
400 lldb::offset_t offset = 0;
401 SetError(GPRRegSet, Read, -1);
402 SetError(FPURegSet, Read, -1);
403 SetError(EXCRegSet, Read, -1);
404
405 while (offset < data.GetByteSize()) {
406 int flavor = data.GetU32(&offset);
407 uint32_t count = data.GetU32(&offset);
408 offset_t next_thread_state = offset + (count * 4);
409 switch (flavor) {
410 case GPRAltRegSet:
411 case GPRRegSet: {
412 // r0-r15, plus CPSR
413 uint32_t gpr_buf_count = (sizeof(gpr.r) / sizeof(gpr.r[0])) + 1;
414 if (count == gpr_buf_count) {
415 for (uint32_t i = 0; i < (count - 1); ++i) {
416 gpr.r[i] = data.GetU32(&offset);
417 }
418 gpr.cpsr = data.GetU32(&offset);
419
421 }
422 } break;
423
424 case FPURegSet: {
425 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.floats;
426 const int fpu_reg_buf_size = sizeof(fpu.floats);
427 if (data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
428 fpu_reg_buf) == fpu_reg_buf_size) {
429 offset += fpu_reg_buf_size;
430 fpu.fpscr = data.GetU32(&offset);
432 }
433 } break;
434
435 case EXCRegSet:
436 if (count == 3) {
437 exc.exception = data.GetU32(&offset);
438 exc.fsr = data.GetU32(&offset);
439 exc.far = data.GetU32(&offset);
441 }
442 break;
443 }
444 offset = next_thread_state;
445 }
446 }
447
448 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
449 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
450 if (reg_ctx_sp) {
451 RegisterContext *reg_ctx = reg_ctx_sp.get();
452
453 data.PutHex32(GPRRegSet); // Flavor
455 PrintRegisterValue(reg_ctx, "r0", nullptr, 4, data);
456 PrintRegisterValue(reg_ctx, "r1", nullptr, 4, data);
457 PrintRegisterValue(reg_ctx, "r2", nullptr, 4, data);
458 PrintRegisterValue(reg_ctx, "r3", nullptr, 4, data);
459 PrintRegisterValue(reg_ctx, "r4", nullptr, 4, data);
460 PrintRegisterValue(reg_ctx, "r5", nullptr, 4, data);
461 PrintRegisterValue(reg_ctx, "r6", nullptr, 4, data);
462 PrintRegisterValue(reg_ctx, "r7", nullptr, 4, data);
463 PrintRegisterValue(reg_ctx, "r8", nullptr, 4, data);
464 PrintRegisterValue(reg_ctx, "r9", nullptr, 4, data);
465 PrintRegisterValue(reg_ctx, "r10", nullptr, 4, data);
466 PrintRegisterValue(reg_ctx, "r11", nullptr, 4, data);
467 PrintRegisterValue(reg_ctx, "r12", nullptr, 4, data);
468 PrintRegisterValue(reg_ctx, "sp", nullptr, 4, data);
469 PrintRegisterValue(reg_ctx, "lr", nullptr, 4, data);
470 PrintRegisterValue(reg_ctx, "pc", nullptr, 4, data);
471 PrintRegisterValue(reg_ctx, "cpsr", nullptr, 4, data);
472
473 // Write out the EXC registers
474 // data.PutHex32 (EXCRegSet);
475 // data.PutHex32 (EXCWordCount);
476 // WriteRegister (reg_ctx, "exception", NULL, 4, data);
477 // WriteRegister (reg_ctx, "fsr", NULL, 4, data);
478 // WriteRegister (reg_ctx, "far", NULL, 4, data);
479 return true;
480 }
481 return false;
482 }
483
484protected:
485 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
486
487 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
488
489 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
490
491 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
492
493 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
494 return 0;
495 }
496
497 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
498 return 0;
499 }
500
501 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
502 return 0;
503 }
504
505 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
506 return -1;
507 }
508};
509
511public:
517
518 void InvalidateAllRegisters() override {
519 // Do nothing... registers are always valid...
520 }
521
523 lldb::offset_t offset = 0;
524 SetError(GPRRegSet, Read, -1);
525 SetError(FPURegSet, Read, -1);
526 SetError(EXCRegSet, Read, -1);
527 while (offset < data.GetByteSize()) {
528 int flavor = data.GetU32(&offset);
529 uint32_t count = data.GetU32(&offset);
530 offset_t next_thread_state = offset + (count * 4);
531 switch (flavor) {
532 case GPRRegSet:
533 // x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1
534 // 32-bit register)
535 if (count >= (33 * 2) + 1) {
536 for (uint32_t i = 0; i < 29; ++i)
537 gpr.x[i] = data.GetU64(&offset);
538 gpr.fp = data.GetU64(&offset);
539 gpr.lr = data.GetU64(&offset);
540 gpr.sp = data.GetU64(&offset);
541 gpr.pc = data.GetU64(&offset);
542 gpr.cpsr = data.GetU32(&offset);
544 }
545 break;
546 case FPURegSet: {
547 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.v[0];
548 const int fpu_reg_buf_size = sizeof(fpu);
549 if (fpu_reg_buf_size == count * sizeof(uint32_t) &&
550 data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
551 fpu_reg_buf) == fpu_reg_buf_size) {
553 }
554 } break;
555 case EXCRegSet:
556 if (count == 4) {
557 exc.far = data.GetU64(&offset);
558 exc.esr = data.GetU32(&offset);
559 exc.exception = data.GetU32(&offset);
561 }
562 break;
563 }
564 offset = next_thread_state;
565 }
566 }
567
568 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
569 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
570 if (reg_ctx_sp) {
571 RegisterContext *reg_ctx = reg_ctx_sp.get();
572
573 data.PutHex32(GPRRegSet); // Flavor
575 PrintRegisterValue(reg_ctx, "x0", nullptr, 8, data);
576 PrintRegisterValue(reg_ctx, "x1", nullptr, 8, data);
577 PrintRegisterValue(reg_ctx, "x2", nullptr, 8, data);
578 PrintRegisterValue(reg_ctx, "x3", nullptr, 8, data);
579 PrintRegisterValue(reg_ctx, "x4", nullptr, 8, data);
580 PrintRegisterValue(reg_ctx, "x5", nullptr, 8, data);
581 PrintRegisterValue(reg_ctx, "x6", nullptr, 8, data);
582 PrintRegisterValue(reg_ctx, "x7", nullptr, 8, data);
583 PrintRegisterValue(reg_ctx, "x8", nullptr, 8, data);
584 PrintRegisterValue(reg_ctx, "x9", nullptr, 8, data);
585 PrintRegisterValue(reg_ctx, "x10", nullptr, 8, data);
586 PrintRegisterValue(reg_ctx, "x11", nullptr, 8, data);
587 PrintRegisterValue(reg_ctx, "x12", nullptr, 8, data);
588 PrintRegisterValue(reg_ctx, "x13", nullptr, 8, data);
589 PrintRegisterValue(reg_ctx, "x14", nullptr, 8, data);
590 PrintRegisterValue(reg_ctx, "x15", nullptr, 8, data);
591 PrintRegisterValue(reg_ctx, "x16", nullptr, 8, data);
592 PrintRegisterValue(reg_ctx, "x17", nullptr, 8, data);
593 PrintRegisterValue(reg_ctx, "x18", nullptr, 8, data);
594 PrintRegisterValue(reg_ctx, "x19", nullptr, 8, data);
595 PrintRegisterValue(reg_ctx, "x20", nullptr, 8, data);
596 PrintRegisterValue(reg_ctx, "x21", nullptr, 8, data);
597 PrintRegisterValue(reg_ctx, "x22", nullptr, 8, data);
598 PrintRegisterValue(reg_ctx, "x23", nullptr, 8, data);
599 PrintRegisterValue(reg_ctx, "x24", nullptr, 8, data);
600 PrintRegisterValue(reg_ctx, "x25", nullptr, 8, data);
601 PrintRegisterValue(reg_ctx, "x26", nullptr, 8, data);
602 PrintRegisterValue(reg_ctx, "x27", nullptr, 8, data);
603 PrintRegisterValue(reg_ctx, "x28", nullptr, 8, data);
604 PrintRegisterValue(reg_ctx, "fp", nullptr, 8, data);
605 PrintRegisterValue(reg_ctx, "lr", nullptr, 8, data);
606 PrintRegisterValue(reg_ctx, "sp", nullptr, 8, data);
607 PrintRegisterValue(reg_ctx, "pc", nullptr, 8, data);
608 PrintRegisterValue(reg_ctx, "cpsr", nullptr, 4, data);
609 data.PutHex32(0); // uint32_t pad at the end
610
611 // Write out the EXC registers
612 data.PutHex32(EXCRegSet);
614 PrintRegisterValue(reg_ctx, "far", nullptr, 8, data);
615 PrintRegisterValue(reg_ctx, "esr", nullptr, 4, data);
616 PrintRegisterValue(reg_ctx, "exception", nullptr, 4, data);
617 return true;
618 }
619 return false;
620 }
621
622protected:
623 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
624
625 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
626
627 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
628
629 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
630
631 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
632 return 0;
633 }
634
635 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
636 return 0;
637 }
638
639 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
640 return 0;
641 }
642
643 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
644 return -1;
645 }
646};
647
650public:
656
657 void InvalidateAllRegisters() override {
658 // Do nothing... registers are always valid...
659 }
660
662 lldb::offset_t offset = 0;
663 SetError(GPRRegSet, Read, -1);
664 SetError(FPURegSet, Read, -1);
665 SetError(EXCRegSet, Read, -1);
666 SetError(CSRRegSet, Read, -1);
667 while (offset < data.GetByteSize()) {
668 int flavor = data.GetU32(&offset);
669 uint32_t count = data.GetU32(&offset);
670 offset_t next_thread_state = offset + (count * 4);
671 switch (flavor) {
672 case GPRRegSet:
673 // x0-x31 + pc
674 if (count >= 32) {
675 for (uint32_t i = 0; i < 32; ++i)
676 ((uint32_t *)&gpr.x0)[i] = data.GetU32(&offset);
677 gpr.pc = data.GetU32(&offset);
679 }
680 break;
681 case FPURegSet: {
682 // f0-f31 + fcsr
683 if (count >= 32) {
684 for (uint32_t i = 0; i < 32; ++i)
685 ((uint32_t *)&fpr.f0)[i] = data.GetU32(&offset);
686 fpr.fcsr = data.GetU32(&offset);
688 }
689 } break;
690 case EXCRegSet:
691 if (count == 3) {
692 exc.exception = data.GetU32(&offset);
693 exc.fsr = data.GetU32(&offset);
694 exc.far = data.GetU32(&offset);
696 }
697 break;
698 }
699 offset = next_thread_state;
700 }
701 }
702
703 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
704 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
705 if (reg_ctx_sp) {
706 RegisterContext *reg_ctx = reg_ctx_sp.get();
707
708 data.PutHex32(GPRRegSet); // Flavor
710 PrintRegisterValue(reg_ctx, "x0", nullptr, 4, data);
711 PrintRegisterValue(reg_ctx, "x1", nullptr, 4, data);
712 PrintRegisterValue(reg_ctx, "x2", nullptr, 4, data);
713 PrintRegisterValue(reg_ctx, "x3", nullptr, 4, data);
714 PrintRegisterValue(reg_ctx, "x4", nullptr, 4, data);
715 PrintRegisterValue(reg_ctx, "x5", nullptr, 4, data);
716 PrintRegisterValue(reg_ctx, "x6", nullptr, 4, data);
717 PrintRegisterValue(reg_ctx, "x7", nullptr, 4, data);
718 PrintRegisterValue(reg_ctx, "x8", nullptr, 4, data);
719 PrintRegisterValue(reg_ctx, "x9", nullptr, 4, data);
720 PrintRegisterValue(reg_ctx, "x10", nullptr, 4, data);
721 PrintRegisterValue(reg_ctx, "x11", nullptr, 4, data);
722 PrintRegisterValue(reg_ctx, "x12", nullptr, 4, data);
723 PrintRegisterValue(reg_ctx, "x13", nullptr, 4, data);
724 PrintRegisterValue(reg_ctx, "x14", nullptr, 4, data);
725 PrintRegisterValue(reg_ctx, "x15", nullptr, 4, data);
726 PrintRegisterValue(reg_ctx, "x16", nullptr, 4, data);
727 PrintRegisterValue(reg_ctx, "x17", nullptr, 4, data);
728 PrintRegisterValue(reg_ctx, "x18", nullptr, 4, data);
729 PrintRegisterValue(reg_ctx, "x19", nullptr, 4, data);
730 PrintRegisterValue(reg_ctx, "x20", nullptr, 4, data);
731 PrintRegisterValue(reg_ctx, "x21", nullptr, 4, data);
732 PrintRegisterValue(reg_ctx, "x22", nullptr, 4, data);
733 PrintRegisterValue(reg_ctx, "x23", nullptr, 4, data);
734 PrintRegisterValue(reg_ctx, "x24", nullptr, 4, data);
735 PrintRegisterValue(reg_ctx, "x25", nullptr, 4, data);
736 PrintRegisterValue(reg_ctx, "x26", nullptr, 4, data);
737 PrintRegisterValue(reg_ctx, "x27", nullptr, 4, data);
738 PrintRegisterValue(reg_ctx, "x28", nullptr, 4, data);
739 PrintRegisterValue(reg_ctx, "x29", nullptr, 4, data);
740 PrintRegisterValue(reg_ctx, "x30", nullptr, 4, data);
741 PrintRegisterValue(reg_ctx, "x31", nullptr, 4, data);
742 PrintRegisterValue(reg_ctx, "pc", nullptr, 4, data);
743 data.PutHex32(0); // uint32_t pad at the end
744
745 // Write out the EXC registers
746 data.PutHex32(EXCRegSet);
748 PrintRegisterValue(reg_ctx, "exception", nullptr, 4, data);
749 PrintRegisterValue(reg_ctx, "fsr", nullptr, 4, data);
750 PrintRegisterValue(reg_ctx, "far", nullptr, 4, data);
751 return true;
752 }
753 return false;
754 }
755
756protected:
757 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
758
759 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
760
761 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
762
763 int DoReadCSR(lldb::tid_t tid, int flavor, CSR &csr) override { return -1; }
764
765 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
766 return 0;
767 }
768
769 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
770 return 0;
771 }
772
773 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
774 return 0;
775 }
776
777 int DoWriteCSR(lldb::tid_t tid, int flavor, const CSR &csr) override {
778 return 0;
779 }
780};
781
782static uint32_t MachHeaderSizeFromMagic(uint32_t magic) {
783 switch (magic) {
784 case MH_MAGIC:
785 case MH_CIGAM:
786 return sizeof(struct llvm::MachO::mach_header);
787
788 case MH_MAGIC_64:
789 case MH_CIGAM_64:
790 return sizeof(struct llvm::MachO::mach_header_64);
791 break;
792
793 default:
794 break;
795 }
796 return 0;
797}
798
799#define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
800
802
808
812
814 DataExtractorSP extractor_sp,
815 lldb::offset_t data_offset,
816 const FileSpec *file,
817 lldb::offset_t file_offset,
818 lldb::offset_t length) {
819 if (!extractor_sp || !extractor_sp->HasData()) {
820 DataBufferSP data_sp = MapFileData(*file, length, file_offset);
821 if (!data_sp)
822 return nullptr;
823 data_offset = 0;
824 extractor_sp = std::make_shared<DataExtractor>(data_sp);
825 }
826
827 if (!ObjectFileMachO::MagicBytesMatch(extractor_sp, data_offset, length))
828 return nullptr;
829
830 // Update the data to contain the entire file if it doesn't already
831 if (extractor_sp->GetByteSize() < length) {
832 DataBufferSP data_sp = MapFileData(*file, length, file_offset);
833 if (!data_sp)
834 return nullptr;
835 data_offset = 0;
836 extractor_sp = std::make_shared<DataExtractor>(data_sp);
837 }
838 auto objfile_up = std::make_unique<ObjectFileMachO>(
839 module_sp, extractor_sp, data_offset, file, file_offset, length);
840 if (!objfile_up || !objfile_up->ParseHeader())
841 return nullptr;
842
843 return objfile_up.release();
844}
845
847 const lldb::ModuleSP &module_sp, WritableDataBufferSP data_sp,
848 const ProcessSP &process_sp, lldb::addr_t header_addr) {
849 DataExtractorSP extractor_sp = std::make_shared<DataExtractor>(data_sp);
850 if (ObjectFileMachO::MagicBytesMatch(extractor_sp, 0,
851 extractor_sp->GetByteSize())) {
852 std::unique_ptr<ObjectFile> objfile_up(
853 new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr));
854 if (objfile_up.get() && objfile_up->ParseHeader())
855 return objfile_up.release();
856 }
857 return nullptr;
858}
859
861 const lldb_private::FileSpec &file, lldb::DataExtractorSP &extractor_sp,
862 lldb::offset_t file_offset, lldb::offset_t length) {
863 if (!extractor_sp || !extractor_sp->HasData())
864 return {};
865
866 ModuleSpecList specs;
867 if (ObjectFileMachO::MagicBytesMatch(extractor_sp, 0,
868 extractor_sp->GetByteSize())) {
869 llvm::MachO::mach_header header;
870 offset_t data_offset = 0;
871 if (ParseHeader(extractor_sp, &data_offset, header)) {
872 size_t header_and_load_cmds =
873 header.sizeofcmds + MachHeaderSizeFromMagic(header.magic);
874 if (header_and_load_cmds >= extractor_sp->GetByteSize()) {
875 DataBufferSP file_data_sp =
876 MapFileData(file, header_and_load_cmds, file_offset);
877 if (file_data_sp)
878 extractor_sp->SetData(file_data_sp);
879 data_offset = MachHeaderSizeFromMagic(header.magic);
880 }
881 if (extractor_sp && extractor_sp->HasData()) {
882 ModuleSpec base_spec;
883 base_spec.GetFileSpec() = file;
884 base_spec.SetObjectOffset(file_offset);
885 base_spec.SetObjectSize(length);
886 GetAllArchSpecs(header, *extractor_sp, data_offset, base_spec, specs);
887 }
888 }
889 }
890 return specs;
891}
892
894 static constexpr llvm::StringLiteral g_segment_name_TEXT("__TEXT");
895 return g_segment_name_TEXT;
896}
897
899 static constexpr llvm::StringLiteral g_segment_name_DATA("__DATA");
900 return g_segment_name_DATA;
901}
902
904 static constexpr llvm::StringLiteral g_segment_name("__DATA_DIRTY");
905 return g_segment_name;
906}
907
909 static constexpr llvm::StringLiteral g_segment_name("__DATA_CONST");
910 return g_segment_name;
911}
912
914 static constexpr llvm::StringLiteral g_segment_name_OBJC("__OBJC");
915 return g_segment_name_OBJC;
916}
917
919 static constexpr llvm::StringLiteral g_section_name_LINKEDIT("__LINKEDIT");
920 return g_section_name_LINKEDIT;
921}
922
924 static constexpr llvm::StringLiteral g_section_name("__DWARF");
925 return g_section_name;
926}
927
929 static constexpr llvm::StringLiteral g_section_name("__LLVM_COV");
930 return g_section_name;
931}
932
934 static constexpr llvm::StringLiteral g_section_name_eh_frame("__eh_frame");
935 return g_section_name_eh_frame;
936}
937
939 static constexpr llvm::StringLiteral g_section_name_lldb_no_nlist(
940 "__lldb_no_nlist");
941 return g_section_name_lldb_no_nlist;
942}
943
945 lldb::addr_t data_offset,
946 lldb::addr_t data_length) {
947 lldb::offset_t offset = data_offset;
948 uint32_t magic = extractor_sp->GetU32(&offset);
949
950 offset += 4; // cputype
951 offset += 4; // cpusubtype
952 uint32_t filetype = extractor_sp->GetU32(&offset);
953
954 // A fileset has a Mach-O header but is not an
955 // individual file and must be handled via an
956 // ObjectContainer plugin.
957 if (filetype == llvm::MachO::MH_FILESET)
958 return false;
959
960 return MachHeaderSizeFromMagic(magic) != 0;
961}
962
964 DataExtractorSP extractor_sp,
965 lldb::offset_t data_offset,
966 const FileSpec *file,
967 lldb::offset_t file_offset,
968 lldb::offset_t length)
969 : ObjectFile(module_sp, file, file_offset, length, extractor_sp,
970 data_offset),
974 ::memset(&m_header, 0, sizeof(m_header));
975 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
976}
977
979 lldb::WritableDataBufferSP header_data_sp,
980 const lldb::ProcessSP &process_sp,
981 lldb::addr_t header_addr)
982 : ObjectFile(module_sp, process_sp, header_addr,
983 std::make_shared<DataExtractor>(header_data_sp)),
987 ::memset(&m_header, 0, sizeof(m_header));
988 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
989}
990
992 lldb::offset_t *data_offset_ptr,
993 llvm::MachO::mach_header &header) {
994 extractor_sp->SetByteOrder(endian::InlHostByteOrder());
995 // Leave magic in the original byte order
996 header.magic = extractor_sp->GetU32(data_offset_ptr);
997 bool can_parse = false;
998 bool is_64_bit = false;
999 switch (header.magic) {
1000 case MH_MAGIC:
1001 extractor_sp->SetByteOrder(endian::InlHostByteOrder());
1002 extractor_sp->SetAddressByteSize(4);
1003 can_parse = true;
1004 break;
1005
1006 case MH_MAGIC_64:
1007 extractor_sp->SetByteOrder(endian::InlHostByteOrder());
1008 extractor_sp->SetAddressByteSize(8);
1009 can_parse = true;
1010 is_64_bit = true;
1011 break;
1012
1013 case MH_CIGAM:
1014 extractor_sp->SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1016 : eByteOrderBig);
1017 extractor_sp->SetAddressByteSize(4);
1018 can_parse = true;
1019 break;
1020
1021 case MH_CIGAM_64:
1022 extractor_sp->SetByteOrder(endian::InlHostByteOrder() == eByteOrderBig
1024 : eByteOrderBig);
1025 extractor_sp->SetAddressByteSize(8);
1026 is_64_bit = true;
1027 can_parse = true;
1028 break;
1029
1030 default:
1031 break;
1032 }
1033
1034 if (can_parse) {
1035 extractor_sp->GetU32(data_offset_ptr, &header.cputype, 6);
1036 if (is_64_bit)
1037 *data_offset_ptr += 4;
1038 return true;
1039 } else {
1040 memset(&header, 0, sizeof(header));
1041 }
1042 return false;
1043}
1044
1046 ModuleSP module_sp(GetModule());
1047 if (!module_sp)
1048 return false;
1049
1050 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1051 bool can_parse = false;
1052 lldb::offset_t offset = 0;
1053 m_data_nsp->SetByteOrder(endian::InlHostByteOrder());
1054 // Leave magic in the original byte order
1055 m_header.magic = m_data_nsp->GetU32(&offset);
1056 switch (m_header.magic) {
1057 case MH_MAGIC:
1058 m_data_nsp->SetByteOrder(endian::InlHostByteOrder());
1059 m_data_nsp->SetAddressByteSize(4);
1060 can_parse = true;
1061 break;
1062
1063 case MH_MAGIC_64:
1064 m_data_nsp->SetByteOrder(endian::InlHostByteOrder());
1065 m_data_nsp->SetAddressByteSize(8);
1066 can_parse = true;
1067 break;
1068
1069 case MH_CIGAM:
1072 : eByteOrderBig);
1073 m_data_nsp->SetAddressByteSize(4);
1074 can_parse = true;
1075 break;
1076
1077 case MH_CIGAM_64:
1080 : eByteOrderBig);
1081 m_data_nsp->SetAddressByteSize(8);
1082 can_parse = true;
1083 break;
1084
1085 default:
1086 break;
1087 }
1088
1089 if (can_parse) {
1090 m_data_nsp->GetU32(&offset, &m_header.cputype, 6);
1091
1092 ModuleSpecList all_specs;
1093 ModuleSpec base_spec;
1095 MachHeaderSizeFromMagic(m_header.magic), base_spec,
1096 all_specs);
1097
1098 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
1099 ArchSpec mach_arch =
1101
1102 // Check if the module has a required architecture
1103 const ArchSpec &module_arch = module_sp->GetArchitecture();
1104 if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
1105 continue;
1106
1107 if (SetModulesArchitecture(mach_arch)) {
1108 const size_t header_and_lc_size =
1109 m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
1110 if (m_data_nsp->GetByteSize() < header_and_lc_size) {
1111 DataBufferSP data_sp;
1112 ProcessSP process_sp(m_process_wp.lock());
1113 if (process_sp) {
1114 data_sp = ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
1115 } else {
1116 // Read in all only the load command data from the file on disk
1117 data_sp = MapFileData(m_file, header_and_lc_size, m_file_offset);
1118 if (data_sp->GetByteSize() != header_and_lc_size)
1119 continue;
1120 }
1121 if (data_sp)
1122 m_data_nsp->SetData(data_sp);
1123 }
1124 }
1125 return true;
1126 }
1127 // None found.
1128 return false;
1129 } else {
1130 memset(&m_header, 0, sizeof(struct llvm::MachO::mach_header));
1131 }
1132 return false;
1133}
1134
1136 return m_data_nsp->GetByteOrder();
1137}
1138
1140 return m_header.filetype == MH_EXECUTE;
1141}
1142
1144 return m_header.filetype == MH_DYLINKER;
1145}
1146
1148 return m_header.flags & MH_DYLIB_IN_CACHE;
1149}
1150
1152 return m_header.filetype == MH_KEXT_BUNDLE;
1153}
1154
1156 return m_data_nsp->GetAddressByteSize();
1157}
1158
1160 Symtab *symtab = GetSymtab();
1161 if (!symtab)
1163
1164 const Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
1165 if (symbol) {
1166 if (symbol->ValueIsAddress()) {
1167 SectionSP section_sp(symbol->GetAddressRef().GetSection());
1168 if (section_sp) {
1169 const lldb::SectionType section_type = section_sp->GetType();
1170 switch (section_type) {
1173
1174 case eSectionTypeCode:
1175 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
1176 // For ARM we have a bit in the n_desc field of the symbol that
1177 // tells us ARM/Thumb which is bit 0x0008.
1180 }
1181 return AddressClass::eCode;
1182
1185
1186 case eSectionTypeData:
1190 case eSectionTypeData4:
1191 case eSectionTypeData8:
1192 case eSectionTypeData16:
1200 return AddressClass::eData;
1201
1202 case eSectionTypeDebug:
1237 case eSectionTypeCTF:
1241 return AddressClass::eDebug;
1242
1248
1254 case eSectionTypeOther:
1256 }
1257 }
1258 }
1259
1260 const SymbolType symbol_type = symbol->GetType();
1261 switch (symbol_type) {
1262 case eSymbolTypeAny:
1266
1267 case eSymbolTypeCode:
1270 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
1271 // For ARM we have a bit in the n_desc field of the symbol that tells
1272 // us ARM/Thumb which is bit 0x0008.
1275 }
1276 return AddressClass::eCode;
1277
1278 case eSymbolTypeData:
1279 return AddressClass::eData;
1280 case eSymbolTypeRuntime:
1285 return AddressClass::eDebug;
1287 return AddressClass::eDebug;
1289 return AddressClass::eDebug;
1291 return AddressClass::eDebug;
1292 case eSymbolTypeBlock:
1293 return AddressClass::eDebug;
1294 case eSymbolTypeLocal:
1295 return AddressClass::eData;
1296 case eSymbolTypeParam:
1297 return AddressClass::eData;
1299 return AddressClass::eData;
1301 return AddressClass::eDebug;
1303 return AddressClass::eDebug;
1305 return AddressClass::eDebug;
1307 return AddressClass::eDebug;
1309 return AddressClass::eDebug;
1313 return AddressClass::eDebug;
1315 return AddressClass::eDebug;
1326 case eSymbolTypeASTFile:
1327 return AddressClass::eDebug;
1328 }
1329 }
1331}
1332
1334 if (m_dysymtab.cmd == 0) {
1335 ModuleSP module_sp(GetModule());
1336 if (module_sp) {
1338 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1339 const lldb::offset_t load_cmd_offset = offset;
1340
1341 llvm::MachO::load_command lc = {};
1342 if (!ReadMachOCommand(*m_data_nsp, offset, lc))
1343 break;
1344 if (lc.cmd == LC_DYSYMTAB) {
1345 m_dysymtab.cmd = lc.cmd;
1346 m_dysymtab.cmdsize = lc.cmdsize;
1347 if (m_data_nsp->GetU32(&offset, &m_dysymtab.ilocalsym,
1348 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2) ==
1349 nullptr) {
1350 // Clear m_dysymtab if we were unable to read all items from the
1351 // load command
1352 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
1353 }
1354 }
1355 offset = load_cmd_offset + lc.cmdsize;
1356 }
1357 }
1358 }
1359 if (m_dysymtab.cmd)
1360 return m_dysymtab.nlocalsym <= 1;
1361 return false;
1362}
1363
1365 EncryptedFileRanges result;
1367
1368 llvm::MachO::encryption_info_command encryption_cmd;
1369 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1370 const lldb::offset_t load_cmd_offset = offset;
1371 if (!ReadMachOCommand(*m_data_nsp, offset, encryption_cmd))
1372 break;
1373
1374 // LC_ENCRYPTION_INFO and LC_ENCRYPTION_INFO_64 have the same sizes for the
1375 // 3 fields we care about, so treat them the same.
1376 if (encryption_cmd.cmd == LC_ENCRYPTION_INFO ||
1377 encryption_cmd.cmd == LC_ENCRYPTION_INFO_64) {
1378 if (m_data_nsp->GetU32(&offset, &encryption_cmd.cryptoff, 3)) {
1379 if (encryption_cmd.cryptid != 0) {
1381 entry.SetRangeBase(encryption_cmd.cryptoff);
1382 entry.SetByteSize(encryption_cmd.cryptsize);
1383 result.Append(entry);
1384 }
1385 }
1386 }
1387 offset = load_cmd_offset + encryption_cmd.cmdsize;
1388 }
1389
1390 return result;
1391}
1392
1394 llvm::MachO::segment_command_64 &seg_cmd, uint32_t cmd_idx) {
1395 if (m_length == 0 || seg_cmd.filesize == 0)
1396 return;
1397
1398 if (IsSharedCacheBinary() && !IsInMemory()) {
1399 // In shared cache images, the load commands are relative to the
1400 // shared cache file, and not the specific image we are
1401 // examining. Let's fix this up so that it looks like a normal
1402 // image.
1403 llvm::StringRef segname(seg_cmd.segname,
1404 strnlen(seg_cmd.segname, sizeof(seg_cmd.segname)));
1405 if (segname == GetSegmentNameTEXT())
1406 m_text_address = seg_cmd.vmaddr;
1407 if (segname == GetSegmentNameLINKEDIT())
1408 m_linkedit_original_offset = seg_cmd.fileoff;
1409
1410 seg_cmd.fileoff = seg_cmd.vmaddr - m_text_address;
1411 }
1412
1413 if (seg_cmd.fileoff > m_length) {
1414 // We have a load command that says it extends past the end of the file.
1415 // This is likely a corrupt file. We don't have any way to return an error
1416 // condition here (this method was likely invoked from something like
1417 // ObjectFile::GetSectionList()), so we just null out the section contents,
1418 // and dump a message to stdout. The most common case here is core file
1419 // debugging with a truncated file.
1420 const char *lc_segment_name =
1421 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1422 GetModule()->ReportWarning(
1423 "load command {0} {1} has a fileoff ({2:x16}) that extends beyond "
1424 "the end of the file ({3:x16}), ignoring this section",
1425 cmd_idx, lc_segment_name, seg_cmd.fileoff, m_length);
1426
1427 seg_cmd.fileoff = 0;
1428 seg_cmd.filesize = 0;
1429 }
1430
1431 if (seg_cmd.fileoff + seg_cmd.filesize > m_length) {
1432 // We have a load command that says it extends past the end of the file.
1433 // This is likely a corrupt file. We don't have any way to return an error
1434 // condition here (this method was likely invoked from something like
1435 // ObjectFile::GetSectionList()), so we just null out the section contents,
1436 // and dump a message to stdout. The most common case here is core file
1437 // debugging with a truncated file.
1438 const char *lc_segment_name =
1439 seg_cmd.cmd == LC_SEGMENT_64 ? "LC_SEGMENT_64" : "LC_SEGMENT";
1440 GetModule()->ReportWarning(
1441 "load command {0} {1} has a fileoff + filesize ({2:x16}) that "
1442 "extends beyond the end of the file ({3:x16}), the segment will be "
1443 "truncated to match",
1444 cmd_idx, lc_segment_name, seg_cmd.fileoff + seg_cmd.filesize, m_length);
1445
1446 // Truncate the length
1447 seg_cmd.filesize = m_length - seg_cmd.fileoff;
1448 }
1449}
1450
1451static uint32_t
1452GetSegmentPermissions(const llvm::MachO::segment_command_64 &seg_cmd) {
1453 uint32_t result = 0;
1454 if (seg_cmd.initprot & VM_PROT_READ)
1455 result |= ePermissionsReadable;
1456 if (seg_cmd.initprot & VM_PROT_WRITE)
1457 result |= ePermissionsWritable;
1458 if (seg_cmd.initprot & VM_PROT_EXECUTE)
1459 result |= ePermissionsExecutable;
1460 return result;
1461}
1462
1463static lldb::SectionType GetSectionType(uint32_t flags,
1464 llvm::StringRef section_name) {
1465
1466 if (flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS))
1467 return eSectionTypeCode;
1468
1469 uint32_t mach_sect_type = flags & SECTION_TYPE;
1470 static constexpr llvm::StringLiteral g_sect_name_objc_data("__objc_data");
1471 static constexpr llvm::StringLiteral g_sect_name_objc_msgrefs(
1472 "__objc_msgrefs");
1473 static constexpr llvm::StringLiteral g_sect_name_objc_selrefs(
1474 "__objc_selrefs");
1475 static constexpr llvm::StringLiteral g_sect_name_objc_classrefs(
1476 "__objc_classrefs");
1477 static constexpr llvm::StringLiteral g_sect_name_objc_superrefs(
1478 "__objc_superrefs");
1479 static constexpr llvm::StringLiteral g_sect_name_objc_const("__objc_const");
1480 static constexpr llvm::StringLiteral g_sect_name_objc_classlist(
1481 "__objc_classlist");
1482 static constexpr llvm::StringLiteral g_sect_name_cfstring("__cfstring");
1483
1484 static constexpr llvm::StringLiteral g_sect_name_dwarf_debug_str_offs(
1485 "__debug_str_offs");
1486 static constexpr llvm::StringLiteral g_sect_name_dwarf_debug_str_offs_dwo(
1487 "__debug_str_offs.dwo");
1488 static constexpr llvm::StringLiteral g_sect_name_dwarf_apple_names(
1489 "__apple_names");
1490 static constexpr llvm::StringLiteral g_sect_name_dwarf_apple_types(
1491 "__apple_types");
1492 static constexpr llvm::StringLiteral g_sect_name_dwarf_apple_namespaces(
1493 "__apple_namespac");
1494 static constexpr llvm::StringLiteral g_sect_name_dwarf_apple_objc(
1495 "__apple_objc");
1496 static constexpr llvm::StringLiteral g_sect_name_eh_frame("__eh_frame");
1497 static constexpr llvm::StringLiteral g_sect_name_compact_unwind(
1498 "__unwind_info");
1499 static constexpr llvm::StringLiteral g_sect_name_text("__text");
1500 static constexpr llvm::StringLiteral g_sect_name_data("__data");
1501 static constexpr llvm::StringLiteral g_sect_name_go_symtab("__gosymtab");
1502 static constexpr llvm::StringLiteral g_sect_name_ctf("__ctf");
1503 static constexpr llvm::StringLiteral g_sect_name_lldb_summaries(
1504 "__lldbsummaries");
1505 static constexpr llvm::StringLiteral g_sect_name_lldb_formatters(
1506 "__lldbformatters");
1507 static constexpr llvm::StringLiteral g_sect_name_swift_ast("__swift_ast");
1508
1509 if (section_name == g_sect_name_dwarf_debug_str_offs)
1511 if (section_name == g_sect_name_dwarf_debug_str_offs_dwo)
1513
1514 llvm::StringRef stripped_name = section_name;
1515 if (stripped_name.consume_front("__debug_"))
1516 return ObjectFile::GetDWARFSectionTypeFromName(stripped_name);
1517
1518 if (section_name == g_sect_name_dwarf_apple_names)
1520 if (section_name == g_sect_name_dwarf_apple_types)
1522 if (section_name == g_sect_name_dwarf_apple_namespaces)
1524 if (section_name == g_sect_name_dwarf_apple_objc)
1526 if (section_name == g_sect_name_objc_selrefs)
1528 if (section_name == g_sect_name_objc_msgrefs)
1530 if (section_name == g_sect_name_eh_frame)
1531 return eSectionTypeEHFrame;
1532 if (section_name == g_sect_name_compact_unwind)
1534 if (section_name == g_sect_name_cfstring)
1536 if (section_name == g_sect_name_go_symtab)
1537 return eSectionTypeGoSymtab;
1538 if (section_name == g_sect_name_ctf)
1539 return eSectionTypeCTF;
1540 if (section_name == g_sect_name_lldb_summaries)
1542 if (section_name == g_sect_name_lldb_formatters)
1544 if (section_name == g_sect_name_swift_ast)
1546 if (section_name == g_sect_name_objc_data ||
1547 section_name == g_sect_name_objc_classrefs ||
1548 section_name == g_sect_name_objc_superrefs ||
1549 section_name == g_sect_name_objc_const ||
1550 section_name == g_sect_name_objc_classlist) {
1552 }
1553
1554 switch (mach_sect_type) {
1555 // TODO: categorize sections by other flags for regular sections
1556 case S_REGULAR:
1557 if (section_name == g_sect_name_text)
1558 return eSectionTypeCode;
1559 if (section_name == g_sect_name_data)
1560 return eSectionTypeData;
1561 return eSectionTypeOther;
1562 case S_ZEROFILL:
1563 return eSectionTypeZeroFill;
1564 case S_CSTRING_LITERALS: // section with only literal C strings
1566 case S_4BYTE_LITERALS: // section with only 4 byte literals
1567 return eSectionTypeData4;
1568 case S_8BYTE_LITERALS: // section with only 8 byte literals
1569 return eSectionTypeData8;
1570 case S_LITERAL_POINTERS: // section with only pointers to literals
1572 case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
1574 case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
1576 case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
1577 // the reserved2 field
1578 return eSectionTypeCode;
1579 case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
1580 // initialization
1582 case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
1583 // termination
1585 case S_COALESCED:
1586 return eSectionTypeOther;
1587 case S_GB_ZEROFILL:
1588 return eSectionTypeZeroFill;
1589 case S_INTERPOSING: // section with only pairs of function pointers for
1590 // interposing
1591 return eSectionTypeCode;
1592 case S_16BYTE_LITERALS: // section with only 16 byte literals
1593 return eSectionTypeData16;
1594 case S_DTRACE_DOF:
1595 return eSectionTypeDebug;
1596 case S_LAZY_DYLIB_SYMBOL_POINTERS:
1598 default:
1599 return eSectionTypeOther;
1600 }
1601}
1602
1614
1616 const llvm::MachO::load_command &load_cmd_, lldb::offset_t offset,
1617 uint32_t cmd_idx, SegmentParsingContext &context) {
1618 llvm::MachO::segment_command_64 load_cmd;
1619 memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
1620
1621 if (!m_data_nsp->GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
1622 return;
1623
1624 ModuleSP module_sp = GetModule();
1625 const bool is_core = GetType() == eTypeCoreFile;
1626 const bool is_dsym = (m_header.filetype == MH_DSYM);
1627 bool add_section = true;
1628 bool add_to_unified = true;
1629 llvm::StringRef segname(load_cmd.segname,
1630 strnlen(load_cmd.segname, sizeof(load_cmd.segname)));
1631
1632 SectionSP unified_section_sp(context.UnifiedList.FindSectionByName(segname));
1633 if (is_dsym && unified_section_sp) {
1634 if (segname == GetSegmentNameLINKEDIT()) {
1635 // We need to keep the __LINKEDIT segment private to this object file
1636 // only
1637 add_to_unified = false;
1638 } else {
1639 // This is the dSYM file and this section has already been created by the
1640 // object file, no need to create it.
1641 add_section = false;
1642 }
1643 }
1644 load_cmd.vmaddr = m_data_nsp->GetAddress(&offset);
1645 load_cmd.vmsize = m_data_nsp->GetAddress(&offset);
1646 load_cmd.fileoff = m_data_nsp->GetAddress(&offset);
1647 load_cmd.filesize = m_data_nsp->GetAddress(&offset);
1648 if (!m_data_nsp->GetU32(&offset, &load_cmd.maxprot, 4))
1649 return;
1650
1651 SanitizeSegmentCommand(load_cmd, cmd_idx);
1652
1653 const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
1654 const bool segment_is_encrypted =
1655 (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1656
1657 // Use a segment ID of the segment index shifted left by 8 so they never
1658 // conflict with any of the sections.
1659 SectionSP segment_sp;
1660 if (add_section && (!segname.empty() || is_core)) {
1661 segment_sp = std::make_shared<Section>(
1662 module_sp, // Module to which this section belongs
1663 this, // Object file to which this sections belongs
1664 ++context.NextSegmentIdx
1665 << 8, // Section ID is the 1 based segment index
1666 // shifted right by 8 bits as not to collide with any of the 256
1667 // section IDs that are possible
1668 segname.str(), // Name of this section
1669 eSectionTypeContainer, // This section is a container of other
1670 // sections.
1671 load_cmd.vmaddr, // File VM address == addresses as they are
1672 // found in the object file
1673 load_cmd.vmsize, // VM size in bytes of this section
1674 load_cmd.fileoff, // Offset to the data for this section in
1675 // the file
1676 load_cmd.filesize, // Size in bytes of this section as found
1677 // in the file
1678 0, // Segments have no alignment information
1679 load_cmd.flags); // Flags for this section
1680
1681 segment_sp->SetIsEncrypted(segment_is_encrypted);
1682 m_sections_up->AddSection(segment_sp);
1683 segment_sp->SetPermissions(segment_permissions);
1684 if (add_to_unified)
1685 context.UnifiedList.AddSection(segment_sp);
1686 } else if (unified_section_sp) {
1687 // If this is a dSYM and the file addresses in the dSYM differ from the
1688 // file addresses in the ObjectFile, we must use the file base address for
1689 // the Section from the dSYM for the DWARF to resolve correctly.
1690 // This only happens with binaries in the shared cache in practice;
1691 // normally a mismatch like this would give a binary & dSYM that do not
1692 // match UUIDs. When a binary is included in the shared cache, its
1693 // segments are rearranged to optimize the shared cache, so its file
1694 // addresses will differ from what the ObjectFile had originally,
1695 // and what the dSYM has.
1696 if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1698 "Installing dSYM's {0} segment file address over ObjectFile's "
1699 "so symbol table/debug info resolves correctly for {1}",
1700 segname, module_sp->GetFileSpec().GetFilename());
1701
1702 // Make sure we've parsed the symbol table from the ObjectFile before
1703 // we go around changing its Sections.
1704 module_sp->GetObjectFile()->GetSymtab();
1705 // eh_frame would present the same problems but we parse that on a per-
1706 // function basis as-needed so it's more difficult to remove its use of
1707 // the Sections. Realistically, the environments where this code path
1708 // will be taken will not have eh_frame sections.
1709
1710 unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1711
1712 // Notify the module that the section addresses have been changed once
1713 // we're done so any file-address caches can be updated.
1714 context.FileAddressesChanged = true;
1715 }
1716 m_sections_up->AddSection(unified_section_sp);
1717 }
1718
1719 llvm::MachO::section_64 sect64;
1720 ::memset(&sect64, 0, sizeof(sect64));
1721 // Push a section into our mach sections for the section at index zero
1722 // (NO_SECT) if we don't have any mach sections yet...
1723 if (m_mach_sections.empty())
1724 m_mach_sections.push_back(sect64);
1725 uint32_t segment_sect_idx;
1726 const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
1727
1728 // 64 bit mach-o files have sections with 32 bit file offsets. If any section
1729 // data end will exceed UINT32_MAX, then we need to do some bookkeeping to
1730 // ensure we can access this data correctly.
1731 uint64_t section_offset_adjust = 0;
1732 const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1733 for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1734 ++segment_sect_idx) {
1735 if (m_data_nsp->GetU8(&offset, (uint8_t *)sect64.sectname,
1736 sizeof(sect64.sectname)) == nullptr)
1737 break;
1738 if (m_data_nsp->GetU8(&offset, (uint8_t *)sect64.segname,
1739 sizeof(sect64.segname)) == nullptr)
1740 break;
1741 sect64.addr = m_data_nsp->GetAddress(&offset);
1742 sect64.size = m_data_nsp->GetAddress(&offset);
1743
1744 if (m_data_nsp->GetU32(&offset, &sect64.offset, num_u32s) == nullptr)
1745 break;
1746
1747 if (IsSharedCacheBinary() && !IsInMemory()) {
1748 sect64.offset = sect64.addr - m_text_address;
1749 }
1750
1751 // Keep a list of mach sections around in case we need to get at data that
1752 // isn't stored in the abstracted Sections.
1753 m_mach_sections.push_back(sect64);
1754
1755 // Make sure we can load sections in mach-o files where some sections cross
1756 // a 4GB boundary. llvm::MachO::section_64 have only 32 bit file offsets
1757 // for the file offset of the section contents, so we need to track and
1758 // sections that overflow and adjust the offsets accordingly.
1759 const uint64_t section_file_offset =
1760 (uint64_t)sect64.offset + section_offset_adjust;
1761 const uint64_t end_section_offset = (uint64_t)sect64.offset + sect64.size;
1762 if (end_section_offset >= UINT32_MAX)
1763 section_offset_adjust += end_section_offset & 0xFFFFFFFF00000000ull;
1764
1765 if (add_section) {
1766 llvm::StringRef section_name(
1767 sect64.sectname, strnlen(sect64.sectname, sizeof(sect64.sectname)));
1768 if (segname.empty()) {
1769 // We have a segment with no name so we need to conjure up segments
1770 // that correspond to the section's segname if there isn't already such
1771 // a section. If there is such a section, we resize the section so that
1772 // it spans all sections. We also mark these sections as fake so
1773 // address matches don't hit if they land in the gaps between the child
1774 // sections.
1775 segname = llvm::StringRef(
1776 sect64.segname, strnlen(sect64.segname, sizeof(sect64.segname)));
1777 segment_sp = context.UnifiedList.FindSectionByName(segname);
1778 if (segment_sp.get()) {
1779 Section *segment = segment_sp.get();
1780 // Grow the section size as needed.
1781 const lldb::addr_t sect64_min_addr = sect64.addr;
1782 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1783 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1784 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1785 const lldb::addr_t curr_seg_max_addr =
1786 curr_seg_min_addr + curr_seg_byte_size;
1787 if (sect64_min_addr >= curr_seg_min_addr) {
1788 const lldb::addr_t new_seg_byte_size =
1789 sect64_max_addr - curr_seg_min_addr;
1790 // Only grow the section size if needed
1791 if (new_seg_byte_size > curr_seg_byte_size)
1792 segment->SetByteSize(new_seg_byte_size);
1793 } else {
1794 // We need to change the base address of the segment and adjust the
1795 // child section offsets for all existing children.
1796 const lldb::addr_t slide_amount =
1797 sect64_min_addr - curr_seg_min_addr;
1798 segment->Slide(slide_amount, false);
1799 segment->GetChildren().Slide(-slide_amount, false);
1800 segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1801 }
1802
1803 // Grow the section size as needed.
1804 if (section_file_offset) {
1805 const lldb::addr_t segment_min_file_offset =
1806 segment->GetFileOffset();
1807 const lldb::addr_t segment_max_file_offset =
1808 segment_min_file_offset + segment->GetFileSize();
1809
1810 const lldb::addr_t section_min_file_offset = section_file_offset;
1811 const lldb::addr_t section_max_file_offset =
1812 section_min_file_offset + sect64.size;
1813 const lldb::addr_t new_file_offset =
1814 std::min(section_min_file_offset, segment_min_file_offset);
1815 const lldb::addr_t new_file_size =
1816 std::max(section_max_file_offset, segment_max_file_offset) -
1817 new_file_offset;
1818 segment->SetFileOffset(new_file_offset);
1819 segment->SetFileSize(new_file_size);
1820 }
1821 } else {
1822 // Create a fake section for the section's named segment
1823 segment_sp = std::make_shared<Section>(
1824 segment_sp, // Parent section
1825 module_sp, // Module to which this section belongs
1826 this, // Object file to which this section belongs
1827 ++context.NextSegmentIdx
1828 << 8, // Section ID is the 1 based segment index
1829 // shifted right by 8 bits as not to
1830 // collide with any of the 256 section IDs
1831 // that are possible
1832 segname.str(), // Name of this section
1833 eSectionTypeContainer, // This section is a container of
1834 // other sections.
1835 sect64.addr, // File VM address == addresses as they are
1836 // found in the object file
1837 sect64.size, // VM size in bytes of this section
1838 section_file_offset, // Offset to the data for this section in
1839 // the file
1840 section_file_offset ? sect64.size : 0, // Size in bytes of
1841 // this section as
1842 // found in the file
1843 sect64.align,
1844 load_cmd.flags); // Flags for this section
1845 segment_sp->SetIsFake(true);
1846 segment_sp->SetPermissions(segment_permissions);
1847 m_sections_up->AddSection(segment_sp);
1848 if (add_to_unified)
1849 context.UnifiedList.AddSection(segment_sp);
1850 segment_sp->SetIsEncrypted(segment_is_encrypted);
1851 }
1852 }
1853 assert(segment_sp.get());
1854
1855 lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
1856
1857 SectionSP section_sp = std::make_shared<Section>(
1858 segment_sp, module_sp, this, ++context.NextSectionIdx,
1859 section_name.str(), sect_type,
1860 sect64.addr - segment_sp->GetFileAddress(), sect64.size,
1861 section_file_offset, section_file_offset == 0 ? 0 : sect64.size,
1862 sect64.align, sect64.flags);
1863 // Set the section to be encrypted to match the segment
1864
1865 bool section_is_encrypted = false;
1866 if (!segment_is_encrypted && load_cmd.filesize != 0)
1867 section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
1868 section_file_offset) != nullptr;
1869
1870 section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
1871 section_sp->SetPermissions(segment_permissions);
1872 segment_sp->GetChildren().AddSection(section_sp);
1873
1874 if (segment_sp->IsFake()) {
1875 segment_sp.reset();
1876 segname = {};
1877 }
1878 }
1879 }
1880 if (segment_sp && is_dsym) {
1881 if (first_segment_sectID <= context.NextSectionIdx) {
1882 lldb::user_id_t sect_uid;
1883 for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
1884 ++sect_uid) {
1885 SectionSP curr_section_sp(
1886 segment_sp->GetChildren().FindSectionByID(sect_uid));
1887 SectionSP next_section_sp;
1888 if (sect_uid + 1 <= context.NextSectionIdx)
1889 next_section_sp =
1890 segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
1891
1892 if (curr_section_sp.get()) {
1893 if (curr_section_sp->GetByteSize() == 0) {
1894 if (next_section_sp.get() != nullptr)
1895 curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
1896 curr_section_sp->GetFileAddress());
1897 else
1898 curr_section_sp->SetByteSize(load_cmd.vmsize);
1899 }
1900 }
1901 }
1902 }
1903 }
1904}
1905
1907 const llvm::MachO::load_command &load_cmd, lldb::offset_t offset) {
1908 m_dysymtab.cmd = load_cmd.cmd;
1909 m_dysymtab.cmdsize = load_cmd.cmdsize;
1910 m_data_nsp->GetU32(&offset, &m_dysymtab.ilocalsym,
1911 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1912}
1913
1915 if (m_sections_up)
1916 return;
1917
1918 m_sections_up = std::make_unique<SectionList>();
1919
1921 // bool dump_sections = false;
1922 ModuleSP module_sp(GetModule());
1923
1924 offset = MachHeaderSizeFromMagic(m_header.magic);
1925
1926 SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
1927 llvm::MachO::load_command load_cmd;
1928 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1929 const lldb::offset_t load_cmd_offset = offset;
1930 if (!ReadMachOCommand(*m_data_nsp, offset, load_cmd))
1931 break;
1932
1933 if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1934 ProcessSegmentCommand(load_cmd, offset, i, context);
1935 else if (load_cmd.cmd == LC_DYSYMTAB)
1936 ProcessDysymtabCommand(load_cmd, offset);
1937
1938 offset = load_cmd_offset + load_cmd.cmdsize;
1939 }
1940
1941 if (context.FileAddressesChanged && module_sp)
1942 module_sp->SectionFileAddressesChanged();
1943}
1944
1946public:
1948 : m_section_list(section_list), m_section_infos() {
1949 // Get the number of sections down to a depth of 1 to include all segments
1950 // and their sections, but no other sections that may be added for debug
1951 // map or
1952 m_section_infos.resize(section_list->GetNumSections(1));
1953 }
1954
1955 SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1956 if (n_sect == 0)
1957 return SectionSP();
1958 if (n_sect < m_section_infos.size()) {
1959 if (!m_section_infos[n_sect].section_sp) {
1960 SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
1961 m_section_infos[n_sect].section_sp = section_sp;
1962 if (section_sp) {
1963 m_section_infos[n_sect].vm_range.SetRangeBase(
1964 section_sp->GetFileAddress());
1965 m_section_infos[n_sect].vm_range.SetByteSize(
1966 section_sp->GetByteSize());
1967 } else {
1968 std::string filename = "<unknown>";
1969 SectionSP first_section_sp(m_section_list->GetSectionAtIndex(0));
1970 if (first_section_sp)
1971 filename = first_section_sp->GetObjectFile()->GetFileSpec().GetPath();
1972
1974 llvm::formatv("unable to find section {0} for a symbol in "
1975 "{1}, corrupt file?",
1976 n_sect, filename));
1977 }
1978 }
1979 if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
1980 // Symbol is in section.
1981 return m_section_infos[n_sect].section_sp;
1982 } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1983 m_section_infos[n_sect].vm_range.GetRangeBase() == file_addr) {
1984 // Symbol is in section with zero size, but has the same start address
1985 // as the section. This can happen with linker symbols (symbols that
1986 // start with the letter 'l' or 'L'.
1987 return m_section_infos[n_sect].section_sp;
1988 }
1989 }
1990 return m_section_list->FindSectionContainingFileAddress(file_addr);
1991 }
1992
1993protected:
2001 std::vector<SectionInfo> m_section_infos;
2002};
2003
2004static bool
2005TryParseV2ObjCMetadataSymbol(const char *&symbol_name,
2006 const char *&symbol_name_non_abi_mangled,
2007 SymbolType &type) {
2008 static constexpr llvm::StringLiteral g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2009 static constexpr llvm::StringLiteral g_objc_v2_prefix_metaclass(
2010 "_OBJC_METACLASS_$_");
2011 static constexpr llvm::StringLiteral g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2012
2013 llvm::StringRef symbol_name_ref(symbol_name);
2014 if (symbol_name_ref.empty())
2015 return false;
2016
2017 if (symbol_name_ref.starts_with(g_objc_v2_prefix_class)) {
2018 symbol_name_non_abi_mangled = symbol_name + 1;
2019 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
2020 type = eSymbolTypeObjCClass;
2021 return true;
2022 }
2023
2024 if (symbol_name_ref.starts_with(g_objc_v2_prefix_metaclass)) {
2025 symbol_name_non_abi_mangled = symbol_name + 1;
2026 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
2028 return true;
2029 }
2030
2031 if (symbol_name_ref.starts_with(g_objc_v2_prefix_ivar)) {
2032 symbol_name_non_abi_mangled = symbol_name + 1;
2033 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
2034 type = eSymbolTypeObjCIVar;
2035 return true;
2036 }
2037
2038 return false;
2039}
2040
2041static SymbolType GetSymbolType(const char *&symbol_name,
2042 bool &demangled_is_synthesized,
2043 const SectionSP &text_section_sp,
2044 const SectionSP &data_section_sp,
2045 const SectionSP &data_dirty_section_sp,
2046 const SectionSP &data_const_section_sp,
2047 const SectionSP &symbol_section) {
2049
2050 llvm::StringRef symbol_sect_name = symbol_section->GetName();
2051 if (symbol_section->IsDescendant(text_section_sp.get())) {
2052 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
2053 S_ATTR_SELF_MODIFYING_CODE |
2054 S_ATTR_SOME_INSTRUCTIONS))
2055 type = eSymbolTypeData;
2056 else
2057 type = eSymbolTypeCode;
2058 } else if (symbol_section->IsDescendant(data_section_sp.get()) ||
2059 symbol_section->IsDescendant(data_dirty_section_sp.get()) ||
2060 symbol_section->IsDescendant(data_const_section_sp.get())) {
2061 if (symbol_sect_name.starts_with("__objc")) {
2062 type = eSymbolTypeRuntime;
2063
2064 if (symbol_name) {
2065 llvm::StringRef symbol_name_ref(symbol_name);
2066 if (symbol_name_ref.starts_with("OBJC_")) {
2067 static const llvm::StringRef g_objc_v2_prefix_class("OBJC_CLASS_$_");
2068 static const llvm::StringRef g_objc_v2_prefix_metaclass(
2069 "OBJC_METACLASS_$_");
2070 static const llvm::StringRef g_objc_v2_prefix_ivar("OBJC_IVAR_$_");
2071 if (symbol_name_ref.starts_with(g_objc_v2_prefix_class)) {
2072 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
2073 type = eSymbolTypeObjCClass;
2074 demangled_is_synthesized = true;
2075 } else if (symbol_name_ref.starts_with(g_objc_v2_prefix_metaclass)) {
2076 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
2078 demangled_is_synthesized = true;
2079 } else if (symbol_name_ref.starts_with(g_objc_v2_prefix_ivar)) {
2080 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
2081 type = eSymbolTypeObjCIVar;
2082 demangled_is_synthesized = true;
2083 }
2084 }
2085 }
2086 } else if (symbol_sect_name.starts_with("__gcc_except_tab")) {
2087 type = eSymbolTypeException;
2088 } else {
2089 type = eSymbolTypeData;
2090 }
2091 } else if (symbol_sect_name.starts_with("__IMPORT")) {
2092 type = eSymbolTypeTrampoline;
2093 }
2094 return type;
2095}
2096
2097static std::optional<struct nlist_64>
2098ParseNList(DataExtractor &nlist_data, lldb::offset_t &nlist_data_offset,
2099 size_t nlist_byte_size) {
2100 struct nlist_64 nlist;
2101 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
2102 return {};
2103 nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
2104 nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
2105 nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
2106 nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
2107 nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
2108 return nlist;
2109}
2110
2112 const struct nlist_64 &nlist,
2113 bool &has_source_files,
2114 bool &has_debug_map) {
2115 if (type == eSymbolTypeSourceFile)
2116 has_source_files = true;
2117 else if (type == eSymbolTypeObjectFile && nlist.n_type == N_OSO &&
2118 nlist.n_desc == 1)
2119 has_debug_map = true;
2120}
2121
2122enum { DebugSymbols = true, NonDebugSymbols = false };
2123
2125 ModuleSP module_sp(GetModule());
2126 if (!module_sp)
2127 return;
2128
2129 Log *log = GetLog(LLDBLog::Symbols);
2130
2131 const FileSpec &file = m_file ? m_file : module_sp->GetFileSpec();
2132 llvm::StringRef file_name = file.GetFilename().nonEmptyOr("<Unknown>");
2133 LLDB_SCOPED_TIMERF("ObjectFileMachO::ParseSymtab () module = %s",
2134 file_name.str().c_str());
2135 LLDB_LOG(log, "Parsing symbol table for {0}", file_name);
2136 Progress progress("Parsing symbol table", file_name.str());
2137
2138 LinkeditDataCommandLargeOffsets function_starts_load_command;
2139 LinkeditDataCommandLargeOffsets exports_trie_load_command;
2142 SymtabCommandLargeOffsets symtab_load_command;
2143 // The data element of type bool indicates that this entry is thumb
2144 // code.
2145 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2146
2147 // Record the address of every function/data that we add to the symtab.
2148 // We add symbols to the table in the order of most information (nlist
2149 // records) to least (function starts), and avoid duplicating symbols
2150 // via this set.
2151 llvm::DenseSet<addr_t> symbols_added;
2152
2153 // We are using a llvm::DenseSet for "symbols_added" so we must be sure we
2154 // do not add the empty key to the set.
2155 auto add_symbol_addr = [&symbols_added](lldb::addr_t file_addr) {
2156 // Don't add the empty key.
2157 if (file_addr == UINT64_MAX)
2158 return;
2159 symbols_added.insert(file_addr);
2160 };
2161 FunctionStarts function_starts;
2163 uint32_t i;
2164 FileSpecList dylib_files;
2165 UUID image_uuid;
2166
2167 for (i = 0; i < m_header.ncmds; ++i) {
2168 const lldb::offset_t cmd_offset = offset;
2169 // Read in the load command and load command size
2170 llvm::MachO::load_command lc;
2171 if (!ReadMachOCommand(*m_data_nsp, offset, lc))
2172 break;
2173 // Watch for the symbol table load command
2174 switch (lc.cmd) {
2175 case LC_SYMTAB: {
2176 llvm::MachO::symtab_command lc_obj;
2177 if (m_data_nsp->GetU32(&offset, &lc_obj.symoff, 4)) {
2178 lc_obj.cmd = lc.cmd;
2179 lc_obj.cmdsize = lc.cmdsize;
2180 symtab_load_command = lc_obj;
2181 }
2182 } break;
2183
2184 case LC_DYLD_INFO:
2185 case LC_DYLD_INFO_ONLY: {
2186 llvm::MachO::dyld_info_command lc_obj;
2187 if (m_data_nsp->GetU32(&offset, &lc_obj.rebase_off, 10)) {
2188 lc_obj.cmd = lc.cmd;
2189 lc_obj.cmdsize = lc.cmdsize;
2190 dyld_info = lc_obj;
2191 }
2192 } break;
2193
2194 case LC_LOAD_DYLIB:
2195 case LC_LOAD_WEAK_DYLIB:
2196 case LC_REEXPORT_DYLIB:
2197 case LC_LOADFVMLIB:
2198 case LC_LOAD_UPWARD_DYLIB: {
2199 uint32_t name_offset = cmd_offset + m_data_nsp->GetU32(&offset);
2200 if (std::optional<llvm::StringRef> path =
2201 m_data_nsp->PeekCStr(name_offset)) {
2202 FileSpec file_spec(*path);
2203 // Strip the path if there is @rpath, @executable, etc so we just use
2204 // the basename
2205 if (path->starts_with("@"))
2206 file_spec.ClearDirectory();
2207
2208 if (lc.cmd == LC_REEXPORT_DYLIB) {
2209 m_reexported_dylibs.AppendIfUnique(file_spec);
2210 }
2211
2212 dylib_files.Append(file_spec);
2213 }
2214 } break;
2215
2216 case LC_DYLD_EXPORTS_TRIE: {
2217 llvm::MachO::linkedit_data_command lc_obj;
2218 lc_obj.cmd = lc.cmd;
2219 lc_obj.cmdsize = lc.cmdsize;
2220 if (m_data_nsp->GetU32(&offset, &lc_obj.dataoff, 2))
2221 exports_trie_load_command = lc_obj;
2222 } break;
2223 case LC_FUNCTION_STARTS: {
2224 llvm::MachO::linkedit_data_command lc_obj;
2225 lc_obj.cmd = lc.cmd;
2226 lc_obj.cmdsize = lc.cmdsize;
2227 if (m_data_nsp->GetU32(&offset, &lc_obj.dataoff, 2))
2228 function_starts_load_command = lc_obj;
2229 } break;
2230
2231 case LC_UUID: {
2232 const uint8_t *uuid_bytes = m_data_nsp->PeekData(offset, 16);
2233
2234 if (uuid_bytes)
2235 image_uuid = UUID(uuid_bytes, 16);
2236 break;
2237 }
2238
2239 default:
2240 break;
2241 }
2242 offset = cmd_offset + lc.cmdsize;
2243 }
2244
2245 if (!symtab_load_command.cmd)
2246 return;
2247
2248 SectionList *section_list = GetSectionList();
2249 if (section_list == nullptr)
2250 return;
2251
2252 bool has_source_files = false;
2253 bool has_debug_map = false;
2254
2255 const uint32_t addr_byte_size = m_data_nsp->GetAddressByteSize();
2256 const ByteOrder byte_order = m_data_nsp->GetByteOrder();
2257 bool bit_width_32 = addr_byte_size == 4;
2258 const size_t nlist_byte_size =
2259 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2260
2261 DataExtractor nlist_data(nullptr, 0, byte_order, addr_byte_size);
2262 DataExtractor strtab_data(nullptr, 0, byte_order, addr_byte_size);
2263 DataExtractor function_starts_data(nullptr, 0, byte_order, addr_byte_size);
2264 DataExtractor indirect_symbol_index_data(nullptr, 0, byte_order,
2265 addr_byte_size);
2266 DataExtractor dyld_trie_data(nullptr, 0, byte_order, addr_byte_size);
2267
2268 const addr_t nlist_data_byte_size =
2269 symtab_load_command.nsyms * nlist_byte_size;
2270 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2271 addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2272
2273 ProcessSP process_sp(m_process_wp.lock());
2274 Process *process = process_sp.get();
2275
2276 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2277 bool is_shared_cache_image = IsSharedCacheBinary();
2278 bool is_local_shared_cache_image = is_shared_cache_image && !IsInMemory();
2279
2280 SectionSP text_section_sp(
2281 section_list->FindSectionByName(GetSegmentNameTEXT()));
2282 SectionSP data_section_sp(
2283 section_list->FindSectionByName(GetSegmentNameDATA()));
2284 SectionSP linkedit_section_sp(
2285 section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2286 SectionSP data_dirty_section_sp(
2287 section_list->FindSectionByName(GetSegmentNameDATA_DIRTY()));
2288 SectionSP data_const_section_sp(
2289 section_list->FindSectionByName(GetSegmentNameDATA_CONST()));
2290 SectionSP objc_section_sp(
2291 section_list->FindSectionByName(GetSegmentNameOBJC()));
2292 SectionSP eh_frame_section_sp;
2293 SectionSP lldb_no_nlist_section_sp;
2294 llvm::StringRef g_section_name_eh_frame = GetSectionNameEHFrame();
2295 llvm::StringRef g_section_name_lldb_no_nlist = GetSectionNameLLDBNoNlist();
2296 if (text_section_sp.get()) {
2297 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2298 g_section_name_eh_frame);
2299 lldb_no_nlist_section_sp = text_section_sp->GetChildren().FindSectionByName(
2300 g_section_name_lldb_no_nlist);
2301 } else {
2302 eh_frame_section_sp =
2303 section_list->FindSectionByName(g_section_name_eh_frame);
2304 lldb_no_nlist_section_sp =
2305 section_list->FindSectionByName(g_section_name_lldb_no_nlist);
2306 }
2307
2308 if (process && m_header.filetype != llvm::MachO::MH_OBJECT &&
2309 !is_local_shared_cache_image) {
2310 Target &target = process->GetTarget();
2311
2312 memory_module_load_level = target.GetMemoryModuleLoadLevel();
2313
2314 // If __TEXT,__lldb_no_nlist section is present in this binary,
2315 // and we're reading it out of memory, do not read any of the
2316 // nlist entries. They are not needed in lldb and it may be
2317 // expensive to load these. This is to handle a dylib consisting
2318 // of only metadata, no code, but it has many nlist entries.
2319 if (lldb_no_nlist_section_sp)
2320 memory_module_load_level = eMemoryModuleLoadLevelMinimal;
2321
2322 // Reading mach file from memory in a process or core file...
2323
2324 if (linkedit_section_sp) {
2325 addr_t linkedit_load_addr =
2326 linkedit_section_sp->GetLoadBaseAddress(&target);
2327 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2328 // We might be trying to access the symbol table before the
2329 // __LINKEDIT's load address has been set in the target. We can't
2330 // fail to read the symbol table, so calculate the right address
2331 // manually
2332 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2333 m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2334 }
2335
2336 const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset();
2337 const addr_t symoff_addr = linkedit_load_addr +
2338 symtab_load_command.symoff -
2339 linkedit_file_offset;
2340 strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2341 linkedit_file_offset;
2342
2343 // Always load dyld - the dynamic linker - from memory if we didn't
2344 // find a binary anywhere else. lldb will not register
2345 // dylib/framework/bundle loads/unloads if we don't have the dyld
2346 // symbols, we force dyld to load from memory despite the user's
2347 // target.memory-module-load-level setting.
2348 if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2349 m_header.filetype == llvm::MachO::MH_DYLINKER) {
2350 DataBufferSP nlist_data_sp(
2351 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2352 if (nlist_data_sp)
2353 nlist_data.SetData(nlist_data_sp, 0, nlist_data_sp->GetByteSize());
2354 if (dysymtab.nindirectsyms != 0) {
2355 const addr_t indirect_syms_addr = linkedit_load_addr +
2356 dysymtab.indirectsymoff -
2357 linkedit_file_offset;
2358 DataBufferSP indirect_syms_data_sp(ReadMemory(
2359 process_sp, indirect_syms_addr, dysymtab.nindirectsyms * 4));
2360 if (indirect_syms_data_sp)
2361 indirect_symbol_index_data.SetData(
2362 indirect_syms_data_sp, 0, indirect_syms_data_sp->GetByteSize());
2363 // If this binary is outside the shared cache,
2364 // cache the string table.
2365 // Binaries in the shared cache all share a giant string table,
2366 // and we can't share the string tables across multiple
2367 // ObjectFileMachO's, so we'd end up re-reading this mega-strtab
2368 // for every binary in the shared cache - it would be a big perf
2369 // problem. For binaries outside the shared cache, it's faster to
2370 // read the entire strtab at once instead of piece-by-piece as we
2371 // process the nlist records.
2372 if (!is_shared_cache_image) {
2373 DataBufferSP strtab_data_sp(
2374 ReadMemory(process_sp, strtab_addr, strtab_data_byte_size));
2375 if (strtab_data_sp) {
2376 strtab_data.SetData(strtab_data_sp, 0,
2377 strtab_data_sp->GetByteSize());
2378 }
2379 }
2380 }
2381 if (memory_module_load_level >= eMemoryModuleLoadLevelPartial) {
2382 if (function_starts_load_command.cmd) {
2383 const addr_t func_start_addr =
2384 linkedit_load_addr + function_starts_load_command.dataoff -
2385 linkedit_file_offset;
2386 DataBufferSP func_start_data_sp(
2387 ReadMemory(process_sp, func_start_addr,
2388 function_starts_load_command.datasize));
2389 if (func_start_data_sp)
2390 function_starts_data.SetData(func_start_data_sp, 0,
2391 func_start_data_sp->GetByteSize());
2392 }
2393 }
2394 }
2395 }
2396 } else {
2397 if (is_local_shared_cache_image && linkedit_section_sp) {
2398 // The load commands in shared cache images are relative to the
2399 // beginning of the shared cache, not the library image. The
2400 // data we get handed when creating the ObjectFileMachO starts
2401 // at the beginning of a specific library and spans to the end
2402 // of the cache to be able to reach the shared LINKEDIT
2403 // segments. We need to convert the load command offsets to be
2404 // relative to the beginning of our specific image.
2405 lldb::addr_t linkedit_offset = linkedit_section_sp->GetFileOffset();
2406 lldb::offset_t linkedit_slide =
2407 linkedit_offset - m_linkedit_original_offset;
2408 symtab_load_command.symoff += linkedit_slide;
2409 symtab_load_command.stroff += linkedit_slide;
2410 dyld_info.export_off += linkedit_slide;
2411 dysymtab.indirectsymoff += linkedit_slide;
2412 function_starts_load_command.dataoff += linkedit_slide;
2413 exports_trie_load_command.dataoff += linkedit_slide;
2414 }
2415
2416 nlist_data = *m_data_nsp->GetSubsetExtractorSP(symtab_load_command.symoff,
2417 nlist_data_byte_size);
2418 strtab_data = *m_data_nsp->GetSubsetExtractorSP(symtab_load_command.stroff,
2419 strtab_data_byte_size);
2420
2421 // We shouldn't have exports data from both the LC_DYLD_INFO command
2422 // AND the LC_DYLD_EXPORTS_TRIE command in the same binary:
2423 lldbassert(!((dyld_info.export_size > 0)
2424 && (exports_trie_load_command.datasize > 0)));
2425 if (dyld_info.export_size > 0) {
2426 dyld_trie_data = *m_data_nsp->GetSubsetExtractorSP(dyld_info.export_off,
2427 dyld_info.export_size);
2428 } else if (exports_trie_load_command.datasize > 0) {
2429 dyld_trie_data =
2430 *m_data_nsp->GetSubsetExtractorSP(exports_trie_load_command.dataoff,
2431 exports_trie_load_command.datasize);
2432 }
2433
2434 if (dysymtab.nindirectsyms != 0) {
2435 indirect_symbol_index_data = *m_data_nsp->GetSubsetExtractorSP(
2436 dysymtab.indirectsymoff, dysymtab.nindirectsyms * 4);
2437 }
2438 if (function_starts_load_command.cmd) {
2439 function_starts_data = *m_data_nsp->GetSubsetExtractorSP(
2440 function_starts_load_command.dataoff,
2441 function_starts_load_command.datasize);
2442 }
2443 }
2444
2445 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
2446 const bool always_thumb = GetArchitecture().IsAlwaysThumbInstructions();
2447
2448 // lldb works best if it knows the start address of all functions in a
2449 // module. Linker symbols or debug info are normally the best source of
2450 // information for start addr / size but they may be stripped in a released
2451 // binary. Two additional sources of information exist in Mach-O binaries:
2452 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2453 // function's start address in the
2454 // binary, relative to the text section.
2455 // eh_frame - the eh_frame FDEs have the start addr & size of
2456 // each function
2457 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2458 // all modern binaries.
2459 // Binaries built to run on older releases may need to use eh_frame
2460 // information.
2461
2462 if (text_section_sp && function_starts_data.GetByteSize()) {
2463 FunctionStarts::Entry function_start_entry;
2464 function_start_entry.data = false;
2465 lldb::offset_t function_start_offset = 0;
2466 function_start_entry.addr = text_section_sp->GetFileAddress();
2467 uint64_t delta;
2468 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2469 0) {
2470 // Now append the current entry
2471 function_start_entry.addr += delta;
2472 if (is_arm) {
2473 if (function_start_entry.addr & 1) {
2474 function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK;
2475 function_start_entry.data = true;
2476 } else if (always_thumb) {
2477 function_start_entry.data = true;
2478 }
2479 }
2480 function_starts.Append(function_start_entry);
2481 }
2482 } else {
2483 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
2484 // load command claiming an eh_frame but it doesn't actually have the
2485 // eh_frame content. And if we have a dSYM, we don't need to do any of
2486 // this fill-in-the-missing-symbols works anyway - the debug info should
2487 // give us all the functions in the module.
2488 if (text_section_sp.get() && eh_frame_section_sp.get() &&
2490 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
2493 eh_frame.GetFunctionAddressAndSizeVector(functions);
2494 addr_t text_base_addr = text_section_sp->GetFileAddress();
2495 size_t count = functions.GetSize();
2496 for (size_t i = 0; i < count; ++i) {
2498 functions.GetEntryAtIndex(i);
2499 if (func) {
2500 FunctionStarts::Entry function_start_entry;
2501 function_start_entry.addr = func->base - text_base_addr;
2502 if (is_arm) {
2503 if (function_start_entry.addr & 1) {
2504 function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK;
2505 function_start_entry.data = true;
2506 } else if (always_thumb) {
2507 function_start_entry.data = true;
2508 }
2509 }
2510 function_starts.Append(function_start_entry);
2511 }
2512 }
2513 }
2514 }
2515
2516 const size_t function_starts_count = function_starts.GetSize();
2517
2518 // For user process binaries (executables, dylibs, frameworks, bundles), if
2519 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2520 // going to assume the binary has been stripped. Don't allow assembly
2521 // language instruction emulation because we don't know proper function
2522 // start boundaries.
2523 //
2524 // For all other types of binaries (kernels, stand-alone bare board
2525 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2526 // sections - we should not make any assumptions about them based on that.
2527 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2529 Log *unwind_or_symbol_log(GetLog(LLDBLog::Symbols | LLDBLog::Unwind));
2530
2531 if (unwind_or_symbol_log)
2532 module_sp->LogMessage(
2533 unwind_or_symbol_log,
2534 "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2535 }
2536
2537 const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get()
2538 ? eh_frame_section_sp->GetID()
2539 : static_cast<user_id_t>(NO_SECT);
2540
2541 uint32_t N_SO_index = UINT32_MAX;
2542
2543 MachSymtabSectionInfo section_info(section_list);
2544 std::vector<uint32_t> N_FUN_indexes;
2545 std::vector<uint32_t> N_NSYM_indexes;
2546 std::vector<uint32_t> N_INCL_indexes;
2547 std::vector<uint32_t> N_BRAC_indexes;
2548 std::vector<uint32_t> N_COMM_indexes;
2549 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2550 typedef llvm::DenseMap<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2551 typedef llvm::DenseMap<const char *, uint32_t> ConstNameToSymbolIndexMap;
2552 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2553 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2554 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
2555 // Any symbols that get merged into another will get an entry in this map
2556 // so we know
2557 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2558 Symbol *symbol_ptr = nullptr;
2559
2560 uint32_t sym_idx = 0;
2561 Symbol *sym = nullptr;
2562 size_t num_syms = 0;
2563 std::string memory_symbol_name;
2564 uint32_t unmapped_local_symbols_found = 0;
2565
2566 std::vector<TrieEntryWithOffset> reexport_trie_entries;
2567 std::vector<TrieEntryWithOffset> external_sym_trie_entries;
2568 std::set<lldb::addr_t> resolver_addresses;
2569
2570 const size_t dyld_trie_data_size = dyld_trie_data.GetByteSize();
2571 if (dyld_trie_data_size > 0) {
2572 LLDB_LOG(log, "Parsing {0} bytes of dyld trie data", dyld_trie_data_size);
2573 SectionSP text_segment_sp =
2575 lldb::addr_t text_segment_file_addr = LLDB_INVALID_ADDRESS;
2576 if (text_segment_sp)
2577 text_segment_file_addr = text_segment_sp->GetFileAddress();
2578 ParseTrieEntries(dyld_trie_data, is_arm, text_segment_file_addr,
2579 resolver_addresses, reexport_trie_entries,
2580 external_sym_trie_entries);
2581 }
2582
2583 typedef std::set<ConstString> IndirectSymbols;
2584 IndirectSymbols indirect_symbol_names;
2585
2586 typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
2587 typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
2588 UndefinedNameToDescMap undefined_name_to_desc;
2589 SymbolIndexToName reexport_shlib_needs_fixup;
2590
2591 // Symbol merging depends on the debug symbols being parsed first, so this
2592 // lambda runs twice: once for the debug symbols, then for the rest.
2593 auto ParseSymbolLambda = [&](struct nlist_64 &nlist, uint32_t nlist_idx,
2594 bool debug_only, const DataExtractor &strtab) {
2595 const bool is_debug = ((nlist.n_type & N_STAB) != 0);
2596 if (is_debug != debug_only)
2597 return;
2598
2599 const char *symbol_name_non_abi_mangled = nullptr;
2600 const char *symbol_name = nullptr;
2601
2602 if (strtab.GetByteSize() > 0) {
2603 std::optional<llvm::StringRef> name = strtab.PeekCStr(nlist.n_strx);
2604
2605 if (!name) {
2606 // No symbol should be NULL, even the symbols with no string values
2607 // should have an offset zero which points to an empty C-string
2608 // DSC unmapped locals are numbered from nsyms.
2609 const bool is_dsc_local = nlist_idx >= symtab_load_command.nsyms;
2610 Debugger::ReportError(llvm::formatv(
2611 "{0}symbol[{1}] has invalid or unterminated string table offset "
2612 "{2:x} in {3}, ignoring symbol",
2613 is_dsc_local ? "DSC unmapped local " : "",
2614 is_dsc_local ? nlist_idx - symtab_load_command.nsyms : nlist_idx,
2615 nlist.n_strx, module_sp->GetFileSpec().GetPath()));
2616 return;
2617 }
2618 // The code below spells "no name" as a nullptr.
2619 if (!name->empty())
2620 symbol_name = name->data();
2621 } else {
2622 const addr_t str_addr = strtab_addr + nlist.n_strx;
2623 Status str_error;
2624 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
2625 str_error))
2626 symbol_name = memory_symbol_name.c_str();
2627 }
2628
2630 SectionSP symbol_section;
2631 bool add_nlist = true;
2632 bool is_gsym = false;
2633 bool demangled_is_synthesized = false;
2634 bool set_value = true;
2635
2636 assert(sym_idx < num_syms);
2637 sym[sym_idx].SetDebug(is_debug);
2638
2639 if (is_debug) {
2640 switch (nlist.n_type) {
2641 case N_GSYM: {
2642 // global symbol: name,,NO_SECT,type,0
2643 // Sometimes the N_GSYM value contains the address.
2644
2645 // FIXME: In the .o files, we have a GSYM and a debug symbol for all
2646 // the ObjC data. They
2647 // have the same address, but we want to ensure that we always find
2648 // only the real symbol, 'cause we don't currently correctly
2649 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
2650 // type. This is a temporary hack to make sure the ObjectiveC
2651 // symbols get treated correctly. To do this right, we should
2652 // coalesce all the GSYM & global symbols that have the same
2653 // address.
2654 is_gsym = true;
2655 sym[sym_idx].SetExternal(true);
2656
2657 if (TryParseV2ObjCMetadataSymbol(symbol_name,
2658 symbol_name_non_abi_mangled, type)) {
2659 demangled_is_synthesized = true;
2660 } else {
2661 if (nlist.n_value != 0)
2662 symbol_section =
2663 section_info.GetSection(nlist.n_sect, nlist.n_value);
2664
2665 type = eSymbolTypeData;
2666 }
2667 } break;
2668
2669 case N_FNAME:
2670 // procedure name (f77 kludge): name,,NO_SECT,0,0
2671 type = eSymbolTypeCompiler;
2672 break;
2673
2674 case N_FUN:
2675 // procedure: name,,n_sect,linenumber,address
2676 if (symbol_name) {
2677 type = eSymbolTypeCode;
2678 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
2679
2680 N_FUN_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx));
2681 // We use the current number of symbols in the symbol table in
2682 // lieu of using nlist_idx in case we ever start trimming entries
2683 // out
2684 N_FUN_indexes.push_back(sym_idx);
2685 } else {
2686 type = eSymbolTypeCompiler;
2687
2688 if (!N_FUN_indexes.empty()) {
2689 // Copy the size of the function into the original STAB entry
2690 // so we don't have to hunt for it later
2691 symtab.SymbolAtIndex(N_FUN_indexes.back())
2692 ->SetByteSize(nlist.n_value);
2693 N_FUN_indexes.pop_back();
2694 // We don't really need the end function STAB as it contains
2695 // the size which we already placed with the original symbol,
2696 // so don't add it if we want a minimal symbol table
2697 add_nlist = false;
2698 }
2699 }
2700 break;
2701
2702 case N_STSYM:
2703 // static symbol: name,,n_sect,type,address
2704 N_STSYM_addr_to_sym_idx.insert(std::make_pair(nlist.n_value, sym_idx));
2705 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
2706 if (symbol_name && symbol_name[0]) {
2707 type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
2709 }
2710 break;
2711
2712 case N_LCSYM:
2713 // .lcomm symbol: name,,n_sect,type,address
2714 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
2716 break;
2717
2718 case N_BNSYM:
2719 // We use the current number of symbols in the symbol table in lieu
2720 // of using nlist_idx in case we ever start trimming entries out
2721 // Skip these if we want minimal symbol tables
2722 add_nlist = false;
2723 break;
2724
2725 case N_ENSYM:
2726 // Set the size of the N_BNSYM to the terminating index of this
2727 // N_ENSYM so that we can always skip the entire symbol if we need
2728 // to navigate more quickly at the source level when parsing STABS
2729 // Skip these if we want minimal symbol tables
2730 add_nlist = false;
2731 break;
2732
2733 case N_OPT:
2734 // emitted with gcc2_compiled and in gcc source
2735 type = eSymbolTypeCompiler;
2736 break;
2737
2738 case N_RSYM:
2739 // register sym: name,,NO_SECT,type,register
2740 type = eSymbolTypeVariable;
2741 break;
2742
2743 case N_SLINE:
2744 // src line: 0,,n_sect,linenumber,address
2745 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
2746 type = eSymbolTypeLineEntry;
2747 break;
2748
2749 case N_SSYM:
2750 // structure elt: name,,NO_SECT,type,struct_offset
2752 break;
2753
2754 case N_SO:
2755 // source file name
2756 type = eSymbolTypeSourceFile;
2757 if (symbol_name == nullptr) {
2758 add_nlist = false;
2759 if (N_SO_index != UINT32_MAX) {
2760 // Set the size of the N_SO to the terminating index of this
2761 // N_SO so that we can always skip the entire N_SO if we need
2762 // to navigate more quickly at the source level when parsing
2763 // STABS
2764 symbol_ptr = symtab.SymbolAtIndex(N_SO_index);
2765 symbol_ptr->SetByteSize(sym_idx);
2766 symbol_ptr->SetSizeIsSibling(true);
2767 }
2768 N_NSYM_indexes.clear();
2769 N_INCL_indexes.clear();
2770 N_BRAC_indexes.clear();
2771 N_COMM_indexes.clear();
2772 N_FUN_indexes.clear();
2773 N_SO_index = UINT32_MAX;
2774 } else {
2775 // We use the current number of symbols in the symbol table in
2776 // lieu of using nlist_idx in case we ever start trimming entries
2777 // out
2778 const bool N_SO_has_full_path = symbol_name[0] == '/';
2779 if (N_SO_has_full_path) {
2780 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
2781 // We have two consecutive N_SO entries where the first
2782 // contains a directory and the second contains a full path.
2783 sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name));
2784 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
2785 add_nlist = false;
2786 } else {
2787 // This is the first entry in a N_SO that contains a
2788 // directory or a full path to the source file
2789 N_SO_index = sym_idx;
2790 }
2791 } else if ((N_SO_index == sym_idx - 1) &&
2792 ((sym_idx - 1) < num_syms)) {
2793 // This is usually the second N_SO entry that contains just the
2794 // filename, so here we combine it with the first one if we are
2795 // minimizing the symbol table
2796 llvm::StringRef so_path =
2797 sym[sym_idx - 1].GetMangled().GetDemangledName().GetStringRef();
2798 if (!so_path.empty()) {
2799 std::string full_so_path(so_path);
2800 const size_t double_slash_pos = full_so_path.find("//");
2801 if (double_slash_pos != std::string::npos) {
2802 // The linker has been generating bad N_SO entries with
2803 // doubled up paths in the format "%s%s" where the first
2804 // string in the DW_AT_comp_dir, and the second is the
2805 // directory for the source file so you end up with a path
2806 // that looks like "/tmp/src//tmp/src/"
2807 FileSpec so_dir(so_path);
2808 if (!FileSystem::Instance().Exists(so_dir)) {
2809 so_dir.SetFile(&full_so_path[double_slash_pos + 1],
2810 FileSpec::Style::native);
2811 if (FileSystem::Instance().Exists(so_dir)) {
2812 // Trim off the incorrect path
2813 full_so_path.erase(0, double_slash_pos + 1);
2814 }
2815 }
2816 }
2817 if (*full_so_path.rbegin() != '/')
2818 full_so_path += '/';
2819 full_so_path += symbol_name;
2820 sym[sym_idx - 1].GetMangled().SetValue(
2821 ConstString(full_so_path.c_str()));
2822 add_nlist = false;
2823 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
2824 }
2825 } else {
2826 // This could be a relative path to a N_SO
2827 N_SO_index = sym_idx;
2828 }
2829 }
2830 break;
2831
2832 case N_OSO:
2833 // object file name: name,,0,0,st_mtime
2834 type = eSymbolTypeObjectFile;
2835 break;
2836
2837 case N_LSYM:
2838 // local sym: name,,NO_SECT,type,offset
2839 type = eSymbolTypeLocal;
2840 break;
2841
2842 // INCL scopes
2843 case N_BINCL:
2844 // include file beginning: name,,NO_SECT,0,sum We use the current
2845 // number of symbols in the symbol table in lieu of using nlist_idx
2846 // in case we ever start trimming entries out
2847 N_INCL_indexes.push_back(sym_idx);
2848 type = eSymbolTypeScopeBegin;
2849 break;
2850
2851 case N_EINCL:
2852 // include file end: name,,NO_SECT,0,0
2853 // Set the size of the N_BINCL to the terminating index of this
2854 // N_EINCL so that we can always skip the entire symbol if we need
2855 // to navigate more quickly at the source level when parsing STABS
2856 if (!N_INCL_indexes.empty()) {
2857 symbol_ptr = symtab.SymbolAtIndex(N_INCL_indexes.back());
2858 symbol_ptr->SetByteSize(sym_idx + 1);
2859 symbol_ptr->SetSizeIsSibling(true);
2860 N_INCL_indexes.pop_back();
2861 }
2862 type = eSymbolTypeScopeEnd;
2863 break;
2864
2865 case N_SOL:
2866 // #included file name: name,,n_sect,0,address
2867 type = eSymbolTypeHeaderFile;
2868
2869 // We currently don't use the header files on darwin
2870 add_nlist = false;
2871 break;
2872
2873 case N_PARAMS:
2874 // compiler parameters: name,,NO_SECT,0,0
2875 type = eSymbolTypeCompiler;
2876 break;
2877
2878 case N_VERSION:
2879 // compiler version: name,,NO_SECT,0,0
2880 type = eSymbolTypeCompiler;
2881 break;
2882
2883 case N_OLEVEL:
2884 // compiler -O level: name,,NO_SECT,0,0
2885 type = eSymbolTypeCompiler;
2886 break;
2887
2888 case N_PSYM:
2889 // parameter: name,,NO_SECT,type,offset
2890 type = eSymbolTypeVariable;
2891 break;
2892
2893 case N_ENTRY:
2894 // alternate entry: name,,n_sect,linenumber,address
2895 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
2896 type = eSymbolTypeLineEntry;
2897 break;
2898
2899 // Left and Right Braces
2900 case N_LBRAC:
2901 // left bracket: 0,,NO_SECT,nesting level,address We use the
2902 // current number of symbols in the symbol table in lieu of using
2903 // nlist_idx in case we ever start trimming entries out
2904 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
2905 N_BRAC_indexes.push_back(sym_idx);
2906 type = eSymbolTypeScopeBegin;
2907 break;
2908
2909 case N_RBRAC:
2910 // right bracket: 0,,NO_SECT,nesting level,address Set the size of
2911 // the N_LBRAC to the terminating index of this N_RBRAC so that we
2912 // can always skip the entire symbol if we need to navigate more
2913 // quickly at the source level when parsing STABS
2914 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
2915 if (!N_BRAC_indexes.empty()) {
2916 symbol_ptr = symtab.SymbolAtIndex(N_BRAC_indexes.back());
2917 symbol_ptr->SetByteSize(sym_idx + 1);
2918 symbol_ptr->SetSizeIsSibling(true);
2919 N_BRAC_indexes.pop_back();
2920 }
2921 type = eSymbolTypeScopeEnd;
2922 break;
2923
2924 case N_EXCL:
2925 // deleted include file: name,,NO_SECT,0,sum
2926 type = eSymbolTypeHeaderFile;
2927 break;
2928
2929 // COMM scopes
2930 case N_BCOMM:
2931 // begin common: name,,NO_SECT,0,0
2932 // We use the current number of symbols in the symbol table in lieu
2933 // of using nlist_idx in case we ever start trimming entries out
2934 type = eSymbolTypeScopeBegin;
2935 N_COMM_indexes.push_back(sym_idx);
2936 break;
2937
2938 case N_ECOML:
2939 // end common (local name): 0,,n_sect,0,address
2940 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
2941 [[fallthrough]];
2942
2943 case N_ECOMM:
2944 // end common: name,,n_sect,0,0
2945 // Set the size of the N_BCOMM to the terminating index of this
2946 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
2947 // we need to navigate more quickly at the source level when
2948 // parsing STABS
2949 if (!N_COMM_indexes.empty()) {
2950 symbol_ptr = symtab.SymbolAtIndex(N_COMM_indexes.back());
2951 symbol_ptr->SetByteSize(sym_idx + 1);
2952 symbol_ptr->SetSizeIsSibling(true);
2953 N_COMM_indexes.pop_back();
2954 }
2955 type = eSymbolTypeScopeEnd;
2956 break;
2957
2958 case N_LENG:
2959 // second stab entry with length information
2960 type = eSymbolTypeAdditional;
2961 break;
2962
2963 case N_AST:
2964 // AST file path: name,,NO_SECT,0,0
2965 type = eSymbolTypeASTFile;
2966 break;
2967
2968 default:
2969 break;
2970 }
2971 } else {
2972 uint8_t n_type = N_TYPE & nlist.n_type;
2973 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
2974
2975 switch (n_type) {
2976 case N_INDR: {
2977 std::optional<llvm::StringRef> reexport_name_str =
2978 strtab.PeekCStr(nlist.n_value);
2979 if (reexport_name_str && !reexport_name_str->empty() && symbol_name) {
2980 type = eSymbolTypeReExported;
2981 ConstString reexport_name(reexport_name_str->drop_front(
2982 reexport_name_str->front() == '_' ? 1 : 0));
2983 sym[sym_idx].SetReExportedSymbolName(reexport_name);
2984 set_value = false;
2985 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
2986 indirect_symbol_names.insert(
2987 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
2988 } else
2989 type = eSymbolTypeUndefined;
2990 } break;
2991
2992 case N_UNDF:
2993 if (symbol_name && symbol_name[0]) {
2994 ConstString undefined_name(symbol_name +
2995 ((symbol_name[0] == '_') ? 1 : 0));
2996 undefined_name_to_desc[undefined_name] = nlist.n_desc;
2997 }
2998 [[fallthrough]];
2999
3000 case N_PBUD:
3001 type = eSymbolTypeUndefined;
3002 break;
3003
3004 case N_ABS:
3005 type = eSymbolTypeAbsolute;
3006 break;
3007
3008 case N_SECT: {
3009 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3010
3011 if (!symbol_section) {
3012 // TODO: warn about this?
3013 add_nlist = false;
3014 break;
3015 }
3016
3017 if (TEXT_eh_frame_sectID == nlist.n_sect) {
3018 type = eSymbolTypeException;
3019 } else {
3020 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
3021
3022 switch (section_type) {
3023 case S_CSTRING_LITERALS:
3024 type = eSymbolTypeData;
3025 break; // section with only literal C strings
3026 case S_4BYTE_LITERALS:
3027 type = eSymbolTypeData;
3028 break; // section with only 4 byte literals
3029 case S_8BYTE_LITERALS:
3030 type = eSymbolTypeData;
3031 break; // section with only 8 byte literals
3032 case S_LITERAL_POINTERS:
3033 type = eSymbolTypeTrampoline;
3034 break; // section with only pointers to literals
3035 case S_NON_LAZY_SYMBOL_POINTERS:
3036 type = eSymbolTypeTrampoline;
3037 break; // section with only non-lazy symbol pointers
3038 case S_LAZY_SYMBOL_POINTERS:
3039 type = eSymbolTypeTrampoline;
3040 break; // section with only lazy symbol pointers
3041 case S_SYMBOL_STUBS:
3042 type = eSymbolTypeTrampoline;
3043 break; // section with only symbol stubs, byte size of stub in
3044 // the reserved2 field
3045 case S_MOD_INIT_FUNC_POINTERS:
3046 type = eSymbolTypeCode;
3047 break; // section with only function pointers for initialization
3048 case S_MOD_TERM_FUNC_POINTERS:
3049 type = eSymbolTypeCode;
3050 break; // section with only function pointers for termination
3051 case S_INTERPOSING:
3052 type = eSymbolTypeTrampoline;
3053 break; // section with only pairs of function pointers for
3054 // interposing
3055 case S_16BYTE_LITERALS:
3056 type = eSymbolTypeData;
3057 break; // section with only 16 byte literals
3058 case S_DTRACE_DOF:
3060 break;
3061 case S_LAZY_DYLIB_SYMBOL_POINTERS:
3062 type = eSymbolTypeTrampoline;
3063 break;
3064 default:
3065 switch (symbol_section->GetType()) {
3067 type = eSymbolTypeCode;
3068 break;
3069 case eSectionTypeData:
3070 case eSectionTypeDataCString: // Inlined C string data
3071 case eSectionTypeDataCStringPointers: // Pointers to C string
3072 // data
3073 case eSectionTypeDataSymbolAddress: // Address of a symbol in
3074 // the symbol table
3075 case eSectionTypeData4:
3076 case eSectionTypeData8:
3077 case eSectionTypeData16:
3078 type = eSymbolTypeData;
3079 break;
3080 default:
3081 break;
3082 }
3083 break;
3084 }
3085
3086 if (type == eSymbolTypeInvalid) {
3087 llvm::StringRef symbol_sect_name = symbol_section->GetName();
3088 if (symbol_section->IsDescendant(text_section_sp.get())) {
3089 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
3090 S_ATTR_SELF_MODIFYING_CODE |
3091 S_ATTR_SOME_INSTRUCTIONS))
3092 type = eSymbolTypeData;
3093 else
3094 type = eSymbolTypeCode;
3095 } else if (symbol_section->IsDescendant(data_section_sp.get()) ||
3096 symbol_section->IsDescendant(
3097 data_dirty_section_sp.get()) ||
3098 symbol_section->IsDescendant(
3099 data_const_section_sp.get())) {
3100 if (symbol_sect_name.starts_with("__objc")) {
3101 type = eSymbolTypeRuntime;
3102
3104 symbol_name, symbol_name_non_abi_mangled, type))
3105 demangled_is_synthesized = true;
3106 } else if (symbol_sect_name.starts_with("__gcc_except_tab")) {
3107 type = eSymbolTypeException;
3108 } else {
3109 type = eSymbolTypeData;
3110 }
3111 } else if (symbol_sect_name.starts_with("__IMPORT")) {
3112 type = eSymbolTypeTrampoline;
3113 } else if (symbol_section->IsDescendant(objc_section_sp.get())) {
3114 type = eSymbolTypeRuntime;
3115 if (symbol_name && symbol_name[0] == '.') {
3116 llvm::StringRef symbol_name_ref(symbol_name);
3117 llvm::StringRef g_objc_v1_prefix_class(".objc_class_name_");
3118 if (symbol_name_ref.starts_with(g_objc_v1_prefix_class)) {
3119 symbol_name_non_abi_mangled = symbol_name;
3120 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
3121 type = eSymbolTypeObjCClass;
3122 demangled_is_synthesized = true;
3123 }
3124 }
3125 }
3126 }
3127 }
3128 } break;
3129 }
3130 }
3131
3132 if (!add_nlist) {
3133 sym[sym_idx].Clear();
3134 return;
3135 }
3136
3137 uint64_t symbol_value = nlist.n_value;
3138
3139 if (symbol_name_non_abi_mangled) {
3140 sym[sym_idx].GetMangled().SetMangledName(
3141 ConstString(symbol_name_non_abi_mangled));
3142 sym[sym_idx].GetMangled().SetDemangledName(ConstString(symbol_name));
3143 } else {
3144
3145 if (symbol_name && symbol_name[0] == '_') {
3146 symbol_name++; // Skip the leading underscore
3147 }
3148
3149 if (symbol_name) {
3150 ConstString const_symbol_name(symbol_name);
3151 sym[sym_idx].GetMangled().SetValue(const_symbol_name);
3152 }
3153 }
3154
3155 if (is_gsym) {
3156 const char *gsym_name = sym[sym_idx]
3157 .GetMangled()
3159 .GetCString();
3160 if (gsym_name)
3161 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3162 }
3163
3164 if (symbol_section) {
3165 const addr_t section_file_addr = symbol_section->GetFileAddress();
3166 symbol_value -= section_file_addr;
3167 }
3168
3169 if (!is_debug) {
3170 if (type == eSymbolTypeCode) {
3171 // See if we can find a N_FUN entry for any code symbols. If we do
3172 // find a match, and the name matches, then we can merge the two into
3173 // just the function symbol to avoid duplicate entries in the symbol
3174 // table.
3175 std::pair<ValueToSymbolIndexMap::const_iterator,
3176 ValueToSymbolIndexMap::const_iterator>
3177 range;
3178 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
3179 if (range.first != range.second) {
3180 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
3181 pos != range.second; ++pos) {
3182 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) ==
3183 sym[pos->second].GetMangled().GetName(
3185 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3186 // We just need the flags from the linker symbol, so put these
3187 // flags into the N_FUN flags to avoid duplicate symbols in the
3188 // symbol table.
3189 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
3190 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
3191 if (resolver_addresses.find(nlist.n_value) !=
3192 resolver_addresses.end())
3193 sym[pos->second].SetType(eSymbolTypeResolver);
3194 sym[sym_idx].Clear();
3195 return;
3196 }
3197 }
3198 } else {
3199 if (resolver_addresses.find(nlist.n_value) !=
3200 resolver_addresses.end())
3201 type = eSymbolTypeResolver;
3202 }
3203 } else if (type == eSymbolTypeData || type == eSymbolTypeObjCClass ||
3204 type == eSymbolTypeObjCMetaClass ||
3205 type == eSymbolTypeObjCIVar) {
3206 // See if we can find a N_STSYM entry for any data symbols. If we do
3207 // find a match, and the name matches, then we can merge the two into
3208 // just the Static symbol to avoid duplicate entries in the symbol
3209 // table.
3210 std::pair<ValueToSymbolIndexMap::const_iterator,
3211 ValueToSymbolIndexMap::const_iterator>
3212 range;
3213 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
3214 if (range.first != range.second) {
3215 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
3216 pos != range.second; ++pos) {
3217 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) ==
3218 sym[pos->second].GetMangled().GetName(
3220 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3221 // We just need the flags from the linker symbol, so put these
3222 // flags into the N_STSYM flags to avoid duplicate symbols in
3223 // the symbol table.
3224 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
3225 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
3226 sym[sym_idx].Clear();
3227 return;
3228 }
3229 }
3230 } else {
3231 // Combine N_GSYM stab entries with the non stab symbol.
3232 const char *gsym_name = sym[sym_idx]
3233 .GetMangled()
3235 .GetCString();
3236 if (gsym_name) {
3237 ConstNameToSymbolIndexMap::const_iterator pos =
3238 N_GSYM_name_to_sym_idx.find(gsym_name);
3239 if (pos != N_GSYM_name_to_sym_idx.end()) {
3240 const uint32_t GSYM_sym_idx = pos->second;
3241 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
3242 // Copy the address, because often the N_GSYM address has an
3243 // invalid address of zero when the global is a common symbol.
3244 sym[GSYM_sym_idx].GetAddressRef() =
3245 Address(symbol_section, symbol_value);
3246 add_symbol_addr(sym[GSYM_sym_idx].GetAddress().GetFileAddress());
3247 // We just need the flags from the linker symbol, so put these
3248 // flags into the N_GSYM flags to avoid duplicate symbols in
3249 // the symbol table.
3250 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
3251 sym[sym_idx].Clear();
3252 return;
3253 }
3254 }
3255 }
3256 }
3257 }
3258
3259 sym[sym_idx].SetID(nlist_idx);
3260 sym[sym_idx].SetType(type);
3261 if (set_value) {
3262 sym[sym_idx].GetAddressRef() = Address(symbol_section, symbol_value);
3263 if (symbol_section)
3264 add_symbol_addr(sym[sym_idx].GetAddress().GetFileAddress());
3265 }
3266 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
3267 UpdateHasSourceFilesAndDebugMap(type, nlist, has_source_files,
3268 has_debug_map);
3269 if (nlist.n_desc & N_WEAK_REF)
3270 sym[sym_idx].SetIsWeak(true);
3271
3272 if (demangled_is_synthesized)
3273 sym[sym_idx].SetDemangledNameIsSynthesized(true);
3274
3275 ++sym_idx;
3276 };
3277
3278 // Parses the nlists at offset, numbering them
3279 // [first_nlist_idx, end_nlist_idx).
3280 auto ParseNListsLambda = [&](DataExtractor &nlist_extractor,
3281 lldb::offset_t offset, uint32_t first_nlist_idx,
3282 uint32_t end_nlist_idx,
3283 const DataExtractor &strtab) {
3284 // First parse all the nlists but don't process them yet. See the next
3285 // comment for an explanation why.
3286 std::vector<struct nlist_64> nlists;
3287 nlists.reserve(
3288 std::min<uint64_t>(end_nlist_idx - first_nlist_idx,
3289 nlist_extractor.GetByteSize() / nlist_byte_size));
3290 for (uint32_t i = first_nlist_idx; i < end_nlist_idx; ++i) {
3291 if (auto nlist = ParseNList(nlist_extractor, offset, nlist_byte_size))
3292 nlists.push_back(*nlist);
3293 else
3294 break;
3295 }
3296
3297 // Now parse all the debug symbols. This is needed to merge non-debug
3298 // symbols in the next step. Non-debug symbols are always coalesced into
3299 // the debug symbol. Doing this in one step would mean that some symbols
3300 // won't be merged.
3301 uint32_t nlist_idx = first_nlist_idx;
3302 for (auto &nlist : nlists)
3303 ParseSymbolLambda(nlist, nlist_idx++, DebugSymbols, strtab);
3304
3305 // Finally parse all the non debug symbols.
3306 nlist_idx = first_nlist_idx;
3307 for (auto &nlist : nlists)
3308 ParseSymbolLambda(nlist, nlist_idx++, NonDebugSymbols, strtab);
3309 };
3310
3311#if TARGET_OS_IPHONE
3312
3313 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
3314 // optimized by moving LOCAL symbols out of the memory mapped portion of
3315 // the DSC. The symbol information has all been retained, but it isn't
3316 // available in the normal nlist data. However, there *are* duplicate
3317 // entries of *some*
3318 // LOCAL symbols in the normal nlist data. To handle this situation
3319 // correctly, we must first attempt
3320 // to fetch any DSC unmapped symbol information. If we find any, we set a
3321 // flag that tells the normal nlist parser to ignore all LOCAL symbols.
3322
3323 __block void *nlist_buffer = nullptr;
3324 __block unsigned nlist_count = 0;
3325 __block char *string_table = nullptr;
3326 __block vm_offset_t vm_nlist_memory = 0;
3327 __block mach_msg_type_number_t vm_nlist_bytes_read = 0;
3328 __block vm_offset_t vm_string_memory = 0;
3329 __block mach_msg_type_number_t vm_string_bytes_read = 0;
3330
3331 llvm::scope_exit _(^{
3332 if (vm_nlist_memory)
3333 vm_deallocate(mach_task_self(), vm_nlist_memory, vm_nlist_bytes_read);
3334 if (vm_string_memory)
3335 vm_deallocate(mach_task_self(), vm_string_memory, vm_string_bytes_read);
3336 });
3337
3338 if (IsSharedCacheBinary()) {
3339 // Before we can start mapping the DSC, we need to make certain the
3340 // target process is actually using the cache we can find.
3341
3342 // Next we need to determine the correct path for the dyld shared cache.
3343
3344 ArchSpec header_arch = GetArchitecture();
3345
3346 UUID dsc_uuid;
3347 UUID process_shared_cache_uuid;
3348 addr_t process_shared_cache_base_addr;
3349
3350 if (process) {
3351 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr,
3352 process_shared_cache_uuid);
3353 }
3354
3355 __block bool found_image = false;
3356
3357 // Compute the size of the string table. We need to ask dyld for a
3358 // new SPI to avoid this step.
3359 auto nlist_extraction_block = ^(const void *nlistStart, uint64_t nlistCount,
3360 const char *stringTable) {
3361 if (!nlistStart || !nlistCount)
3362 return;
3363
3364 // The buffers passed here are valid only inside the block.
3365 // Use vm_read to make a cheap copy of them available for our
3366 // processing later.
3367 kern_return_t ret = vm_read(mach_task_self(), (vm_address_t)nlistStart,
3368 nlist_byte_size * nlistCount,
3369 &vm_nlist_memory, &vm_nlist_bytes_read);
3370 if (ret != KERN_SUCCESS)
3371 return;
3372 assert(vm_nlist_bytes_read == nlist_byte_size * nlistCount);
3373
3374 // We don't know the size of the string table. It's cheaper
3375 // to map the whole VM region than to determine the size by
3376 // parsing all the nlist entries.
3377 vm_address_t string_address = (vm_address_t)stringTable;
3378 vm_size_t region_size;
3379 mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
3380 vm_region_basic_info_data_t info;
3381 memory_object_name_t object;
3382 ret = vm_region_64(mach_task_self(), &string_address, &region_size,
3383 VM_REGION_BASIC_INFO_64, (vm_region_info_t)&info,
3384 &info_count, &object);
3385 if (ret != KERN_SUCCESS)
3386 return;
3387
3388 ret = vm_read(mach_task_self(), (vm_address_t)stringTable,
3389 region_size - ((vm_address_t)stringTable - string_address),
3390 &vm_string_memory, &vm_string_bytes_read);
3391 if (ret != KERN_SUCCESS)
3392 return;
3393
3394 nlist_buffer = (void *)vm_nlist_memory;
3395 string_table = (char *)vm_string_memory;
3396 nlist_count = nlistCount;
3397 };
3398
3399 // The shared-cache-binary-loading setting only exists for hosts without
3400 // the indexing SPIs.
3401 SharedCacheImageInfo image_info = HostInfo::GetSharedCacheImageInfo(
3402 image_uuid, process_shared_cache_uuid,
3404 if (void *image = image_info.GetImageBaton()) {
3405 found_image = true;
3406 dyld_image_local_nlist_content_4Symbolication((dyld_image_t)image,
3407 nlist_extraction_block);
3408 }
3409
3410 // Images outside the indexed caches need the much slower enumeration.
3411 if (!found_image) {
3412 dyld_for_each_installed_shared_cache(^(dyld_shared_cache_t shared_cache) {
3413 uuid_t cache_uuid;
3414 dyld_shared_cache_copy_uuid(shared_cache, &cache_uuid);
3415 if (found_image)
3416 return;
3417
3418 if (process_shared_cache_uuid.IsValid() &&
3419 process_shared_cache_uuid != UUID(&cache_uuid, 16))
3420 return;
3421
3422 dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
3423 uuid_t dsc_image_uuid;
3424 if (found_image)
3425 return;
3426
3427 dyld_image_copy_uuid(image, &dsc_image_uuid);
3428 if (image_uuid != UUID(dsc_image_uuid, 16))
3429 return;
3430
3431 found_image = true;
3432 dyld_image_local_nlist_content_4Symbolication(image,
3433 nlist_extraction_block);
3434 });
3435 });
3436 }
3437 if (nlist_buffer) {
3438 unmapped_local_symbols_found = nlist_count;
3439
3440 // The normal nlist code cannot correctly size the Symbols
3441 // array, we need to allocate it here.
3442 sym = symtab.Resize(symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
3443 unmapped_local_symbols_found - m_dysymtab.nlocalsym);
3444 num_syms = symtab.GetNumSymbols();
3445 }
3446 }
3447#endif
3448 lldb::offset_t nlist_data_offset = 0;
3449
3450 if (nlist_data.GetByteSize() > 0) {
3451
3452 const uint64_t max_nsyms = nlist_data.GetByteSize() / nlist_byte_size;
3453 const uint64_t max_nindirectsyms =
3454 indirect_symbol_index_data.GetByteSize() / sizeof(uint32_t);
3455
3456 // If the sym array was not created while parsing the DSC unmapped
3457 // symbols, create it now.
3458 if (sym == nullptr) {
3459 sym = symtab.Resize(
3460 std::min<uint64_t>(symtab_load_command.nsyms, max_nsyms) +
3461 std::min<uint64_t>(m_dysymtab.nindirectsyms, max_nindirectsyms));
3462 num_syms = symtab.GetNumSymbols();
3463 }
3464
3465 uint32_t first_nlist_idx = 0;
3466 if (unmapped_local_symbols_found) {
3467 assert(m_dysymtab.ilocalsym == 0);
3468 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3469 first_nlist_idx = m_dysymtab.nlocalsym;
3470 }
3471
3472 ParseNListsLambda(nlist_data, nlist_data_offset, first_nlist_idx,
3473 symtab_load_command.nsyms, strtab_data);
3474 }
3475
3476#if TARGET_OS_IPHONE
3477 if (nlist_buffer) {
3478 DataExtractor dsc_local_symbols_data(nlist_buffer,
3479 nlist_count * nlist_byte_size,
3480 byte_order, addr_byte_size);
3481 DataExtractor dsc_string_table_data(string_table, vm_string_bytes_read,
3482 byte_order, addr_byte_size);
3483 // Symbol IDs are LC_SYMTAB indexes and must ascend in parse order, so the
3484 // unmapped locals are parsed last and numbered from nsyms.
3485 ParseNListsLambda(dsc_local_symbols_data, 0, symtab_load_command.nsyms,
3486 symtab_load_command.nsyms + nlist_count,
3487 dsc_string_table_data);
3488 }
3489#endif
3490
3491 for (const auto &pos : reexport_shlib_needs_fixup) {
3492 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3493 if (undef_pos != undefined_name_to_desc.end()) {
3494 const uint8_t dylib_ordinal =
3495 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3496 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
3497 sym[pos.first].SetReExportedSymbolSharedLibrary(
3498 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3499 }
3500 }
3501
3502 // Count how many trie symbols we'll add to the symbol table
3503 int trie_symbol_table_augment_count = 0;
3504 for (auto &e : external_sym_trie_entries) {
3505 if (!symbols_added.contains(e.entry.address))
3506 trie_symbol_table_augment_count++;
3507 }
3508
3509 if (num_syms < sym_idx + trie_symbol_table_augment_count) {
3510 num_syms = sym_idx + trie_symbol_table_augment_count;
3511 sym = symtab.Resize(num_syms);
3512 }
3513 uint32_t synthetic_sym_id =
3514 symtab_load_command.nsyms + unmapped_local_symbols_found;
3515
3516 // Add symbols from the trie to the symbol table.
3517 for (auto &e : external_sym_trie_entries) {
3518 if (symbols_added.contains(e.entry.address))
3519 continue;
3520
3521 // Find the section that this trie address is in, use that to annotate
3522 // symbol type as we add the trie address and name to the symbol table.
3523 Address symbol_addr;
3524 if (module_sp->ResolveFileAddress(e.entry.address, symbol_addr)) {
3525 SectionSP symbol_section(symbol_addr.GetSection());
3526 const char *symbol_name = e.entry.name.GetCString();
3527 bool demangled_is_synthesized = false;
3528 SymbolType type =
3529 GetSymbolType(symbol_name, demangled_is_synthesized, text_section_sp,
3530 data_section_sp, data_dirty_section_sp,
3531 data_const_section_sp, symbol_section);
3532
3533 sym[sym_idx].SetType(type);
3534 if (symbol_section) {
3535 sym[sym_idx].SetID(synthetic_sym_id++);
3536 sym[sym_idx].GetMangled().SetMangledName(ConstString(symbol_name));
3537 if (demangled_is_synthesized)
3538 sym[sym_idx].SetDemangledNameIsSynthesized(true);
3539 sym[sym_idx].SetIsSynthetic(true);
3540 sym[sym_idx].SetExternal(true);
3541 sym[sym_idx].GetAddressRef() = symbol_addr;
3542 add_symbol_addr(symbol_addr.GetFileAddress());
3543 if (e.entry.flags & TRIE_SYMBOL_IS_THUMB)
3545 ++sym_idx;
3546 }
3547 }
3548 }
3549
3550 if (function_starts_count > 0) {
3551 uint32_t num_synthetic_function_symbols = 0;
3552 for (i = 0; i < function_starts_count; ++i) {
3553 if (!symbols_added.contains(function_starts.GetEntryRef(i).addr))
3554 ++num_synthetic_function_symbols;
3555 }
3556
3557 if (num_synthetic_function_symbols > 0) {
3558 if (num_syms < sym_idx + num_synthetic_function_symbols) {
3559 num_syms = sym_idx + num_synthetic_function_symbols;
3560 sym = symtab.Resize(num_syms);
3561 }
3562 for (i = 0; i < function_starts_count; ++i) {
3563 const FunctionStarts::Entry *func_start_entry =
3564 function_starts.GetEntryAtIndex(i);
3565 if (!symbols_added.contains(func_start_entry->addr)) {
3566 addr_t symbol_file_addr = func_start_entry->addr;
3567 uint32_t symbol_flags = 0;
3568 if (func_start_entry->data)
3569 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3570 Address symbol_addr;
3571 if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
3572 SectionSP symbol_section(symbol_addr.GetSection());
3573 if (symbol_section) {
3574 sym[sym_idx].SetID(synthetic_sym_id++);
3575 // Don't set the name for any synthetic symbols, the Symbol
3576 // object will generate one if needed when the name is accessed
3577 // via accessors.
3578 sym[sym_idx].GetMangled().SetDemangledName(ConstString());
3579 sym[sym_idx].SetType(eSymbolTypeCode);
3580 sym[sym_idx].SetIsSynthetic(true);
3581 sym[sym_idx].GetAddressRef() = symbol_addr;
3582 add_symbol_addr(symbol_addr.GetFileAddress());
3583 if (symbol_flags)
3584 sym[sym_idx].SetFlags(symbol_flags);
3585 ++sym_idx;
3586 }
3587 }
3588 }
3589 }
3590 }
3591 }
3592
3593 // Trim our symbols down to just what we ended up with after removing any
3594 // symbols.
3595 if (sym_idx < num_syms) {
3596 num_syms = sym_idx;
3597 sym = symtab.Resize(num_syms);
3598 }
3599
3600 // Now synthesize indirect symbols
3601 if (m_dysymtab.nindirectsyms != 0) {
3602 if (indirect_symbol_index_data.GetByteSize()) {
3603 NListIndexToSymbolIndexMap::const_iterator end_index_pos =
3604 m_nlist_idx_to_sym_idx.end();
3605
3606 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
3607 ++sect_idx) {
3608 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
3609 S_SYMBOL_STUBS) {
3610 uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
3611 if (symbol_stub_byte_size == 0)
3612 continue;
3613
3614 const uint32_t num_symbol_stubs =
3615 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
3616
3617 if (num_symbol_stubs == 0)
3618 continue;
3619
3620 const uint32_t symbol_stub_index_offset =
3621 m_mach_sections[sect_idx].reserved1;
3622 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx) {
3623 const uint32_t symbol_stub_index =
3624 symbol_stub_index_offset + stub_idx;
3625 const lldb::addr_t symbol_stub_addr =
3626 m_mach_sections[sect_idx].addr +
3627 (stub_idx * symbol_stub_byte_size);
3628 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
3629 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
3630 symbol_stub_offset, 4)) {
3631 const uint32_t stub_sym_id =
3632 indirect_symbol_index_data.GetU32(&symbol_stub_offset);
3633 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
3634 continue;
3635
3636 NListIndexToSymbolIndexMap::const_iterator index_pos =
3637 m_nlist_idx_to_sym_idx.find(stub_sym_id);
3638 Symbol *stub_symbol = nullptr;
3639 if (index_pos != end_index_pos) {
3640 // We have a remapping from the original nlist index to a
3641 // current symbol index, so just look this up by index
3642 stub_symbol = symtab.SymbolAtIndex(index_pos->second);
3643 } else {
3644 // We need to lookup a symbol using the original nlist symbol
3645 // index since this index is coming from the S_SYMBOL_STUBS
3646 stub_symbol = symtab.FindSymbolByID(stub_sym_id);
3647 }
3648
3649 if (stub_symbol) {
3650 Address so_addr(symbol_stub_addr, section_list);
3651
3652 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
3653 // Change the external symbol into a trampoline that makes
3654 // sense These symbols were N_UNDF N_EXT, and are useless
3655 // to us, so we can re-use them so we don't have to make up
3656 // a synthetic symbol for no good reason.
3657 if (resolver_addresses.find(symbol_stub_addr) ==
3658 resolver_addresses.end())
3659 stub_symbol->SetType(eSymbolTypeTrampoline);
3660 else
3661 stub_symbol->SetType(eSymbolTypeResolver);
3662 stub_symbol->SetExternal(false);
3663 stub_symbol->GetAddressRef() = so_addr;
3664 stub_symbol->SetByteSize(symbol_stub_byte_size);
3665 } else {
3666 // Make a synthetic symbol to describe the trampoline stub
3667 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
3668 if (sym_idx >= num_syms) {
3669 sym = symtab.Resize(++num_syms);
3670 stub_symbol = nullptr; // this pointer no longer valid
3671 }
3672 sym[sym_idx].SetID(synthetic_sym_id++);
3673 sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
3674 if (resolver_addresses.find(symbol_stub_addr) ==
3675 resolver_addresses.end())
3676 sym[sym_idx].SetType(eSymbolTypeTrampoline);
3677 else
3678 sym[sym_idx].SetType(eSymbolTypeResolver);
3679 sym[sym_idx].SetIsSynthetic(true);
3680 sym[sym_idx].GetAddressRef() = so_addr;
3681 add_symbol_addr(so_addr.GetFileAddress());
3682 sym[sym_idx].SetByteSize(symbol_stub_byte_size);
3683 ++sym_idx;
3684 }
3685 } else {
3686 LLDB_LOGF(log,
3687 "warning: symbol stub referencing symbol table "
3688 "symbol %u that isn't in our minimal symbol table, "
3689 "fix this!!!",
3690 stub_sym_id);
3691 }
3692 }
3693 }
3694 }
3695 }
3696 }
3697 }
3698
3699 if (!reexport_trie_entries.empty()) {
3700 for (const auto &e : reexport_trie_entries) {
3701 if (e.entry.import_name) {
3702 // Only add indirect symbols from the Trie entries if we didn't have
3703 // a N_INDR nlist entry for this already
3704 if (indirect_symbol_names.find(e.entry.name) ==
3705 indirect_symbol_names.end()) {
3706 // Make a synthetic symbol to describe re-exported symbol.
3707 if (sym_idx >= num_syms)
3708 sym = symtab.Resize(++num_syms);
3709 sym[sym_idx].SetID(synthetic_sym_id++);
3710 sym[sym_idx].GetMangled() = Mangled(e.entry.name);
3711 sym[sym_idx].SetType(eSymbolTypeReExported);
3712 sym[sym_idx].SetIsSynthetic(true);
3713 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
3714 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
3716 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
3717 }
3718 ++sym_idx;
3719 }
3720 }
3721 }
3722 }
3723
3724 // Set these after the last Resize(), which clears whether the symbol table
3725 // has source files.
3726 symtab.SetHasSourceFiles(has_source_files);
3727 symtab.SetHasDebugMap(has_debug_map);
3728}
3729
3731 ModuleSP module_sp(GetModule());
3732 if (module_sp) {
3733 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
3734 s->Printf("%p: ", static_cast<void *>(this));
3735 s->Indent();
3736 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
3737 s->PutCString("ObjectFileMachO64");
3738 else
3739 s->PutCString("ObjectFileMachO32");
3740
3741 *s << ", file = '" << m_file;
3742 ModuleSpecList all_specs;
3743 ModuleSpec base_spec;
3745 MachHeaderSizeFromMagic(m_header.magic), base_spec,
3746 all_specs);
3747 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
3748 *s << "', triple";
3749 if (e)
3750 s->Printf("[%d]", i);
3751 *s << " = ";
3752 *s << all_specs.GetModuleSpecRefAtIndex(i)
3754 .GetTriple()
3755 .getTriple();
3756 }
3757 *s << "\n";
3758 SectionList *sections = GetSectionList();
3759 if (sections)
3760 sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
3761 UINT32_MAX);
3762
3763 if (Symtab *symtab = m_symtab.load())
3764 symtab->Dump(s, nullptr, eSortOrderNone);
3765 }
3766}
3767
3768UUID ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
3769 const lldb_private::DataExtractor &data,
3770 lldb::offset_t lc_offset) {
3771 uint32_t i;
3772 llvm::MachO::uuid_command load_cmd;
3773
3774 lldb::offset_t offset = lc_offset;
3775 for (i = 0; i < header.ncmds; ++i) {
3776 const lldb::offset_t cmd_offset = offset;
3777 if (!ReadMachOCommand(data, offset, load_cmd))
3778 break;
3779
3780 if (load_cmd.cmd == LC_UUID) {
3781 const uint8_t *uuid_bytes = data.PeekData(offset, 16);
3782
3783 if (uuid_bytes) {
3784 // OpenCL on Mac OS X uses the same UUID for each of its object files.
3785 // We pretend these object files have no UUID to prevent crashing.
3786
3787 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
3788 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
3789 0xbb, 0x14, 0xf0, 0x0d};
3790
3791 if (!memcmp(uuid_bytes, opencl_uuid, 16))
3792 return UUID();
3793
3794 return UUID(uuid_bytes, 16);
3795 }
3796 return UUID();
3797 }
3798 offset = cmd_offset + load_cmd.cmdsize;
3799 }
3800 return UUID();
3801}
3802
3803static llvm::StringRef GetOSName(uint32_t cmd) {
3804 switch (cmd) {
3805 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
3806 return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
3807 case llvm::MachO::LC_VERSION_MIN_MACOSX:
3808 return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
3809 case llvm::MachO::LC_VERSION_MIN_TVOS:
3810 return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
3811 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
3812 return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
3813 default:
3814 llvm_unreachable("unexpected LC_VERSION load command");
3815 }
3816}
3817
3818namespace {
3819struct OSEnv {
3820 llvm::StringRef os_type;
3821 llvm::StringRef environment;
3822 OSEnv(uint32_t cmd) {
3823 switch (cmd) {
3824 case llvm::MachO::PLATFORM_MACOS:
3825 os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
3826 return;
3827 case llvm::MachO::PLATFORM_IOS:
3828 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
3829 return;
3830 case llvm::MachO::PLATFORM_TVOS:
3831 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
3832 return;
3833 case llvm::MachO::PLATFORM_WATCHOS:
3834 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
3835 return;
3836 case llvm::MachO::PLATFORM_BRIDGEOS:
3837 os_type = llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
3838 return;
3839 case llvm::MachO::PLATFORM_DRIVERKIT:
3840 os_type = llvm::Triple::getOSTypeName(llvm::Triple::DriverKit);
3841 return;
3842 case llvm::MachO::PLATFORM_MACCATALYST:
3843 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
3844 environment = llvm::Triple::getEnvironmentTypeName(llvm::Triple::MacABI);
3845 return;
3846 case llvm::MachO::PLATFORM_IOSSIMULATOR:
3847 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
3848 environment =
3849 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
3850 return;
3851 case llvm::MachO::PLATFORM_TVOSSIMULATOR:
3852 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
3853 environment =
3854 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
3855 return;
3856 case llvm::MachO::PLATFORM_WATCHOSSIMULATOR:
3857 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
3858 environment =
3859 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
3860 return;
3861 case llvm::MachO::PLATFORM_XROS:
3862 os_type = llvm::Triple::getOSTypeName(llvm::Triple::XROS);
3863 return;
3864 case llvm::MachO::PLATFORM_XROS_SIMULATOR:
3865 os_type = llvm::Triple::getOSTypeName(llvm::Triple::XROS);
3866 environment =
3867 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
3868 return;
3869 default: {
3870 Log *log(GetLog(LLDBLog::Symbols | LLDBLog::Process));
3871 LLDB_LOGF(log, "unsupported platform in LC_BUILD_VERSION");
3872 }
3873 }
3874 }
3875};
3876
3877struct MinOS {
3878 uint32_t major_version, minor_version, patch_version;
3879 MinOS(uint32_t version)
3880 : major_version(version >> 16), minor_version((version >> 8) & 0xffu),
3881 patch_version(version & 0xffu) {}
3882};
3883} // namespace
3884
3885void ObjectFileMachO::GetAllArchSpecs(const llvm::MachO::mach_header &header,
3886 const lldb_private::DataExtractor &data,
3887 lldb::offset_t lc_offset,
3888 ModuleSpec &base_spec,
3889 lldb_private::ModuleSpecList &all_specs) {
3890 auto &base_arch = base_spec.GetArchitecture();
3891 base_arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
3892 if (!base_arch.IsValid())
3893 return;
3894
3895 bool found_any = false;
3896 auto add_triple = [&](const llvm::Triple &triple) {
3897 auto spec = base_spec;
3898 spec.GetArchitecture().GetTriple() = triple;
3899 if (spec.GetArchitecture().IsValid()) {
3900 spec.GetUUID() = ObjectFileMachO::GetUUID(header, data, lc_offset);
3901 all_specs.Append(spec);
3902 found_any = true;
3903 }
3904 };
3905
3906 // Set OS to an unspecified unknown or a "*" so it can match any OS
3907 llvm::Triple base_triple = base_arch.GetTriple();
3908 base_triple.setOS(llvm::Triple::UnknownOS);
3909 base_triple.setOSName(llvm::StringRef());
3910
3911 if (header.filetype == MH_PRELOAD) {
3912 if (header.cputype == CPU_TYPE_ARM) {
3913 // If this is a 32-bit arm binary, and it's a standalone binary, force
3914 // the Vendor to Apple so we don't accidentally pick up the generic
3915 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
3916 // frame pointer register; most other armv7 ABIs use a combination of
3917 // r7 and r11.
3918 base_triple.setVendor(llvm::Triple::Apple);
3919 } else {
3920 // Set vendor to an unspecified unknown or a "*" so it can match any
3921 // vendor This is required for correct behavior of EFI debugging on
3922 // x86_64
3923 base_triple.setVendor(llvm::Triple::UnknownVendor);
3924 base_triple.setVendorName(llvm::StringRef());
3925 }
3926 return add_triple(base_triple);
3927 }
3928
3929 llvm::MachO::load_command load_cmd;
3930
3931 // See if there is an LC_VERSION_MIN_* load command that can give
3932 // us the OS type.
3933 lldb::offset_t offset = lc_offset;
3934 for (uint32_t i = 0; i < header.ncmds; ++i) {
3935 const lldb::offset_t cmd_offset = offset;
3936 if (!ReadMachOCommand(data, offset, load_cmd))
3937 break;
3938
3939 llvm::MachO::version_min_command version_min;
3940 switch (load_cmd.cmd) {
3941 case llvm::MachO::LC_VERSION_MIN_MACOSX:
3942 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
3943 case llvm::MachO::LC_VERSION_MIN_TVOS:
3944 case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
3945 if (load_cmd.cmdsize != sizeof(version_min))
3946 break;
3947 if (data.ExtractBytes(cmd_offset, sizeof(version_min),
3948 data.GetByteOrder(), &version_min) == 0)
3949 break;
3950 MinOS min_os(version_min.version);
3951 llvm::SmallString<32> os_name;
3952 llvm::raw_svector_ostream os(os_name);
3953 os << GetOSName(load_cmd.cmd) << min_os.major_version << '.'
3954 << min_os.minor_version << '.' << min_os.patch_version;
3955
3956 auto triple = base_triple;
3957 triple.setOSName(os.str());
3958
3959 // Disambiguate legacy simulator platforms.
3960 if (load_cmd.cmd != llvm::MachO::LC_VERSION_MIN_MACOSX &&
3961 (base_triple.getArch() == llvm::Triple::x86_64 ||
3962 base_triple.getArch() == llvm::Triple::x86)) {
3963 // The combination of legacy LC_VERSION_MIN load command and
3964 // x86 architecture always indicates a simulator environment.
3965 // The combination of LC_VERSION_MIN and arm architecture only
3966 // appears for native binaries. Back-deploying simulator
3967 // binaries on Apple Silicon Macs use the modern unambigous
3968 // LC_BUILD_VERSION load commands; no special handling required.
3969 triple.setEnvironment(llvm::Triple::Simulator);
3970 }
3971 add_triple(triple);
3972 break;
3973 }
3974 default:
3975 break;
3976 }
3977
3978 offset = cmd_offset + load_cmd.cmdsize;
3979 }
3980
3981 // See if there are LC_BUILD_VERSION load commands that can give
3982 // us the OS type.
3983 offset = lc_offset;
3984 for (uint32_t i = 0; i < header.ncmds; ++i) {
3985 const lldb::offset_t cmd_offset = offset;
3986 if (!ReadMachOCommand(data, offset, load_cmd))
3987 break;
3988
3989 do {
3990 if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
3991 llvm::MachO::build_version_command build_version;
3992 if (load_cmd.cmdsize < sizeof(build_version)) {
3993 // Malformed load command.
3994 break;
3995 }
3996 if (data.ExtractBytes(cmd_offset, sizeof(build_version),
3997 data.GetByteOrder(), &build_version) == 0)
3998 break;
3999 MinOS min_os(build_version.minos);
4000 OSEnv os_env(build_version.platform);
4001 llvm::SmallString<16> os_name;
4002 llvm::raw_svector_ostream os(os_name);
4003 os << os_env.os_type << min_os.major_version << '.'
4004 << min_os.minor_version << '.' << min_os.patch_version;
4005 auto triple = base_triple;
4006 triple.setOSName(os.str());
4007 os_name.clear();
4008 if (!os_env.environment.empty())
4009 triple.setEnvironmentName(os_env.environment);
4010 add_triple(triple);
4011 }
4012 } while (false);
4013 offset = cmd_offset + load_cmd.cmdsize;
4014 }
4015
4016 if (!found_any) {
4017 add_triple(base_triple);
4018 }
4019}
4020
4022 ModuleSP module_sp, const llvm::MachO::mach_header &header,
4023 const lldb_private::DataExtractor &data, lldb::offset_t lc_offset) {
4024 ModuleSpecList all_specs;
4025 ModuleSpec base_spec;
4026 GetAllArchSpecs(header, data, MachHeaderSizeFromMagic(header.magic),
4027 base_spec, all_specs);
4028
4029 // If the object file offers multiple alternative load commands,
4030 // pick the one that matches the module.
4031 if (module_sp) {
4032 const ArchSpec &module_arch = module_sp->GetArchitecture();
4033 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
4034 ArchSpec mach_arch =
4036 if (module_arch.IsCompatibleMatch(mach_arch))
4037 return mach_arch;
4038 }
4039 }
4040
4041 // Return the first arch we found.
4042 if (all_specs.GetSize() == 0)
4043 return {};
4044 return all_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
4045}
4046
4048 ModuleSP module_sp(GetModule());
4049 if (module_sp) {
4050 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4052 return GetUUID(m_header, *m_data_nsp, offset);
4053 }
4054 return UUID();
4055}
4056
4058 ModuleSP module_sp = GetModule();
4059 if (!module_sp)
4060 return 0;
4061
4062 uint32_t count = 0;
4063 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4064 llvm::MachO::load_command load_cmd;
4066 std::vector<std::string> rpath_paths;
4067 std::vector<std::string> rpath_relative_paths;
4068 std::vector<std::string> at_exec_relative_paths;
4069 uint32_t i;
4070 for (i = 0; i < m_header.ncmds; ++i) {
4071 const uint32_t cmd_offset = offset;
4072 if (!ReadMachOCommand(*m_data_nsp, offset, load_cmd))
4073 break;
4074
4075 switch (load_cmd.cmd) {
4076 case LC_RPATH:
4077 case LC_LOAD_DYLIB:
4078 case LC_LOAD_WEAK_DYLIB:
4079 case LC_REEXPORT_DYLIB:
4080 case LC_LOAD_DYLINKER:
4081 case LC_LOADFVMLIB:
4082 case LC_LOAD_UPWARD_DYLIB: {
4083 uint32_t name_offset = cmd_offset + m_data_nsp->GetU32(&offset);
4084 // For LC_LOAD_DYLIB there is an alternate encoding
4085 // which adds a uint32_t `flags` field for `DYLD_USE_*`
4086 // flags. This can be detected by a timestamp field with
4087 // the `DYLIB_USE_MARKER` constant value.
4088 bool is_delayed_init = false;
4089 uint32_t use_command_marker = m_data_nsp->GetU32(&offset);
4090 if (use_command_marker == 0x1a741800 /* DYLIB_USE_MARKER */) {
4091 offset += 4; /* uint32_t current_version */
4092 offset += 4; /* uint32_t compat_version */
4093 uint32_t flags = m_data_nsp->GetU32(&offset);
4094 // If this LC_LOAD_DYLIB is marked delay-init,
4095 // don't report it as a dependent library -- it
4096 // may be loaded in the process at some point,
4097 // but will most likely not be load at launch.
4098 if (flags & 0x08 /* DYLIB_USE_DELAYED_INIT */)
4099 is_delayed_init = true;
4100 }
4101 std::optional<llvm::StringRef> maybe_path =
4102 m_data_nsp->PeekCStr(name_offset);
4103 if (maybe_path && !is_delayed_init) {
4104 llvm::StringRef path = *maybe_path;
4105 if (load_cmd.cmd == LC_RPATH)
4106 rpath_paths.push_back(path.str());
4107 else if (path.consume_front("@rpath"))
4108 rpath_relative_paths.push_back(path.str());
4109 else if (path.consume_front("@executable_path"))
4110 at_exec_relative_paths.push_back(path.str());
4111 else if (!path.starts_with("@")) {
4112 FileSpec file_spec(path);
4113 if (files.AppendIfUnique(file_spec))
4114 count++;
4115 }
4116 }
4117 } break;
4118
4119 default:
4120 break;
4121 }
4122 offset = cmd_offset + load_cmd.cmdsize;
4123 }
4124
4125 FileSpec this_file_spec(m_file);
4126 FileSystem::Instance().Resolve(this_file_spec);
4127
4128 if (!rpath_paths.empty()) {
4129 // Fixup all LC_RPATH values to be absolute paths.
4130 const std::string this_directory = this_file_spec.GetDirectory().str();
4131 for (auto &rpath : rpath_paths) {
4132 if (llvm::StringRef(rpath).starts_with(g_loader_path))
4133 rpath = this_directory + rpath.substr(g_loader_path.size());
4134 else if (llvm::StringRef(rpath).starts_with(g_executable_path))
4135 rpath = this_directory + rpath.substr(g_executable_path.size());
4136 }
4137
4138 for (const auto &rpath_relative_path : rpath_relative_paths) {
4139 for (const auto &rpath : rpath_paths) {
4140 std::string path = rpath;
4141 path += rpath_relative_path;
4142 // It is OK to resolve this path because we must find a file on disk
4143 // for us to accept it anyway if it is rpath relative.
4144 FileSpec file_spec(path);
4145 FileSystem::Instance().Resolve(file_spec);
4146 if (FileSystem::Instance().Exists(file_spec) &&
4147 files.AppendIfUnique(file_spec)) {
4148 count++;
4149 break;
4150 }
4151 }
4152 }
4153 }
4154
4155 // We may have @executable_paths but no RPATHS. Figure those out here.
4156 // Only do this if this object file is the executable. We have no way to
4157 // get back to the actual executable otherwise, so we won't get the right
4158 // path.
4159 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
4160 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
4161 for (const auto &at_exec_relative_path : at_exec_relative_paths) {
4162 FileSpec file_spec =
4163 exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
4164 if (FileSystem::Instance().Exists(file_spec) &&
4165 files.AppendIfUnique(file_spec))
4166 count++;
4167 }
4168 }
4169 return count;
4170}
4171
4173 // If the object file is not an executable it can't hold the entry point.
4174 // m_entry_point_address is initialized to an invalid address, so we can just
4175 // return that. If m_entry_point_address is valid it means we've found it
4176 // already, so return the cached value.
4177
4178 if ((!IsExecutable() && !IsDynamicLoader()) ||
4179 m_entry_point_address.IsValid()) {
4180 return m_entry_point_address;
4181 }
4182
4183 // Otherwise, look for the UnixThread or Thread command. The data for the
4184 // Thread command is given in /usr/include/mach-o.h, but it is basically:
4185 //
4186 // uint32_t flavor - this is the flavor argument you would pass to
4187 // thread_get_state
4188 // uint32_t count - this is the count of longs in the thread state data
4189 // struct XXX_thread_state state - this is the structure from
4190 // <machine/thread_status.h> corresponding to the flavor.
4191 // <repeat this trio>
4192 //
4193 // So we just keep reading the various register flavors till we find the GPR
4194 // one, then read the PC out of there.
4195 // FIXME: We will need to have a "RegisterContext data provider" class at some
4196 // point that can get all the registers
4197 // out of data in this form & attach them to a given thread. That should
4198 // underlie the MacOS X User process plugin, and we'll also need it for the
4199 // MacOS X Core File process plugin. When we have that we can also use it
4200 // here.
4201 //
4202 // For now we hard-code the offsets and flavors we need:
4203 //
4204 //
4205
4206 ModuleSP module_sp(GetModule());
4207 if (module_sp) {
4208 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4209 llvm::MachO::load_command load_cmd;
4211 uint32_t i;
4212 lldb::addr_t start_address = LLDB_INVALID_ADDRESS;
4213 bool done = false;
4214
4215 for (i = 0; i < m_header.ncmds; ++i) {
4216 const lldb::offset_t cmd_offset = offset;
4217 if (!ReadMachOCommand(*m_data_nsp, offset, load_cmd))
4218 break;
4219
4220 switch (load_cmd.cmd) {
4221 case LC_UNIXTHREAD:
4222 case LC_THREAD: {
4223 while (offset < cmd_offset + load_cmd.cmdsize) {
4224 uint32_t flavor = m_data_nsp->GetU32(&offset);
4225 uint32_t count = m_data_nsp->GetU32(&offset);
4226 if (count == 0) {
4227 // We've gotten off somehow, log and exit;
4228 return m_entry_point_address;
4229 }
4230
4231 switch (m_header.cputype) {
4232 case llvm::MachO::CPU_TYPE_ARM:
4233 if (flavor == 1 ||
4234 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32
4235 // from mach/arm/thread_status.h
4236 {
4237 offset += 60; // This is the offset of pc in the GPR thread state
4238 // data structure.
4239 start_address = m_data_nsp->GetU32(&offset);
4240 done = true;
4241 }
4242 break;
4243 case llvm::MachO::CPU_TYPE_ARM64:
4244 case llvm::MachO::CPU_TYPE_ARM64_32:
4245 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h
4246 {
4247 offset += 256; // This is the offset of pc in the GPR thread state
4248 // data structure.
4249 start_address = m_data_nsp->GetU64(&offset);
4250 done = true;
4251 }
4252 break;
4253 case llvm::MachO::CPU_TYPE_X86_64:
4254 if (flavor ==
4255 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h
4256 {
4257 offset += 16 * 8; // This is the offset of rip in the GPR thread
4258 // state data structure.
4259 start_address = m_data_nsp->GetU64(&offset);
4260 done = true;
4261 }
4262 break;
4263 default:
4264 return m_entry_point_address;
4265 }
4266 // Haven't found the GPR flavor yet, skip over the data for this
4267 // flavor:
4268 if (done)
4269 break;
4270 offset += count * 4;
4271 }
4272 } break;
4273 case LC_MAIN: {
4274 uint64_t entryoffset = m_data_nsp->GetU64(&offset);
4275 SectionSP text_segment_sp =
4277 if (text_segment_sp) {
4278 done = true;
4279 start_address = text_segment_sp->GetFileAddress() + entryoffset;
4280 }
4281 } break;
4282
4283 default:
4284 break;
4285 }
4286 if (done)
4287 break;
4288
4289 // Go to the next load command:
4290 offset = cmd_offset + load_cmd.cmdsize;
4291 }
4292
4293 if (start_address == LLDB_INVALID_ADDRESS && IsDynamicLoader()) {
4294 if (GetSymtab()) {
4295 const Symbol *dyld_start_sym =
4299 if (dyld_start_sym && dyld_start_sym->GetAddress().IsValid()) {
4300 start_address = dyld_start_sym->GetAddress().GetFileAddress();
4301 }
4302 }
4303 }
4304
4305 if (start_address != LLDB_INVALID_ADDRESS) {
4306 // We got the start address from the load commands, so now resolve that
4307 // address in the sections of this ObjectFile:
4308 if (!m_entry_point_address.ResolveAddressUsingFileSections(
4309 start_address, GetSectionList())) {
4310 m_entry_point_address.Clear();
4311 }
4312 } else {
4313 // We couldn't read the UnixThread load command - maybe it wasn't there.
4314 // As a fallback look for the "start" symbol in the main executable.
4315
4316 ModuleSP module_sp(GetModule());
4317
4318 if (module_sp) {
4319 SymbolContextList contexts;
4320 SymbolContext context;
4321 module_sp->FindSymbolsWithNameAndType(ConstString("start"),
4322 eSymbolTypeCode, contexts);
4323 if (contexts.GetSize()) {
4324 if (contexts.GetContextAtIndex(0, context))
4326 }
4327 }
4328 }
4329 }
4330
4331 return m_entry_point_address;
4332}
4333
4335 lldb_private::Address header_addr;
4336 SectionList *section_list = GetSectionList();
4337 if (section_list) {
4338 SectionSP text_segment_sp(
4339 section_list->FindSectionByName(GetSegmentNameTEXT()));
4340 if (text_segment_sp)
4341 header_addr = Address(text_segment_sp, /*offset=*/0);
4342 }
4343 return header_addr;
4344}
4345
4347 ModuleSP module_sp(GetModule());
4348 if (module_sp) {
4349 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4353 FileRangeArray::Entry file_range;
4354 llvm::MachO::thread_command thread_cmd;
4355 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
4356 const uint32_t cmd_offset = offset;
4357 if (!ReadMachOCommand(*m_data_nsp, offset, thread_cmd))
4358 break;
4359
4360 if (thread_cmd.cmd == LC_THREAD) {
4361 file_range.SetRangeBase(offset);
4362 file_range.SetByteSize(thread_cmd.cmdsize - 8);
4363 m_thread_context_offsets.Append(file_range);
4364 }
4365 offset = cmd_offset + thread_cmd.cmdsize;
4366 }
4367 }
4368 }
4369 return m_thread_context_offsets.GetSize();
4370}
4371
4372std::vector<std::tuple<offset_t, offset_t>>
4374 std::vector<std::tuple<offset_t, offset_t>> results;
4375 ModuleSP module_sp(GetModule());
4376 if (module_sp) {
4377 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4378
4380 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
4381 const uint32_t cmd_offset = offset;
4382 llvm::MachO::load_command lc = {};
4383 if (!ReadMachOCommand(*m_data_nsp, offset, lc))
4384 break;
4385 if (lc.cmd == LC_NOTE) {
4386 char data_owner[17];
4387 m_data_nsp->CopyData(offset, 16, data_owner);
4388 data_owner[16] = '\0';
4389 offset += 16;
4390
4391 if (name == data_owner) {
4392 offset_t payload_offset = m_data_nsp->GetU64_unchecked(&offset);
4393 offset_t payload_size = m_data_nsp->GetU64_unchecked(&offset);
4394 results.push_back({payload_offset, payload_size});
4395 }
4396 }
4397 offset = cmd_offset + lc.cmdsize;
4398 }
4399 }
4400 return results;
4401}
4402
4404 Log *log(
4406 ModuleSP module_sp(GetModule());
4407 if (module_sp) {
4408 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4409
4410 auto lc_notes = FindLC_NOTEByName("kern ver str");
4411 for (auto lc_note : lc_notes) {
4412 offset_t payload_offset = std::get<0>(lc_note);
4413 offset_t payload_size = std::get<1>(lc_note);
4414 uint32_t version;
4415 if (m_data_nsp->GetU32(&payload_offset, &version, 1) != nullptr) {
4416 if (version == 1) {
4417 uint32_t strsize = payload_size - sizeof(uint32_t);
4418 std::string result(strsize, '\0');
4419 m_data_nsp->CopyData(payload_offset, strsize, result.data());
4420 LLDB_LOGF(log, "LC_NOTE 'kern ver str' found with text '%s'",
4421 result.c_str());
4422 return result;
4423 }
4424 }
4425 }
4426
4427 // Second, make a pass over the load commands looking for an obsolete
4428 // LC_IDENT load command.
4430 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
4431 const uint32_t cmd_offset = offset;
4432 llvm::MachO::ident_command ident_command;
4433 if (!ReadMachOCommand(*m_data_nsp, offset, ident_command))
4434 break;
4435 if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) {
4436 std::string result(ident_command.cmdsize, '\0');
4437 if (m_data_nsp->CopyData(offset, ident_command.cmdsize,
4438 result.data()) == ident_command.cmdsize) {
4439 LLDB_LOGF(log, "LC_IDENT found with text '%s'", result.c_str());
4440 return result;
4441 }
4442 }
4443 offset = cmd_offset + ident_command.cmdsize;
4444 }
4445 }
4446 return {};
4447}
4448
4450 AddressableBits addressable_bits;
4451
4453 ModuleSP module_sp(GetModule());
4454 if (module_sp) {
4455 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4456 auto lc_notes = FindLC_NOTEByName("addrable bits");
4457 for (auto lc_note : lc_notes) {
4458 offset_t payload_offset = std::get<0>(lc_note);
4459 uint32_t version;
4460 if (m_data_nsp->GetU32(&payload_offset, &version, 1) != nullptr) {
4461 if (version == 3) {
4462 uint32_t num_addr_bits =
4463 m_data_nsp->GetU32_unchecked(&payload_offset);
4464 addressable_bits.SetAddressableBits(num_addr_bits);
4465 LLDB_LOGF(log,
4466 "LC_NOTE 'addrable bits' v3 found, value %d "
4467 "bits",
4468 num_addr_bits);
4469 }
4470 if (version == 4) {
4471 uint32_t lo_addr_bits = m_data_nsp->GetU32_unchecked(&payload_offset);
4472 uint32_t hi_addr_bits = m_data_nsp->GetU32_unchecked(&payload_offset);
4473
4474 if (lo_addr_bits == hi_addr_bits)
4475 addressable_bits.SetAddressableBits(lo_addr_bits);
4476 else
4477 addressable_bits.SetAddressableBits(lo_addr_bits, hi_addr_bits);
4478 LLDB_LOGF(log, "LC_NOTE 'addrable bits' v4 found, value %d & %d bits",
4479 lo_addr_bits, hi_addr_bits);
4480 }
4481 }
4482 }
4483 }
4484 return addressable_bits;
4485}
4486
4488 bool &value_is_offset,
4489 UUID &uuid,
4490 ObjectFile::BinaryType &type) {
4491 Log *log(
4493 value = LLDB_INVALID_ADDRESS;
4494 value_is_offset = false;
4495 uuid.Clear();
4496 uint32_t log2_pagesize = 0; // not currently passed up to caller
4497 uint32_t platform = 0; // not currently passed up to caller
4498 ModuleSP module_sp(GetModule());
4499 if (module_sp) {
4500 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4501
4502 auto lc_notes = FindLC_NOTEByName("main bin spec");
4503 for (auto lc_note : lc_notes) {
4504 offset_t payload_offset = std::get<0>(lc_note);
4505
4506 // struct main_bin_spec
4507 // {
4508 // uint32_t version; // currently 2
4509 // uint32_t type; // 0 == unspecified,
4510 // // 1 == kernel
4511 // // 2 == user process,
4512 // dyld mach-o binary addr
4513 // // 3 == standalone binary
4514 // // 4 == user process,
4515 // // dyld_all_image_infos addr
4516 // uint64_t address; // UINT64_MAX if address not specified
4517 // uint64_t slide; // slide, UINT64_MAX if unspecified
4518 // // 0 if no slide needs to be applied to
4519 // // file address
4520 // uuid_t uuid; // all zero's if uuid not specified
4521 // uint32_t log2_pagesize; // process page size in log base 2,
4522 // // e.g. 4k pages are 12.
4523 // // 0 for unspecified
4524 // uint32_t platform; // The Mach-O platform for this corefile.
4525 // // 0 for unspecified.
4526 // // The values are defined in
4527 // // <mach-o/loader.h>, PLATFORM_*.
4528 // } __attribute((packed));
4529
4530 // "main bin spec" (main binary specification) data payload is
4531 // formatted:
4532 // uint32_t version [currently 1]
4533 // uint32_t type [0 == unspecified, 1 == kernel,
4534 // 2 == user process, 3 == firmware ]
4535 // uint64_t address [ UINT64_MAX if address not specified ]
4536 // uuid_t uuid [ all zero's if uuid not specified ]
4537 // uint32_t log2_pagesize [ process page size in log base
4538 // 2, e.g. 4k pages are 12.
4539 // 0 for unspecified ]
4540 // uint32_t unused [ for alignment ]
4541
4542 uint32_t version;
4543 if (m_data_nsp->GetU32(&payload_offset, &version, 1) != nullptr &&
4544 version <= 2) {
4545 uint32_t binspec_type = 0;
4546 uuid_t raw_uuid;
4547 memset(raw_uuid, 0, sizeof(uuid_t));
4548
4549 if (!m_data_nsp->GetU32(&payload_offset, &binspec_type, 1))
4550 return false;
4551 if (!m_data_nsp->GetU64(&payload_offset, &value, 1))
4552 return false;
4553 uint64_t slide = LLDB_INVALID_ADDRESS;
4554 if (version > 1 && !m_data_nsp->GetU64(&payload_offset, &slide, 1))
4555 return false;
4556 if (value == LLDB_INVALID_ADDRESS && slide != LLDB_INVALID_ADDRESS) {
4557 value = slide;
4558 value_is_offset = true;
4559 }
4560
4561 if (m_data_nsp->CopyData(payload_offset, sizeof(uuid_t), raw_uuid) !=
4562 0) {
4563 uuid = UUID(raw_uuid, sizeof(uuid_t));
4564 // convert the "main bin spec" type into our
4565 // ObjectFile::BinaryType enum
4566 const char *typestr = "unrecognized type";
4567 type = eBinaryTypeInvalid;
4568 switch (binspec_type) {
4569 case 0:
4570 type = eBinaryTypeUnknown;
4571 typestr = "uknown";
4572 break;
4573 case 1:
4574 type = eBinaryTypeKernel;
4575 typestr = "xnu kernel";
4576 break;
4577 case 2:
4578 type = eBinaryTypeUser;
4579 typestr = "userland dyld";
4580 break;
4581 case 3:
4582 type = eBinaryTypeStandalone;
4583 typestr = "standalone";
4584 break;
4585 case 4:
4587 typestr = "userland dyld_all_image_infos";
4588 break;
4589 }
4590 LLDB_LOGF(log,
4591 "LC_NOTE 'main bin spec' found, version %d type %d "
4592 "(%s), value 0x%" PRIx64 " value-is-slide==%s uuid %s",
4593 version, type, typestr, value,
4594 value_is_offset ? "true" : "false",
4595 uuid.GetAsString().c_str());
4596 if (!m_data_nsp->GetU32(&payload_offset, &log2_pagesize, 1))
4597 return false;
4598 if (version > 1 && !m_data_nsp->GetU32(&payload_offset, &platform, 1))
4599 return false;
4600 return true;
4601 }
4602 }
4603 }
4604 }
4605 return false;
4606}
4607
4609 std::vector<lldb::tid_t> &tids) {
4610 tids.clear();
4611 ModuleSP module_sp(GetModule());
4612 if (module_sp) {
4613 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4614
4617 StructuredData::Dictionary *dict = object_sp->GetAsDictionary();
4618 StructuredData::Array *threads;
4619 if (!dict->GetValueForKeyAsArray("threads", threads) || !threads) {
4620 LLDB_LOGF(log,
4621 "'process metadata' LC_NOTE does not have a 'threads' key");
4622 return false;
4623 }
4624 if (threads->GetSize() != GetNumThreadContexts()) {
4625 LLDB_LOGF(log, "Unable to read 'process metadata' LC_NOTE, number of "
4626 "threads does not match number of LC_THREADS.");
4627 return false;
4628 }
4629 const size_t num_threads = threads->GetSize();
4630 for (size_t i = 0; i < num_threads; i++) {
4631 std::optional<StructuredData::Dictionary *> maybe_thread =
4632 threads->GetItemAtIndexAsDictionary(i);
4633 if (!maybe_thread) {
4634 LLDB_LOGF(log,
4635 "Unable to read 'process metadata' LC_NOTE, threads "
4636 "array does not have a dictionary at index %zu.",
4637 i);
4638 return false;
4639 }
4640 StructuredData::Dictionary *thread = *maybe_thread;
4642 if (thread->GetValueForKeyAsInteger<lldb::tid_t>("thread_id", tid))
4643 if (tid == 0)
4645 tids.push_back(tid);
4646 }
4647
4648 if (log) {
4649 StreamString logmsg;
4650 logmsg.Printf("LC_NOTE 'process metadata' found: ");
4651 dict->Dump(logmsg, /* pretty_print */ false);
4652 LLDB_LOGF(log, "%s", logmsg.GetData());
4653 }
4654 return true;
4655 }
4656 }
4657 return false;
4658}
4659
4660/// Return the payload of an LC_NOTE, decompressing it if needed.
4661///
4662/// A payload is either stored as is, or compressed in the layout of a GNU
4663/// .zdebug section:
4664///
4665/// offset size contents
4666/// 0 4 magic "ZLIB"
4667/// 4 8 uncompressed size, big-endian uint64_t
4668/// 12 n RFC 1950 zlib stream
4669///
4670/// The size is big-endian regardless of the corefile's byte order. An
4671/// uncompressed payload must not start with the magic.
4672static llvm::Expected<std::string> ReadLCNotePayload(const DataExtractor &data,
4673 lldb::offset_t offset,
4674 uint64_t size) {
4675 const uint8_t *bytes = data.PeekData(offset, size);
4676 if (!bytes)
4677 return llvm::createStringError(
4678 "payload of %" PRIu64 " bytes is out of bounds", size);
4679 llvm::ArrayRef<uint8_t> payload(bytes, size);
4680
4681 constexpr llvm::StringLiteral magic = "ZLIB";
4682 constexpr size_t header_size = magic.size() + sizeof(uint64_t);
4683 if (!llvm::toStringRef(payload).starts_with(magic))
4684 return llvm::toStringRef(payload).str();
4685 if (payload.size() < header_size)
4686 return llvm::createStringError("compressed payload header is truncated");
4687
4688 uint64_t uncompressed_size =
4689 llvm::support::endian::read64be(payload.data() + magic.size());
4690 llvm::ArrayRef<uint8_t> compressed = payload.drop_front(header_size);
4691 // Deflate cannot exceed a 1032:1 ratio. A larger claimed size is corrupt and
4692 // must not size the allocation.
4693 if (uncompressed_size / 1032 > compressed.size())
4694 return llvm::createStringError("uncompressed size %" PRIu64
4695 " is impossible for %zu compressed bytes",
4696 uncompressed_size, compressed.size());
4697 if (!llvm::compression::zlib::isAvailable())
4698 return llvm::createStringError(
4699 "payload is zlib-compressed but LLDB was built without zlib");
4700
4701 llvm::SmallVector<uint8_t, 0> uncompressed;
4702 if (llvm::Error err = llvm::compression::zlib::decompress(
4703 compressed, uncompressed, uncompressed_size))
4704 return err;
4705 return llvm::toStringRef(uncompressed).str();
4706}
4707
4709 ModuleSP module_sp(GetModule());
4710 if (!module_sp)
4711 return {};
4712
4714 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4715 auto lc_notes = FindLC_NOTEByName("process metadata");
4716 if (lc_notes.size() == 0)
4717 return {};
4718
4719 if (lc_notes.size() > 1)
4720 LLDB_LOGF(
4721 log,
4722 "Multiple 'process metadata' LC_NOTEs found, only using the first.");
4723
4724 auto [payload_offset, payload_size] = lc_notes[0];
4725 llvm::Expected<std::string> json =
4726 ReadLCNotePayload(*m_data_nsp, payload_offset, payload_size);
4727 if (!json) {
4728 LLDB_LOG_ERROR(log, json.takeError(),
4729 "Unable to read 'process metadata' LC_NOTE: {0}");
4730 return {};
4731 }
4732 StructuredData::ObjectSP object_sp =
4733 StructuredData::ParseJSON(llvm::StringRef(*json).rtrim('\0'));
4734 if (!object_sp) {
4735 LLDB_LOGF(log, "Unable to read 'process metadata' LC_NOTE, did not "
4736 "parse as valid JSON.");
4737 return {};
4738 }
4739 StructuredData::Dictionary *dict = object_sp->GetAsDictionary();
4740 if (!dict) {
4741 LLDB_LOGF(log, "Unable to read 'process metadata' LC_NOTE, did not "
4742 "get a dictionary.");
4743 return {};
4744 }
4745
4746 return object_sp;
4747}
4748
4751 lldb_private::Thread &thread) {
4752 lldb::RegisterContextSP reg_ctx_sp;
4753
4754 ModuleSP module_sp(GetModule());
4755 if (module_sp) {
4756 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4759
4760 const FileRangeArray::Entry *thread_context_file_range =
4761 m_thread_context_offsets.GetEntryAtIndex(idx);
4762 if (thread_context_file_range) {
4763
4764 DataExtractor data(*m_data_nsp, thread_context_file_range->GetRangeBase(),
4765 thread_context_file_range->GetByteSize());
4766
4767 switch (m_header.cputype) {
4768 case llvm::MachO::CPU_TYPE_ARM64:
4769 case llvm::MachO::CPU_TYPE_ARM64_32:
4770 reg_ctx_sp =
4771 std::make_shared<RegisterContextDarwin_arm64_Mach>(thread, data);
4772 break;
4773
4774 case llvm::MachO::CPU_TYPE_ARM:
4775 reg_ctx_sp =
4776 std::make_shared<RegisterContextDarwin_arm_Mach>(thread, data);
4777 break;
4778
4779 case llvm::MachO::CPU_TYPE_X86_64:
4780 reg_ctx_sp =
4781 std::make_shared<RegisterContextDarwin_x86_64_Mach>(thread, data);
4782 break;
4783
4784 case llvm::MachO::CPU_TYPE_RISCV:
4785 reg_ctx_sp =
4786 std::make_shared<RegisterContextDarwin_riscv32_Mach>(thread, data);
4787 break;
4788 }
4789 }
4790 }
4791 return reg_ctx_sp;
4792}
4793
4795 switch (m_header.filetype) {
4796 case MH_OBJECT: // 0x1u
4797 if (GetAddressByteSize() == 4) {
4798 // 32 bit kexts are just object files, but they do have a valid
4799 // UUID load command.
4800 if (GetUUID()) {
4801 // this checking for the UUID load command is not enough we could
4802 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
4803 // this is required of kexts
4804 if (m_strata == eStrataInvalid)
4806 return eTypeSharedLibrary;
4807 }
4808 }
4809 return eTypeObjectFile;
4810
4811 case MH_EXECUTE:
4812 return eTypeExecutable; // 0x2u
4813 case MH_FVMLIB:
4814 return eTypeSharedLibrary; // 0x3u
4815 case MH_CORE:
4816 return eTypeCoreFile; // 0x4u
4817 case MH_PRELOAD:
4818 return eTypeSharedLibrary; // 0x5u
4819 case MH_DYLIB:
4820 return eTypeSharedLibrary; // 0x6u
4821 case MH_DYLINKER:
4822 return eTypeDynamicLinker; // 0x7u
4823 case MH_BUNDLE:
4824 return eTypeSharedLibrary; // 0x8u
4825 case MH_DYLIB_STUB:
4826 return eTypeStubLibrary; // 0x9u
4827 case MH_DSYM:
4828 return eTypeDebugInfo; // 0xAu
4829 case MH_KEXT_BUNDLE:
4830 return eTypeSharedLibrary; // 0xBu
4831 default:
4832 break;
4833 }
4834 return eTypeUnknown;
4835}
4836
4838 switch (m_header.filetype) {
4839 case MH_OBJECT: // 0x1u
4840 {
4841 // 32 bit kexts are just object files, but they do have a valid
4842 // UUID load command.
4843 if (GetUUID()) {
4844 // this checking for the UUID load command is not enough we could
4845 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as
4846 // this is required of kexts
4847 if (m_type == eTypeInvalid)
4849
4850 return eStrataKernel;
4851 }
4852 }
4853 return eStrataUnknown;
4854
4855 case MH_EXECUTE: // 0x2u
4856 // Check for the MH_DYLDLINK bit in the flags
4857 if (m_header.flags & MH_DYLDLINK) {
4858 return eStrataUser;
4859 } else {
4860 SectionList *section_list = GetSectionList();
4861 if (section_list) {
4862 if (section_list->FindSectionByName("__KLD"))
4863 return eStrataKernel;
4864 }
4865 }
4866 return eStrataRawImage;
4867
4868 case MH_FVMLIB:
4869 return eStrataUser; // 0x3u
4870 case MH_CORE:
4871 return eStrataUnknown; // 0x4u
4872 case MH_PRELOAD:
4873 return eStrataRawImage; // 0x5u
4874 case MH_DYLIB:
4875 return eStrataUser; // 0x6u
4876 case MH_DYLINKER:
4877 return eStrataUser; // 0x7u
4878 case MH_BUNDLE:
4879 return eStrataUser; // 0x8u
4880 case MH_DYLIB_STUB:
4881 return eStrataUser; // 0x9u
4882 case MH_DSYM:
4883 return eStrataUnknown; // 0xAu
4884 case MH_KEXT_BUNDLE:
4885 return eStrataKernel; // 0xBu
4886 default:
4887 break;
4888 }
4889 return eStrataUnknown;
4890}
4891
4892llvm::VersionTuple ObjectFileMachO::GetVersion() {
4893 ModuleSP module_sp(GetModule());
4894 if (module_sp) {
4895 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4896 llvm::MachO::dylib_command load_cmd;
4898 uint32_t version_cmd = 0;
4899 uint64_t version = 0;
4900 uint32_t i;
4901 for (i = 0; i < m_header.ncmds; ++i) {
4902 const lldb::offset_t cmd_offset = offset;
4903 if (!ReadMachOCommand(*m_data_nsp, offset, load_cmd))
4904 break;
4905
4906 if (load_cmd.cmd == LC_ID_DYLIB) {
4907 if (version_cmd == 0) {
4908 version_cmd = load_cmd.cmd;
4909 if (m_data_nsp->GetU32(&offset, &load_cmd.dylib, 4) == nullptr)
4910 break;
4911 version = load_cmd.dylib.current_version;
4912 }
4913 break; // Break for now unless there is another more complete version
4914 // number load command in the future.
4915 }
4916 offset = cmd_offset + load_cmd.cmdsize;
4917 }
4918
4919 if (version_cmd == LC_ID_DYLIB) {
4920 unsigned major = (version & 0xFFFF0000ull) >> 16;
4921 unsigned minor = (version & 0x0000FF00ull) >> 8;
4922 unsigned subminor = (version & 0x000000FFull);
4923 return llvm::VersionTuple(major, minor, subminor);
4924 }
4925 }
4926 return llvm::VersionTuple();
4927}
4928
4930 ModuleSP module_sp(GetModule());
4931 ArchSpec arch;
4932 if (module_sp) {
4933 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4934
4935 return GetArchitecture(module_sp, m_header, *m_data_nsp,
4937 }
4938 return arch;
4939}
4940
4942 addr_t &base_addr, UUID &uuid) {
4943 uuid.Clear();
4944 base_addr = LLDB_INVALID_ADDRESS;
4945 if (process && process->GetDynamicLoader()) {
4946 DynamicLoader *dl = process->GetDynamicLoader();
4947 LazyBool using_shared_cache;
4948 LazyBool private_shared_cache;
4949 FileSpec sc_filepath;
4950 std::optional<uint64_t> size;
4951 dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache,
4952 private_shared_cache, sc_filepath, size);
4953 }
4955 LLDB_LOGF(
4956 log,
4957 "inferior process shared cache has a UUID of %s, base address 0x%" PRIx64,
4958 uuid.GetAsString().c_str(), base_addr);
4959}
4960
4961// From dyld SPI header dyld_process_info.h
4962typedef void *dyld_process_info;
4964 uuid_t cacheUUID; // UUID of cache used by process
4965 uint64_t cacheBaseAddress; // load address of dyld shared cache
4966 bool noCache; // process is running without a dyld cache
4967 bool privateCache; // process is using a private copy of its dyld cache
4968};
4969
4970// #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with
4971// llvm enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile
4972// errors. So we need to use the actual underlying types of task_t and
4973// kern_return_t below.
4974extern "C" unsigned int /*task_t*/ mach_task_self();
4975
4977 uuid.Clear();
4978 base_addr = LLDB_INVALID_ADDRESS;
4979
4980#if defined(__APPLE__)
4981 uint8_t *(*dyld_get_all_image_infos)(void);
4982 dyld_get_all_image_infos =
4983 (uint8_t * (*)()) dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos");
4984 if (dyld_get_all_image_infos) {
4985 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos();
4986 if (dyld_all_image_infos_address) {
4987 uint32_t *version = (uint32_t *)
4988 dyld_all_image_infos_address; // version <mach-o/dyld_images.h>
4989 if (*version >= 13) {
4990 uuid_t *sharedCacheUUID_address = 0;
4991 int wordsize = sizeof(uint8_t *);
4992 if (wordsize == 8) {
4993 sharedCacheUUID_address =
4994 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
4995 160); // sharedCacheUUID <mach-o/dyld_images.h>
4996 if (*version >= 15)
4997 base_addr =
4998 *(uint64_t
4999 *)((uint8_t *)dyld_all_image_infos_address +
5000 176); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5001 } else {
5002 sharedCacheUUID_address =
5003 (uuid_t *)((uint8_t *)dyld_all_image_infos_address +
5004 84); // sharedCacheUUID <mach-o/dyld_images.h>
5005 if (*version >= 15) {
5006 base_addr = 0;
5007 base_addr =
5008 *(uint32_t
5009 *)((uint8_t *)dyld_all_image_infos_address +
5010 100); // sharedCacheBaseAddress <mach-o/dyld_images.h>
5011 }
5012 }
5013 uuid = UUID(sharedCacheUUID_address, sizeof(uuid_t));
5014 }
5015 }
5016 } else {
5017 // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI
5018 dyld_process_info (*dyld_process_info_create)(
5019 unsigned int /* task_t */ task, uint64_t timestamp,
5020 unsigned int /*kern_return_t*/ *kernelError);
5021 void (*dyld_process_info_get_cache)(void *info, void *cacheInfo);
5022 void (*dyld_process_info_release)(dyld_process_info info);
5023
5024 dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t,
5025 unsigned int /*kern_return_t*/ *))
5026 dlsym(RTLD_DEFAULT, "_dyld_process_info_create");
5027 dyld_process_info_get_cache = (void (*)(void *, void *))dlsym(
5028 RTLD_DEFAULT, "_dyld_process_info_get_cache");
5029 dyld_process_info_release =
5030 (void (*)(void *))dlsym(RTLD_DEFAULT, "_dyld_process_info_release");
5031
5032 if (dyld_process_info_create && dyld_process_info_get_cache) {
5033 unsigned int /*kern_return_t */ kern_ret;
5034 dyld_process_info process_info =
5035 dyld_process_info_create(::mach_task_self(), 0, &kern_ret);
5036 if (process_info) {
5038 memset(&sc_info, 0, sizeof(struct lldb_copy__dyld_process_cache_info));
5039 dyld_process_info_get_cache(process_info, &sc_info);
5040 if (sc_info.cacheBaseAddress != 0) {
5041 base_addr = sc_info.cacheBaseAddress;
5042 uuid = UUID(sc_info.cacheUUID, sizeof(uuid_t));
5043 }
5044 dyld_process_info_release(process_info);
5045 }
5046 }
5047 }
5049 if (log && uuid.IsValid())
5050 LLDB_LOGF(log,
5051 "lldb's in-memory shared cache has a UUID of %s base address of "
5052 "0x%" PRIx64,
5053 uuid.GetAsString().c_str(), base_addr);
5054#endif
5055}
5056
5057static llvm::VersionTuple FindMinimumVersionInfo(DataExtractor &data,
5058 lldb::offset_t offset,
5059 size_t ncmds) {
5060 for (size_t i = 0; i < ncmds; i++) {
5061 const lldb::offset_t load_cmd_offset = offset;
5062 llvm::MachO::load_command lc = {};
5063 if (!ReadMachOCommand(data, offset, lc))
5064 break;
5065
5066 uint32_t version = 0;
5067 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX ||
5068 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS ||
5069 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS ||
5070 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) {
5071 // struct version_min_command {
5072 // uint32_t cmd; // LC_VERSION_MIN_*
5073 // uint32_t cmdsize;
5074 // uint32_t version; // X.Y.Z encoded in nibbles xxxx.yy.zz
5075 // uint32_t sdk;
5076 // };
5077 // We want to read version.
5078 version = data.GetU32(&offset);
5079 } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) {
5080 // struct build_version_command {
5081 // uint32_t cmd; // LC_BUILD_VERSION
5082 // uint32_t cmdsize;
5083 // uint32_t platform;
5084 // uint32_t minos; // X.Y.Z encoded in nibbles xxxx.yy.zz
5085 // uint32_t sdk;
5086 // uint32_t ntools;
5087 // };
5088 // We want to read minos.
5089 offset += sizeof(uint32_t); // Skip over platform
5090 version = data.GetU32(&offset); // Extract minos
5091 }
5092
5093 if (version) {
5094 const uint32_t xxxx = version >> 16;
5095 const uint32_t yy = (version >> 8) & 0xffu;
5096 const uint32_t zz = version & 0xffu;
5097 if (xxxx)
5098 return llvm::VersionTuple(xxxx, yy, zz);
5099 }
5100 offset = load_cmd_offset + lc.cmdsize;
5101 }
5102 return llvm::VersionTuple();
5103}
5104
5111
5118
5120 return m_header.filetype == llvm::MachO::MH_DYLINKER;
5121}
5122
5124 // Dsymutil guarantees that the .debug_aranges accelerator is complete and can
5125 // be trusted by LLDB.
5126 return m_header.filetype == llvm::MachO::MH_DSYM;
5127}
5128
5132
5134 // Find the first address of the mach header which is the first non-zero file
5135 // sized section whose file offset is zero. This is the base file address of
5136 // the mach-o file which can be subtracted from the vmaddr of the other
5137 // segments found in memory and added to the load address
5138 ModuleSP module_sp = GetModule();
5139 if (!module_sp)
5140 return nullptr;
5141 SectionList *section_list = GetSectionList();
5142 if (!section_list)
5143 return nullptr;
5144
5145 // Some binaries can have a TEXT segment with a non-zero file offset.
5146 // Binaries in the shared cache are one example. Some hand-generated
5147 // binaries may not be laid out in the normal TEXT,DATA,LC_SYMTAB order
5148 // in the file, even though they're laid out correctly in vmaddr terms.
5149 SectionSP text_segment_sp =
5150 section_list->FindSectionByName(GetSegmentNameTEXT());
5151 if (text_segment_sp.get() && SectionIsLoadable(text_segment_sp.get()))
5152 return text_segment_sp.get();
5153
5154 const size_t num_sections = section_list->GetSize();
5155 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5156 Section *section = section_list->GetSectionAtIndex(sect_idx).get();
5157 if (section->GetFileOffset() == 0 && SectionIsLoadable(section))
5158 return section;
5159 }
5160
5161 return nullptr;
5162}
5163
5165 assert(section.GetObjectFile() == this && "Wrong object file!");
5166 SectionSP segment = section.GetParent();
5167 if (!segment)
5168 return false;
5169
5170 const bool is_data_const_got =
5171 segment->GetName() == "__DATA_CONST" && section.GetName() == "__got";
5172 const bool is_auth_const_ptr =
5173 segment->GetName() == "__AUTH_CONST" &&
5174 (section.GetName() == "__auth_got" || section.GetName() == "__auth_ptr");
5175 return is_data_const_got || is_auth_const_ptr;
5176}
5177
5179 if (!section)
5180 return false;
5181 if (section->IsThreadSpecific())
5182 return false;
5183 if (GetModule().get() != section->GetModule().get())
5184 return false;
5185 // firmware style binaries with llvm gcov segment do
5186 // not have that segment mapped into memory.
5187 if (section->GetName() == GetSegmentNameLLVM_COV()) {
5188 const Strata strata = GetStrata();
5189 if (strata == eStrataKernel || strata == eStrataRawImage)
5190 return false;
5191 }
5192 // Be careful with __LINKEDIT and __DWARF segments
5193 if (section->GetName() == GetSegmentNameLINKEDIT() ||
5194 section->GetName() == GetSegmentNameDWARF()) {
5195 // Only map __LINKEDIT and __DWARF if we have an in memory image and
5196 // this isn't a kernel binary like a kext or mach_kernel.
5197 const bool is_memory_image = (bool)m_process_wp.lock();
5198 const Strata strata = GetStrata();
5199 if (is_memory_image == false || strata == eStrataKernel)
5200 return false;
5201 }
5202 return true;
5203}
5204
5206 lldb::addr_t header_load_address, const Section *header_section,
5207 const Section *section) {
5208 ModuleSP module_sp = GetModule();
5209 if (module_sp && header_section && section &&
5210 header_load_address != LLDB_INVALID_ADDRESS) {
5211 lldb::addr_t file_addr = header_section->GetFileAddress();
5212 if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section))
5213 return section->GetFileAddress() - file_addr + header_load_address;
5214 }
5215 return LLDB_INVALID_ADDRESS;
5216}
5217
5219 bool value_is_offset) {
5221 ModuleSP module_sp = GetModule();
5222 if (!module_sp)
5223 return false;
5224
5225 SectionList *section_list = GetSectionList();
5226 if (!section_list)
5227 return false;
5228
5229 size_t num_loaded_sections = 0;
5230 const size_t num_sections = section_list->GetSize();
5231
5232 // Warn if some top-level segments map to the same address. The binary may be
5233 // malformed.
5234 const bool warn_multiple = true;
5235
5236 if (log) {
5237 StreamString logmsg;
5238 logmsg << "ObjectFileMachO::SetLoadAddress ";
5239 if (GetFileSpec())
5240 logmsg << "path='" << GetFileSpec().GetPath() << "' ";
5241 if (GetUUID()) {
5242 logmsg << "uuid=" << GetUUID().GetAsString();
5243 }
5244 LLDB_LOGF(log, "%s", logmsg.GetData());
5245 }
5246 if (value_is_offset) {
5247 // "value" is an offset to apply to each top level segment
5248 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5249 // Iterate through the object file sections to find all of the
5250 // sections that size on disk (to avoid __PAGEZERO) and load them
5251 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5252 if (SectionIsLoadable(section_sp.get())) {
5253 LLDB_LOG(
5254 log,
5255 "ObjectFileMachO::SetLoadAddress segment '{0}' load addr is {1:x}",
5256 section_sp->GetName(), section_sp->GetFileAddress() + value);
5257 if (target.SetSectionLoadAddress(section_sp,
5258 section_sp->GetFileAddress() + value,
5259 warn_multiple))
5260 ++num_loaded_sections;
5261 }
5262 }
5263 } else {
5264 // "value" is the new base address of the mach_header, adjust each
5265 // section accordingly
5266
5267 Section *mach_header_section = GetMachHeaderSection();
5268 if (mach_header_section) {
5269 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
5270 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
5271
5272 lldb::addr_t section_load_addr =
5274 value, mach_header_section, section_sp.get());
5275 if (section_load_addr != LLDB_INVALID_ADDRESS) {
5276 LLDB_LOG(log,
5277 "ObjectFileMachO::SetLoadAddress segment '{0}' load addr is "
5278 "{1:x}",
5279 section_sp->GetName(), section_load_addr);
5280 if (target.SetSectionLoadAddress(section_sp, section_load_addr,
5281 warn_multiple))
5282 ++num_loaded_sections;
5283 }
5284 }
5285 }
5286 }
5287 return num_loaded_sections > 0;
5288}
5289
5291 uint32_t version; // currently 1
5292 uint32_t imgcount; // number of binary images
5293 uint64_t entries_fileoff; // file offset in the corefile of where the array of
5294 // struct entry's begin.
5295 uint32_t entries_size; // size of 'struct entry'.
5296 uint32_t unused;
5297};
5298
5300 uint64_t filepath_offset; // offset in corefile to c-string of the file path,
5301 // UINT64_MAX if unavailable.
5302 uuid_t uuid; // uint8_t[16]. should be set to all zeroes if
5303 // uuid is unknown.
5304 uint64_t load_address; // UINT64_MAX if unknown.
5305 uint64_t seg_addrs_offset; // offset to the array of struct segment_vmaddr's.
5306 uint32_t segment_count; // The number of segments for this binary.
5307 uint32_t unused;
5308
5311 memset(&uuid, 0, sizeof(uuid_t));
5312 segment_count = 0;
5315 unused = 0;
5316 }
5319 memcpy(&uuid, &rhs.uuid, sizeof(uuid_t));
5323 unused = rhs.unused;
5324 }
5325};
5326
5328 char segname[16];
5329 uint64_t vmaddr;
5330 uint64_t unused;
5331
5333 memset(&segname, 0, 16);
5335 unused = 0;
5336 }
5338 memcpy(&segname, &rhs.segname, 16);
5339 vmaddr = rhs.vmaddr;
5340 unused = rhs.unused;
5341 }
5342};
5343
5344// Write the payload for the "all image infos" LC_NOTE into
5345// the supplied all_image_infos_payload, assuming that this
5346// will be written into the corefile starting at
5347// initial_file_offset.
5348//
5349// The placement of this payload is a little tricky. We're
5350// laying this out as
5351//
5352// 1. header (struct all_image_info_header)
5353// 2. Array of fixed-size (struct image_entry)'s, one
5354// per binary image present in the process.
5355// 3. Arrays of (struct segment_vmaddr)'s, a varying number
5356// for each binary image.
5357// 4. Variable length c-strings of binary image filepaths,
5358// one per binary.
5359//
5360// To compute where everything will be laid out in the
5361// payload, we need to iterate over the images and calculate
5362// how many segment_vmaddr structures each image will need,
5363// and how long each image's filepath c-string is. There
5364// are some multiple passes over the image list while calculating
5365// everything.
5366
5367static offset_t
5369 offset_t initial_file_offset,
5370 StreamString &all_image_infos_payload,
5372 Target &target = process_sp->GetTarget();
5373 ModuleList modules = target.GetImages();
5374
5375 // stack-only corefiles have no reason to include binaries that
5376 // are not executing; we're trying to make the smallest corefile
5377 // we can, so leave the rest out.
5379 modules.Clear();
5380
5381 std::set<std::string> executing_uuids;
5382 std::vector<ThreadSP> thread_list =
5383 process_sp->CalculateCoreFileThreadList(options);
5384 for (const ThreadSP &thread_sp : thread_list) {
5385 uint32_t stack_frame_count = thread_sp->GetStackFrameCount();
5386 for (uint32_t j = 0; j < stack_frame_count; j++) {
5387 StackFrameSP stack_frame_sp = thread_sp->GetStackFrameAtIndex(j);
5388 Address pc = stack_frame_sp->GetFrameCodeAddress();
5389 ModuleSP module_sp = pc.GetModule();
5390 if (module_sp) {
5391 UUID uuid = module_sp->GetUUID();
5392 if (uuid.IsValid()) {
5393 executing_uuids.insert(uuid.GetAsString());
5394 modules.AppendIfNeeded(module_sp);
5395 }
5396 }
5397 }
5398 }
5399 size_t modules_count = modules.GetSize();
5400
5401 struct all_image_infos_header infos;
5402 infos.version = 1;
5403 infos.imgcount = modules_count;
5404 infos.entries_size = sizeof(image_entry);
5405 infos.entries_fileoff = initial_file_offset + sizeof(all_image_infos_header);
5406 infos.unused = 0;
5407
5408 all_image_infos_payload.PutHex32(infos.version);
5409 all_image_infos_payload.PutHex32(infos.imgcount);
5410 all_image_infos_payload.PutHex64(infos.entries_fileoff);
5411 all_image_infos_payload.PutHex32(infos.entries_size);
5412 all_image_infos_payload.PutHex32(infos.unused);
5413
5414 // First create the structures for all of the segment name+vmaddr vectors
5415 // for each module, so we will know the size of them as we add the
5416 // module entries.
5417 std::vector<std::vector<segment_vmaddr>> modules_segment_vmaddrs;
5418 for (size_t i = 0; i < modules_count; i++) {
5419 ModuleSP module = modules.GetModuleAtIndex(i);
5420
5421 SectionList *sections = module->GetSectionList();
5422 size_t sections_count = sections->GetSize();
5423 std::vector<segment_vmaddr> segment_vmaddrs;
5424 for (size_t j = 0; j < sections_count; j++) {
5425 SectionSP section = sections->GetSectionAtIndex(j);
5426 if (!section->GetParent().get()) {
5427 addr_t vmaddr = section->GetLoadBaseAddress(&target);
5428 if (vmaddr == LLDB_INVALID_ADDRESS)
5429 continue;
5430 llvm::StringRef name = section->GetName();
5431 segment_vmaddr seg_vmaddr;
5432 // This is the uncommon case where strncpy is exactly
5433 // the right one, doesn't need to be null-terminated.
5434 // The segment name in a Mach-O LC_SEGMENT/LC_SEGMENT_64 is char[16] and
5435 // is not guaranteed to be null-terminated if all 16 characters are
5436 // used.
5437 // coverity[buffer_size_warning]
5438 strncpy(seg_vmaddr.segname, name.data(),
5439 std::min(name.size(), sizeof(seg_vmaddr.segname)));
5440 seg_vmaddr.vmaddr = vmaddr;
5441 seg_vmaddr.unused = 0;
5442 segment_vmaddrs.push_back(seg_vmaddr);
5443 }
5444 }
5445 modules_segment_vmaddrs.push_back(segment_vmaddrs);
5446 }
5447
5448 offset_t size_of_vmaddr_structs = 0;
5449 for (size_t i = 0; i < modules_segment_vmaddrs.size(); i++) {
5450 size_of_vmaddr_structs +=
5451 modules_segment_vmaddrs[i].size() * sizeof(segment_vmaddr);
5452 }
5453
5454 offset_t size_of_filepath_cstrings = 0;
5455 for (size_t i = 0; i < modules_count; i++) {
5456 ModuleSP module_sp = modules.GetModuleAtIndex(i);
5457 size_of_filepath_cstrings += module_sp->GetFileSpec().GetPath().size() + 1;
5458 }
5459
5460 // Calculate the file offsets of our "all image infos" payload in the
5461 // corefile. initial_file_offset the original value passed in to this method.
5462
5463 offset_t start_of_entries =
5464 initial_file_offset + sizeof(all_image_infos_header);
5465 offset_t start_of_seg_vmaddrs =
5466 start_of_entries + sizeof(image_entry) * modules_count;
5467 offset_t start_of_filenames = start_of_seg_vmaddrs + size_of_vmaddr_structs;
5468
5469 offset_t final_file_offset = start_of_filenames + size_of_filepath_cstrings;
5470
5471 // Now write the one-per-module 'struct image_entry' into the
5472 // StringStream; keep track of where the struct segment_vmaddr
5473 // entries for each module will end up in the corefile.
5474
5475 offset_t current_string_offset = start_of_filenames;
5476 offset_t current_segaddrs_offset = start_of_seg_vmaddrs;
5477 for (size_t i = 0; i < modules_count; i++) {
5478 ModuleSP module_sp = modules.GetModuleAtIndex(i);
5479
5480 struct image_entry ent;
5481 memcpy(&ent.uuid, module_sp->GetUUID().GetBytes().data(), sizeof(ent.uuid));
5482 if (modules_segment_vmaddrs[i].size() > 0) {
5483 ent.segment_count = modules_segment_vmaddrs[i].size();
5484 ent.seg_addrs_offset = current_segaddrs_offset;
5485 }
5486 ent.filepath_offset = current_string_offset;
5487 ObjectFile *objfile = module_sp->GetObjectFile();
5488 if (objfile) {
5489 Address base_addr(objfile->GetBaseAddress());
5490 if (base_addr.IsValid()) {
5491 ent.load_address = base_addr.GetLoadAddress(&target);
5492 }
5493 }
5494
5495 all_image_infos_payload.PutHex64(ent.filepath_offset);
5496 all_image_infos_payload.PutRawBytes(ent.uuid, sizeof(ent.uuid));
5497 all_image_infos_payload.PutHex64(ent.load_address);
5498 all_image_infos_payload.PutHex64(ent.seg_addrs_offset);
5499 all_image_infos_payload.PutHex32(ent.segment_count);
5500
5501 if (executing_uuids.find(module_sp->GetUUID().GetAsString()) !=
5502 executing_uuids.end())
5503 all_image_infos_payload.PutHex32(1);
5504 else
5505 all_image_infos_payload.PutHex32(0);
5506
5507 current_segaddrs_offset += ent.segment_count * sizeof(segment_vmaddr);
5508 current_string_offset += module_sp->GetFileSpec().GetPath().size() + 1;
5509 }
5510
5511 // Now write the struct segment_vmaddr entries into the StringStream.
5512
5513 for (size_t i = 0; i < modules_segment_vmaddrs.size(); i++) {
5514 if (modules_segment_vmaddrs[i].size() == 0)
5515 continue;
5516 for (struct segment_vmaddr segvm : modules_segment_vmaddrs[i]) {
5517 all_image_infos_payload.PutRawBytes(segvm.segname, sizeof(segvm.segname));
5518 all_image_infos_payload.PutHex64(segvm.vmaddr);
5519 all_image_infos_payload.PutHex64(segvm.unused);
5520 }
5521 }
5522
5523 for (size_t i = 0; i < modules_count; i++) {
5524 ModuleSP module_sp = modules.GetModuleAtIndex(i);
5525 std::string filepath = module_sp->GetFileSpec().GetPath();
5526 all_image_infos_payload.PutRawBytes(filepath.data(), filepath.size() + 1);
5527 }
5528
5529 return final_file_offset;
5530}
5531
5532// Temp struct used to combine contiguous memory regions with
5533// identical permissions.
5539
5542 Status &error) {
5543 // The FileSpec and Process are already checked in PluginManager::SaveCore.
5544 assert(options.GetOutputFile().has_value());
5545 assert(process_sp);
5546 const FileSpec outfile = options.GetOutputFile().value();
5547
5548 // MachO defaults to dirty pages
5551
5552 Target &target = process_sp->GetTarget();
5553 const ArchSpec target_arch = target.GetArchitecture();
5554 const llvm::Triple &target_triple = target_arch.GetTriple();
5555 if (target_triple.getVendor() == llvm::Triple::Apple &&
5556 (target_triple.getOS() == llvm::Triple::MacOSX ||
5557 target_triple.getOS() == llvm::Triple::IOS ||
5558 target_triple.getOS() == llvm::Triple::WatchOS ||
5559 target_triple.getOS() == llvm::Triple::TvOS ||
5560 target_triple.getOS() == llvm::Triple::BridgeOS ||
5561 target_triple.getOS() == llvm::Triple::XROS)) {
5562 bool make_core = false;
5563 switch (target_arch.GetMachine()) {
5564 case llvm::Triple::aarch64:
5565 case llvm::Triple::aarch64_32:
5566 case llvm::Triple::arm:
5567 case llvm::Triple::thumb:
5568 case llvm::Triple::x86:
5569 case llvm::Triple::x86_64:
5570 make_core = true;
5571 break;
5572 default:
5574 "unsupported core architecture: %s", target_triple.str().c_str());
5575 break;
5576 }
5577
5578 if (make_core) {
5579 CoreFileMemoryRanges core_ranges;
5580 error = process_sp->CalculateCoreFileSaveRanges(options, core_ranges);
5581 if (error.Success()) {
5582 const uint32_t addr_byte_size = target_arch.GetAddressByteSize();
5583 const ByteOrder byte_order = target_arch.GetByteOrder();
5584 std::vector<llvm::MachO::segment_command_64> segment_load_commands;
5585 for (const auto &core_range_info : core_ranges) {
5586 // TODO: Refactor RangeDataVector to have a data iterator.
5587 const auto &core_range = core_range_info.data;
5588 uint32_t cmd_type = LC_SEGMENT_64;
5589 uint32_t segment_size = sizeof(llvm::MachO::segment_command_64);
5590 if (addr_byte_size == 4) {
5591 cmd_type = LC_SEGMENT;
5592 segment_size = sizeof(llvm::MachO::segment_command);
5593 }
5594 // Skip any ranges with no read/write/execute permissions and empty
5595 // ranges.
5596 if (core_range.lldb_permissions == 0 || core_range.range.size() == 0)
5597 continue;
5598 uint32_t vm_prot = 0;
5599 if (core_range.lldb_permissions & ePermissionsReadable)
5600 vm_prot |= VM_PROT_READ;
5601 if (core_range.lldb_permissions & ePermissionsWritable)
5602 vm_prot |= VM_PROT_WRITE;
5603 if (core_range.lldb_permissions & ePermissionsExecutable)
5604 vm_prot |= VM_PROT_EXECUTE;
5605 const addr_t vm_addr = core_range.range.start();
5606 const addr_t vm_size = core_range.range.size();
5607 llvm::MachO::segment_command_64 segment = {
5608 cmd_type, // uint32_t cmd;
5609 segment_size, // uint32_t cmdsize;
5610 {0}, // char segname[16];
5611 vm_addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O
5612 vm_size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O
5613 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O
5614 vm_size, // uint64_t filesize; // uint32_t for 32-bit Mach-O
5615 vm_prot, // uint32_t maxprot;
5616 vm_prot, // uint32_t initprot;
5617 0, // uint32_t nsects;
5618 0}; // uint32_t flags;
5619 segment_load_commands.push_back(segment);
5620 }
5621
5622 StreamString buffer(Stream::eBinary, byte_order);
5623
5624 llvm::MachO::mach_header_64 mach_header;
5625 mach_header.magic = addr_byte_size == 8 ? MH_MAGIC_64 : MH_MAGIC;
5626 mach_header.cputype = target_arch.GetMachOCPUType();
5627 mach_header.cpusubtype = target_arch.GetMachOCPUSubType();
5628 mach_header.filetype = MH_CORE;
5629 mach_header.ncmds = segment_load_commands.size();
5630 mach_header.flags = 0;
5631 mach_header.reserved = 0;
5632 ThreadList &thread_list = process_sp->GetThreadList();
5633 const uint32_t num_threads = thread_list.GetSize();
5634
5635 // Make an array of LC_THREAD data items. Each one contains the
5636 // contents of the LC_THREAD load command. The data doesn't contain
5637 // the load command + load command size, we will add the load command
5638 // and load command size as we emit the data.
5639 std::vector<StreamString> LC_THREAD_datas(num_threads);
5640 for (auto &LC_THREAD_data : LC_THREAD_datas) {
5641 LC_THREAD_data.GetFlags().Set(Stream::eBinary);
5642 LC_THREAD_data.SetByteOrder(byte_order);
5643 }
5644 for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) {
5645 ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx));
5646 if (thread_sp) {
5647 switch (mach_header.cputype) {
5648 case llvm::MachO::CPU_TYPE_ARM64:
5649 case llvm::MachO::CPU_TYPE_ARM64_32:
5651 thread_sp.get(), LC_THREAD_datas[thread_idx]);
5652 break;
5653
5654 case llvm::MachO::CPU_TYPE_ARM:
5656 thread_sp.get(), LC_THREAD_datas[thread_idx]);
5657 break;
5658
5659 case llvm::MachO::CPU_TYPE_X86_64:
5661 thread_sp.get(), LC_THREAD_datas[thread_idx]);
5662 break;
5663
5664 case llvm::MachO::CPU_TYPE_RISCV:
5666 thread_sp.get(), LC_THREAD_datas[thread_idx]);
5667 break;
5668 }
5669 }
5670 }
5671
5672 // The size of the load command is the size of the segments...
5673 if (addr_byte_size == 8) {
5674 mach_header.sizeofcmds = segment_load_commands.size() *
5675 sizeof(llvm::MachO::segment_command_64);
5676 } else {
5677 mach_header.sizeofcmds = segment_load_commands.size() *
5678 sizeof(llvm::MachO::segment_command);
5679 }
5680
5681 // and the size of all LC_THREAD load command
5682 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
5683 ++mach_header.ncmds;
5684 mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize();
5685 }
5686
5687 // Bits will be set to indicate which bits are NOT used in
5688 // addressing in this process or 0 for unknown.
5689 uint64_t address_mask = process_sp->GetCodeAddressMask();
5690 if (address_mask != LLDB_INVALID_ADDRESS_MASK) {
5691 // LC_NOTE "addrable bits"
5692 mach_header.ncmds++;
5693 mach_header.sizeofcmds += sizeof(llvm::MachO::note_command);
5694 }
5695
5696 // LC_NOTE "process metadata"
5697 mach_header.ncmds++;
5698 mach_header.sizeofcmds += sizeof(llvm::MachO::note_command);
5699
5700 // LC_NOTE "all image infos"
5701 mach_header.ncmds++;
5702 mach_header.sizeofcmds += sizeof(llvm::MachO::note_command);
5703
5704 // Write the mach header
5705 buffer.PutHex32(mach_header.magic);
5706 buffer.PutHex32(mach_header.cputype);
5707 buffer.PutHex32(mach_header.cpusubtype);
5708 buffer.PutHex32(mach_header.filetype);
5709 buffer.PutHex32(mach_header.ncmds);
5710 buffer.PutHex32(mach_header.sizeofcmds);
5711 buffer.PutHex32(mach_header.flags);
5712 if (addr_byte_size == 8) {
5713 buffer.PutHex32(mach_header.reserved);
5714 }
5715
5716 // Skip the mach header and all load commands and align to the next
5717 // 0x1000 byte boundary
5718 addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds;
5719
5720 file_offset = llvm::alignTo(file_offset, 16);
5721 std::vector<std::unique_ptr<LCNoteEntry>> lc_notes;
5722
5723 // Add "addrable bits" LC_NOTE when an address mask is available
5724 if (address_mask != LLDB_INVALID_ADDRESS_MASK) {
5725 std::unique_ptr<LCNoteEntry> addrable_bits_lcnote_up(
5726 new LCNoteEntry(byte_order));
5727 addrable_bits_lcnote_up->name = "addrable bits";
5728 addrable_bits_lcnote_up->payload_file_offset = file_offset;
5729 int bits = std::bitset<64>(~address_mask).count();
5730 addrable_bits_lcnote_up->payload.PutHex32(4); // version
5731 addrable_bits_lcnote_up->payload.PutHex32(
5732 bits); // # of bits used for low addresses
5733 addrable_bits_lcnote_up->payload.PutHex32(
5734 bits); // # of bits used for high addresses
5735 addrable_bits_lcnote_up->payload.PutHex32(0); // reserved
5736
5737 file_offset += addrable_bits_lcnote_up->payload.GetSize();
5738
5739 lc_notes.push_back(std::move(addrable_bits_lcnote_up));
5740 }
5741
5742 // Add "process metadata" LC_NOTE
5743 std::unique_ptr<LCNoteEntry> thread_extrainfo_lcnote_up(
5744 new LCNoteEntry(byte_order));
5745 thread_extrainfo_lcnote_up->name = "process metadata";
5746 thread_extrainfo_lcnote_up->payload_file_offset = file_offset;
5747
5749 std::make_shared<StructuredData::Dictionary>());
5751 std::make_shared<StructuredData::Array>());
5752 for (const ThreadSP &thread_sp :
5753 process_sp->CalculateCoreFileThreadList(options)) {
5755 std::make_shared<StructuredData::Dictionary>());
5756 thread->AddIntegerItem("thread_id", thread_sp->GetID());
5757 threads->AddItem(thread);
5758 }
5759 dict->AddItem("threads", threads);
5760 StreamString strm;
5761 dict->Dump(strm, /* pretty */ false);
5762 thread_extrainfo_lcnote_up->payload.PutRawBytes(strm.GetData(),
5763 strm.GetSize());
5764
5765 file_offset += thread_extrainfo_lcnote_up->payload.GetSize();
5766 file_offset = llvm::alignTo(file_offset, 16);
5767 lc_notes.push_back(std::move(thread_extrainfo_lcnote_up));
5768
5769 // Add "all image infos" LC_NOTE
5770 std::unique_ptr<LCNoteEntry> all_image_infos_lcnote_up(
5771 new LCNoteEntry(byte_order));
5772 all_image_infos_lcnote_up->name = "all image infos";
5773 all_image_infos_lcnote_up->payload_file_offset = file_offset;
5774 file_offset = CreateAllImageInfosPayload(
5775 process_sp, file_offset, all_image_infos_lcnote_up->payload,
5776 options);
5777 lc_notes.push_back(std::move(all_image_infos_lcnote_up));
5778
5779 // Add LC_NOTE load commands
5780 for (auto &lcnote : lc_notes) {
5781 // Add the LC_NOTE load command to the file.
5782 buffer.PutHex32(LC_NOTE);
5783 buffer.PutHex32(sizeof(llvm::MachO::note_command));
5784 char namebuf[16];
5785 memset(namebuf, 0, sizeof(namebuf));
5786 // This is the uncommon case where strncpy is exactly
5787 // the right one, doesn't need to be null-terminated.
5788 // LC_NOTE name field is char[16] and is not guaranteed to be
5789 // null-terminated.
5790 // coverity[buffer_size_warning]
5791 strncpy(namebuf, lcnote->name.c_str(), sizeof(namebuf));
5792 buffer.PutRawBytes(namebuf, sizeof(namebuf));
5793 buffer.PutHex64(lcnote->payload_file_offset);
5794 buffer.PutHex64(lcnote->payload.GetSize());
5795 }
5796
5797 // Align to 4096-byte page boundary for the LC_SEGMENTs.
5798 file_offset = llvm::alignTo(file_offset, 4096);
5799
5800 for (auto &segment : segment_load_commands) {
5801 segment.fileoff = file_offset;
5802 file_offset += segment.filesize;
5803 }
5804
5805 // Write out all of the LC_THREAD load commands
5806 for (const auto &LC_THREAD_data : LC_THREAD_datas) {
5807 const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize();
5808 buffer.PutHex32(LC_THREAD);
5809 buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data
5810 buffer.Write(LC_THREAD_data.GetString().data(), LC_THREAD_data_size);
5811 }
5812
5813 // Write out all of the segment load commands
5814 for (const auto &segment : segment_load_commands) {
5815 buffer.PutHex32(segment.cmd);
5816 buffer.PutHex32(segment.cmdsize);
5817 buffer.PutRawBytes(segment.segname, sizeof(segment.segname));
5818 if (addr_byte_size == 8) {
5819 buffer.PutHex64(segment.vmaddr);
5820 buffer.PutHex64(segment.vmsize);
5821 buffer.PutHex64(segment.fileoff);
5822 buffer.PutHex64(segment.filesize);
5823 } else {
5824 buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr));
5825 buffer.PutHex32(static_cast<uint32_t>(segment.vmsize));
5826 buffer.PutHex32(static_cast<uint32_t>(segment.fileoff));
5827 buffer.PutHex32(static_cast<uint32_t>(segment.filesize));
5828 }
5829 buffer.PutHex32(segment.maxprot);
5830 buffer.PutHex32(segment.initprot);
5831 buffer.PutHex32(segment.nsects);
5832 buffer.PutHex32(segment.flags);
5833 }
5834
5835 std::string core_file_path(outfile.GetPath());
5836 auto core_file = FileSystem::Instance().Open(
5839 if (!core_file) {
5840 error = Status::FromError(core_file.takeError());
5841 } else {
5842 // Read 1 page at a time
5843 uint8_t bytes[0x1000];
5844 // Write the mach header and load commands out to the core file
5845 size_t bytes_written = buffer.GetString().size();
5846 error =
5847 core_file.get()->Write(buffer.GetString().data(), bytes_written);
5848 if (error.Success()) {
5849
5850 for (auto &lcnote : lc_notes) {
5851 if (core_file.get()->SeekFromStart(lcnote->payload_file_offset) ==
5852 -1) {
5854 "Unable to seek to corefile pos "
5855 "to write '%s' LC_NOTE payload",
5856 lcnote->name.c_str());
5857 return false;
5858 }
5859 bytes_written = lcnote->payload.GetSize();
5860 error = core_file.get()->Write(lcnote->payload.GetData(),
5861 bytes_written);
5862 if (!error.Success())
5863 return false;
5864 }
5865
5866 // Now write the file data for all memory segments in the process
5867 for (const auto &segment : segment_load_commands) {
5868 if (core_file.get()->SeekFromStart(segment.fileoff) == -1) {
5870 "unable to seek to offset 0x%" PRIx64 " in '%s'",
5871 segment.fileoff, core_file_path.c_str());
5872 break;
5873 }
5874
5875 target.GetDebugger().GetAsyncOutputStream()->Printf(
5876 "Saving %" PRId64
5877 " bytes of data for memory region at 0x%" PRIx64 "\n",
5878 segment.vmsize, segment.vmaddr);
5879 addr_t bytes_left = segment.vmsize;
5880 addr_t addr = segment.vmaddr;
5882 while (bytes_left > 0 && error.Success()) {
5883 const size_t bytes_to_read =
5884 bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left;
5885
5886 // In a savecore setting, we don't really care about caching,
5887 // as the data is dumped and very likely never read again,
5888 // so we call ReadMemoryFromInferior to bypass it.
5889 const size_t bytes_read = process_sp->ReadMemoryFromInferior(
5890 addr, bytes, bytes_to_read, memory_read_error);
5891
5892 if (bytes_read == bytes_to_read) {
5893 size_t bytes_written = bytes_read;
5894 error = core_file.get()->Write(bytes, bytes_written);
5895 bytes_left -= bytes_read;
5896 addr += bytes_read;
5897 } else {
5898 // Some pages within regions are not readable, those should
5899 // be zero filled
5900 memset(bytes, 0, bytes_to_read);
5901 size_t bytes_written = bytes_to_read;
5902 error = core_file.get()->Write(bytes, bytes_written);
5903 bytes_left -= bytes_to_read;
5904 addr += bytes_to_read;
5905 }
5906 }
5907 }
5908 }
5909 }
5910 }
5911 }
5912 return true; // This is the right plug to handle saving core files for
5913 // this process
5914 }
5915 return false;
5916}
5917
5920 MachOCorefileAllImageInfos image_infos;
5923
5924 auto lc_notes = FindLC_NOTEByName("all image infos");
5925 for (auto lc_note : lc_notes) {
5926 offset_t payload_offset = std::get<0>(lc_note);
5927 // Read the struct all_image_infos_header.
5928 uint32_t version = m_data_nsp->GetU32(&payload_offset);
5929 if (version != 1) {
5930 return image_infos;
5931 }
5932 uint32_t imgcount = m_data_nsp->GetU32(&payload_offset);
5933 uint64_t entries_fileoff = m_data_nsp->GetU64(&payload_offset);
5934 // 'entries_size' is not used, nor is the 'unused' entry.
5935 // offset += 4; // uint32_t entries_size;
5936 // offset += 4; // uint32_t unused;
5937
5938 LLDB_LOGF(log, "LC_NOTE 'all image infos' found version %d with %d images",
5939 version, imgcount);
5940 payload_offset = entries_fileoff;
5941 for (uint32_t i = 0; i < imgcount; i++) {
5942 // Read the struct image_entry.
5943 offset_t filepath_offset = m_data_nsp->GetU64(&payload_offset);
5944 uuid_t uuid;
5945 memcpy(&uuid, m_data_nsp->GetData(&payload_offset, sizeof(uuid_t)),
5946 sizeof(uuid_t));
5947 uint64_t load_address = m_data_nsp->GetU64(&payload_offset);
5948 offset_t seg_addrs_offset = m_data_nsp->GetU64(&payload_offset);
5949 uint32_t segment_count = m_data_nsp->GetU32(&payload_offset);
5950 uint32_t currently_executing = m_data_nsp->GetU32(&payload_offset);
5951
5953 image_entry.filename =
5954 (const char *)m_data_nsp->GetCStr(&filepath_offset);
5955 image_entry.uuid = UUID(uuid, sizeof(uuid_t));
5956 image_entry.load_address = load_address;
5957 image_entry.currently_executing = currently_executing;
5958
5959 offset_t seg_vmaddrs_offset = seg_addrs_offset;
5960 for (uint32_t j = 0; j < segment_count; j++) {
5961 char segname[17];
5962 m_data_nsp->CopyData(seg_vmaddrs_offset, 16, segname);
5963 segname[16] = '\0';
5964 seg_vmaddrs_offset += 16;
5965 uint64_t vmaddr = m_data_nsp->GetU64(&seg_vmaddrs_offset);
5966 seg_vmaddrs_offset += 8; /* unused */
5967
5968 std::tuple<ConstString, addr_t> new_seg{ConstString(segname), vmaddr};
5969 image_entry.segment_load_addresses.push_back(new_seg);
5970 }
5971 LLDB_LOGF(log, " image entry: %s %s 0x%" PRIx64 " %s",
5972 image_entry.filename.c_str(),
5973 image_entry.uuid.GetAsString().c_str(),
5975 image_entry.currently_executing ? "currently executing"
5976 : "not currently executing");
5977 image_infos.all_image_infos.push_back(image_entry);
5978 }
5979 }
5980
5981 lc_notes = FindLC_NOTEByName("load binary");
5982 for (auto lc_note : lc_notes) {
5983 offset_t payload_offset = std::get<0>(lc_note);
5984 uint32_t version = m_data_nsp->GetU32(&payload_offset);
5985 if (version == 1) {
5986 uuid_t uuid;
5987 memcpy(&uuid, m_data_nsp->GetData(&payload_offset, sizeof(uuid_t)),
5988 sizeof(uuid_t));
5989 uint64_t load_address = m_data_nsp->GetU64(&payload_offset);
5990 uint64_t slide = m_data_nsp->GetU64(&payload_offset);
5991 std::string filename = m_data_nsp->GetCStr(&payload_offset);
5992
5994 image_entry.filename = filename;
5995 image_entry.uuid = UUID(uuid, sizeof(uuid_t));
5996 image_entry.load_address = load_address;
5997 image_entry.slide = slide;
5998 image_entry.currently_executing = true;
5999 image_infos.all_image_infos.push_back(image_entry);
6000 LLDB_LOGF(log,
6001 "LC_NOTE 'load binary' found, filename %s uuid %s load "
6002 "address 0x%" PRIx64 " slide 0x%" PRIx64,
6003 filename.c_str(),
6004 image_entry.uuid.IsValid()
6005 ? image_entry.uuid.GetAsString().c_str()
6006 : "00000000-0000-0000-0000-000000000000",
6007 load_address, slide);
6008 }
6009 }
6010
6011 return image_infos;
6012}
6013
6017
6018 bool found_platform_binary = false;
6019 ModuleList added_modules;
6020
6021 llvm::SmallVector<const MachOCorefileImageEntry *> pending_images;
6022 std::vector<DynamicLoader::BinarySpec> pending_specs;
6023
6024 for (MachOCorefileImageEntry &image : image_infos.all_image_infos) {
6025 // If this is a platform binary, it has been loaded (or registered with
6026 // the DynamicLoader to be loaded), we don't need to do any further
6027 // processing. We're not going to call ModulesDidLoad on this in this
6028 // method, so notify==true.
6029 //
6030 // Setting up a platform binary can replace the Target's platform and
6031 // dynamic loader, so no image is searched for until this loop has run to
6032 // the end.
6033 if (process.GetTarget()
6034 .GetDebugger()
6037 true /* notify */)) {
6038 LLDB_LOGF(log,
6039 "ObjectFileMachO::%s binary at 0x%" PRIx64
6040 " is a platform binary, has been handled by a Platform plugin.",
6041 __FUNCTION__, image.load_address);
6042 found_platform_binary = true;
6043 continue;
6044 }
6045
6046 bool value_is_offset = image.load_address == LLDB_INVALID_ADDRESS;
6047 uint64_t value = value_is_offset ? image.slide : image.load_address;
6048 if (value_is_offset && value == LLDB_INVALID_ADDRESS) {
6049 // We have neither address nor slide; so we will find the binary
6050 // by UUID and load it at slide/offset 0.
6051 value = 0;
6052 }
6053
6054 // We have either a UUID, or we have a load address which
6055 // and can try to read load commands and find a UUID.
6056 if (!image.uuid.IsValid() &&
6057 (value_is_offset || value == LLDB_INVALID_ADDRESS))
6058 continue;
6059
6061 bin_spec.name = image.filename;
6062 bin_spec.uuid = image.uuid;
6063 bin_spec.value = value;
6064 bin_spec.value_is_offset = value_is_offset;
6066 bin_spec.notify = false;
6067 // Userland Darwin binaries will have segment load addresses via
6068 // the `all image infos` LC_NOTE.
6069 bin_spec.set_address_in_target = image.segment_load_addresses.empty();
6071 !image.segment_load_addresses.empty();
6072
6073 pending_images.push_back(&image);
6074 pending_specs.push_back(std::move(bin_spec));
6075 }
6076
6077 DynamicLoader::LocateBinaries(&process, pending_specs);
6078
6079 for (auto [image, bin_spec] :
6080 llvm::zip_equal(pending_images, pending_specs)) {
6081 ModuleSP module_sp;
6082 if (llvm::Expected<ModuleSP> loaded =
6083 DynamicLoader::LoadBinaryInTarget(&process, bin_spec)) {
6084 module_sp = *loaded;
6085 } else if (bin_spec.force_symbol_search) {
6087 << llvm::toString(loaded.takeError()) << "\n";
6088 } else {
6089 // A corefile image that isn't on this machine is routine, and has
6090 // already been logged.
6091 llvm::consumeError(loaded.takeError());
6092 }
6093
6094 if (!module_sp)
6095 continue;
6096
6097 added_modules.Append(module_sp, false /* notify */);
6098
6099 // We have a list of segment load address
6100 if (image->segment_load_addresses.size() > 0) {
6101 if (log) {
6102 std::string uuidstr = image->uuid.GetAsString();
6103 log->Printf("ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
6104 "UUID %s with section load addresses",
6105 module_sp->GetFileSpec().GetPath().c_str(),
6106 uuidstr.c_str());
6107 }
6108 ObjectFile *objfile = module_sp->GetObjectFile();
6109 SectionList *sectlist = objfile ? objfile->GetSectionList() : nullptr;
6110 for (auto name_vmaddr_tuple : image->segment_load_addresses) {
6111 if (sectlist) {
6112 SectionSP sect_sp =
6113 sectlist->FindSectionByName(std::get<0>(name_vmaddr_tuple));
6114 if (sect_sp) {
6116 sect_sp, std::get<1>(name_vmaddr_tuple));
6117 }
6118 }
6119 }
6120 } else {
6121 if (log) {
6122 std::string uuidstr = image->uuid.GetAsString();
6123 log->Printf("ObjectFileMachO::LoadCoreFileImages adding binary '%s' "
6124 "UUID %s with %s 0x%" PRIx64,
6125 module_sp->GetFileSpec().GetPath().c_str(), uuidstr.c_str(),
6126 bin_spec.value_is_offset ? "slide" : "load address",
6127 bin_spec.value);
6128 }
6129 bool changed;
6130 module_sp->SetLoadAddress(process.GetTarget(), bin_spec.value,
6131 bin_spec.value_is_offset, changed);
6132 }
6133 }
6134
6135 if (added_modules.GetSize() > 0) {
6136 process.GetTarget().ModulesDidLoad(added_modules);
6137 process.Flush();
6138 return true;
6139 }
6140 // Return true if the only binary we found was the platform binary,
6141 // and it was loaded outside the scope of this method.
6142 if (found_platform_binary)
6143 return true;
6144
6145 // No binaries.
6146 return false;
6147}
unsigned char uuid_t[16]
static llvm::raw_ostream & error(Stream &strm)
void dyld_shared_cache_copy_uuid(dyld_shared_cache_t cache, uuid_t *uuid)
struct dyld_image_s * dyld_image_t
struct dyld_shared_cache_s * dyld_shared_cache_t
bool dyld_image_copy_uuid(dyld_image_t cache, uuid_t *uuid)
void dyld_shared_cache_for_each_image(dyld_shared_cache_t cache, void(^block)(dyld_image_t image))
static const char * memory_read_error
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
static bool ReadMachOCommand(DataExtractor &data, lldb::offset_t &offset, T &cmd)
Read a Mach-O load-command header (cmd + cmdsize) from data at offset into cmd, advancing offset by 8...
static uint32_t MachHeaderSizeFromMagic(uint32_t magic)
static uint32_t GetSegmentPermissions(const llvm::MachO::segment_command_64 &seg_cmd)
static constexpr llvm::StringLiteral g_loader_path
static std::optional< struct nlist_64 > ParseNList(DataExtractor &nlist_data, lldb::offset_t &nlist_data_offset, size_t nlist_byte_size)
static bool ReadMachOCommand(const DataExtractor &data, lldb::offset_t &offset, T &cmd)
Read a Mach-O load-command header (cmd + cmdsize) from data at offset into cmd, advancing offset by 8...
static constexpr llvm::StringLiteral g_executable_path
static void PrintRegisterValue(RegisterContext *reg_ctx, const char *name, const char *alt_name, size_t reg_byte_size, Stream &data)
static llvm::Expected< std::string > ReadLCNotePayload(const DataExtractor &data, lldb::offset_t offset, uint64_t size)
Return the payload of an LC_NOTE, decompressing it if needed.
static lldb::SectionType GetSectionType(uint32_t flags, llvm::StringRef section_name)
static llvm::StringRef GetOSName(uint32_t cmd)
static llvm::VersionTuple FindMinimumVersionInfo(DataExtractor &data, lldb::offset_t offset, size_t ncmds)
unsigned int mach_task_self()
static void UpdateHasSourceFilesAndDebugMap(SymbolType type, const struct nlist_64 &nlist, bool &has_source_files, bool &has_debug_map)
#define MACHO_NLIST_ARM_SYMBOL_IS_THUMB
@ NonDebugSymbols
@ DebugSymbols
void * dyld_process_info
static uint32_t MachHeaderSizeFromMagic(uint32_t magic)
static offset_t CreateAllImageInfosPayload(const lldb::ProcessSP &process_sp, offset_t initial_file_offset, StreamString &all_image_infos_payload, lldb_private::SaveCoreOptions &options)
static bool TryParseV2ObjCMetadataSymbol(const char *&symbol_name, const char *&symbol_name_non_abi_mangled, SymbolType &type)
static SymbolType GetSymbolType(const char *&symbol_name, bool &demangled_is_synthesized, const SectionSP &text_section_sp, const SectionSP &data_section_sp, const SectionSP &data_dirty_section_sp, const SectionSP &data_const_section_sp, const SectionSP &symbol_section)
#define LLDB_PLUGIN_DEFINE(PluginName)
#define KERN_SUCCESS
Constants returned by various RegisterContextDarwin_*** functions.
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:91
static llvm::StringRef GetName(XcodeSDK::Type type)
Definition XcodeSDK.cpp:21
std::vector< SectionInfo > m_section_infos
SectionSP GetSection(uint8_t n_sect, addr_t file_addr)
MachSymtabSectionInfo(SectionList *section_list)
bool SectionIsLoadable(const lldb_private::Section *section)
llvm::MachO::mach_header m_header
bool m_allow_assembly_emulation_unwind_plans
std::optional< llvm::VersionTuple > m_min_os_version
lldb_private::AddressableBits GetAddressableBits() override
Some object files may have the number of bits used for addressing embedded in them,...
uint32_t GetDependentModules(lldb_private::FileSpecList &files) override
Extract the dependent modules from an object file.
static lldb_private::ObjectFile * CreateMemoryInstance(const lldb::ModuleSP &module_sp, lldb::WritableDataBufferSP data_sp, const lldb::ProcessSP &process_sp, lldb::addr_t header_addr)
FileRangeArray m_thread_context_offsets
ObjectFile::Type CalculateType() override
The object file should be able to calculate its type by looking at its file header and possibly the s...
lldb_private::RangeVector< uint32_t, uint32_t, 8 > EncryptedFileRanges
static bool MagicBytesMatch(lldb::DataExtractorSP extractor_sp, lldb::addr_t offset, lldb::addr_t length)
std::vector< std::tuple< lldb::offset_t, lldb::offset_t > > FindLC_NOTEByName(std::string name)
void Dump(lldb_private::Stream *s) override
Dump a description of this object to a Stream.
bool AllowAssemblyEmulationUnwindPlans() override
Returns if the function bounds for symbols in this symbol file are likely accurate.
std::string GetIdentifierString() override
Some object files may have an identifier string embedded in them, e.g.
void ProcessSegmentCommand(const llvm::MachO::load_command &load_cmd, lldb::offset_t offset, uint32_t cmd_idx, SegmentParsingContext &context)
std::vector< llvm::MachO::section_64 > m_mach_sections
static llvm::StringRef GetSegmentNameLINKEDIT()
bool SetLoadAddress(lldb_private::Target &target, lldb::addr_t value, bool value_is_offset) override
Sets the load address for an entire module, assuming a rigid slide of sections, if possible in the im...
void GetProcessSharedCacheUUID(lldb_private::Process *, lldb::addr_t &base_addr, lldb_private::UUID &uuid)
Intended for same-host arm device debugging where lldb needs to detect libraries in the shared cache ...
bool IsGOTSection(const lldb_private::Section &section) const override
Returns true if the section is a global offset table section.
bool GetIsDynamicLinkEditor() override
Return true if this file is a dynamic link editor (dyld)
lldb::ByteOrder GetByteOrder() const override
Gets whether endian swapping should occur when extracting data from this object file.
bool ParseHeader() override
Attempts to parse the object header.
bool IsStripped() override
Detect if this object file has been stripped of local symbols.
lldb_private::UUID GetUUID() override
Gets the UUID for this object file.
llvm::VersionTuple GetMinimumOSVersion() override
Get the minimum OS version this object file can run on.
static llvm::StringRef GetPluginDescriptionStatic()
static llvm::StringRef GetPluginNameStatic()
lldb::RegisterContextSP GetThreadContextAtIndex(uint32_t idx, lldb_private::Thread &thread) override
lldb_private::FileSpecList m_reexported_dylibs
static void GetAllArchSpecs(const llvm::MachO::mach_header &header, const lldb_private::DataExtractor &data, lldb::offset_t lc_offset, lldb_private::ModuleSpec &base_spec, lldb_private::ModuleSpecList &all_specs)
Enumerate all ArchSpecs supported by this Mach-O file.
bool GetCorefileThreadExtraInfos(std::vector< lldb::tid_t > &tids) override
Get metadata about thread ids from the corefile.
static llvm::StringRef GetSectionNameEHFrame()
bool IsDynamicLoader() const
static void Terminate()
bool IsExecutable() const override
Tells whether this object file is capable of being the main executable for a process.
lldb_private::Address GetEntryPointAddress() override
Returns the address of the Entry Point in this object file - if the object file doesn't have an entry...
lldb_private::Address m_entry_point_address
static void Initialize()
bool LoadCoreFileImages(lldb_private::Process &process) override
Load binaries listed in a corefile.
bool CanTrustAddressRanges() override
Can we trust the address ranges accelerator associated with this object file to be complete.
void SanitizeSegmentCommand(llvm::MachO::segment_command_64 &seg_cmd, uint32_t cmd_idx)
static lldb_private::ObjectFile * CreateInstance(const lldb::ModuleSP &module_sp, lldb::DataExtractorSP extractor_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t file_offset, lldb::offset_t length)
llvm::VersionTuple GetSDKVersion() override
Get the SDK OS version this object file was built with.
lldb_private::ArchSpec GetArchitecture() override
Get the ArchSpec for this object file.
lldb_private::Address GetBaseAddress() override
Returns base address of this object file.
size_t ParseSymtab()
bool IsSharedCacheBinary() const override
Tells whether this object file is part of a shared cache.
static llvm::StringRef GetSectionNameLLDBNoNlist()
lldb::addr_t m_text_address
uint32_t GetAddressByteSize() const override
Gets the address size in bytes for the current object file.
static lldb_private::ModuleSpecList GetModuleSpecifications(const lldb_private::FileSpec &file, lldb::DataExtractorSP &extractor_sp, lldb::offset_t file_offset, lldb::offset_t length)
static llvm::StringRef GetSegmentNameDATA()
llvm::MachO::dysymtab_command m_dysymtab
bool GetCorefileMainBinaryInfo(lldb::addr_t &value, bool &value_is_offset, lldb_private::UUID &uuid, ObjectFile::BinaryType &type) override
static llvm::StringRef GetSegmentNameDATA_DIRTY()
static bool SaveCore(const lldb::ProcessSP &process_sp, lldb_private::SaveCoreOptions &options, lldb_private::Status &error)
void ProcessDysymtabCommand(const llvm::MachO::load_command &load_cmd, lldb::offset_t offset)
static llvm::StringRef GetSegmentNameLLVM_COV()
MachOCorefileAllImageInfos GetCorefileAllImageInfos()
Get the list of binary images that were present in the process when the corefile was produced.
lldb::addr_t CalculateSectionLoadAddressForMemoryImage(lldb::addr_t mach_header_load_address, const lldb_private::Section *mach_header_section, const lldb_private::Section *section)
bool m_thread_context_offsets_valid
ObjectFile::Strata CalculateStrata() override
The object file should be able to calculate the strata of the object file.
void CreateSections(lldb_private::SectionList &unified_section_list) override
static llvm::StringRef GetSegmentNameDATA_CONST()
lldb_private::AddressClass GetAddressClass(lldb::addr_t file_addr) override
Get the address type given a file address in an object file.
lldb_private::StructuredData::ObjectSP GetCorefileProcessMetadata() override
Get process metadata from the corefile in a StructuredData dictionary.
static llvm::StringRef GetSegmentNameOBJC()
std::optional< llvm::VersionTuple > m_sdk_versions
ObjectFileMachO(const lldb::ModuleSP &module_sp, lldb::DataExtractorSP extractor_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t offset, lldb::offset_t length)
void GetLLDBSharedCacheUUID(lldb::addr_t &base_addir, lldb_private::UUID &uuid)
Intended for same-host arm device debugging where lldb will read shared cache libraries out of its ow...
llvm::VersionTuple GetVersion() override
Get the object file version numbers.
EncryptedFileRanges GetEncryptedFileRanges()
uint32_t GetNumThreadContexts() override
static llvm::StringRef GetSegmentNameDWARF()
static llvm::StringRef GetSegmentNameTEXT()
lldb::offset_t m_linkedit_original_offset
lldb_private::Section * GetMachHeaderSection()
int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override
RegisterContextDarwin_arm64_Mach(lldb_private::Thread &thread, const DataExtractor &data)
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data)
int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override
static bool Create_LC_THREAD(Thread *thread, Stream &data)
bool SetError(int flavor, uint32_t err_idx, int err)
RegisterContextDarwin_arm64(lldb_private::Thread &thread, uint32_t concrete_frame_idx)
RegisterContextDarwin_arm_Mach(lldb_private::Thread &thread, const DataExtractor &data)
int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override
int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data)
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override
static bool Create_LC_THREAD(Thread *thread, Stream &data)
RegisterContextDarwin_arm(lldb_private::Thread &thread, uint32_t concrete_frame_idx)
bool SetError(int flavor, uint32_t err_idx, int err)
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override
int DoWriteCSR(lldb::tid_t tid, int flavor, const CSR &csr) override
RegisterContextDarwin_riscv32_Mach(lldb_private::Thread &thread, const DataExtractor &data)
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override
int DoReadCSR(lldb::tid_t tid, int flavor, CSR &csr) override
static bool Create_LC_THREAD(Thread *thread, Stream &data)
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data)
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override
RegisterContextDarwin_riscv32(lldb_private::Thread &thread, uint32_t concrete_frame_idx)
bool SetError(int flavor, uint32_t err_idx, int err)
RegisterContextDarwin_x86_64_Mach(lldb_private::Thread &thread, const DataExtractor &data)
int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override
static bool Create_LC_THREAD(Thread *thread, Stream &data)
void SetRegisterDataFrom_LC_THREAD(const DataExtractor &data)
int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override
int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override
int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override
int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override
int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override
RegisterContextDarwin_x86_64(lldb_private::Thread &thread, uint32_t concrete_frame_idx)
bool SetError(int flavor, uint32_t err_idx, int err)
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:303
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition Address.h:426
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:283
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
A class which holds the metadata from a remote stub/corefile note about how many bits are used for ad...
void SetAddressableBits(uint32_t addressing_bits)
When a single value is available for the number of bits.
An architecture specification class.
Definition ArchSpec.h:32
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:710
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:375
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:465
bool IsAlwaysThumbInstructions() const
Detect whether this architecture uses thumb code exclusively.
bool SetArchitecture(ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os=0)
Change the architecture object type, CPU type and OS type.
Definition ArchSpec.cpp:909
uint32_t GetMachOCPUSubType() const
Definition ArchSpec.cpp:698
bool IsCompatibleMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, CompatibleMatch).
Definition ArchSpec.h:517
uint32_t GetMachOCPUType() const
Definition ArchSpec.cpp:694
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition ArchSpec.cpp:759
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:702
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
void GetFunctionAddressAndSizeVector(FunctionAddressAndSizeVector &function_info)
RangeVector< lldb::addr_t, uint32_t > FunctionAddressAndSizeVector
An data extractor class.
virtual uint32_t GetU32_unchecked(lldb::offset_t *offset_ptr) const
uint64_t GetU64(lldb::offset_t *offset_ptr) const
Extract a uint64_t value from *offset_ptr.
bool ValidOffsetForDataOfSize(lldb::offset_t offset, lldb::offset_t length) const
Test the availability of length bytes of data from offset.
virtual const uint8_t * PeekData(lldb::offset_t offset, lldb::offset_t length) const
Peek at a bytes at offset.
virtual uint64_t GetByteSize() const
Get the number of bytes contained in this object.
uint64_t GetAddress_unchecked(lldb::offset_t *offset_ptr) const
uint32_t GetU32(lldb::offset_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
virtual uint8_t GetU8_unchecked(lldb::offset_t *offset_ptr) const
lldb::ByteOrder GetByteOrder() const
Get the current byte order value.
virtual uint16_t GetU16_unchecked(lldb::offset_t *offset_ptr) const
size_t ExtractBytes(lldb::offset_t offset, lldb::offset_t length, lldb::ByteOrder dst_byte_order, void *dst) const
Extract an arbitrary number of bytes in the specified byte order.
lldb::StreamUP GetAsyncErrorStream()
static void ReportError(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report error events.
PlatformList & GetPlatformList()
Definition Debugger.h:234
lldb::StreamUP GetAsyncOutputStream()
A plug-in interface definition class for dynamic loaders.
static void LocateBinaries(Process *process, llvm::MutableArrayRef< BinarySpec > bin_specs)
Search for a batch of binaries, without mutating the Target.
virtual bool GetSharedCacheInformation(lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache, LazyBool &private_shared_cache, lldb_private::FileSpec &shared_cache_path, std::optional< uint64_t > &size)
Get information about the shared cache for a process, if possible.
static llvm::Expected< lldb::ModuleSP > LoadBinaryInTarget(Process *process, BinarySpec &bin_spec)
Add a binary that LocateBinaries searched for to the Target, and set its load address.
A file collection class.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
Get file at index.
void Append(const FileSpec &file)
Append a FileSpec object to the list.
size_t GetSize() const
Get the number of files in the file list.
bool AppendIfUnique(const FileSpec &file)
Append a FileSpec object if unique.
A file utility class.
Definition FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
FileSpec CopyByAppendingPathComponent(llvm::StringRef component) const
Definition FileSpec.cpp:425
void ClearDirectory()
Clear the directory in this object.
Definition FileSpec.cpp:373
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
llvm::StringRef GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:233
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
FileSpec CopyByRemovingLastPathComponent() const
Definition FileSpec.cpp:431
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
void void Printf(const char *format,...) __attribute__((format(printf
Prefer using LLDB_LOGF whenever possible.
Definition Log.cpp:177
A class that handles mangled names.
Definition Mangled.h:36
void SetDemangledName(ConstString name)
Definition Mangled.h:161
ConstString GetDemangledName() const
Demangled name get accessor.
Definition Mangled.cpp:238
void SetMangledName(ConstString name)
Definition Mangled.h:163
void SetValue(ConstString name)
Set the string value in this object.
Definition Mangled.cpp:219
ConstString GetName(NamePreference preference=ePreferDemangled) const
Best name get accessor.
Definition Mangled.cpp:297
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
A collection class for Module objects.
Definition ModuleList.h:139
void Clear()
Clear the object's state.
bool AppendIfNeeded(const lldb::ModuleSP &new_module, bool notify=true)
Append a module to the module list, if it is not already there.
lldb::ModuleSP GetModuleAtIndex(size_t idx) const
Get the module shared pointer for the module at index idx.
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
size_t GetSize() const
Gets the size of the module list.
void Append(const ModuleSpec &spec)
Definition ModuleSpec.h:371
ModuleSpec & GetModuleSpecRefAtIndex(size_t i)
Definition ModuleSpec.h:384
void SetObjectSize(uint64_t object_size)
Definition ModuleSpec.h:119
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:93
void SetObjectOffset(uint64_t object_offset)
Definition ModuleSpec.h:113
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:47
std::atomic< lldb_private::Symtab * > m_symtab
Owned.
Definition ObjectFile.h:809
std::unique_ptr< lldb_private::SectionList > m_sections_up
Definition ObjectFile.h:804
static lldb::DataBufferSP MapFileData(const FileSpec &file, uint64_t Size, uint64_t Offset)
const lldb::addr_t m_memory_addr
Set if the object file only exists in memory.
Definition ObjectFile.h:799
static lldb::SectionType GetDWARFSectionTypeFromName(llvm::StringRef name)
Parses the section type from a section name for DWARF sections.
Symtab * GetSymtab(bool can_create=true)
Gets the symbol table for the currently selected architecture (and object for archives).
DataExtractorNSP m_data_nsp
The data for this object file so things can be parsed lazily.
Definition ObjectFile.h:793
static lldb::WritableDataBufferSP ReadMemory(const lldb::ProcessSP &process_sp, lldb::addr_t addr, size_t byte_size)
@ eTypeExecutable
A normal executable.
Definition ObjectFile.h:56
@ eTypeDebugInfo
An object file that contains only debug information.
Definition ObjectFile.h:58
@ eTypeStubLibrary
A library that can be linked against but not used for execution.
Definition ObjectFile.h:66
@ eTypeObjectFile
An intermediate object file.
Definition ObjectFile.h:62
@ eTypeDynamicLinker
The platform's dynamic linker executable.
Definition ObjectFile.h:60
@ eTypeCoreFile
A core file that has a checkpoint of a program's execution state.
Definition ObjectFile.h:54
@ eTypeSharedLibrary
A shared library that can be used during execution.
Definition ObjectFile.h:64
lldb::addr_t m_file_offset
The offset in bytes into the file, or the address in memory.
Definition ObjectFile.h:788
static lldb::SymbolType GetSymbolTypeFromName(llvm::StringRef name, lldb::SymbolType symbol_type_hint=lldb::eSymbolTypeUndefined)
bool SetModulesArchitecture(const ArchSpec &new_arch)
Sets the architecture for a module.
virtual FileSpec & GetFileSpec()
Get accessor to the object file specification.
Definition ObjectFile.h:285
virtual SectionList * GetSectionList(bool update_module_section_list=true)
Gets the section list for the currently selected architecture (and object for archives).
ObjectFile(const lldb::ModuleSP &module_sp, const FileSpec *file_spec_ptr, lldb::offset_t file_offset, lldb::offset_t length, lldb::DataExtractorSP extractor_sp, lldb::offset_t data_offset)
Construct with a parent module, offset, and header data.
bool IsInMemory() const
Returns true if the object file exists only in memory.
Definition ObjectFile.h:696
lldb::ProcessWP m_process_wp
Definition ObjectFile.h:797
lldb::addr_t m_length
The length of this object file if it is known (can be zero if length is unknown or can't be determine...
Definition ObjectFile.h:790
BinaryType
If we have a corefile binary hint, this enum specifies the binary type which we can use to select the...
Definition ObjectFile.h:84
@ eBinaryTypeKernel
kernel binary
Definition ObjectFile.h:88
@ eBinaryTypeUser
user process binary, dyld addr
Definition ObjectFile.h:90
@ eBinaryTypeUserAllImageInfos
user process binary, dyld_all_image_infos addr
Definition ObjectFile.h:92
@ eBinaryTypeStandalone
standalone binary / firmware
Definition ObjectFile.h:94
virtual lldb_private::Address GetBaseAddress()
Returns base address of this object file.
Definition ObjectFile.h:473
bool LoadPlatformBinaryAndSetup(Process *process, lldb::addr_t addr, bool notify)
Detect a binary in memory that will determine which Platform and DynamicLoader should be used in this...
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
A plug-in interface definition class for debugging a process.
Definition Process.h:370
void Flush()
Flush all data in the process.
Definition Process.cpp:6403
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:3243
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1271
A Progress indicator helper class.
Definition Progress.h:60
const Entry * FindEntryThatContains(B addr) const
Definition RangeMap.h:338
const Entry * GetEntryAtIndex(size_t i) const
Definition RangeMap.h:297
void Append(const Entry &entry)
Definition RangeMap.h:179
size_t GetSize() const
Definition RangeMap.h:295
const RegisterInfo * GetRegisterInfoByName(llvm::StringRef reg_name, uint32_t start_idx=0)
virtual bool ReadRegister(const RegisterInfo *reg_info, RegisterValue &reg_value)=0
const void * GetBytes() const
const std::optional< lldb_private::FileSpec > GetOutputFile() const
lldb::SaveCoreStyle GetStyle() const
void SetStyle(lldb::SaveCoreStyle style)
size_t GetNumSections(uint32_t depth) const
Definition Section.cpp:544
size_t GetSize() const
Definition Section.h:76
lldb::SectionSP FindSectionByName(llvm::StringRef section_name) const
Definition Section.cpp:562
size_t AddSection(const lldb::SectionSP &section_sp)
Definition Section.cpp:483
void Dump(llvm::raw_ostream &s, unsigned indent, Target *target, bool show_header, uint32_t depth) const
Definition Section.cpp:648
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:555
bool IsThreadSpecific() const
Definition Section.h:220
lldb::SectionSP GetParent() const
Definition Section.h:218
lldb::offset_t GetFileOffset() const
Definition Section.h:180
llvm::StringRef GetName() const
Definition Section.h:210
lldb::addr_t GetFileAddress() const
Definition Section.cpp:194
ObjectFile * GetObjectFile()
Definition Section.h:230
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition Stream.h:111
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t PutHex64(uint64_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:307
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
@ eBinary
Get and put data as binary instead of as the default string mode.
Definition Stream.h:32
size_t PutHex32(uint32_t uvalue, lldb::ByteOrder byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:291
size_t PutRawBytes(const void *s, size_t src_len, lldb::ByteOrder src_byte_order=lldb::eByteOrderInvalid, lldb::ByteOrder dst_byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:364
unsigned GetIndentLevel() const
Get the current indentation level.
Definition Stream.cpp:193
std::optional< Dictionary * > GetItemAtIndexAsDictionary(size_t idx) const
Retrieves the element at index idx from a StructuredData::Array if it is a Dictionary.
bool GetValueForKeyAsArray(llvm::StringRef key, Array *&result) const
void Dump(lldb_private::Stream &s, bool pretty_print=true) const
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
static ObjectSP ParseJSON(llvm::StringRef json_text)
std::shared_ptr< Array > ArraySP
Defines a list of symbol context objects.
bool GetContextAtIndex(size_t idx, SymbolContext &sc) const
Get accessor for a symbol context at index idx.
uint32_t GetSize() const
Get accessor for a symbol context list size.
Defines a symbol context baton that can be handed other debug core functions.
Symbol * symbol
The Symbol for a given query.
bool ValueIsAddress() const
Definition Symbol.cpp:192
void SetReExportedSymbolName(ConstString name)
Definition Symbol.cpp:222
void SetType(lldb::SymbolType type)
Definition Symbol.h:199
void SetSizeIsSibling(bool b)
Definition Symbol.h:248
Mangled & GetMangled()
Definition Symbol.h:162
Address & GetAddressRef()
Definition Symbol.h:78
void SetIsWeak(bool b)
Definition Symbol.h:235
uint32_t GetFlags() const
Definition Symbol.h:203
bool SetReExportedSymbolSharedLibrary(const FileSpec &fspec)
Definition Symbol.cpp:231
lldb::addr_t GetByteSize() const
Definition Symbol.cpp:470
lldb::SymbolType GetType() const
Definition Symbol.h:197
void SetFlags(uint32_t flags)
Definition Symbol.h:205
Address GetAddress() const
Definition Symbol.h:98
void SetIsSynthetic(bool b)
Definition Symbol.h:215
void SetByteSize(lldb::addr_t size)
Definition Symbol.h:241
void SetDemangledNameIsSynthesized(bool b)
Definition Symbol.h:265
void SetExternal(bool b)
Definition Symbol.h:227
void SetDebug(bool b)
Definition Symbol.h:223
void SetID(uint32_t uid)
Definition Symbol.h:160
Symbol * FindSymbolByID(lldb::user_id_t uid) const
Definition Symtab.cpp:253
Symbol * SymbolAtIndex(size_t idx)
Definition Symtab.cpp:262
Symbol * FindFirstSymbolWithNameAndType(ConstString name, lldb::SymbolType symbol_type, Debug symbol_debug_type, Visibility symbol_visibility)
Definition Symtab.cpp:850
Symbol * Resize(size_t count)
Definition Symtab.cpp:55
Symbol * FindSymbolContainingFileAddress(lldb::addr_t file_addr)
Definition Symtab.cpp:1022
void SetHasDebugMap(bool has_debug_map)
Set whether this symbol table has a debug map.
Definition Symtab.cpp:94
size_t GetNumSymbols() const
Definition Symtab.cpp:83
void SetHasSourceFiles(bool has_source_files)
Set whether this symbol table contains any source file symbols.
Definition Symtab.cpp:104
MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const
Definition Target.cpp:5964
void ModulesDidLoad(ModuleList &module_list)
This call may preload module symbols, and may do so in parallel depending on the following target set...
Definition Target.cpp:2012
Debugger & GetDebugger() const
Definition Target.h:1378
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1295
const ArchSpec & GetArchitecture() const
Definition Target.h:1337
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition Target.cpp:3649
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
void Clear()
Definition UUID.h:62
std::string GetAsString(llvm::StringRef separator="-") const
Definition UUID.cpp:54
bool IsValid() const
Definition UUID.h:69
#define UINT64_MAX
#define LLDB_INVALID_ADDRESS_MASK
Address Mask Bits not used for addressing are set to 1 in the mask; all mask bits set is an invalid v...
#define LLDB_INVALID_THREAD_ID
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
lldb::ByteOrder InlHostByteOrder()
Definition Endian.h:25
A class that represents a running process on the host machine.
constexpr uint64_t THUMB_ADDRESS_BIT_MASK
Mask that clears the low Thumb bit from an ARM function address.
Definition MachOTrie.h:30
bool ParseTrieEntries(DataExtractor &data, const bool is_arm, lldb::addr_t text_seg_base_addr, std::set< lldb::addr_t > &resolver_addresses, std::vector< TrieEntryWithOffset > &reexports, std::vector< TrieEntryWithOffset > &ext_symbols)
Parse the Mach-O export trie (the dyld symbol trie from LC_DYLD_INFO or LC_DYLD_EXPORTS_TRIE) startin...
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
constexpr uint64_t TRIE_SYMBOL_IS_THUMB
Set on TrieEntry::flags for an ARM symbol whose address has the low Thumb bit set; the bit is strippe...
Definition MachOTrie.h:27
static uint32_t bits(const uint32_t val, const uint32_t msbit, const uint32_t lsbit)
Definition ARMUtils.h:265
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
uint64_t offset_t
Definition lldb-types.h:86
@ eSymbolSharedCacheUseHostAndInferiorSharedCache
std::shared_ptr< lldb_private::Process > ProcessSP
SymbolType
Symbol types.
@ eSymbolTypeUndefined
@ eSymbolTypeVariableType
@ eSymbolTypeObjCMetaClass
@ eSymbolTypeReExported
@ eSymbolTypeObjCClass
@ eSymbolTypeObjectFile
@ eSymbolTypeTrampoline
@ eSymbolTypeResolver
@ eSymbolTypeSourceFile
@ eSymbolTypeException
@ eSymbolTypeVariable
@ eSymbolTypeASTFile
The symbol's name is the path to a compiler AST file.
@ eSymbolTypeAbsolute
@ eSymbolTypeAdditional
When symbols take more than one entry, the extra entries get this type.
@ eSymbolTypeInstrumentation
@ eSymbolTypeHeaderFile
@ eSymbolTypeCommonBlock
@ eSymbolTypeCompiler
@ eSymbolTypeLineHeader
@ eSymbolTypeObjCIVar
@ eSymbolTypeLineEntry
@ eSymbolTypeScopeBegin
@ eSymbolTypeScopeEnd
ByteOrder
Byte ordering definitions.
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::Section > SectionSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
@ eSectionTypeDWARFDebugStrOffsets
@ eSectionTypeELFDynamicSymbols
Elf SHT_DYNSYM section.
@ eSectionTypeInvalid
@ eSectionTypeDWARFDebugPubNames
@ eSectionTypeDataObjCCFStrings
Objective-C const CFString/NSString objects.
@ eSectionTypeZeroFill
@ eSectionTypeDWARFDebugLocDwo
@ eSectionTypeDWARFDebugFrame
@ eSectionTypeARMextab
@ eSectionTypeContainer
The section contains child sections.
@ eSectionTypeDWARFDebugLocLists
DWARF v5 .debug_loclists.
@ eSectionTypeDWARFDebugTypes
DWARF .debug_types section.
@ eSectionTypeDataSymbolAddress
Address of a symbol in the symbol table.
@ eSectionTypeELFDynamicLinkInfo
Elf SHT_DYNAMIC section.
@ eSectionTypeDWARFDebugMacInfo
@ eSectionTypeAbsoluteAddress
Dummy section for symbols with absolute address.
@ eSectionTypeCompactUnwind
compact unwind section in Mach-O, __TEXT,__unwind_info
@ eSectionTypeELFRelocationEntries
Elf SHT_REL or SHT_REL section.
@ eSectionTypeDWARFAppleNamespaces
@ eSectionTypeLLDBFormatters
@ eSectionTypeDWARFDebugNames
DWARF v5 .debug_names.
@ eSectionTypeDWARFDebugRngLists
DWARF v5 .debug_rnglists.
@ eSectionTypeEHFrame
@ eSectionTypeDWARFDebugStrOffsetsDwo
@ eSectionTypeDWARFDebugMacro
@ eSectionTypeDWARFAppleTypes
@ eSectionTypeWasmGlobal
@ eSectionTypeDWARFDebugInfo
@ eSectionTypeDWARFDebugTypesDwo
@ eSectionTypeDWARFDebugRanges
@ eSectionTypeDWARFDebugRngListsDwo
@ eSectionTypeLLDBTypeSummaries
@ eSectionTypeGoSymtab
@ eSectionTypeARMexidx
@ eSectionTypeDWARFDebugLine
@ eSectionTypeDWARFDebugPubTypes
@ eSectionTypeDataObjCMessageRefs
Pointer to function pointer + selector.
@ eSectionTypeDWARFDebugTuIndex
@ eSectionTypeDWARFDebugStr
@ eSectionTypeDWARFDebugLineStr
DWARF v5 .debug_line_str.
@ eSectionTypeDWARFDebugLoc
@ eSectionTypeDWARFAppleNames
@ eSectionTypeDataCStringPointers
Pointers to C string data.
@ eSectionTypeDWARFAppleObjC
@ eSectionTypeSwiftModules
@ eSectionTypeDWARFDebugCuIndex
@ eSectionTypeDWARFDebugAranges
@ eSectionTypeDWARFDebugAbbrevDwo
@ eSectionTypeDWARFGNUDebugAltLink
@ eSectionTypeDWARFDebugStrDwo
@ eSectionTypeDWARFDebugAbbrev
@ eSectionTypeDataPointers
@ eSectionTypeDWARFDebugLocListsDwo
@ eSectionTypeDWARFDebugInfoDwo
@ eSectionTypeDWARFDebugAddr
@ eSectionTypeWasmName
@ eSectionTypeDataCString
Inlined C string data.
@ eSectionTypeELFSymbolTable
Elf SHT_SYMTAB section.
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
uint64_t tid_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Module > ModuleSP
The LC_DYSYMTAB's dysymtab_command has 32-bit file offsets that we will use as virtual address offset...
std::vector< MachOCorefileImageEntry > all_image_infos
A corefile may include metadata about all of the binaries that were present in the process when the c...
std::vector< std::tuple< lldb_private::ConstString, lldb::addr_t > > segment_load_addresses
lldb_private::SectionList & UnifiedList
SegmentParsingContext(EncryptedFileRanges EncryptedRanges, lldb_private::SectionList &UnifiedList)
uint32_t segment_count
uint64_t load_address
uint64_t filepath_offset
image_entry(const image_entry &rhs)
uint32_t unused
uint64_t seg_addrs_offset
uuid_t uuid
image_entry()
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.
bool allow_memory_image_last_resort
If no better binary image can be found, allow reading the binary out of memory, if possible,...
UUID uuid
UUID of the binary to be loaded.
std::string name
Name of the binary, if available.
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.
BaseType GetRangeBase() const
Definition RangeMap.h:45
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
void SetByteSize(SizeType s)
Definition RangeMap.h:89
Every register is described in detail including its name, alternate name (optional),...
uint32_t byte_size
Size in bytes of the register.
segment_vmaddr(const segment_vmaddr &rhs)