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