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