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