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