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