LLDB mainline
ObjectFileMachO.cpp
Go to the documentation of this file.
1//===-- ObjectFileMachO.cpp -----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/ADT/ScopeExit.h"
10#include "llvm/ADT/StringRef.h"
11
16#include "lldb/Core/Debugger.h"
17#include "lldb/Core/Module.h"
20#include "lldb/Core/Progress.h"
21#include "lldb/Core/Section.h"
22#include "lldb/Host/Host.h"
28#include "lldb/Target/Process.h"
30#include "lldb/Target/Target.h"
31#include "lldb/Target/Thread.h"
38#include "lldb/Utility/Log.h"
41#include "lldb/Utility/Status.h"
43#include "lldb/Utility/Timer.h"
44#include "lldb/Utility/UUID.h"
45
46#include "lldb/Host/SafeMachO.h"
47
48#include "llvm/ADT/DenseSet.h"
49#include "llvm/Support/FormatVariadic.h"
50#include "llvm/Support/MemoryBuffer.h"
51
52#include "ObjectFileMachO.h"
53
54#if defined(__APPLE__)
55#include <TargetConditionals.h>
56// GetLLDBSharedCacheUUID() needs to call dlsym()
57#include <dlfcn.h>
58#include <mach/mach_init.h>
59#include <mach/vm_map.h>
60#include <lldb/Host/SafeMachO.h>
61#endif
62
63#ifndef __APPLE__
65#else
66#include <uuid/uuid.h>
67#endif
68
69#include <bitset>
70#include <memory>
71#include <optional>
72
73// Unfortunately the signpost header pulls in the system MachO header, too.
74#ifdef CPU_TYPE_ARM
75#undef CPU_TYPE_ARM
76#endif
77#ifdef CPU_TYPE_ARM64
78#undef CPU_TYPE_ARM64
79#endif
80#ifdef CPU_TYPE_ARM64_32
81#undef CPU_TYPE_ARM64_32
82#endif
83#ifdef CPU_TYPE_I386
84#undef CPU_TYPE_I386
85#endif
86#ifdef CPU_TYPE_X86_64
87#undef CPU_TYPE_X86_64
88#endif
89#ifdef MH_DYLINKER
90#undef MH_DYLINKER
91#endif
92#ifdef MH_OBJECT
93#undef MH_OBJECT
94#endif
95#ifdef LC_VERSION_MIN_MACOSX
96#undef LC_VERSION_MIN_MACOSX
97#endif
98#ifdef LC_VERSION_MIN_IPHONEOS
99#undef LC_VERSION_MIN_IPHONEOS
100#endif
101#ifdef LC_VERSION_MIN_TVOS
102#undef LC_VERSION_MIN_TVOS
103#endif
104#ifdef LC_VERSION_MIN_WATCHOS
105#undef LC_VERSION_MIN_WATCHOS
106#endif
107#ifdef LC_BUILD_VERSION
108#undef LC_BUILD_VERSION
109#endif
110#ifdef PLATFORM_MACOS
111#undef PLATFORM_MACOS
112#endif
113#ifdef PLATFORM_MACCATALYST
114#undef PLATFORM_MACCATALYST
115#endif
116#ifdef PLATFORM_IOS
117#undef PLATFORM_IOS
118#endif
119#ifdef PLATFORM_IOSSIMULATOR
120#undef PLATFORM_IOSSIMULATOR
121#endif
122#ifdef PLATFORM_TVOS
123#undef PLATFORM_TVOS
124#endif
125#ifdef PLATFORM_TVOSSIMULATOR
126#undef PLATFORM_TVOSSIMULATOR
127#endif
128#ifdef PLATFORM_WATCHOS
129#undef PLATFORM_WATCHOS
130#endif
131#ifdef PLATFORM_WATCHOSSIMULATOR
132#undef PLATFORM_WATCHOSSIMULATOR
133#endif
134
135#define THUMB_ADDRESS_BIT_MASK 0xfffffffffffffffeull
136using namespace lldb;
137using namespace lldb_private;
138using namespace llvm::MachO;
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:
169 const DataExtractor &data)
170 : RegisterContextDarwin_x86_64(thread, 0) {
172 }
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 bool done = false;
184
185 while (!done) {
186 int flavor = data.GetU32(&offset);
187 if (flavor == 0)
188 done = true;
189 else {
190 uint32_t i;
191 uint32_t count = data.GetU32(&offset);
192 switch (flavor) {
193 case GPRRegSet:
194 for (i = 0; i < count; ++i)
195 (&gpr.rax)[i] = data.GetU64(&offset);
197 done = true;
198
199 break;
200 case FPURegSet:
201 // TODO: fill in FPU regs....
202 // SetError (FPURegSet, Read, -1);
203 done = true;
204
205 break;
206 case EXCRegSet:
207 exc.trapno = data.GetU32(&offset);
208 exc.err = data.GetU32(&offset);
209 exc.faultvaddr = data.GetU64(&offset);
211 done = true;
212 break;
213 case 7:
214 case 8:
215 case 9:
216 // fancy flavors that encapsulate of the above flavors...
217 break;
218
219 default:
220 done = true;
221 break;
222 }
223 }
224 }
225 }
226
227 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
228 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
229 if (reg_ctx_sp) {
230 RegisterContext *reg_ctx = reg_ctx_sp.get();
231
232 data.PutHex32(GPRRegSet); // Flavor
234 PrintRegisterValue(reg_ctx, "rax", nullptr, 8, data);
235 PrintRegisterValue(reg_ctx, "rbx", nullptr, 8, data);
236 PrintRegisterValue(reg_ctx, "rcx", nullptr, 8, data);
237 PrintRegisterValue(reg_ctx, "rdx", nullptr, 8, data);
238 PrintRegisterValue(reg_ctx, "rdi", nullptr, 8, data);
239 PrintRegisterValue(reg_ctx, "rsi", nullptr, 8, data);
240 PrintRegisterValue(reg_ctx, "rbp", nullptr, 8, data);
241 PrintRegisterValue(reg_ctx, "rsp", nullptr, 8, data);
242 PrintRegisterValue(reg_ctx, "r8", nullptr, 8, data);
243 PrintRegisterValue(reg_ctx, "r9", nullptr, 8, data);
244 PrintRegisterValue(reg_ctx, "r10", nullptr, 8, data);
245 PrintRegisterValue(reg_ctx, "r11", nullptr, 8, data);
246 PrintRegisterValue(reg_ctx, "r12", nullptr, 8, data);
247 PrintRegisterValue(reg_ctx, "r13", nullptr, 8, data);
248 PrintRegisterValue(reg_ctx, "r14", nullptr, 8, data);
249 PrintRegisterValue(reg_ctx, "r15", nullptr, 8, data);
250 PrintRegisterValue(reg_ctx, "rip", nullptr, 8, data);
251 PrintRegisterValue(reg_ctx, "rflags", nullptr, 8, data);
252 PrintRegisterValue(reg_ctx, "cs", nullptr, 8, data);
253 PrintRegisterValue(reg_ctx, "fs", nullptr, 8, data);
254 PrintRegisterValue(reg_ctx, "gs", nullptr, 8, data);
255
256 // // Write out the FPU registers
257 // const size_t fpu_byte_size = sizeof(FPU);
258 // size_t bytes_written = 0;
259 // data.PutHex32 (FPURegSet);
260 // data.PutHex32 (fpu_byte_size/sizeof(uint64_t));
261 // bytes_written += data.PutHex32(0); // uint32_t pad[0]
262 // bytes_written += data.PutHex32(0); // uint32_t pad[1]
263 // bytes_written += WriteRegister (reg_ctx, "fcw", "fctrl", 2,
264 // data); // uint16_t fcw; // "fctrl"
265 // bytes_written += WriteRegister (reg_ctx, "fsw" , "fstat", 2,
266 // data); // uint16_t fsw; // "fstat"
267 // bytes_written += WriteRegister (reg_ctx, "ftw" , "ftag", 1,
268 // data); // uint8_t ftw; // "ftag"
269 // bytes_written += data.PutHex8 (0); // uint8_t pad1;
270 // bytes_written += WriteRegister (reg_ctx, "fop" , NULL, 2,
271 // data); // uint16_t fop; // "fop"
272 // bytes_written += WriteRegister (reg_ctx, "fioff", "ip", 4,
273 // data); // uint32_t ip; // "fioff"
274 // bytes_written += WriteRegister (reg_ctx, "fiseg", NULL, 2,
275 // data); // uint16_t cs; // "fiseg"
276 // bytes_written += data.PutHex16 (0); // uint16_t pad2;
277 // bytes_written += WriteRegister (reg_ctx, "dp", "fooff" , 4,
278 // data); // uint32_t dp; // "fooff"
279 // bytes_written += WriteRegister (reg_ctx, "foseg", NULL, 2,
280 // data); // uint16_t ds; // "foseg"
281 // bytes_written += data.PutHex16 (0); // uint16_t pad3;
282 // bytes_written += WriteRegister (reg_ctx, "mxcsr", NULL, 4,
283 // data); // uint32_t mxcsr;
284 // bytes_written += WriteRegister (reg_ctx, "mxcsrmask", NULL,
285 // 4, data);// uint32_t mxcsrmask;
286 // bytes_written += WriteRegister (reg_ctx, "stmm0", NULL,
287 // sizeof(MMSReg), data);
288 // bytes_written += WriteRegister (reg_ctx, "stmm1", NULL,
289 // sizeof(MMSReg), data);
290 // bytes_written += WriteRegister (reg_ctx, "stmm2", NULL,
291 // sizeof(MMSReg), data);
292 // bytes_written += WriteRegister (reg_ctx, "stmm3", NULL,
293 // sizeof(MMSReg), data);
294 // bytes_written += WriteRegister (reg_ctx, "stmm4", NULL,
295 // sizeof(MMSReg), data);
296 // bytes_written += WriteRegister (reg_ctx, "stmm5", NULL,
297 // sizeof(MMSReg), data);
298 // bytes_written += WriteRegister (reg_ctx, "stmm6", NULL,
299 // sizeof(MMSReg), data);
300 // bytes_written += WriteRegister (reg_ctx, "stmm7", NULL,
301 // sizeof(MMSReg), data);
302 // bytes_written += WriteRegister (reg_ctx, "xmm0" , NULL,
303 // sizeof(XMMReg), data);
304 // bytes_written += WriteRegister (reg_ctx, "xmm1" , NULL,
305 // sizeof(XMMReg), data);
306 // bytes_written += WriteRegister (reg_ctx, "xmm2" , NULL,
307 // sizeof(XMMReg), data);
308 // bytes_written += WriteRegister (reg_ctx, "xmm3" , NULL,
309 // sizeof(XMMReg), data);
310 // bytes_written += WriteRegister (reg_ctx, "xmm4" , NULL,
311 // sizeof(XMMReg), data);
312 // bytes_written += WriteRegister (reg_ctx, "xmm5" , NULL,
313 // sizeof(XMMReg), data);
314 // bytes_written += WriteRegister (reg_ctx, "xmm6" , NULL,
315 // sizeof(XMMReg), data);
316 // bytes_written += WriteRegister (reg_ctx, "xmm7" , NULL,
317 // sizeof(XMMReg), data);
318 // bytes_written += WriteRegister (reg_ctx, "xmm8" , NULL,
319 // sizeof(XMMReg), data);
320 // bytes_written += WriteRegister (reg_ctx, "xmm9" , NULL,
321 // sizeof(XMMReg), data);
322 // bytes_written += WriteRegister (reg_ctx, "xmm10", NULL,
323 // sizeof(XMMReg), data);
324 // bytes_written += WriteRegister (reg_ctx, "xmm11", NULL,
325 // sizeof(XMMReg), data);
326 // bytes_written += WriteRegister (reg_ctx, "xmm12", NULL,
327 // sizeof(XMMReg), data);
328 // bytes_written += WriteRegister (reg_ctx, "xmm13", NULL,
329 // sizeof(XMMReg), data);
330 // bytes_written += WriteRegister (reg_ctx, "xmm14", NULL,
331 // sizeof(XMMReg), data);
332 // bytes_written += WriteRegister (reg_ctx, "xmm15", NULL,
333 // sizeof(XMMReg), data);
334 //
335 // // Fill rest with zeros
336 // for (size_t i=0, n = fpu_byte_size - bytes_written; i<n; ++
337 // i)
338 // data.PutChar(0);
339
340 // Write out the EXC registers
341 data.PutHex32(EXCRegSet);
343 PrintRegisterValue(reg_ctx, "trapno", nullptr, 4, data);
344 PrintRegisterValue(reg_ctx, "err", nullptr, 4, data);
345 PrintRegisterValue(reg_ctx, "faultvaddr", nullptr, 8, data);
346 return true;
347 }
348 return false;
349 }
350
351protected:
352 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
353
354 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
355
356 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
357
358 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
359 return 0;
360 }
361
362 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
363 return 0;
364 }
365
366 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
367 return 0;
368 }
369};
370
372public:
374 const DataExtractor &data)
375 : RegisterContextDarwin_i386(thread, 0) {
377 }
378
379 void InvalidateAllRegisters() override {
380 // Do nothing... registers are always valid...
381 }
382
384 lldb::offset_t offset = 0;
385 SetError(GPRRegSet, Read, -1);
386 SetError(FPURegSet, Read, -1);
387 SetError(EXCRegSet, Read, -1);
388 bool done = false;
389
390 while (!done) {
391 int flavor = data.GetU32(&offset);
392 if (flavor == 0)
393 done = true;
394 else {
395 uint32_t i;
396 uint32_t count = data.GetU32(&offset);
397 switch (flavor) {
398 case GPRRegSet:
399 for (i = 0; i < count; ++i)
400 (&gpr.eax)[i] = data.GetU32(&offset);
402 done = true;
403
404 break;
405 case FPURegSet:
406 // TODO: fill in FPU regs....
407 // SetError (FPURegSet, Read, -1);
408 done = true;
409
410 break;
411 case EXCRegSet:
412 exc.trapno = data.GetU32(&offset);
413 exc.err = data.GetU32(&offset);
414 exc.faultvaddr = data.GetU32(&offset);
416 done = true;
417 break;
418 case 7:
419 case 8:
420 case 9:
421 // fancy flavors that encapsulate of the above flavors...
422 break;
423
424 default:
425 done = true;
426 break;
427 }
428 }
429 }
430 }
431
432 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
433 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
434 if (reg_ctx_sp) {
435 RegisterContext *reg_ctx = reg_ctx_sp.get();
436
437 data.PutHex32(GPRRegSet); // Flavor
439 PrintRegisterValue(reg_ctx, "eax", nullptr, 4, data);
440 PrintRegisterValue(reg_ctx, "ebx", nullptr, 4, data);
441 PrintRegisterValue(reg_ctx, "ecx", nullptr, 4, data);
442 PrintRegisterValue(reg_ctx, "edx", nullptr, 4, data);
443 PrintRegisterValue(reg_ctx, "edi", nullptr, 4, data);
444 PrintRegisterValue(reg_ctx, "esi", nullptr, 4, data);
445 PrintRegisterValue(reg_ctx, "ebp", nullptr, 4, data);
446 PrintRegisterValue(reg_ctx, "esp", nullptr, 4, data);
447 PrintRegisterValue(reg_ctx, "ss", nullptr, 4, data);
448 PrintRegisterValue(reg_ctx, "eflags", nullptr, 4, data);
449 PrintRegisterValue(reg_ctx, "eip", nullptr, 4, data);
450 PrintRegisterValue(reg_ctx, "cs", nullptr, 4, data);
451 PrintRegisterValue(reg_ctx, "ds", nullptr, 4, data);
452 PrintRegisterValue(reg_ctx, "es", nullptr, 4, data);
453 PrintRegisterValue(reg_ctx, "fs", nullptr, 4, data);
454 PrintRegisterValue(reg_ctx, "gs", nullptr, 4, data);
455
456 // Write out the EXC registers
457 data.PutHex32(EXCRegSet);
459 PrintRegisterValue(reg_ctx, "trapno", nullptr, 4, data);
460 PrintRegisterValue(reg_ctx, "err", nullptr, 4, data);
461 PrintRegisterValue(reg_ctx, "faultvaddr", nullptr, 4, data);
462 return true;
463 }
464 return false;
465 }
466
467protected:
468 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return 0; }
469
470 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return 0; }
471
472 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return 0; }
473
474 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
475 return 0;
476 }
477
478 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
479 return 0;
480 }
481
482 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
483 return 0;
484 }
485};
486
488public:
490 const DataExtractor &data)
491 : RegisterContextDarwin_arm(thread, 0) {
493 }
494
495 void InvalidateAllRegisters() override {
496 // Do nothing... registers are always valid...
497 }
498
500 lldb::offset_t offset = 0;
501 SetError(GPRRegSet, Read, -1);
502 SetError(FPURegSet, Read, -1);
503 SetError(EXCRegSet, Read, -1);
504 bool done = false;
505
506 while (!done) {
507 int flavor = data.GetU32(&offset);
508 uint32_t count = data.GetU32(&offset);
509 lldb::offset_t next_thread_state = offset + (count * 4);
510 switch (flavor) {
511 case GPRAltRegSet:
512 case GPRRegSet: {
513 // r0-r15, plus CPSR
514 uint32_t gpr_buf_count = (sizeof(gpr.r) / sizeof(gpr.r[0])) + 1;
515 if (count == gpr_buf_count) {
516 for (uint32_t i = 0; i < (count - 1); ++i) {
517 gpr.r[i] = data.GetU32(&offset);
518 }
519 gpr.cpsr = data.GetU32(&offset);
520
522 }
523 }
524 offset = next_thread_state;
525 break;
526
527 case FPURegSet: {
528 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.floats;
529 const int fpu_reg_buf_size = sizeof(fpu.floats);
530 if (data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
531 fpu_reg_buf) == fpu_reg_buf_size) {
532 offset += fpu_reg_buf_size;
533 fpu.fpscr = data.GetU32(&offset);
535 } else {
536 done = true;
537 }
538 }
539 offset = next_thread_state;
540 break;
541
542 case EXCRegSet:
543 if (count == 3) {
544 exc.exception = data.GetU32(&offset);
545 exc.fsr = data.GetU32(&offset);
546 exc.far = data.GetU32(&offset);
548 }
549 done = true;
550 offset = next_thread_state;
551 break;
552
553 // Unknown register set flavor, stop trying to parse.
554 default:
555 done = true;
556 }
557 }
558 }
559
560 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
561 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
562 if (reg_ctx_sp) {
563 RegisterContext *reg_ctx = reg_ctx_sp.get();
564
565 data.PutHex32(GPRRegSet); // Flavor
567 PrintRegisterValue(reg_ctx, "r0", nullptr, 4, data);
568 PrintRegisterValue(reg_ctx, "r1", nullptr, 4, data);
569 PrintRegisterValue(reg_ctx, "r2", nullptr, 4, data);
570 PrintRegisterValue(reg_ctx, "r3", nullptr, 4, data);
571 PrintRegisterValue(reg_ctx, "r4", nullptr, 4, data);
572 PrintRegisterValue(reg_ctx, "r5", nullptr, 4, data);
573 PrintRegisterValue(reg_ctx, "r6", nullptr, 4, data);
574 PrintRegisterValue(reg_ctx, "r7", nullptr, 4, data);
575 PrintRegisterValue(reg_ctx, "r8", nullptr, 4, data);
576 PrintRegisterValue(reg_ctx, "r9", nullptr, 4, data);
577 PrintRegisterValue(reg_ctx, "r10", nullptr, 4, data);
578 PrintRegisterValue(reg_ctx, "r11", nullptr, 4, data);
579 PrintRegisterValue(reg_ctx, "r12", nullptr, 4, data);
580 PrintRegisterValue(reg_ctx, "sp", nullptr, 4, data);
581 PrintRegisterValue(reg_ctx, "lr", nullptr, 4, data);
582 PrintRegisterValue(reg_ctx, "pc", nullptr, 4, data);
583 PrintRegisterValue(reg_ctx, "cpsr", nullptr, 4, data);
584
585 // Write out the EXC registers
586 // data.PutHex32 (EXCRegSet);
587 // data.PutHex32 (EXCWordCount);
588 // WriteRegister (reg_ctx, "exception", NULL, 4, data);
589 // WriteRegister (reg_ctx, "fsr", NULL, 4, data);
590 // WriteRegister (reg_ctx, "far", NULL, 4, data);
591 return true;
592 }
593 return false;
594 }
595
596protected:
597 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
598
599 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
600
601 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
602
603 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
604
605 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
606 return 0;
607 }
608
609 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
610 return 0;
611 }
612
613 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
614 return 0;
615 }
616
617 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
618 return -1;
619 }
620};
621
623public:
625 const DataExtractor &data)
626 : RegisterContextDarwin_arm64(thread, 0) {
628 }
629
630 void InvalidateAllRegisters() override {
631 // Do nothing... registers are always valid...
632 }
633
635 lldb::offset_t offset = 0;
636 SetError(GPRRegSet, Read, -1);
637 SetError(FPURegSet, Read, -1);
638 SetError(EXCRegSet, Read, -1);
639 bool done = false;
640 while (!done) {
641 int flavor = data.GetU32(&offset);
642 uint32_t count = data.GetU32(&offset);
643 lldb::offset_t next_thread_state = offset + (count * 4);
644 switch (flavor) {
645 case GPRRegSet:
646 // x0-x29 + fp + lr + sp + pc (== 33 64-bit registers) plus cpsr (1
647 // 32-bit register)
648 if (count >= (33 * 2) + 1) {
649 for (uint32_t i = 0; i < 29; ++i)
650 gpr.x[i] = data.GetU64(&offset);
651 gpr.fp = data.GetU64(&offset);
652 gpr.lr = data.GetU64(&offset);
653 gpr.sp = data.GetU64(&offset);
654 gpr.pc = data.GetU64(&offset);
655 gpr.cpsr = data.GetU32(&offset);
657 }
658 offset = next_thread_state;
659 break;
660 case FPURegSet: {
661 uint8_t *fpu_reg_buf = (uint8_t *)&fpu.v[0];
662 const int fpu_reg_buf_size = sizeof(fpu);
663 if (fpu_reg_buf_size == count * sizeof(uint32_t) &&
664 data.ExtractBytes(offset, fpu_reg_buf_size, eByteOrderLittle,
665 fpu_reg_buf) == fpu_reg_buf_size) {
667 } else {
668 done = true;
669 }
670 }
671 offset = next_thread_state;
672 break;
673 case EXCRegSet:
674 if (count == 4) {
675 exc.far = data.GetU64(&offset);
676 exc.esr = data.GetU32(&offset);
677 exc.exception = data.GetU32(&offset);
679 }
680 offset = next_thread_state;
681 break;
682 default:
683 done = true;
684 break;
685 }
686 }
687 }
688
689 static bool Create_LC_THREAD(Thread *thread, Stream &data) {
690 RegisterContextSP reg_ctx_sp(thread->GetRegisterContext());
691 if (reg_ctx_sp) {
692 RegisterContext *reg_ctx = reg_ctx_sp.get();
693
694 data.PutHex32(GPRRegSet); // Flavor
696 PrintRegisterValue(reg_ctx, "x0", nullptr, 8, data);
697 PrintRegisterValue(reg_ctx, "x1", nullptr, 8, data);
698 PrintRegisterValue(reg_ctx, "x2", nullptr, 8, data);
699 PrintRegisterValue(reg_ctx, "x3", nullptr, 8, data);
700 PrintRegisterValue(reg_ctx, "x4", nullptr, 8, data);
701 PrintRegisterValue(reg_ctx, "x5", nullptr, 8, data);
702 PrintRegisterValue(reg_ctx, "x6", nullptr, 8, data);
703 PrintRegisterValue(reg_ctx, "x7", nullptr, 8, data);
704 PrintRegisterValue(reg_ctx, "x8", nullptr, 8, data);
705 PrintRegisterValue(reg_ctx, "x9", nullptr, 8, data);
706 PrintRegisterValue(reg_ctx, "x10", nullptr, 8, data);
707 PrintRegisterValue(reg_ctx, "x11", nullptr, 8, data);
708 PrintRegisterValue(reg_ctx, "x12", nullptr, 8, data);
709 PrintRegisterValue(reg_ctx, "x13", nullptr, 8, data);
710 PrintRegisterValue(reg_ctx, "x14", nullptr, 8, data);
711 PrintRegisterValue(reg_ctx, "x15", nullptr, 8, data);
712 PrintRegisterValue(reg_ctx, "x16", nullptr, 8, data);
713 PrintRegisterValue(reg_ctx, "x17", nullptr, 8, data);
714 PrintRegisterValue(reg_ctx, "x18", nullptr, 8, data);
715 PrintRegisterValue(reg_ctx, "x19", nullptr, 8, data);
716 PrintRegisterValue(reg_ctx, "x20", nullptr, 8, data);
717 PrintRegisterValue(reg_ctx, "x21", nullptr, 8, data);
718 PrintRegisterValue(reg_ctx, "x22", nullptr, 8, data);
719 PrintRegisterValue(reg_ctx, "x23", nullptr, 8, data);
720 PrintRegisterValue(reg_ctx, "x24", nullptr, 8, data);
721 PrintRegisterValue(reg_ctx, "x25", nullptr, 8, data);
722 PrintRegisterValue(reg_ctx, "x26", nullptr, 8, data);
723 PrintRegisterValue(reg_ctx, "x27", nullptr, 8, data);
724 PrintRegisterValue(reg_ctx, "x28", nullptr, 8, data);
725 PrintRegisterValue(reg_ctx, "fp", nullptr, 8, data);
726 PrintRegisterValue(reg_ctx, "lr", nullptr, 8, data);
727 PrintRegisterValue(reg_ctx, "sp", nullptr, 8, data);
728 PrintRegisterValue(reg_ctx, "pc", nullptr, 8, data);
729 PrintRegisterValue(reg_ctx, "cpsr", nullptr, 4, data);
730 data.PutHex32(0); // uint32_t pad at the end
731
732 // Write out the EXC registers
733 data.PutHex32(EXCRegSet);
735 PrintRegisterValue(reg_ctx, "far", nullptr, 8, data);
736 PrintRegisterValue(reg_ctx, "esr", nullptr, 4, data);
737 PrintRegisterValue(reg_ctx, "exception", nullptr, 4, data);
738 return true;
739 }
740 return false;
741 }
742
743protected:
744 int DoReadGPR(lldb::tid_t tid, int flavor, GPR &gpr) override { return -1; }
745
746 int DoReadFPU(lldb::tid_t tid, int flavor, FPU &fpu) override { return -1; }
747
748 int DoReadEXC(lldb::tid_t tid, int flavor, EXC &exc) override { return -1; }
749
750 int DoReadDBG(lldb::tid_t tid, int flavor, DBG &dbg) override { return -1; }
751
752 int DoWriteGPR(lldb::tid_t tid, int flavor, const GPR &gpr) override {
753 return 0;
754 }
755
756 int DoWriteFPU(lldb::tid_t tid, int flavor, const FPU &fpu) override {
757 return 0;
758 }
759
760 int DoWriteEXC(lldb::tid_t tid, int flavor, const EXC &exc) override {
761 return 0;
762 }
763
764 int DoWriteDBG(lldb::tid_t tid, int flavor, const DBG &dbg) override {
765 return -1;
766 }
767};
768
769static uint32_t MachHeaderSizeFromMagic(uint32_t magic) {
770 switch (magic) {
771 case MH_MAGIC:
772 case MH_CIGAM:
773 return sizeof(struct llvm::MachO::mach_header);
774
775 case MH_MAGIC_64:
776 case MH_CIGAM_64:
777 return sizeof(struct llvm::MachO::mach_header_64);
778 break;
779
780 default:
781 break;
782 }
783 return 0;
784}
785
786#define MACHO_NLIST_ARM_SYMBOL_IS_THUMB 0x0008
787
789
794}
795
798}
799
801 DataBufferSP data_sp,
802 lldb::offset_t data_offset,
803 const FileSpec *file,
804 lldb::offset_t file_offset,
805 lldb::offset_t length) {
806 if (!data_sp) {
807 data_sp = MapFileData(*file, length, file_offset);
808 if (!data_sp)
809 return nullptr;
810 data_offset = 0;
811 }
812
813 if (!ObjectFileMachO::MagicBytesMatch(data_sp, data_offset, length))
814 return nullptr;
815
816 // Update the data to contain the entire file if it doesn't already
817 if (data_sp->GetByteSize() < length) {
818 data_sp = MapFileData(*file, length, file_offset);
819 if (!data_sp)
820 return nullptr;
821 data_offset = 0;
822 }
823 auto objfile_up = std::make_unique<ObjectFileMachO>(
824 module_sp, data_sp, data_offset, file, file_offset, length);
825 if (!objfile_up || !objfile_up->ParseHeader())
826 return nullptr;
827
828 return objfile_up.release();
829}
830
832 const lldb::ModuleSP &module_sp, WritableDataBufferSP data_sp,
833 const ProcessSP &process_sp, lldb::addr_t header_addr) {
834 if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
835 std::unique_ptr<ObjectFile> objfile_up(
836 new ObjectFileMachO(module_sp, data_sp, process_sp, header_addr));
837 if (objfile_up.get() && objfile_up->ParseHeader())
838 return objfile_up.release();
839 }
840 return nullptr;
841}
842
844 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
845 lldb::offset_t data_offset, lldb::offset_t file_offset,
847 const size_t initial_count = specs.GetSize();
848
849 if (ObjectFileMachO::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
850 DataExtractor data;
851 data.SetData(data_sp);
852 llvm::MachO::mach_header header;
853 if (ParseHeader(data, &data_offset, header)) {
854 size_t header_and_load_cmds =
855 header.sizeofcmds + MachHeaderSizeFromMagic(header.magic);
856 if (header_and_load_cmds >= data_sp->GetByteSize()) {
857 data_sp = MapFileData(file, header_and_load_cmds, file_offset);
858 data.SetData(data_sp);
859 data_offset = MachHeaderSizeFromMagic(header.magic);
860 }
861 if (data_sp) {
862 ModuleSpec base_spec;
863 base_spec.GetFileSpec() = file;
864 base_spec.SetObjectOffset(file_offset);
865 base_spec.SetObjectSize(length);
866 GetAllArchSpecs(header, data, data_offset, base_spec, specs);
867 }
868 }
869 }
870 return specs.GetSize() - initial_count;
871}
872
874 static ConstString g_segment_name_TEXT("__TEXT");
875 return g_segment_name_TEXT;
876}
877
879 static ConstString g_segment_name_DATA("__DATA");
880 return g_segment_name_DATA;
881}
882
884 static ConstString g_segment_name("__DATA_DIRTY");
885 return g_segment_name;
886}
887
889 static ConstString g_segment_name("__DATA_CONST");
890 return g_segment_name;
891}
892
894 static ConstString g_segment_name_OBJC("__OBJC");
895 return g_segment_name_OBJC;
896}
897
899 static ConstString g_section_name_LINKEDIT("__LINKEDIT");
900 return g_section_name_LINKEDIT;
901}
902
904 static ConstString g_section_name("__DWARF");
905 return g_section_name;
906}
907
909 static ConstString g_section_name("__LLVM_COV");
910 return g_section_name;
911}
912
914 static ConstString g_section_name_eh_frame("__eh_frame");
915 return g_section_name_eh_frame;
916}
917
919 lldb::addr_t data_offset,
920 lldb::addr_t data_length) {
921 DataExtractor data;
922 data.SetData(data_sp, data_offset, data_length);
923 lldb::offset_t offset = 0;
924 uint32_t magic = data.GetU32(&offset);
925
926 offset += 4; // cputype
927 offset += 4; // cpusubtype
928 uint32_t filetype = data.GetU32(&offset);
929
930 // A fileset has a Mach-O header but is not an
931 // individual file and must be handled via an
932 // ObjectContainer plugin.
933 if (filetype == llvm::MachO::MH_FILESET)
934 return false;
935
936 return MachHeaderSizeFromMagic(magic) != 0;
937}
938
940 DataBufferSP data_sp,
941 lldb::offset_t data_offset,
942 const FileSpec *file,
943 lldb::offset_t file_offset,
944 lldb::offset_t length)
945 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
946 m_mach_sections(), m_entry_point_address(), m_thread_context_offsets(),
947 m_thread_context_offsets_valid(false), m_reexported_dylibs(),
948 m_allow_assembly_emulation_unwind_plans(true) {
949 ::memset(&m_header, 0, sizeof(m_header));
950 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
951}
952
954 lldb::WritableDataBufferSP header_data_sp,
955 const lldb::ProcessSP &process_sp,
956 lldb::addr_t header_addr)
957 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
958 m_mach_sections(), m_entry_point_address(), m_thread_context_offsets(),
959 m_thread_context_offsets_valid(false), m_reexported_dylibs(),
960 m_allow_assembly_emulation_unwind_plans(true) {
961 ::memset(&m_header, 0, sizeof(m_header));
962 ::memset(&m_dysymtab, 0, sizeof(m_dysymtab));
963}
964
966 lldb::offset_t *data_offset_ptr,
967 llvm::MachO::mach_header &header) {
969 // Leave magic in the original byte order
970 header.magic = data.GetU32(data_offset_ptr);
971 bool can_parse = false;
972 bool is_64_bit = false;
973 switch (header.magic) {
974 case MH_MAGIC:
976 data.SetAddressByteSize(4);
977 can_parse = true;
978 break;
979
980 case MH_MAGIC_64:
982 data.SetAddressByteSize(8);
983 can_parse = true;
984 is_64_bit = true;
985 break;
986
987 case MH_CIGAM:
990 : eByteOrderBig);
991 data.SetAddressByteSize(4);
992 can_parse = true;
993 break;
994
995 case MH_CIGAM_64:
998 : eByteOrderBig);
999 data.SetAddressByteSize(8);
1000 is_64_bit = true;
1001 can_parse = true;
1002 break;
1003
1004 default:
1005 break;
1006 }
1007
1008 if (can_parse) {
1009 data.GetU32(data_offset_ptr, &header.cputype, 6);
1010 if (is_64_bit)
1011 *data_offset_ptr += 4;
1012 return true;
1013 } else {
1014 memset(&header, 0, sizeof(header));
1015 }
1016 return false;
1017}
1018
1020 ModuleSP module_sp(GetModule());
1021 if (!module_sp)
1022 return false;
1023
1024 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
1025 bool can_parse = false;
1026 lldb::offset_t offset = 0;
1028 // Leave magic in the original byte order
1029 m_header.magic = m_data.GetU32(&offset);
1030 switch (m_header.magic) {
1031 case MH_MAGIC:
1034 can_parse = true;
1035 break;
1036
1037 case MH_MAGIC_64:
1040 can_parse = true;
1041 break;
1042
1043 case MH_CIGAM:
1046 : eByteOrderBig);
1048 can_parse = true;
1049 break;
1050
1051 case MH_CIGAM_64:
1054 : eByteOrderBig);
1056 can_parse = true;
1057 break;
1058
1059 default:
1060 break;
1061 }
1062
1063 if (can_parse) {
1064 m_data.GetU32(&offset, &m_header.cputype, 6);
1065
1066 ModuleSpecList all_specs;
1067 ModuleSpec base_spec;
1069 base_spec, all_specs);
1070
1071 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
1072 ArchSpec mach_arch =
1074
1075 // Check if the module has a required architecture
1076 const ArchSpec &module_arch = module_sp->GetArchitecture();
1077 if (module_arch.IsValid() && !module_arch.IsCompatibleMatch(mach_arch))
1078 continue;
1079
1080 if (SetModulesArchitecture(mach_arch)) {
1081 const size_t header_and_lc_size =
1082 m_header.sizeofcmds + MachHeaderSizeFromMagic(m_header.magic);
1083 if (m_data.GetByteSize() < header_and_lc_size) {
1084 DataBufferSP data_sp;
1085 ProcessSP process_sp(m_process_wp.lock());
1086 if (process_sp) {
1087 data_sp = ReadMemory(process_sp, m_memory_addr, header_and_lc_size);
1088 } else {
1089 // Read in all only the load command data from the file on disk
1090 data_sp = MapFileData(m_file, header_and_lc_size, m_file_offset);
1091 if (data_sp->GetByteSize() != header_and_lc_size)
1092 continue;
1093 }
1094 if (data_sp)
1095 m_data.SetData(data_sp);
1096 }
1097 }
1098 return true;
1099 }
1100 // None found.
1101 return false;
1102 } else {
1103 memset(&m_header, 0, sizeof(struct llvm::MachO::mach_header));
1104 }
1105 return false;
1106}
1107
1109 return m_data.GetByteOrder();
1110}
1111
1113 return m_header.filetype == MH_EXECUTE;
1114}
1115
1117 return m_header.filetype == MH_DYLINKER;
1118}
1119
1121 return m_header.flags & MH_DYLIB_IN_CACHE;
1122}
1123
1125 return m_header.filetype == MH_KEXT_BUNDLE;
1126}
1127
1129 return m_data.GetAddressByteSize();
1130}
1131
1133 Symtab *symtab = GetSymtab();
1134 if (!symtab)
1135 return AddressClass::eUnknown;
1136
1137 Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
1138 if (symbol) {
1139 if (symbol->ValueIsAddress()) {
1140 SectionSP section_sp(symbol->GetAddressRef().GetSection());
1141 if (section_sp) {
1142 const lldb::SectionType section_type = section_sp->GetType();
1143 switch (section_type) {
1145 return AddressClass::eUnknown;
1146
1147 case eSectionTypeCode:
1148 if (m_header.cputype == llvm::MachO::CPU_TYPE_ARM) {
1149 // For ARM we have a bit in the n_desc field of the symbol that
1150 // tells us ARM/Thumb which is bit 0x0008.
1152 return AddressClass::eCodeAlternateISA;
1153 }
1154 return AddressClass::eCode;
1155
1157 return AddressClass::eUnknown;
1158
1159 case eSectionTypeData:
1163 case eSectionTypeData4:
1164 case eSectionTypeData8:
1165 case eSectionTypeData16:
1171 return AddressClass::eData;
1172
1173 case eSectionTypeDebug:
1208 case eSectionTypeCTF:
1210 return AddressClass::eDebug;
1211
1216 return AddressClass::eRuntime;
1217
1223 case eSectionTypeOther:
1224 return AddressClass::eUnknown;
1225 }
1226 }
1227 }
1228
1229 const SymbolType symbol_type = symbol->GetType();
1230 switch (symbol_type) {
1231 case eSymbolTypeAny:
1232 return AddressClass::eUnknown;
1234 return AddressClass::eUnknown;
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.
1243 return AddressClass::eCodeAlternateISA;
1244 }
1245 return AddressClass::eCode;
1246
1247 case eSymbolTypeData:
1248 return AddressClass::eData;
1249 case eSymbolTypeRuntime:
1250 return AddressClass::eRuntime;
1252 return AddressClass::eRuntime;
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;
1280 return AddressClass::eUnknown;
1282 return AddressClass::eDebug;
1284 return AddressClass::eDebug;
1286 return AddressClass::eUnknown;
1288 return AddressClass::eRuntime;
1290 return AddressClass::eRuntime;
1292 return AddressClass::eRuntime;
1294 return AddressClass::eRuntime;
1295 }
1296 }
1297 return AddressClass::eUnknown;
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.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.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.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.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 ({4: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_abbrev("__debug_abbrev");
1447 static ConstString g_sect_name_dwarf_debug_abbrev_dwo("__debug_abbrev.dwo");
1448 static ConstString g_sect_name_dwarf_debug_addr("__debug_addr");
1449 static ConstString g_sect_name_dwarf_debug_aranges("__debug_aranges");
1450 static ConstString g_sect_name_dwarf_debug_cu_index("__debug_cu_index");
1451 static ConstString g_sect_name_dwarf_debug_frame("__debug_frame");
1452 static ConstString g_sect_name_dwarf_debug_info("__debug_info");
1453 static ConstString g_sect_name_dwarf_debug_info_dwo("__debug_info.dwo");
1454 static ConstString g_sect_name_dwarf_debug_line("__debug_line");
1455 static ConstString g_sect_name_dwarf_debug_line_dwo("__debug_line.dwo");
1456 static ConstString g_sect_name_dwarf_debug_line_str("__debug_line_str");
1457 static ConstString g_sect_name_dwarf_debug_loc("__debug_loc");
1458 static ConstString g_sect_name_dwarf_debug_loclists("__debug_loclists");
1459 static ConstString g_sect_name_dwarf_debug_loclists_dwo("__debug_loclists.dwo");
1460 static ConstString g_sect_name_dwarf_debug_macinfo("__debug_macinfo");
1461 static ConstString g_sect_name_dwarf_debug_macro("__debug_macro");
1462 static ConstString g_sect_name_dwarf_debug_macro_dwo("__debug_macro.dwo");
1463 static ConstString g_sect_name_dwarf_debug_names("__debug_names");
1464 static ConstString g_sect_name_dwarf_debug_pubnames("__debug_pubnames");
1465 static ConstString g_sect_name_dwarf_debug_pubtypes("__debug_pubtypes");
1466 static ConstString g_sect_name_dwarf_debug_ranges("__debug_ranges");
1467 static ConstString g_sect_name_dwarf_debug_rnglists("__debug_rnglists");
1468 static ConstString g_sect_name_dwarf_debug_str("__debug_str");
1469 static ConstString g_sect_name_dwarf_debug_str_dwo("__debug_str.dwo");
1470 static ConstString g_sect_name_dwarf_debug_str_offs("__debug_str_offs");
1471 static ConstString g_sect_name_dwarf_debug_str_offs_dwo("__debug_str_offs.dwo");
1472 static ConstString g_sect_name_dwarf_debug_tu_index("__debug_tu_index");
1473 static ConstString g_sect_name_dwarf_debug_types("__debug_types");
1474 static ConstString g_sect_name_dwarf_apple_names("__apple_names");
1475 static ConstString g_sect_name_dwarf_apple_types("__apple_types");
1476 static ConstString g_sect_name_dwarf_apple_namespaces("__apple_namespac");
1477 static ConstString g_sect_name_dwarf_apple_objc("__apple_objc");
1478 static ConstString g_sect_name_eh_frame("__eh_frame");
1479 static ConstString g_sect_name_compact_unwind("__unwind_info");
1480 static ConstString g_sect_name_text("__text");
1481 static ConstString g_sect_name_data("__data");
1482 static ConstString g_sect_name_go_symtab("__gosymtab");
1483 static ConstString g_sect_name_ctf("__ctf");
1484 static ConstString g_sect_name_swift_ast("__swift_ast");
1485
1486 if (section_name == g_sect_name_dwarf_debug_abbrev)
1488 if (section_name == g_sect_name_dwarf_debug_abbrev_dwo)
1490 if (section_name == g_sect_name_dwarf_debug_addr)
1492 if (section_name == g_sect_name_dwarf_debug_aranges)
1494 if (section_name == g_sect_name_dwarf_debug_cu_index)
1496 if (section_name == g_sect_name_dwarf_debug_frame)
1498 if (section_name == g_sect_name_dwarf_debug_info)
1500 if (section_name == g_sect_name_dwarf_debug_info_dwo)
1502 if (section_name == g_sect_name_dwarf_debug_line)
1504 if (section_name == g_sect_name_dwarf_debug_line_dwo)
1505 return eSectionTypeDWARFDebugLine; // Same as debug_line.
1506 if (section_name == g_sect_name_dwarf_debug_line_str)
1508 if (section_name == g_sect_name_dwarf_debug_loc)
1510 if (section_name == g_sect_name_dwarf_debug_loclists)
1512 if (section_name == g_sect_name_dwarf_debug_loclists_dwo)
1514 if (section_name == g_sect_name_dwarf_debug_macinfo)
1516 if (section_name == g_sect_name_dwarf_debug_macro)
1518 if (section_name == g_sect_name_dwarf_debug_macro_dwo)
1519 return eSectionTypeDWARFDebugMacInfo; // Same as debug_macro.
1520 if (section_name == g_sect_name_dwarf_debug_names)
1522 if (section_name == g_sect_name_dwarf_debug_pubnames)
1524 if (section_name == g_sect_name_dwarf_debug_pubtypes)
1526 if (section_name == g_sect_name_dwarf_debug_ranges)
1528 if (section_name == g_sect_name_dwarf_debug_rnglists)
1530 if (section_name == g_sect_name_dwarf_debug_str)
1532 if (section_name == g_sect_name_dwarf_debug_str_dwo)
1534 if (section_name == g_sect_name_dwarf_debug_str_offs)
1536 if (section_name == g_sect_name_dwarf_debug_str_offs_dwo)
1538 if (section_name == g_sect_name_dwarf_debug_tu_index)
1540 if (section_name == g_sect_name_dwarf_debug_types)
1542 if (section_name == g_sect_name_dwarf_apple_names)
1544 if (section_name == g_sect_name_dwarf_apple_types)
1546 if (section_name == g_sect_name_dwarf_apple_namespaces)
1548 if (section_name == g_sect_name_dwarf_apple_objc)
1550 if (section_name == g_sect_name_objc_selrefs)
1552 if (section_name == g_sect_name_objc_msgrefs)
1554 if (section_name == g_sect_name_eh_frame)
1555 return eSectionTypeEHFrame;
1556 if (section_name == g_sect_name_compact_unwind)
1558 if (section_name == g_sect_name_cfstring)
1560 if (section_name == g_sect_name_go_symtab)
1561 return eSectionTypeGoSymtab;
1562 if (section_name == g_sect_name_ctf)
1563 return eSectionTypeCTF;
1564 if (section_name == g_sect_name_swift_ast)
1566 if (section_name == g_sect_name_objc_data ||
1567 section_name == g_sect_name_objc_classrefs ||
1568 section_name == g_sect_name_objc_superrefs ||
1569 section_name == g_sect_name_objc_const ||
1570 section_name == g_sect_name_objc_classlist) {
1572 }
1573
1574 switch (mach_sect_type) {
1575 // TODO: categorize sections by other flags for regular sections
1576 case S_REGULAR:
1577 if (section_name == g_sect_name_text)
1578 return eSectionTypeCode;
1579 if (section_name == g_sect_name_data)
1580 return eSectionTypeData;
1581 return eSectionTypeOther;
1582 case S_ZEROFILL:
1583 return eSectionTypeZeroFill;
1584 case S_CSTRING_LITERALS: // section with only literal C strings
1586 case S_4BYTE_LITERALS: // section with only 4 byte literals
1587 return eSectionTypeData4;
1588 case S_8BYTE_LITERALS: // section with only 8 byte literals
1589 return eSectionTypeData8;
1590 case S_LITERAL_POINTERS: // section with only pointers to literals
1592 case S_NON_LAZY_SYMBOL_POINTERS: // section with only non-lazy symbol pointers
1594 case S_LAZY_SYMBOL_POINTERS: // section with only lazy symbol pointers
1596 case S_SYMBOL_STUBS: // section with only symbol stubs, byte size of stub in
1597 // the reserved2 field
1598 return eSectionTypeCode;
1599 case S_MOD_INIT_FUNC_POINTERS: // section with only function pointers for
1600 // initialization
1602 case S_MOD_TERM_FUNC_POINTERS: // section with only function pointers for
1603 // termination
1605 case S_COALESCED:
1606 return eSectionTypeOther;
1607 case S_GB_ZEROFILL:
1608 return eSectionTypeZeroFill;
1609 case S_INTERPOSING: // section with only pairs of function pointers for
1610 // interposing
1611 return eSectionTypeCode;
1612 case S_16BYTE_LITERALS: // section with only 16 byte literals
1613 return eSectionTypeData16;
1614 case S_DTRACE_DOF:
1615 return eSectionTypeDebug;
1616 case S_LAZY_DYLIB_SYMBOL_POINTERS:
1618 default:
1619 return eSectionTypeOther;
1620 }
1621}
1622
1626 uint32_t NextSegmentIdx = 0;
1627 uint32_t NextSectionIdx = 0;
1629
1633};
1634
1636 const llvm::MachO::load_command &load_cmd_, lldb::offset_t offset,
1637 uint32_t cmd_idx, SegmentParsingContext &context) {
1638 llvm::MachO::segment_command_64 load_cmd;
1639 memcpy(&load_cmd, &load_cmd_, sizeof(load_cmd_));
1640
1641 if (!m_data.GetU8(&offset, (uint8_t *)load_cmd.segname, 16))
1642 return;
1643
1644 ModuleSP module_sp = GetModule();
1645 const bool is_core = GetType() == eTypeCoreFile;
1646 const bool is_dsym = (m_header.filetype == MH_DSYM);
1647 bool add_section = true;
1648 bool add_to_unified = true;
1649 ConstString const_segname(
1650 load_cmd.segname, strnlen(load_cmd.segname, sizeof(load_cmd.segname)));
1651
1652 SectionSP unified_section_sp(
1653 context.UnifiedList.FindSectionByName(const_segname));
1654 if (is_dsym && unified_section_sp) {
1655 if (const_segname == GetSegmentNameLINKEDIT()) {
1656 // We need to keep the __LINKEDIT segment private to this object file
1657 // only
1658 add_to_unified = false;
1659 } else {
1660 // This is the dSYM file and this section has already been created by the
1661 // object file, no need to create it.
1662 add_section = false;
1663 }
1664 }
1665 load_cmd.vmaddr = m_data.GetAddress(&offset);
1666 load_cmd.vmsize = m_data.GetAddress(&offset);
1667 load_cmd.fileoff = m_data.GetAddress(&offset);
1668 load_cmd.filesize = m_data.GetAddress(&offset);
1669 if (!m_data.GetU32(&offset, &load_cmd.maxprot, 4))
1670 return;
1671
1672 SanitizeSegmentCommand(load_cmd, cmd_idx);
1673
1674 const uint32_t segment_permissions = GetSegmentPermissions(load_cmd);
1675 const bool segment_is_encrypted =
1676 (load_cmd.flags & SG_PROTECTED_VERSION_1) != 0;
1677
1678 // Use a segment ID of the segment index shifted left by 8 so they never
1679 // conflict with any of the sections.
1680 SectionSP segment_sp;
1681 if (add_section && (const_segname || is_core)) {
1682 segment_sp = std::make_shared<Section>(
1683 module_sp, // Module to which this section belongs
1684 this, // Object file to which this sections belongs
1685 ++context.NextSegmentIdx
1686 << 8, // Section ID is the 1 based segment index
1687 // shifted right by 8 bits as not to collide with any of the 256
1688 // section IDs that are possible
1689 const_segname, // Name of this section
1690 eSectionTypeContainer, // This section is a container of other
1691 // sections.
1692 load_cmd.vmaddr, // File VM address == addresses as they are
1693 // found in the object file
1694 load_cmd.vmsize, // VM size in bytes of this section
1695 load_cmd.fileoff, // Offset to the data for this section in
1696 // the file
1697 load_cmd.filesize, // Size in bytes of this section as found
1698 // in the file
1699 0, // Segments have no alignment information
1700 load_cmd.flags); // Flags for this section
1701
1702 segment_sp->SetIsEncrypted(segment_is_encrypted);
1703 m_sections_up->AddSection(segment_sp);
1704 segment_sp->SetPermissions(segment_permissions);
1705 if (add_to_unified)
1706 context.UnifiedList.AddSection(segment_sp);
1707 } else if (unified_section_sp) {
1708 // If this is a dSYM and the file addresses in the dSYM differ from the
1709 // file addresses in the ObjectFile, we must use the file base address for
1710 // the Section from the dSYM for the DWARF to resolve correctly.
1711 // This only happens with binaries in the shared cache in practice;
1712 // normally a mismatch like this would give a binary & dSYM that do not
1713 // match UUIDs. When a binary is included in the shared cache, its
1714 // segments are rearranged to optimize the shared cache, so its file
1715 // addresses will differ from what the ObjectFile had originally,
1716 // and what the dSYM has.
1717 if (is_dsym && unified_section_sp->GetFileAddress() != load_cmd.vmaddr) {
1718 Log *log = GetLog(LLDBLog::Symbols);
1719 if (log) {
1720 log->Printf(
1721 "Installing dSYM's %s segment file address over ObjectFile's "
1722 "so symbol table/debug info resolves correctly for %s",
1723 const_segname.AsCString(),
1724 module_sp->GetFileSpec().GetFilename().AsCString());
1725 }
1726
1727 // Make sure we've parsed the symbol table from the ObjectFile before
1728 // we go around changing its Sections.
1729 module_sp->GetObjectFile()->GetSymtab();
1730 // eh_frame would present the same problems but we parse that on a per-
1731 // function basis as-needed so it's more difficult to remove its use of
1732 // the Sections. Realistically, the environments where this code path
1733 // will be taken will not have eh_frame sections.
1734
1735 unified_section_sp->SetFileAddress(load_cmd.vmaddr);
1736
1737 // Notify the module that the section addresses have been changed once
1738 // we're done so any file-address caches can be updated.
1739 context.FileAddressesChanged = true;
1740 }
1741 m_sections_up->AddSection(unified_section_sp);
1742 }
1743
1744 llvm::MachO::section_64 sect64;
1745 ::memset(&sect64, 0, sizeof(sect64));
1746 // Push a section into our mach sections for the section at index zero
1747 // (NO_SECT) if we don't have any mach sections yet...
1748 if (m_mach_sections.empty())
1749 m_mach_sections.push_back(sect64);
1750 uint32_t segment_sect_idx;
1751 const lldb::user_id_t first_segment_sectID = context.NextSectionIdx + 1;
1752
1753 const uint32_t num_u32s = load_cmd.cmd == LC_SEGMENT ? 7 : 8;
1754 for (segment_sect_idx = 0; segment_sect_idx < load_cmd.nsects;
1755 ++segment_sect_idx) {
1756 if (m_data.GetU8(&offset, (uint8_t *)sect64.sectname,
1757 sizeof(sect64.sectname)) == nullptr)
1758 break;
1759 if (m_data.GetU8(&offset, (uint8_t *)sect64.segname,
1760 sizeof(sect64.segname)) == nullptr)
1761 break;
1762 sect64.addr = m_data.GetAddress(&offset);
1763 sect64.size = m_data.GetAddress(&offset);
1764
1765 if (m_data.GetU32(&offset, &sect64.offset, num_u32s) == nullptr)
1766 break;
1767
1768 if (IsSharedCacheBinary() && !IsInMemory()) {
1769 sect64.offset = sect64.addr - m_text_address;
1770 }
1771
1772 // Keep a list of mach sections around in case we need to get at data that
1773 // isn't stored in the abstracted Sections.
1774 m_mach_sections.push_back(sect64);
1775
1776 if (add_section) {
1777 ConstString section_name(
1778 sect64.sectname, strnlen(sect64.sectname, sizeof(sect64.sectname)));
1779 if (!const_segname) {
1780 // We have a segment with no name so we need to conjure up segments
1781 // that correspond to the section's segname if there isn't already such
1782 // a section. If there is such a section, we resize the section so that
1783 // it spans all sections. We also mark these sections as fake so
1784 // address matches don't hit if they land in the gaps between the child
1785 // sections.
1786 const_segname.SetTrimmedCStringWithLength(sect64.segname,
1787 sizeof(sect64.segname));
1788 segment_sp = context.UnifiedList.FindSectionByName(const_segname);
1789 if (segment_sp.get()) {
1790 Section *segment = segment_sp.get();
1791 // Grow the section size as needed.
1792 const lldb::addr_t sect64_min_addr = sect64.addr;
1793 const lldb::addr_t sect64_max_addr = sect64_min_addr + sect64.size;
1794 const lldb::addr_t curr_seg_byte_size = segment->GetByteSize();
1795 const lldb::addr_t curr_seg_min_addr = segment->GetFileAddress();
1796 const lldb::addr_t curr_seg_max_addr =
1797 curr_seg_min_addr + curr_seg_byte_size;
1798 if (sect64_min_addr >= curr_seg_min_addr) {
1799 const lldb::addr_t new_seg_byte_size =
1800 sect64_max_addr - curr_seg_min_addr;
1801 // Only grow the section size if needed
1802 if (new_seg_byte_size > curr_seg_byte_size)
1803 segment->SetByteSize(new_seg_byte_size);
1804 } else {
1805 // We need to change the base address of the segment and adjust the
1806 // child section offsets for all existing children.
1807 const lldb::addr_t slide_amount =
1808 sect64_min_addr - curr_seg_min_addr;
1809 segment->Slide(slide_amount, false);
1810 segment->GetChildren().Slide(-slide_amount, false);
1811 segment->SetByteSize(curr_seg_max_addr - sect64_min_addr);
1812 }
1813
1814 // Grow the section size as needed.
1815 if (sect64.offset) {
1816 const lldb::addr_t segment_min_file_offset =
1817 segment->GetFileOffset();
1818 const lldb::addr_t segment_max_file_offset =
1819 segment_min_file_offset + segment->GetFileSize();
1820
1821 const lldb::addr_t section_min_file_offset = sect64.offset;
1822 const lldb::addr_t section_max_file_offset =
1823 section_min_file_offset + sect64.size;
1824 const lldb::addr_t new_file_offset =
1825 std::min(section_min_file_offset, segment_min_file_offset);
1826 const lldb::addr_t new_file_size =
1827 std::max(section_max_file_offset, segment_max_file_offset) -
1828 new_file_offset;
1829 segment->SetFileOffset(new_file_offset);
1830 segment->SetFileSize(new_file_size);
1831 }
1832 } else {
1833 // Create a fake section for the section's named segment
1834 segment_sp = std::make_shared<Section>(
1835 segment_sp, // Parent section
1836 module_sp, // Module to which this section belongs
1837 this, // Object file to which this section belongs
1838 ++context.NextSegmentIdx
1839 << 8, // Section ID is the 1 based segment index
1840 // shifted right by 8 bits as not to
1841 // collide with any of the 256 section IDs
1842 // that are possible
1843 const_segname, // Name of this section
1844 eSectionTypeContainer, // This section is a container of
1845 // other sections.
1846 sect64.addr, // File VM address == addresses as they are
1847 // found in the object file
1848 sect64.size, // VM size in bytes of this section
1849 sect64.offset, // Offset to the data for this section in
1850 // the file
1851 sect64.offset ? sect64.size : 0, // Size in bytes of
1852 // this section as
1853 // found in the file
1854 sect64.align,
1855 load_cmd.flags); // Flags for this section
1856 segment_sp->SetIsFake(true);
1857 segment_sp->SetPermissions(segment_permissions);
1858 m_sections_up->AddSection(segment_sp);
1859 if (add_to_unified)
1860 context.UnifiedList.AddSection(segment_sp);
1861 segment_sp->SetIsEncrypted(segment_is_encrypted);
1862 }
1863 }
1864 assert(segment_sp.get());
1865
1866 lldb::SectionType sect_type = GetSectionType(sect64.flags, section_name);
1867
1868 SectionSP section_sp(new Section(
1869 segment_sp, module_sp, this, ++context.NextSectionIdx, section_name,
1870 sect_type, sect64.addr - segment_sp->GetFileAddress(), sect64.size,
1871 sect64.offset, sect64.offset == 0 ? 0 : sect64.size, sect64.align,
1872 sect64.flags));
1873 // Set the section to be encrypted to match the segment
1874
1875 bool section_is_encrypted = false;
1876 if (!segment_is_encrypted && load_cmd.filesize != 0)
1877 section_is_encrypted = context.EncryptedRanges.FindEntryThatContains(
1878 sect64.offset) != nullptr;
1879
1880 section_sp->SetIsEncrypted(segment_is_encrypted || section_is_encrypted);
1881 section_sp->SetPermissions(segment_permissions);
1882 segment_sp->GetChildren().AddSection(section_sp);
1883
1884 if (segment_sp->IsFake()) {
1885 segment_sp.reset();
1886 const_segname.Clear();
1887 }
1888 }
1889 }
1890 if (segment_sp && is_dsym) {
1891 if (first_segment_sectID <= context.NextSectionIdx) {
1892 lldb::user_id_t sect_uid;
1893 for (sect_uid = first_segment_sectID; sect_uid <= context.NextSectionIdx;
1894 ++sect_uid) {
1895 SectionSP curr_section_sp(
1896 segment_sp->GetChildren().FindSectionByID(sect_uid));
1897 SectionSP next_section_sp;
1898 if (sect_uid + 1 <= context.NextSectionIdx)
1899 next_section_sp =
1900 segment_sp->GetChildren().FindSectionByID(sect_uid + 1);
1901
1902 if (curr_section_sp.get()) {
1903 if (curr_section_sp->GetByteSize() == 0) {
1904 if (next_section_sp.get() != nullptr)
1905 curr_section_sp->SetByteSize(next_section_sp->GetFileAddress() -
1906 curr_section_sp->GetFileAddress());
1907 else
1908 curr_section_sp->SetByteSize(load_cmd.vmsize);
1909 }
1910 }
1911 }
1912 }
1913 }
1914}
1915
1917 const llvm::MachO::load_command &load_cmd, lldb::offset_t offset) {
1918 m_dysymtab.cmd = load_cmd.cmd;
1919 m_dysymtab.cmdsize = load_cmd.cmdsize;
1920 m_data.GetU32(&offset, &m_dysymtab.ilocalsym,
1921 (sizeof(m_dysymtab) / sizeof(uint32_t)) - 2);
1922}
1923
1925 if (m_sections_up)
1926 return;
1927
1928 m_sections_up = std::make_unique<SectionList>();
1929
1931 // bool dump_sections = false;
1932 ModuleSP module_sp(GetModule());
1933
1934 offset = MachHeaderSizeFromMagic(m_header.magic);
1935
1936 SegmentParsingContext context(GetEncryptedFileRanges(), unified_section_list);
1937 llvm::MachO::load_command load_cmd;
1938 for (uint32_t i = 0; i < m_header.ncmds; ++i) {
1939 const lldb::offset_t load_cmd_offset = offset;
1940 if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
1941 break;
1942
1943 if (load_cmd.cmd == LC_SEGMENT || load_cmd.cmd == LC_SEGMENT_64)
1944 ProcessSegmentCommand(load_cmd, offset, i, context);
1945 else if (load_cmd.cmd == LC_DYSYMTAB)
1946 ProcessDysymtabCommand(load_cmd, offset);
1947
1948 offset = load_cmd_offset + load_cmd.cmdsize;
1949 }
1950
1951 if (context.FileAddressesChanged && module_sp)
1952 module_sp->SectionFileAddressesChanged();
1953}
1954
1956public:
1958 : m_section_list(section_list), m_section_infos() {
1959 // Get the number of sections down to a depth of 1 to include all segments
1960 // and their sections, but no other sections that may be added for debug
1961 // map or
1962 m_section_infos.resize(section_list->GetNumSections(1));
1963 }
1964
1965 SectionSP GetSection(uint8_t n_sect, addr_t file_addr) {
1966 if (n_sect == 0)
1967 return SectionSP();
1968 if (n_sect < m_section_infos.size()) {
1969 if (!m_section_infos[n_sect].section_sp) {
1970 SectionSP section_sp(m_section_list->FindSectionByID(n_sect));
1971 m_section_infos[n_sect].section_sp = section_sp;
1972 if (section_sp) {
1973 m_section_infos[n_sect].vm_range.SetBaseAddress(
1974 section_sp->GetFileAddress());
1975 m_section_infos[n_sect].vm_range.SetByteSize(
1976 section_sp->GetByteSize());
1977 } else {
1978 std::string filename = "<unknown>";
1979 SectionSP first_section_sp(m_section_list->GetSectionAtIndex(0));
1980 if (first_section_sp)
1981 filename = first_section_sp->GetObjectFile()->GetFileSpec().GetPath();
1982
1984 llvm::formatv("unable to find section {0} for a symbol in "
1985 "{1}, corrupt file?",
1986 n_sect, filename));
1987 }
1988 }
1989 if (m_section_infos[n_sect].vm_range.Contains(file_addr)) {
1990 // Symbol is in section.
1991 return m_section_infos[n_sect].section_sp;
1992 } else if (m_section_infos[n_sect].vm_range.GetByteSize() == 0 &&
1993 m_section_infos[n_sect].vm_range.GetBaseAddress() ==
1994 file_addr) {
1995 // Symbol is in section with zero size, but has the same start address
1996 // as the section. This can happen with linker symbols (symbols that
1997 // start with the letter 'l' or 'L'.
1998 return m_section_infos[n_sect].section_sp;
1999 }
2000 }
2002 }
2003
2004protected:
2007
2010 };
2012 std::vector<SectionInfo> m_section_infos;
2013};
2014
2015#define TRIE_SYMBOL_IS_THUMB (1ULL << 63)
2017 void Dump() const {
2018 printf("0x%16.16llx 0x%16.16llx 0x%16.16llx \"%s\"",
2019 static_cast<unsigned long long>(address),
2020 static_cast<unsigned long long>(flags),
2021 static_cast<unsigned long long>(other), name.GetCString());
2022 if (import_name)
2023 printf(" -> \"%s\"\n", import_name.GetCString());
2024 else
2025 printf("\n");
2026 }
2029 uint64_t flags =
2030 0; // EXPORT_SYMBOL_FLAGS_REEXPORT, EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER,
2031 // TRIE_SYMBOL_IS_THUMB
2032 uint64_t other = 0;
2034};
2035
2039
2041
2042 void Dump(uint32_t idx) const {
2043 printf("[%3u] 0x%16.16llx: ", idx,
2044 static_cast<unsigned long long>(nodeOffset));
2045 entry.Dump();
2046 }
2047
2048 bool operator<(const TrieEntryWithOffset &other) const {
2049 return (nodeOffset < other.nodeOffset);
2050 }
2051};
2052
2054 const bool is_arm, addr_t text_seg_base_addr,
2055 std::vector<llvm::StringRef> &nameSlices,
2056 std::set<lldb::addr_t> &resolver_addresses,
2057 std::vector<TrieEntryWithOffset> &reexports,
2058 std::vector<TrieEntryWithOffset> &ext_symbols) {
2059 if (!data.ValidOffset(offset))
2060 return true;
2061
2062 // Terminal node -- end of a branch, possibly add this to
2063 // the symbol table or resolver table.
2064 const uint64_t terminalSize = data.GetULEB128(&offset);
2065 lldb::offset_t children_offset = offset + terminalSize;
2066 if (terminalSize != 0) {
2067 TrieEntryWithOffset e(offset);
2068 e.entry.flags = data.GetULEB128(&offset);
2069 const char *import_name = nullptr;
2070 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_REEXPORT) {
2071 e.entry.address = 0;
2072 e.entry.other = data.GetULEB128(&offset); // dylib ordinal
2073 import_name = data.GetCStr(&offset);
2074 } else {
2075 e.entry.address = data.GetULEB128(&offset);
2076 if (text_seg_base_addr != LLDB_INVALID_ADDRESS)
2077 e.entry.address += text_seg_base_addr;
2078 if (e.entry.flags & EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER) {
2079 e.entry.other = data.GetULEB128(&offset);
2080 uint64_t resolver_addr = e.entry.other;
2081 if (text_seg_base_addr != LLDB_INVALID_ADDRESS)
2082 resolver_addr += text_seg_base_addr;
2083 if (is_arm)
2084 resolver_addr &= THUMB_ADDRESS_BIT_MASK;
2085 resolver_addresses.insert(resolver_addr);
2086 } else
2087 e.entry.other = 0;
2088 }
2089 bool add_this_entry = false;
2090 if (Flags(e.entry.flags).Test(EXPORT_SYMBOL_FLAGS_REEXPORT) &&
2091 import_name && import_name[0]) {
2092 // add symbols that are reexport symbols with a valid import name.
2093 add_this_entry = true;
2094 } else if (e.entry.flags == 0 &&
2095 (import_name == nullptr || import_name[0] == '\0')) {
2096 // add externally visible symbols, in case the nlist record has
2097 // been stripped/omitted.
2098 add_this_entry = true;
2099 }
2100 if (add_this_entry) {
2101 std::string name;
2102 if (!nameSlices.empty()) {
2103 for (auto name_slice : nameSlices)
2104 name.append(name_slice.data(), name_slice.size());
2105 }
2106 if (name.size() > 1) {
2107 // Skip the leading '_'
2108 e.entry.name.SetCStringWithLength(name.c_str() + 1, name.size() - 1);
2109 }
2110 if (import_name) {
2111 // Skip the leading '_'
2112 e.entry.import_name.SetCString(import_name + 1);
2113 }
2114 if (Flags(e.entry.flags).Test(EXPORT_SYMBOL_FLAGS_REEXPORT)) {
2115 reexports.push_back(e);
2116 } else {
2117 if (is_arm && (e.entry.address & 1)) {
2120 }
2121 ext_symbols.push_back(e);
2122 }
2123 }
2124 }
2125
2126 const uint8_t childrenCount = data.GetU8(&children_offset);
2127 for (uint8_t i = 0; i < childrenCount; ++i) {
2128 const char *cstr = data.GetCStr(&children_offset);
2129 if (cstr)
2130 nameSlices.push_back(llvm::StringRef(cstr));
2131 else
2132 return false; // Corrupt data
2133 lldb::offset_t childNodeOffset = data.GetULEB128(&children_offset);
2134 if (childNodeOffset) {
2135 if (!ParseTrieEntries(data, childNodeOffset, is_arm, text_seg_base_addr,
2136 nameSlices, resolver_addresses, reexports,
2137 ext_symbols)) {
2138 return false;
2139 }
2140 }
2141 nameSlices.pop_back();
2142 }
2143 return true;
2144}
2145
2146static SymbolType GetSymbolType(const char *&symbol_name,
2147 bool &demangled_is_synthesized,
2148 const SectionSP &text_section_sp,
2149 const SectionSP &data_section_sp,
2150 const SectionSP &data_dirty_section_sp,
2151 const SectionSP &data_const_section_sp,
2152 const SectionSP &symbol_section) {
2154
2155 const char *symbol_sect_name = symbol_section->GetName().AsCString();
2156 if (symbol_section->IsDescendant(text_section_sp.get())) {
2157 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
2158 S_ATTR_SELF_MODIFYING_CODE |
2159 S_ATTR_SOME_INSTRUCTIONS))
2160 type = eSymbolTypeData;
2161 else
2162 type = eSymbolTypeCode;
2163 } else if (symbol_section->IsDescendant(data_section_sp.get()) ||
2164 symbol_section->IsDescendant(data_dirty_section_sp.get()) ||
2165 symbol_section->IsDescendant(data_const_section_sp.get())) {
2166 if (symbol_sect_name &&
2167 ::strstr(symbol_sect_name, "__objc") == symbol_sect_name) {
2168 type = eSymbolTypeRuntime;
2169
2170 if (symbol_name) {
2171 llvm::StringRef symbol_name_ref(symbol_name);
2172 if (symbol_name_ref.starts_with("OBJC_")) {
2173 static const llvm::StringRef g_objc_v2_prefix_class("OBJC_CLASS_$_");
2174 static const llvm::StringRef g_objc_v2_prefix_metaclass(
2175 "OBJC_METACLASS_$_");
2176 static const llvm::StringRef g_objc_v2_prefix_ivar("OBJC_IVAR_$_");
2177 if (symbol_name_ref.starts_with(g_objc_v2_prefix_class)) {
2178 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
2179 type = eSymbolTypeObjCClass;
2180 demangled_is_synthesized = true;
2181 } else if (symbol_name_ref.starts_with(g_objc_v2_prefix_metaclass)) {
2182 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
2184 demangled_is_synthesized = true;
2185 } else if (symbol_name_ref.starts_with(g_objc_v2_prefix_ivar)) {
2186 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
2187 type = eSymbolTypeObjCIVar;
2188 demangled_is_synthesized = true;
2189 }
2190 }
2191 }
2192 } else if (symbol_sect_name &&
2193 ::strstr(symbol_sect_name, "__gcc_except_tab") ==
2194 symbol_sect_name) {
2195 type = eSymbolTypeException;
2196 } else {
2197 type = eSymbolTypeData;
2198 }
2199 } else if (symbol_sect_name &&
2200 ::strstr(symbol_sect_name, "__IMPORT") == symbol_sect_name) {
2201 type = eSymbolTypeTrampoline;
2202 }
2203 return type;
2204}
2205
2206static std::optional<struct nlist_64>
2207ParseNList(DataExtractor &nlist_data, lldb::offset_t &nlist_data_offset,
2208 size_t nlist_byte_size) {
2209 struct nlist_64 nlist;
2210 if (!nlist_data.ValidOffsetForDataOfSize(nlist_data_offset, nlist_byte_size))
2211 return {};
2212 nlist.n_strx = nlist_data.GetU32_unchecked(&nlist_data_offset);
2213 nlist.n_type = nlist_data.GetU8_unchecked(&nlist_data_offset);
2214 nlist.n_sect = nlist_data.GetU8_unchecked(&nlist_data_offset);
2215 nlist.n_desc = nlist_data.GetU16_unchecked(&nlist_data_offset);
2216 nlist.n_value = nlist_data.GetAddress_unchecked(&nlist_data_offset);
2217 return nlist;
2218}
2219
2220enum { DebugSymbols = true, NonDebugSymbols = false };
2221
2223 ModuleSP module_sp(GetModule());
2224 if (!module_sp)
2225 return;
2226
2227 Log *log = GetLog(LLDBLog::Symbols);
2228
2229 const FileSpec &file = m_file ? m_file : module_sp->GetFileSpec();
2230 const char *file_name = file.GetFilename().AsCString("<Unknown>");
2231 LLDB_SCOPED_TIMERF("ObjectFileMachO::ParseSymtab () module = %s", file_name);
2232 LLDB_LOG(log, "Parsing symbol table for {0}", file_name);
2233 Progress progress("Parsing symbol table", file_name);
2234
2235 llvm::MachO::symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0};
2236 llvm::MachO::linkedit_data_command function_starts_load_command = {0, 0, 0, 0};
2237 llvm::MachO::linkedit_data_command exports_trie_load_command = {0, 0, 0, 0};
2238 llvm::MachO::dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2239 llvm::MachO::dysymtab_command dysymtab = m_dysymtab;
2240 // The data element of type bool indicates that this entry is thumb
2241 // code.
2242 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts;
2243
2244 // Record the address of every function/data that we add to the symtab.
2245 // We add symbols to the table in the order of most information (nlist
2246 // records) to least (function starts), and avoid duplicating symbols
2247 // via this set.
2248 llvm::DenseSet<addr_t> symbols_added;
2249
2250 // We are using a llvm::DenseSet for "symbols_added" so we must be sure we
2251 // do not add the tombstone or empty keys to the set.
2252 auto add_symbol_addr = [&symbols_added](lldb::addr_t file_addr) {
2253 // Don't add the tombstone or empty keys.
2254 if (file_addr == UINT64_MAX || file_addr == UINT64_MAX - 1)
2255 return;
2256 symbols_added.insert(file_addr);
2257 };
2258 FunctionStarts function_starts;
2260 uint32_t i;
2261 FileSpecList dylib_files;
2262 llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_");
2263 llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_");
2264 llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
2265 UUID image_uuid;
2266
2267 for (i = 0; i < m_header.ncmds; ++i) {
2268 const lldb::offset_t cmd_offset = offset;
2269 // Read in the load command and load command size
2270 llvm::MachO::load_command lc;
2271 if (m_data.GetU32(&offset, &lc, 2) == nullptr)
2272 break;
2273 // Watch for the symbol table load command
2274 switch (lc.cmd) {
2275 case LC_SYMTAB:
2276 symtab_load_command.cmd = lc.cmd;
2277 symtab_load_command.cmdsize = lc.cmdsize;
2278 // Read in the rest of the symtab load command
2279 if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) ==
2280 nullptr) // fill in symoff, nsyms, stroff, strsize fields
2281 return;
2282 break;
2283
2284 case LC_DYLD_INFO:
2285 case LC_DYLD_INFO_ONLY:
2286 if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) {
2287 dyld_info.cmd = lc.cmd;
2288 dyld_info.cmdsize = lc.cmdsize;
2289 } else {
2290 memset(&dyld_info, 0, sizeof(dyld_info));
2291 }
2292 break;
2293
2294 case LC_LOAD_DYLIB:
2295 case LC_LOAD_WEAK_DYLIB:
2296 case LC_REEXPORT_DYLIB:
2297 case LC_LOADFVMLIB:
2298 case LC_LOAD_UPWARD_DYLIB: {
2299 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
2300 const char *path = m_data.PeekCStr(name_offset);
2301 if (path) {
2302 FileSpec file_spec(path);
2303 // Strip the path if there is @rpath, @executable, etc so we just use
2304 // the basename
2305 if (path[0] == '@')
2306 file_spec.ClearDirectory();
2307
2308 if (lc.cmd == LC_REEXPORT_DYLIB) {
2310 }
2311
2312 dylib_files.Append(file_spec);
2313 }
2314 } break;
2315
2316 case LC_DYLD_EXPORTS_TRIE:
2317 exports_trie_load_command.cmd = lc.cmd;
2318 exports_trie_load_command.cmdsize = lc.cmdsize;
2319 if (m_data.GetU32(&offset, &exports_trie_load_command.dataoff, 2) ==
2320 nullptr) // fill in offset and size fields
2321 memset(&exports_trie_load_command, 0,
2322 sizeof(exports_trie_load_command));
2323 break;
2324 case LC_FUNCTION_STARTS:
2325 function_starts_load_command.cmd = lc.cmd;
2326 function_starts_load_command.cmdsize = lc.cmdsize;
2327 if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) ==
2328 nullptr) // fill in data offset and size fields
2329 memset(&function_starts_load_command, 0,
2330 sizeof(function_starts_load_command));
2331 break;
2332
2333 case LC_UUID: {
2334 const uint8_t *uuid_bytes = m_data.PeekData(offset, 16);
2335
2336 if (uuid_bytes)
2337 image_uuid = UUID(uuid_bytes, 16);
2338 break;
2339 }
2340
2341 default:
2342 break;
2343 }
2344 offset = cmd_offset + lc.cmdsize;
2345 }
2346
2347 if (!symtab_load_command.cmd)
2348 return;
2349
2350 SectionList *section_list = GetSectionList();
2351 if (section_list == nullptr)
2352 return;
2353
2354 const uint32_t addr_byte_size = m_data.GetAddressByteSize();
2355 const ByteOrder byte_order = m_data.GetByteOrder();
2356 bool bit_width_32 = addr_byte_size == 4;
2357 const size_t nlist_byte_size =
2358 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64);
2359
2360 DataExtractor nlist_data(nullptr, 0, byte_order, addr_byte_size);
2361 DataExtractor strtab_data(nullptr, 0, byte_order, addr_byte_size);
2362 DataExtractor function_starts_data(nullptr, 0, byte_order, addr_byte_size);
2363 DataExtractor indirect_symbol_index_data(nullptr, 0, byte_order,
2364 addr_byte_size);
2365 DataExtractor dyld_trie_data(nullptr, 0, byte_order, addr_byte_size);
2366
2367 const addr_t nlist_data_byte_size =
2368 symtab_load_command.nsyms * nlist_byte_size;
2369 const addr_t strtab_data_byte_size = symtab_load_command.strsize;
2370 addr_t strtab_addr = LLDB_INVALID_ADDRESS;
2371
2372 ProcessSP process_sp(m_process_wp.lock());
2373 Process *process = process_sp.get();
2374
2375 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete;
2376 bool is_shared_cache_image = IsSharedCacheBinary();
2377 bool is_local_shared_cache_image = is_shared_cache_image && !IsInMemory();
2378 SectionSP linkedit_section_sp(
2379 section_list->FindSectionByName(GetSegmentNameLINKEDIT()));
2380
2381 if (process && m_header.filetype != llvm::MachO::MH_OBJECT &&
2382 !is_local_shared_cache_image) {
2383 Target &target = process->GetTarget();
2384
2385 memory_module_load_level = target.GetMemoryModuleLoadLevel();
2386
2387 // Reading mach file from memory in a process or core file...
2388
2389 if (linkedit_section_sp) {
2390 addr_t linkedit_load_addr =
2391 linkedit_section_sp->GetLoadBaseAddress(&target);
2392 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) {
2393 // We might be trying to access the symbol table before the
2394 // __LINKEDIT's load address has been set in the target. We can't
2395 // fail to read the symbol table, so calculate the right address
2396 // manually
2397 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage(
2398 m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get());
2399 }
2400
2401 const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset();
2402 const addr_t symoff_addr = linkedit_load_addr +
2403 symtab_load_command.symoff -
2404 linkedit_file_offset;
2405 strtab_addr = linkedit_load_addr + symtab_load_command.stroff -
2406 linkedit_file_offset;
2407
2408 // Always load dyld - the dynamic linker - from memory if we didn't
2409 // find a binary anywhere else. lldb will not register
2410 // dylib/framework/bundle loads/unloads if we don't have the dyld
2411 // symbols, we force dyld to load from memory despite the user's
2412 // target.memory-module-load-level setting.
2413 if (memory_module_load_level == eMemoryModuleLoadLevelComplete ||
2414 m_header.filetype == llvm::MachO::MH_DYLINKER) {
2415 DataBufferSP nlist_data_sp(
2416 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size));
2417 if (nlist_data_sp)
2418 nlist_data.SetData(nlist_data_sp, 0, nlist_data_sp->GetByteSize());
2419 if (dysymtab.nindirectsyms != 0) {
2420 const addr_t indirect_syms_addr = linkedit_load_addr +
2421 dysymtab.indirectsymoff -
2422 linkedit_file_offset;
2423 DataBufferSP indirect_syms_data_sp(ReadMemory(
2424 process_sp, indirect_syms_addr, dysymtab.nindirectsyms * 4));
2425 if (indirect_syms_data_sp)
2426 indirect_symbol_index_data.SetData(
2427 indirect_syms_data_sp, 0,
2428 indirect_syms_data_sp->GetByteSize());
2429 // If this binary is outside the shared cache,
2430 // cache the string table.
2431 // Binaries in the shared cache all share a giant string table,
2432 // and we can't share the string tables across multiple
2433 // ObjectFileMachO's, so we'd end up re-reading this mega-strtab
2434 // for every binary in the shared cache - it would be a big perf
2435 // problem. For binaries outside the shared cache, it's faster to
2436 // read the entire strtab at once instead of piece-by-piece as we
2437 // process the nlist records.
2438 if (!is_shared_cache_image) {
2439 DataBufferSP strtab_data_sp(
2440 ReadMemory(process_sp, strtab_addr, strtab_data_byte_size));
2441 if (strtab_data_sp) {
2442 strtab_data.SetData(strtab_data_sp, 0,
2443 strtab_data_sp->GetByteSize());
2444 }
2445 }
2446 }
2447 if (memory_module_load_level >= eMemoryModuleLoadLevelPartial) {
2448 if (function_starts_load_command.cmd) {
2449 const addr_t func_start_addr =
2450 linkedit_load_addr + function_starts_load_command.dataoff -
2451 linkedit_file_offset;
2452 DataBufferSP func_start_data_sp(
2453 ReadMemory(process_sp, func_start_addr,
2454 function_starts_load_command.datasize));
2455 if (func_start_data_sp)
2456 function_starts_data.SetData(func_start_data_sp, 0,
2457 func_start_data_sp->GetByteSize());
2458 }
2459 }
2460 }
2461 }
2462 } else {
2463 if (is_local_shared_cache_image) {
2464 // The load commands in shared cache images are relative to the
2465 // beginning of the shared cache, not the library image. The
2466 // data we get handed when creating the ObjectFileMachO starts
2467 // at the beginning of a specific library and spans to the end
2468 // of the cache to be able to reach the shared LINKEDIT
2469 // segments. We need to convert the load command offsets to be
2470 // relative to the beginning of our specific image.
2471 lldb::addr_t linkedit_offset = linkedit_section_sp->GetFileOffset();
2472 lldb::offset_t linkedit_slide =
2473 linkedit_offset - m_linkedit_original_offset;
2474 symtab_load_command.symoff += linkedit_slide;
2475 symtab_load_command.stroff += linkedit_slide;
2476 dyld_info.export_off += linkedit_slide;
2477 dysymtab.indirectsymoff += linkedit_slide;
2478 function_starts_load_command.dataoff += linkedit_slide;
2479 exports_trie_load_command.dataoff += linkedit_slide;
2480 }
2481
2482 nlist_data.SetData(m_data, symtab_load_command.symoff,
2483 nlist_data_byte_size);
2484 strtab_data.SetData(m_data, symtab_load_command.stroff,
2485 strtab_data_byte_size);
2486
2487 // We shouldn't have exports data from both the LC_DYLD_INFO command
2488 // AND the LC_DYLD_EXPORTS_TRIE command in the same binary:
2489 lldbassert(!((dyld_info.export_size > 0)
2490 && (exports_trie_load_command.datasize > 0)));
2491 if (dyld_info.export_size > 0) {
2492 dyld_trie_data.SetData(m_data, dyld_info.export_off,
2493 dyld_info.export_size);
2494 } else if (exports_trie_load_command.datasize > 0) {
2495 dyld_trie_data.SetData(m_data, exports_trie_load_command.dataoff,
2496 exports_trie_load_command.datasize);
2497 }
2498
2499 if (dysymtab.nindirectsyms != 0) {
2500 indirect_symbol_index_data.SetData(m_data, dysymtab.indirectsymoff,
2501 dysymtab.nindirectsyms * 4);
2502 }
2503 if (function_starts_load_command.cmd) {
2504 function_starts_data.SetData(m_data, function_starts_load_command.dataoff,
2505 function_starts_load_command.datasize);
2506 }
2507 }
2508
2509 const bool have_strtab_data = strtab_data.GetByteSize() > 0;
2510
2511 ConstString g_segment_name_TEXT = GetSegmentNameTEXT();
2512 ConstString g_segment_name_DATA = GetSegmentNameDATA();
2513 ConstString g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY();
2514 ConstString g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST();
2515 ConstString g_segment_name_OBJC = GetSegmentNameOBJC();
2516 ConstString g_section_name_eh_frame = GetSectionNameEHFrame();
2517 SectionSP text_section_sp(
2518 section_list->FindSectionByName(g_segment_name_TEXT));
2519 SectionSP data_section_sp(
2520 section_list->FindSectionByName(g_segment_name_DATA));
2521 SectionSP data_dirty_section_sp(
2522 section_list->FindSectionByName(g_segment_name_DATA_DIRTY));
2523 SectionSP data_const_section_sp(
2524 section_list->FindSectionByName(g_segment_name_DATA_CONST));
2525 SectionSP objc_section_sp(
2526 section_list->FindSectionByName(g_segment_name_OBJC));
2527 SectionSP eh_frame_section_sp;
2528 if (text_section_sp.get())
2529 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName(
2530 g_section_name_eh_frame);
2531 else
2532 eh_frame_section_sp =
2533 section_list->FindSectionByName(g_section_name_eh_frame);
2534
2535 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM);
2536 const bool always_thumb = GetArchitecture().IsAlwaysThumbInstructions();
2537
2538 // lldb works best if it knows the start address of all functions in a
2539 // module. Linker symbols or debug info are normally the best source of
2540 // information for start addr / size but they may be stripped in a released
2541 // binary. Two additional sources of information exist in Mach-O binaries:
2542 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each
2543 // function's start address in the
2544 // binary, relative to the text section.
2545 // eh_frame - the eh_frame FDEs have the start addr & size of
2546 // each function
2547 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on
2548 // all modern binaries.
2549 // Binaries built to run on older releases may need to use eh_frame
2550 // information.
2551
2552 if (text_section_sp && function_starts_data.GetByteSize()) {
2553 FunctionStarts::Entry function_start_entry;
2554 function_start_entry.data = false;
2555 lldb::offset_t function_start_offset = 0;
2556 function_start_entry.addr = text_section_sp->GetFileAddress();
2557 uint64_t delta;
2558 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) >
2559 0) {
2560 // Now append the current entry
2561 function_start_entry.addr += delta;
2562 if (is_arm) {
2563 if (function_start_entry.addr & 1) {
2564 function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK;
2565 function_start_entry.data = true;
2566 } else if (always_thumb) {
2567 function_start_entry.data = true;
2568 }
2569 }
2570 function_starts.Append(function_start_entry);
2571 }
2572 } else {
2573 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the
2574 // load command claiming an eh_frame but it doesn't actually have the
2575 // eh_frame content. And if we have a dSYM, we don't need to do any of
2576 // this fill-in-the-missing-symbols works anyway - the debug info should
2577 // give us all the functions in the module.
2578 if (text_section_sp.get() && eh_frame_section_sp.get() &&
2580 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp,
2583 eh_frame.GetFunctionAddressAndSizeVector(functions);
2584 addr_t text_base_addr = text_section_sp->GetFileAddress();
2585 size_t count = functions.GetSize();
2586 for (size_t i = 0; i < count; ++i) {
2588 functions.GetEntryAtIndex(i);
2589 if (func) {
2590 FunctionStarts::Entry function_start_entry;
2591 function_start_entry.addr = func->base - text_base_addr;
2592 if (is_arm) {
2593 if (function_start_entry.addr & 1) {
2594 function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK;
2595 function_start_entry.data = true;
2596 } else if (always_thumb) {
2597 function_start_entry.data = true;
2598 }
2599 }
2600 function_starts.Append(function_start_entry);
2601 }
2602 }
2603 }
2604 }
2605
2606 const size_t function_starts_count = function_starts.GetSize();
2607
2608 // For user process binaries (executables, dylibs, frameworks, bundles), if
2609 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're
2610 // going to assume the binary has been stripped. Don't allow assembly
2611 // language instruction emulation because we don't know proper function
2612 // start boundaries.
2613 //
2614 // For all other types of binaries (kernels, stand-alone bare board
2615 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame
2616 // sections - we should not make any assumptions about them based on that.
2617 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) {
2619 Log *unwind_or_symbol_log(GetLog(LLDBLog::Symbols | LLDBLog::Unwind));
2620
2621 if (unwind_or_symbol_log)
2622 module_sp->LogMessage(
2623 unwind_or_symbol_log,
2624 "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds");
2625 }
2626
2627 const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get()
2628 ? eh_frame_section_sp->GetID()
2629 : static_cast<user_id_t>(NO_SECT);
2630
2631 uint32_t N_SO_index = UINT32_MAX;
2632
2633 MachSymtabSectionInfo section_info(section_list);
2634 std::vector<uint32_t> N_FUN_indexes;
2635 std::vector<uint32_t> N_NSYM_indexes;
2636 std::vector<uint32_t> N_INCL_indexes;
2637 std::vector<uint32_t> N_BRAC_indexes;
2638 std::vector<uint32_t> N_COMM_indexes;
2639 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap;
2640 typedef llvm::DenseMap<uint32_t, uint32_t> NListIndexToSymbolIndexMap;
2641 typedef llvm::DenseMap<const char *, uint32_t> ConstNameToSymbolIndexMap;
2642 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx;
2643 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx;
2644 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx;
2645 // Any symbols that get merged into another will get an entry in this map
2646 // so we know
2647 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx;
2648 uint32_t nlist_idx = 0;
2649 Symbol *symbol_ptr = nullptr;
2650
2651 uint32_t sym_idx = 0;
2652 Symbol *sym = nullptr;
2653 size_t num_syms = 0;
2654 std::string memory_symbol_name;
2655 uint32_t unmapped_local_symbols_found = 0;
2656
2657 std::vector<TrieEntryWithOffset> reexport_trie_entries;
2658 std::vector<TrieEntryWithOffset> external_sym_trie_entries;
2659 std::set<lldb::addr_t> resolver_addresses;
2660
2661 const size_t dyld_trie_data_size = dyld_trie_data.GetByteSize();
2662 if (dyld_trie_data_size > 0) {
2663 LLDB_LOG(log, "Parsing {0} bytes of dyld trie data", dyld_trie_data_size);
2664 SectionSP text_segment_sp =
2666 lldb::addr_t text_segment_file_addr = LLDB_INVALID_ADDRESS;
2667 if (text_segment_sp)
2668 text_segment_file_addr = text_segment_sp->GetFileAddress();
2669 std::vector<llvm::StringRef> nameSlices;
2670 ParseTrieEntries(dyld_trie_data, 0, is_arm, text_segment_file_addr,
2671 nameSlices, resolver_addresses, reexport_trie_entries,
2672 external_sym_trie_entries);
2673 }
2674
2675 typedef std::set<ConstString> IndirectSymbols;
2676 IndirectSymbols indirect_symbol_names;
2677
2678#if TARGET_OS_IPHONE
2679
2680 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been
2681 // optimized by moving LOCAL symbols out of the memory mapped portion of
2682 // the DSC. The symbol information has all been retained, but it isn't
2683 // available in the normal nlist data. However, there *are* duplicate
2684 // entries of *some*
2685 // LOCAL symbols in the normal nlist data. To handle this situation
2686 // correctly, we must first attempt
2687 // to parse any DSC unmapped symbol information. If we find any, we set a
2688 // flag that tells the normal nlist parser to ignore all LOCAL symbols.
2689
2690 if (IsSharedCacheBinary()) {
2691 // Before we can start mapping the DSC, we need to make certain the
2692 // target process is actually using the cache we can find.
2693
2694 // Next we need to determine the correct path for the dyld shared cache.
2695
2696 ArchSpec header_arch = GetArchitecture();
2697
2698 UUID dsc_uuid;
2699 UUID process_shared_cache_uuid;
2700 addr_t process_shared_cache_base_addr;
2701
2702 if (process) {
2703 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr,
2704 process_shared_cache_uuid);
2705 }
2706
2707 __block bool found_image = false;
2708 __block void *nlist_buffer = nullptr;
2709 __block unsigned nlist_count = 0;
2710 __block char *string_table = nullptr;
2711 __block vm_offset_t vm_nlist_memory = 0;
2712 __block mach_msg_type_number_t vm_nlist_bytes_read = 0;
2713 __block vm_offset_t vm_string_memory = 0;
2714 __block mach_msg_type_number_t vm_string_bytes_read = 0;
2715
2716 auto _ = llvm::make_scope_exit(^{
2717 if (vm_nlist_memory)
2718 vm_deallocate(mach_task_self(), vm_nlist_memory, vm_nlist_bytes_read);
2719 if (vm_string_memory)
2720 vm_deallocate(mach_task_self(), vm_string_memory, vm_string_bytes_read);
2721 });
2722
2723 typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
2724 typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
2725 UndefinedNameToDescMap undefined_name_to_desc;
2726 SymbolIndexToName reexport_shlib_needs_fixup;
2727
2728 dyld_for_each_installed_shared_cache(^(dyld_shared_cache_t shared_cache) {
2729 uuid_t cache_uuid;
2730 dyld_shared_cache_copy_uuid(shared_cache, &cache_uuid);
2731 if (found_image)
2732 return;
2733
2734 if (process_shared_cache_uuid.IsValid() &&
2735 process_shared_cache_uuid != UUID::fromData(&cache_uuid, 16))
2736 return;
2737
2738 dyld_shared_cache_for_each_image(shared_cache, ^(dyld_image_t image) {
2739 uuid_t dsc_image_uuid;
2740 if (found_image)
2741 return;
2742
2743 dyld_image_copy_uuid(image, &dsc_image_uuid);
2744 if (image_uuid != UUID::fromData(dsc_image_uuid, 16))
2745 return;
2746
2747 found_image = true;
2748
2749 // Compute the size of the string table. We need to ask dyld for a
2750 // new SPI to avoid this step.
2751 dyld_image_local_nlist_content_4Symbolication(
2752 image, ^(const void *nlistStart, uint64_t nlistCount,
2753 const char *stringTable) {
2754 if (!nlistStart || !nlistCount)
2755 return;
2756
2757 // The buffers passed here are valid only inside the block.
2758 // Use vm_read to make a cheap copy of them available for our
2759 // processing later.
2760 kern_return_t ret =
2761 vm_read(mach_task_self(), (vm_address_t)nlistStart,
2762 nlist_byte_size * nlistCount, &vm_nlist_memory,
2763 &vm_nlist_bytes_read);
2764 if (ret != KERN_SUCCESS)
2765 return;
2766 assert(vm_nlist_bytes_read == nlist_byte_size * nlistCount);
2767
2768 // We don't know the size of the string table. It's cheaper
2769 // to map the whole VM region than to determine the size by
2770 // parsing all the nlist entries.
2771 vm_address_t string_address = (vm_address_t)stringTable;
2772 vm_size_t region_size;
2773 mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
2774 vm_region_basic_info_data_t info;
2775 memory_object_name_t object;
2776 ret = vm_region_64(mach_task_self(), &string_address,
2777 &region_size, VM_REGION_BASIC_INFO_64,
2778 (vm_region_info_t)&info, &info_count, &object);
2779 if (ret != KERN_SUCCESS)
2780 return;
2781
2782 ret = vm_read(mach_task_self(), (vm_address_t)stringTable,
2783 region_size -
2784 ((vm_address_t)stringTable - string_address),
2785 &vm_string_memory, &vm_string_bytes_read);
2786 if (ret != KERN_SUCCESS)
2787 return;
2788
2789 nlist_buffer = (void *)vm_nlist_memory;
2790 string_table = (char *)vm_string_memory;
2791 nlist_count = nlistCount;
2792 });
2793 });
2794 });
2795 if (nlist_buffer) {
2796 DataExtractor dsc_local_symbols_data(nlist_buffer,
2797 nlist_count * nlist_byte_size,
2798 byte_order, addr_byte_size);
2799 unmapped_local_symbols_found = nlist_count;
2800
2801 // The normal nlist code cannot correctly size the Symbols
2802 // array, we need to allocate it here.
2803 sym = symtab.Resize(
2804 symtab_load_command.nsyms + m_dysymtab.nindirectsyms +
2805 unmapped_local_symbols_found - m_dysymtab.nlocalsym);
2806 num_syms = symtab.GetNumSymbols();
2807
2808 lldb::offset_t nlist_data_offset = 0;
2809
2810 for (uint32_t nlist_index = 0;
2811 nlist_index < nlist_count;
2812 nlist_index++) {
2813 /////////////////////////////
2814 {
2815 std::optional<struct nlist_64> nlist_maybe =
2816 ParseNList(dsc_local_symbols_data, nlist_data_offset,
2817 nlist_byte_size);
2818 if (!nlist_maybe)
2819 break;
2820 struct nlist_64 nlist = *nlist_maybe;
2821
2823 const char *symbol_name = string_table + nlist.n_strx;
2824
2825 if (symbol_name == NULL) {
2826 // No symbol should be NULL, even the symbols with no
2827 // string values should have an offset zero which
2828 // points to an empty C-string
2829 Debugger::ReportError(llvm::formatv(
2830 "DSC unmapped local symbol[{0}] has invalid "
2831 "string table offset {1:x} in {2}, ignoring symbol",
2832 nlist_index, nlist.n_strx,
2833 module_sp->GetFileSpec().GetPath());
2834 continue;
2835 }
2836 if (symbol_name[0] == '\0')
2837 symbol_name = NULL;
2838
2839 const char *symbol_name_non_abi_mangled = NULL;
2840
2841 SectionSP symbol_section;
2842 uint32_t symbol_byte_size = 0;
2843 bool add_nlist = true;
2844 bool is_debug = ((nlist.n_type & N_STAB) != 0);
2845 bool demangled_is_synthesized = false;
2846 bool is_gsym = false;
2847 bool set_value = true;
2848
2849 assert(sym_idx < num_syms);
2850
2851 sym[sym_idx].SetDebug(is_debug);
2852
2853 if (is_debug) {
2854 switch (nlist.n_type) {
2855 case N_GSYM:
2856 // global symbol: name,,NO_SECT,type,0
2857 // Sometimes the N_GSYM value contains the address.
2858
2859 // FIXME: In the .o files, we have a GSYM and a debug
2860 // symbol for all the ObjC data. They
2861 // have the same address, but we want to ensure that
2862 // we always find only the real symbol, 'cause we
2863 // don't currently correctly attribute the
2864 // GSYM one to the ObjCClass/Ivar/MetaClass
2865 // symbol type. This is a temporary hack to make
2866 // sure the ObjectiveC symbols get treated correctly.
2867 // To do this right, we should coalesce all the GSYM
2868 // & global symbols that have the same address.
2869
2870 is_gsym = true;
2871 sym[sym_idx].SetExternal(true);
2872
2873 if (symbol_name && symbol_name[0] == '_' &&
2874 symbol_name[1] == 'O') {
2875 llvm::StringRef symbol_name_ref(symbol_name);
2876 if (symbol_name_ref.starts_with(
2877 g_objc_v2_prefix_class)) {
2878 symbol_name_non_abi_mangled = symbol_name + 1;
2879 symbol_name =
2880 symbol_name + g_objc_v2_prefix_class.size();
2881 type = eSymbolTypeObjCClass;
2882 demangled_is_synthesized = true;
2883
2884 } else if (symbol_name_ref.starts_with(
2885 g_objc_v2_prefix_metaclass)) {
2886 symbol_name_non_abi_mangled = symbol_name + 1;
2887 symbol_name =
2888 symbol_name + g_objc_v2_prefix_metaclass.size();
2890 demangled_is_synthesized = true;
2891 } else if (symbol_name_ref.starts_with(
2892 g_objc_v2_prefix_ivar)) {
2893 symbol_name_non_abi_mangled = symbol_name + 1;
2894 symbol_name =
2895 symbol_name + g_objc_v2_prefix_ivar.size();
2896 type = eSymbolTypeObjCIVar;
2897 demangled_is_synthesized = true;
2898 }
2899 } else {
2900 if (nlist.n_value != 0)
2901 symbol_section = section_info.GetSection(
2902 nlist.n_sect, nlist.n_value);
2903 type = eSymbolTypeData;
2904 }
2905 break;
2906
2907 case N_FNAME:
2908 // procedure name (f77 kludge): name,,NO_SECT,0,0
2909 type = eSymbolTypeCompiler;
2910 break;
2911
2912 case N_FUN:
2913 // procedure: name,,n_sect,linenumber,address
2914 if (symbol_name) {
2915 type = eSymbolTypeCode;
2916 symbol_section = section_info.GetSection(
2917 nlist.n_sect, nlist.n_value);
2918
2919 N_FUN_addr_to_sym_idx.insert(
2920 std::make_pair(nlist.n_value, sym_idx));
2921 // We use the current number of symbols in the
2922 // symbol table in lieu of using nlist_idx in case
2923 // we ever start trimming entries out
2924 N_FUN_indexes.push_back(sym_idx);
2925 } else {
2926 type = eSymbolTypeCompiler;
2927
2928 if (!N_FUN_indexes.empty()) {
2929 // Copy the size of the function into the
2930 // original
2931 // STAB entry so we don't have
2932 // to hunt for it later
2933 symtab.SymbolAtIndex(N_FUN_indexes.back())
2934 ->SetByteSize(nlist.n_value);
2935 N_FUN_indexes.pop_back();
2936 // We don't really need the end function STAB as
2937 // it contains the size which we already placed
2938 // with the original symbol, so don't add it if
2939 // we want a minimal symbol table
2940 add_nlist = false;
2941 }
2942 }
2943 break;
2944
2945 case N_STSYM:
2946 // static symbol: name,,n_sect,type,address
2947 N_STSYM_addr_to_sym_idx.insert(
2948 std::make_pair(nlist.n_value, sym_idx));
2949 symbol_section = section_info.GetSection(nlist.n_sect,
2950 nlist.n_value);
2951 if (symbol_name && symbol_name[0]) {
2953 symbol_name + 1, eSymbolTypeData);
2954 }
2955 break;
2956
2957 case N_LCSYM:
2958 // .lcomm symbol: name,,n_sect,type,address
2959 symbol_section = section_info.GetSection(nlist.n_sect,
2960 nlist.n_value);
2962 break;
2963
2964 case N_BNSYM:
2965 // We use the current number of symbols in the symbol
2966 // table in lieu of using nlist_idx in case we ever
2967 // start trimming entries out Skip these if we want
2968 // minimal symbol tables
2969 add_nlist = false;
2970 break;
2971
2972 case N_ENSYM:
2973 // Set the size of the N_BNSYM to the terminating
2974 // index of this N_ENSYM so that we can always skip
2975 // the entire symbol if we need to navigate more
2976 // quickly at the source level when parsing STABS
2977 // Skip these if we want minimal symbol tables
2978 add_nlist = false;
2979 break;
2980
2981 case N_OPT:
2982 // emitted with gcc2_compiled and in gcc source
2983 type = eSymbolTypeCompiler;
2984 break;
2985
2986 case N_RSYM:
2987 // register sym: name,,NO_SECT,type,register
2988 type = eSymbolTypeVariable;
2989 break;
2990
2991 case N_SLINE:
2992 // src line: 0,,n_sect,linenumber,address
2993 symbol_section = section_info.GetSection(nlist.n_sect,
2994 nlist.n_value);
2995 type = eSymbolTypeLineEntry;
2996 break;
2997
2998 case N_SSYM:
2999 // structure elt: name,,NO_SECT,type,struct_offset
3001 break;
3002
3003 case N_SO:
3004 // source file name
3005 type = eSymbolTypeSourceFile;
3006 if (symbol_name == NULL) {
3007 add_nlist = false;
3008 if (N_SO_index != UINT32_MAX) {
3009 // Set the size of the N_SO to the terminating
3010 // index of this N_SO so that we can always skip
3011 // the entire N_SO if we need to navigate more
3012 // quickly at the source level when parsing STABS
3013 symbol_ptr = symtab.SymbolAtIndex(N_SO_index);
3014 symbol_ptr->SetByteSize(sym_idx);
3015 symbol_ptr->SetSizeIsSibling(true);
3016 }
3017 N_NSYM_indexes.clear();
3018 N_INCL_indexes.clear();
3019 N_BRAC_indexes.clear();
3020 N_COMM_indexes.clear();
3021 N_FUN_indexes.clear();
3022 N_SO_index = UINT32_MAX;
3023 } else {
3024 // We use the current number of symbols in the
3025 // symbol table in lieu of using nlist_idx in case
3026 // we ever start trimming entries out
3027 const bool N_SO_has_full_path = symbol_name[0] == '/';
3028 if (N_SO_has_full_path) {
3029 if ((N_SO_index == sym_idx - 1) &&
3030 ((sym_idx - 1) < num_syms)) {
3031 // We have two consecutive N_SO entries where
3032 // the first contains a directory and the
3033 // second contains a full path.
3034 sym[sym_idx - 1].GetMangled().SetValue(
3035 ConstString(symbol_name));
3036 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3037 add_nlist = false;
3038 } else {
3039 // This is the first entry in a N_SO that
3040 // contains a directory or
3041 // a full path to the source file
3042 N_SO_index = sym_idx;
3043 }
3044 } else if ((N_SO_index == sym_idx - 1) &&
3045 ((sym_idx - 1) < num_syms)) {
3046 // This is usually the second N_SO entry that
3047 // contains just the filename, so here we combine
3048 // it with the first one if we are minimizing the
3049 // symbol table
3050 const char *so_path = sym[sym_idx - 1]
3051 .GetMangled()
3053 .AsCString();
3054 if (so_path && so_path[0]) {
3055 std::string full_so_path(so_path);
3056 const size_t double_slash_pos =
3057 full_so_path.find("//");
3058 if (double_slash_pos != std::string::npos) {
3059 // The linker has been generating bad N_SO
3060 // entries with doubled up paths
3061 // in the format "%s%s" where the first
3062 // string in the DW_AT_comp_dir, and the
3063 // second is the directory for the source
3064 // file so you end up with a path that looks
3065 // like "/tmp/src//tmp/src/"
3066 FileSpec so_dir(so_path);
3067 if (!FileSystem::Instance().Exists(so_dir)) {
3068 so_dir.SetFile(
3069 &full_so_path[double_slash_pos + 1],
3070 FileSpec::Style::native);
3071 if (FileSystem::Instance().Exists(so_dir)) {
3072 // Trim off the incorrect path
3073 full_so_path.erase(0, double_slash_pos + 1);
3074 }
3075 }
3076 }
3077 if (*full_so_path.rbegin() != '/')
3078 full_so_path += '/';
3079 full_so_path += symbol_name;
3080 sym[sym_idx - 1].GetMangled().SetValue(
3081 ConstString(full_so_path.c_str()));
3082 add_nlist = false;
3083 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3084 }
3085 } else {
3086 // This could be a relative path to a N_SO
3087 N_SO_index = sym_idx;
3088 }
3089 }
3090 break;
3091
3092 case N_OSO:
3093 // object file name: name,,0,0,st_mtime
3094 type = eSymbolTypeObjectFile;
3095 break;
3096
3097 case N_LSYM:
3098 // local sym: name,,NO_SECT,type,offset
3099 type = eSymbolTypeLocal;
3100 break;
3101
3102 // INCL scopes
3103 case N_BINCL:
3104 // include file beginning: name,,NO_SECT,0,sum We use
3105 // the current number of symbols in the symbol table
3106 // in lieu of using nlist_idx in case we ever start
3107 // trimming entries out
3108 N_INCL_indexes.push_back(sym_idx);
3109 type = eSymbolTypeScopeBegin;
3110 break;
3111
3112 case N_EINCL:
3113 // include file end: name,,NO_SECT,0,0
3114 // Set the size of the N_BINCL to the terminating
3115 // index of this N_EINCL so that we can always skip
3116 // the entire symbol if we need to navigate more
3117 // quickly at the source level when parsing STABS
3118 if (!N_INCL_indexes.empty()) {
3119 symbol_ptr =
3120 symtab.SymbolAtIndex(N_INCL_indexes.back());
3121 symbol_ptr->SetByteSize(sym_idx + 1);
3122 symbol_ptr->SetSizeIsSibling(true);
3123 N_INCL_indexes.pop_back();
3124 }
3125 type = eSymbolTypeScopeEnd;
3126 break;
3127
3128 case N_SOL:
3129 // #included file name: name,,n_sect,0,address
3130 type = eSymbolTypeHeaderFile;
3131
3132 // We currently don't use the header files on darwin
3133 add_nlist = false;
3134 break;
3135
3136 case N_PARAMS:
3137 // compiler parameters: name,,NO_SECT,0,0
3138 type = eSymbolTypeCompiler;
3139 break;
3140
3141 case N_VERSION:
3142 // compiler version: name,,NO_SECT,0,0
3143 type = eSymbolTypeCompiler;
3144 break;
3145
3146 case N_OLEVEL:
3147 // compiler -O level: name,,NO_SECT,0,0
3148 type = eSymbolTypeCompiler;
3149 break;
3150
3151 case N_PSYM:
3152 // parameter: name,,NO_SECT,type,offset
3153 type = eSymbolTypeVariable;
3154 break;
3155
3156 case N_ENTRY:
3157 // alternate entry: name,,n_sect,linenumber,address
3158 symbol_section = section_info.GetSection(nlist.n_sect,
3159 nlist.n_value);
3160 type = eSymbolTypeLineEntry;
3161 break;
3162
3163 // Left and Right Braces
3164 case N_LBRAC:
3165 // left bracket: 0,,NO_SECT,nesting level,address We
3166 // use the current number of symbols in the symbol
3167 // table in lieu of using nlist_idx in case we ever
3168 // start trimming entries out
3169 symbol_section = section_info.GetSection(nlist.n_sect,
3170 nlist.n_value);
3171 N_BRAC_indexes.push_back(sym_idx);
3172 type = eSymbolTypeScopeBegin;
3173 break;
3174
3175 case N_RBRAC:
3176 // right bracket: 0,,NO_SECT,nesting level,address
3177 // Set the size of the N_LBRAC to the terminating
3178 // index of this N_RBRAC so that we can always skip
3179 // the entire symbol if we need to navigate more
3180 // quickly at the source level when parsing STABS
3181 symbol_section = section_info.GetSection(nlist.n_sect,
3182 nlist.n_value);
3183 if (!N_BRAC_indexes.empty()) {
3184 symbol_ptr =
3185 symtab.SymbolAtIndex(N_BRAC_indexes.back());
3186 symbol_ptr->SetByteSize(sym_idx + 1);
3187 symbol_ptr->SetSizeIsSibling(true);
3188 N_BRAC_indexes.pop_back();
3189 }
3190 type = eSymbolTypeScopeEnd;
3191 break;
3192
3193 case N_EXCL:
3194 // deleted include file: name,,NO_SECT,0,sum
3195 type = eSymbolTypeHeaderFile;
3196 break;
3197
3198 // COMM scopes
3199 case N_BCOMM:
3200 // begin common: name,,NO_SECT,0,0
3201 // We use the current number of symbols in the symbol
3202 // table in lieu of using nlist_idx in case we ever
3203 // start trimming entries out
3204 type = eSymbolTypeScopeBegin;
3205 N_COMM_indexes.push_back(sym_idx);
3206 break;
3207
3208 case N_ECOML:
3209 // end common (local name): 0,,n_sect,0,address
3210 symbol_section = section_info.GetSection(nlist.n_sect,
3211 nlist.n_value);
3212 // Fall through
3213
3214 case N_ECOMM:
3215 // end common: name,,n_sect,0,0
3216 // Set the size of the N_BCOMM to the terminating
3217 // index of this N_ECOMM/N_ECOML so that we can
3218 // always skip the entire symbol if we need to
3219 // navigate more quickly at the source level when
3220 // parsing STABS
3221 if (!N_COMM_indexes.empty()) {
3222 symbol_ptr =
3223 symtab.SymbolAtIndex(N_COMM_indexes.back());
3224 symbol_ptr->SetByteSize(sym_idx + 1);
3225 symbol_ptr->SetSizeIsSibling(true);
3226 N_COMM_indexes.pop_back();
3227 }
3228 type = eSymbolTypeScopeEnd;
3229 break;
3230
3231 case N_LENG:
3232 // second stab entry with length information
3233 type = eSymbolTypeAdditional;
3234 break;
3235
3236 default:
3237 break;
3238 }
3239 } else {
3240 // uint8_t n_pext = N_PEXT & nlist.n_type;
3241 uint8_t n_type = N_TYPE & nlist.n_type;
3242 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
3243
3244 switch (n_type) {
3245 case N_INDR: {
3246 const char *reexport_name_cstr =
3247 strtab_data.PeekCStr(nlist.n_value);
3248 if (reexport_name_cstr && reexport_name_cstr[0]) {
3249 type = eSymbolTypeReExported;
3250 ConstString reexport_name(
3251 reexport_name_cstr +
3252 ((reexport_name_cstr[0] == '_') ? 1 : 0));
3253 sym[sym_idx].SetReExportedSymbolName(reexport_name);
3254 set_value = false;
3255 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
3256 indirect_symbol_names.insert(ConstString(
3257 symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
3258 } else
3259 type = eSymbolTypeUndefined;
3260 } break;
3261
3262 case N_UNDF:
3263 if (symbol_name && symbol_name[0]) {
3264 ConstString undefined_name(
3265 symbol_name + ((symbol_name[0] == '_') ? 1 : 0));
3266 undefined_name_to_desc[undefined_name] = nlist.n_desc;
3267 }
3268 // Fall through
3269 case N_PBUD:
3270 type = eSymbolTypeUndefined;
3271 break;
3272
3273 case N_ABS:
3274 type = eSymbolTypeAbsolute;
3275 break;
3276
3277 case N_SECT: {
3278 symbol_section = section_info.GetSection(nlist.n_sect,
3279 nlist.n_value);
3280
3281 if (symbol_section == NULL) {
3282 // TODO: warn about this?
3283 add_nlist = false;
3284 break;
3285 }
3286
3287 if (TEXT_eh_frame_sectID == nlist.n_sect) {
3288 type = eSymbolTypeException;
3289 } else {
3290 uint32_t section_type =
3291 symbol_section->Get() & SECTION_TYPE;
3292
3293 switch (section_type) {
3294 case S_CSTRING_LITERALS:
3295 type = eSymbolTypeData;
3296 break; // section with only literal C strings
3297 case S_4BYTE_LITERALS:
3298 type = eSymbolTypeData;
3299 break; // section with only 4 byte literals
3300 case S_8BYTE_LITERALS:
3301 type = eSymbolTypeData;
3302 break; // section with only 8 byte literals
3303 case S_LITERAL_POINTERS:
3304 type = eSymbolTypeTrampoline;
3305 break; // section with only pointers to literals
3306 case S_NON_LAZY_SYMBOL_POINTERS:
3307 type = eSymbolTypeTrampoline;
3308 break; // section with only non-lazy symbol
3309 // pointers
3310 case S_LAZY_SYMBOL_POINTERS:
3311 type = eSymbolTypeTrampoline;
3312 break; // section with only lazy symbol pointers
3313 case S_SYMBOL_STUBS:
3314 type = eSymbolTypeTrampoline;
3315 break; // section with only symbol stubs, byte
3316 // size of stub in the reserved2 field
3317 case S_MOD_INIT_FUNC_POINTERS:
3318 type = eSymbolTypeCode;
3319 break; // section with only function pointers for
3320 // initialization
3321 case S_MOD_TERM_FUNC_POINTERS:
3322 type = eSymbolTypeCode;
3323 break; // section with only function pointers for
3324 // termination
3325 case S_INTERPOSING:
3326 type = eSymbolTypeTrampoline;
3327 break; // section with only pairs of function
3328 // pointers for interposing
3329 case S_16BYTE_LITERALS:
3330 type = eSymbolTypeData;
3331 break; // section with only 16 byte literals
3332 case S_DTRACE_DOF:
3334 break;
3335 case S_LAZY_DYLIB_SYMBOL_POINTERS:
3336 type = eSymbolTypeTrampoline;
3337 break;
3338 default:
3339 switch (symbol_section->GetType()) {
3341 type = eSymbolTypeCode;
3342 break;
3343 case eSectionTypeData:
3344 case eSectionTypeDataCString: // Inlined C string
3345 // data
3346 case eSectionTypeDataCStringPointers: // Pointers
3347 // to C
3348 // string
3349 // data
3350 case eSectionTypeDataSymbolAddress: // Address of
3351 // a symbol in
3352 // the symbol
3353 // table
3354 case eSectionTypeData4:
3355 case eSectionTypeData8:
3356 case eSectionTypeData16:
3357 type = eSymbolTypeData;
3358 break;
3359 default:
3360 break;
3361 }
3362 break;
3363 }
3364
3365 if (type == eSymbolTypeInvalid) {
3366 const char *symbol_sect_name =
3367 symbol_section->GetName().AsCString();
3368 if (symbol_section->IsDescendant(
3369 text_section_sp.get())) {
3370 if (symbol_section->IsClear(
3371 S_ATTR_PURE_INSTRUCTIONS |
3372 S_ATTR_SELF_MODIFYING_CODE |
3373 S_ATTR_SOME_INSTRUCTIONS))
3374 type = eSymbolTypeData;
3375 else
3376 type = eSymbolTypeCode;
3377 } else if (symbol_section->IsDescendant(
3378 data_section_sp.get()) ||
3379 symbol_section->IsDescendant(
3380 data_dirty_section_sp.get()) ||
3381 symbol_section->IsDescendant(
3382 data_const_section_sp.get())) {
3383 if (symbol_sect_name &&
3384 ::strstr(symbol_sect_name, "__objc") ==
3385 symbol_sect_name) {
3386 type = eSymbolTypeRuntime;
3387
3388 if (symbol_name) {
3389 llvm::StringRef symbol_name_ref(symbol_name);
3390 if (symbol_name_ref.starts_with("_OBJC_")) {
3391 llvm::StringRef
3392 g_objc_v2_prefix_class(
3393 "_OBJC_CLASS_$_");
3394 llvm::StringRef
3395 g_objc_v2_prefix_metaclass(
3396 "_OBJC_METACLASS_$_");
3397 llvm::StringRef
3398 g_objc_v2_prefix_ivar("_OBJC_IVAR_$_");
3399 if (symbol_name_ref.starts_with(
3400 g_objc_v2_prefix_class)) {
3401 symbol_name_non_abi_mangled =
3402 symbol_name + 1;
3403 symbol_name =
3404 symbol_name +
3405 g_objc_v2_prefix_class.size();
3406 type = eSymbolTypeObjCClass;
3407 demangled_is_synthesized = true;
3408 } else if (
3409 symbol_name_ref.starts_with(
3410 g_objc_v2_prefix_metaclass)) {
3411 symbol_name_non_abi_mangled =
3412 symbol_name + 1;
3413 symbol_name =
3414 symbol_name +
3415 g_objc_v2_prefix_metaclass.size();
3417 demangled_is_synthesized = true;
3418 } else if (symbol_name_ref.starts_with(
3419 g_objc_v2_prefix_ivar)) {
3420 symbol_name_non_abi_mangled =
3421 symbol_name + 1;
3422 symbol_name =
3423 symbol_name +
3424 g_objc_v2_prefix_ivar.size();
3425 type = eSymbolTypeObjCIVar;
3426 demangled_is_synthesized = true;
3427 }
3428 }
3429 }
3430 } else if (symbol_sect_name &&
3431 ::strstr(symbol_sect_name,
3432 "__gcc_except_tab") ==
3433 symbol_sect_name) {
3434 type = eSymbolTypeException;
3435 } else {
3436 type = eSymbolTypeData;
3437 }
3438 } else if (symbol_sect_name &&
3439 ::strstr(symbol_sect_name, "__IMPORT") ==
3440 symbol_sect_name) {
3441 type = eSymbolTypeTrampoline;
3442 } else if (symbol_section->IsDescendant(
3443 objc_section_sp.get())) {
3444 type = eSymbolTypeRuntime;
3445 if (symbol_name && symbol_name[0] == '.') {
3446 llvm::StringRef symbol_name_ref(symbol_name);
3447 llvm::StringRef
3448 g_objc_v1_prefix_class(".objc_class_name_");
3449 if (symbol_name_ref.starts_with(
3450 g_objc_v1_prefix_class)) {
3451 symbol_name_non_abi_mangled = symbol_name;
3452 symbol_name = symbol_name +
3453 g_objc_v1_prefix_class.size();
3454 type = eSymbolTypeObjCClass;
3455 demangled_is_synthesized = true;
3456 }
3457 }
3458 }
3459 }
3460 }
3461 } break;
3462 }
3463 }
3464
3465 if (add_nlist) {
3466 uint64_t symbol_value = nlist.n_value;
3467 if (symbol_name_non_abi_mangled) {
3468 sym[sym_idx].GetMangled().SetMangledName(
3469 ConstString(symbol_name_non_abi_mangled));
3470 sym[sym_idx].GetMangled().SetDemangledName(
3471 ConstString(symbol_name));
3472 } else {
3473 if (symbol_name && symbol_name[0] == '_') {
3474 symbol_name++; // Skip the leading underscore
3475 }
3476
3477 if (symbol_name) {
3478 ConstString const_symbol_name(symbol_name);
3479 sym[sym_idx].GetMangled().SetValue(const_symbol_name);
3480 if (is_gsym && is_debug) {
3481 const char *gsym_name =
3482 sym[sym_idx]
3483 .GetMangled()
3485 .GetCString();
3486 if (gsym_name)
3487 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
3488 }
3489 }
3490 }
3491 if (symbol_section) {
3492 const addr_t section_file_addr =
3493 symbol_section->GetFileAddress();
3494 if (symbol_byte_size == 0 &&
3495 function_starts_count > 0) {
3496 addr_t symbol_lookup_file_addr = nlist.n_value;
3497 // Do an exact address match for non-ARM addresses,
3498 // else get the closest since the symbol might be a
3499 // thumb symbol which has an address with bit zero
3500 // set
3501 FunctionStarts::Entry *func_start_entry =
3502 function_starts.FindEntry(symbol_lookup_file_addr,
3503 !is_arm);
3504 if (is_arm && func_start_entry) {
3505 // Verify that the function start address is the
3506 // symbol address (ARM) or the symbol address + 1
3507 // (thumb)
3508 if (func_start_entry->addr !=
3509 symbol_lookup_file_addr &&
3510 func_start_entry->addr !=
3511 (symbol_lookup_file_addr + 1)) {
3512 // Not the right entry, NULL it out...
3513 func_start_entry = NULL;
3514 }
3515 }
3516 if (func_start_entry) {
3517 func_start_entry->data = true;
3518
3519 addr_t symbol_file_addr = func_start_entry->addr;
3520 uint32_t symbol_flags = 0;
3521 if (is_arm) {
3522 if (symbol_file_addr & 1)
3523 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
3524 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3525 }
3526
3527 const FunctionStarts::Entry *next_func_start_entry =
3528 function_starts.FindNextEntry(func_start_entry);
3529 const addr_t section_end_file_addr =
3530 section_file_addr +
3531 symbol_section->GetByteSize();
3532 if (next_func_start_entry) {
3533 addr_t next_symbol_file_addr =
3534 next_func_start_entry->addr;
3535 // Be sure the clear the Thumb address bit when
3536 // we calculate the size from the current and
3537 // next address
3538 if (is_arm)
3539 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
3540 symbol_byte_size = std::min<lldb::addr_t>(
3541 next_symbol_file_addr - symbol_file_addr,
3542 section_end_file_addr - symbol_file_addr);
3543 } else {
3544 symbol_byte_size =
3545 section_end_file_addr - symbol_file_addr;
3546 }
3547 }
3548 }
3549 symbol_value -= section_file_addr;
3550 }
3551
3552 if (is_debug == false) {
3553 if (type == eSymbolTypeCode) {
3554 // See if we can find a N_FUN entry for any code
3555 // symbols. If we do find a match, and the name
3556 // matches, then we can merge the two into just the
3557 // function symbol to avoid duplicate entries in
3558 // the symbol table
3559 auto range =
3560 N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
3561 if (range.first != range.second) {
3562 bool found_it = false;
3563 for (auto pos = range.first; pos != range.second;
3564 ++pos) {
3565 if (sym[sym_idx].GetMangled().GetName(
3567 sym[pos->second].GetMangled().GetName(
3569 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3570 // We just need the flags from the linker
3571 // symbol, so put these flags
3572 // into the N_FUN flags to avoid duplicate
3573 // symbols in the symbol table
3574 sym[pos->second].SetExternal(
3575 sym[sym_idx].IsExternal());
3576 sym[pos->second].SetFlags(nlist.n_type << 16 |
3577 nlist.n_desc);
3578 if (resolver_addresses.find(nlist.n_value) !=
3579 resolver_addresses.end())
3580 sym[pos->second].SetType(eSymbolTypeResolver);
3581 sym[sym_idx].Clear();
3582 found_it = true;
3583 break;
3584 }
3585 }
3586 if (found_it)
3587 continue;
3588 } else {
3589 if (resolver_addresses.find(nlist.n_value) !=
3590 resolver_addresses.end())
3591 type = eSymbolTypeResolver;
3592 }
3593 } else if (type == eSymbolTypeData ||
3594 type == eSymbolTypeObjCClass ||
3595 type == eSymbolTypeObjCMetaClass ||
3596 type == eSymbolTypeObjCIVar) {
3597 // See if we can find a N_STSYM entry for any data
3598 // symbols. If we do find a match, and the name
3599 // matches, then we can merge the two into just the
3600 // Static symbol to avoid duplicate entries in the
3601 // symbol table
3602 auto range = N_STSYM_addr_to_sym_idx.equal_range(
3603 nlist.n_value);
3604 if (range.first != range.second) {
3605 bool found_it = false;
3606 for (auto pos = range.first; pos != range.second;
3607 ++pos) {
3608 if (sym[sym_idx].GetMangled().GetName(
3610 sym[pos->second].GetMangled().GetName(
3612 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
3613 // We just need the flags from the linker
3614 // symbol, so put these flags
3615 // into the N_STSYM flags to avoid duplicate
3616 // symbols in the symbol table
3617 sym[pos->second].SetExternal(
3618 sym[sym_idx].IsExternal());
3619 sym[pos->second].SetFlags(nlist.n_type << 16 |
3620 nlist.n_desc);
3621 sym[sym_idx].Clear();
3622 found_it = true;
3623 break;
3624 }
3625 }
3626 if (found_it)
3627 continue;
3628 } else {
3629 const char *gsym_name =
3630 sym[sym_idx]
3631 .GetMangled()
3633 .GetCString();
3634 if (gsym_name) {
3635 // Combine N_GSYM stab entries with the non
3636 // stab symbol
3637 ConstNameToSymbolIndexMap::const_iterator pos =
3638 N_GSYM_name_to_sym_idx.find(gsym_name);
3639 if (pos != N_GSYM_name_to_sym_idx.end()) {
3640 const uint32_t GSYM_sym_idx = pos->second;
3641 m_nlist_idx_to_sym_idx[nlist_idx] =
3642 GSYM_sym_idx;
3643 // Copy the address, because often the N_GSYM
3644 // address has an invalid address of zero
3645 // when the global is a common symbol
3646 sym[GSYM_sym_idx].GetAddressRef().SetSection(
3647 symbol_section);
3648 sym[GSYM_sym_idx].GetAddressRef().SetOffset(
3649 symbol_value);
3650 add_symbol_addr(sym[GSYM_sym_idx]
3651 .GetAddress()
3652 .GetFileAddress());
3653 // We just need the flags from the linker
3654 // symbol, so put these flags
3655 // into the N_GSYM flags to avoid duplicate
3656 // symbols in the symbol table
3657 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 |
3658 nlist.n_desc);
3659 sym[sym_idx].Clear();
3660 continue;
3661 }
3662 }
3663 }
3664 }
3665 }
3666
3667 sym[sym_idx].SetID(nlist_idx);
3668 sym[sym_idx].SetType(type);
3669 if (set_value) {
3670 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
3671 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
3672 add_symbol_addr(
3673 sym[sym_idx].GetAddress().GetFileAddress());
3674 }
3675 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
3676
3677 if (symbol_byte_size > 0)
3678 sym[sym_idx].SetByteSize(symbol_byte_size);
3679
3680 if (demangled_is_synthesized)
3681 sym[sym_idx].SetDemangledNameIsSynthesized(true);
3682 ++sym_idx;
3683 } else {
3684 sym[sym_idx].Clear();
3685 }
3686 }
3687 /////////////////////////////
3688 }
3689 }
3690
3691 for (const auto &pos : reexport_shlib_needs_fixup) {
3692 const auto undef_pos = undefined_name_to_desc.find(pos.second);
3693 if (undef_pos != undefined_name_to_desc.end()) {
3694 const uint8_t dylib_ordinal =
3695 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
3696 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
3697 sym[pos.first].SetReExportedSymbolSharedLibrary(
3698 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
3699 }
3700 }
3701 }
3702
3703#endif
3704 lldb::offset_t nlist_data_offset = 0;
3705
3706 if (nlist_data.GetByteSize() > 0) {
3707
3708 // If the sym array was not created while parsing the DSC unmapped
3709 // symbols, create it now.
3710 if (sym == nullptr) {
3711 sym =
3712 symtab.Resize(symtab_load_command.nsyms + m_dysymtab.nindirectsyms);
3713 num_syms = symtab.GetNumSymbols();
3714 }
3715
3716 if (unmapped_local_symbols_found) {
3717 assert(m_dysymtab.ilocalsym == 0);
3718 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size);
3719 nlist_idx = m_dysymtab.nlocalsym;
3720 } else {
3721 nlist_idx = 0;
3722 }
3723
3724 typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap;
3725 typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName;
3726 UndefinedNameToDescMap undefined_name_to_desc;
3727 SymbolIndexToName reexport_shlib_needs_fixup;
3728
3729 // Symtab parsing is a huge mess. Everything is entangled and the code
3730 // requires access to a ridiculous amount of variables. LLDB depends
3731 // heavily on the proper merging of symbols and to get that right we need
3732 // to make sure we have parsed all the debug symbols first. Therefore we
3733 // invoke the lambda twice, once to parse only the debug symbols and then
3734 // once more to parse the remaining symbols.
3735 auto ParseSymbolLambda = [&](struct nlist_64 &nlist, uint32_t nlist_idx,
3736 bool debug_only) {
3737 const bool is_debug = ((nlist.n_type & N_STAB) != 0);
3738 if (is_debug != debug_only)
3739 return true;
3740
3741 const char *symbol_name_non_abi_mangled = nullptr;
3742 const char *symbol_name = nullptr;
3743
3744 if (have_strtab_data) {
3745 symbol_name = strtab_data.PeekCStr(nlist.n_strx);
3746
3747 if (symbol_name == nullptr) {
3748 // No symbol should be NULL, even the symbols with no string values
3749 // should have an offset zero which points to an empty C-string
3750 Debugger::ReportError(llvm::formatv(
3751 "symbol[{0}] has invalid string table offset {1:x} in {2}, "
3752 "ignoring symbol",
3753 nlist_idx, nlist.n_strx, module_sp->GetFileSpec().GetPath()));
3754 return true;
3755 }
3756 if (symbol_name[0] == '\0')
3757 symbol_name = nullptr;
3758 } else {
3759 const addr_t str_addr = strtab_addr + nlist.n_strx;
3760 Status str_error;
3761 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name,
3762 str_error))
3763 symbol_name = memory_symbol_name.c_str();
3764 }
3765
3767 SectionSP symbol_section;
3768 lldb::addr_t symbol_byte_size = 0;
3769 bool add_nlist = true;
3770 bool is_gsym = false;
3771 bool demangled_is_synthesized = false;
3772 bool set_value = true;
3773
3774 assert(sym_idx < num_syms);
3775 sym[sym_idx].SetDebug(is_debug);
3776
3777 if (is_debug) {
3778 switch (nlist.n_type) {
3779 case N_GSYM:
3780 // global symbol: name,,NO_SECT,type,0
3781 // Sometimes the N_GSYM value contains the address.
3782
3783 // FIXME: In the .o files, we have a GSYM and a debug symbol for all
3784 // the ObjC data. They
3785 // have the same address, but we want to ensure that we always find
3786 // only the real symbol, 'cause we don't currently correctly
3787 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol
3788 // type. This is a temporary hack to make sure the ObjectiveC
3789 // symbols get treated correctly. To do this right, we should
3790 // coalesce all the GSYM & global symbols that have the same
3791 // address.
3792 is_gsym = true;
3793 sym[sym_idx].SetExternal(true);
3794
3795 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') {
3796 llvm::StringRef symbol_name_ref(symbol_name);
3797 if (symbol_name_ref.starts_with(g_objc_v2_prefix_class)) {
3798 symbol_name_non_abi_mangled = symbol_name + 1;
3799 symbol_name = symbol_name + g_objc_v2_prefix_class.size();
3800 type = eSymbolTypeObjCClass;
3801 demangled_is_synthesized = true;
3802
3803 } else if (symbol_name_ref.starts_with(
3804 g_objc_v2_prefix_metaclass)) {
3805 symbol_name_non_abi_mangled = symbol_name + 1;
3806 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size();
3808 demangled_is_synthesized = true;
3809 } else if (symbol_name_ref.starts_with(g_objc_v2_prefix_ivar)) {
3810 symbol_name_non_abi_mangled = symbol_name + 1;
3811 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size();
3812 type = eSymbolTypeObjCIVar;
3813 demangled_is_synthesized = true;
3814 }
3815 } else {
3816 if (nlist.n_value != 0)
3817 symbol_section =
3818 section_info.GetSection(nlist.n_sect, nlist.n_value);
3819 type = eSymbolTypeData;
3820 }
3821 break;
3822
3823 case N_FNAME:
3824 // procedure name (f77 kludge): name,,NO_SECT,0,0
3825 type = eSymbolTypeCompiler;
3826 break;
3827
3828 case N_FUN:
3829 // procedure: name,,n_sect,linenumber,address
3830 if (symbol_name) {
3831 type = eSymbolTypeCode;
3832 symbol_section =
3833 section_info.GetSection(nlist.n_sect, nlist.n_value);
3834
3835 N_FUN_addr_to_sym_idx.insert(
3836 std::make_pair(nlist.n_value, sym_idx));
3837 // We use the current number of symbols in the symbol table in
3838 // lieu of using nlist_idx in case we ever start trimming entries
3839 // out
3840 N_FUN_indexes.push_back(sym_idx);
3841 } else {
3842 type = eSymbolTypeCompiler;
3843
3844 if (!N_FUN_indexes.empty()) {
3845 // Copy the size of the function into the original STAB entry
3846 // so we don't have to hunt for it later
3847 symtab.SymbolAtIndex(N_FUN_indexes.back())
3848 ->SetByteSize(nlist.n_value);
3849 N_FUN_indexes.pop_back();
3850 // We don't really need the end function STAB as it contains
3851 // the size which we already placed with the original symbol,
3852 // so don't add it if we want a minimal symbol table
3853 add_nlist = false;
3854 }
3855 }
3856 break;
3857
3858 case N_STSYM:
3859 // static symbol: name,,n_sect,type,address
3860 N_STSYM_addr_to_sym_idx.insert(
3861 std::make_pair(nlist.n_value, sym_idx));
3862 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3863 if (symbol_name && symbol_name[0]) {
3864 type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1,
3866 }
3867 break;
3868
3869 case N_LCSYM:
3870 // .lcomm symbol: name,,n_sect,type,address
3871 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3873 break;
3874
3875 case N_BNSYM:
3876 // We use the current number of symbols in the symbol table in lieu
3877 // of using nlist_idx in case we ever start trimming entries out
3878 // Skip these if we want minimal symbol tables
3879 add_nlist = false;
3880 break;
3881
3882 case N_ENSYM:
3883 // Set the size of the N_BNSYM to the terminating index of this
3884 // N_ENSYM so that we can always skip the entire symbol if we need
3885 // to navigate more quickly at the source level when parsing STABS
3886 // Skip these if we want minimal symbol tables
3887 add_nlist = false;
3888 break;
3889
3890 case N_OPT:
3891 // emitted with gcc2_compiled and in gcc source
3892 type = eSymbolTypeCompiler;
3893 break;
3894
3895 case N_RSYM:
3896 // register sym: name,,NO_SECT,type,register
3897 type = eSymbolTypeVariable;
3898 break;
3899
3900 case N_SLINE:
3901 // src line: 0,,n_sect,linenumber,address
3902 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
3903 type = eSymbolTypeLineEntry;
3904 break;
3905
3906 case N_SSYM:
3907 // structure elt: name,,NO_SECT,type,struct_offset
3909 break;
3910
3911 case N_SO:
3912 // source file name
3913 type = eSymbolTypeSourceFile;
3914 if (symbol_name == nullptr) {
3915 add_nlist = false;
3916 if (N_SO_index != UINT32_MAX) {
3917 // Set the size of the N_SO to the terminating index of this
3918 // N_SO so that we can always skip the entire N_SO if we need
3919 // to navigate more quickly at the source level when parsing
3920 // STABS
3921 symbol_ptr = symtab.SymbolAtIndex(N_SO_index);
3922 symbol_ptr->SetByteSize(sym_idx);
3923 symbol_ptr->SetSizeIsSibling(true);
3924 }
3925 N_NSYM_indexes.clear();
3926 N_INCL_indexes.clear();
3927 N_BRAC_indexes.clear();
3928 N_COMM_indexes.clear();
3929 N_FUN_indexes.clear();
3930 N_SO_index = UINT32_MAX;
3931 } else {
3932 // We use the current number of symbols in the symbol table in
3933 // lieu of using nlist_idx in case we ever start trimming entries
3934 // out
3935 const bool N_SO_has_full_path = symbol_name[0] == '/';
3936 if (N_SO_has_full_path) {
3937 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) {
3938 // We have two consecutive N_SO entries where the first
3939 // contains a directory and the second contains a full path.
3940 sym[sym_idx - 1].GetMangled().SetValue(
3941 ConstString(symbol_name));
3942 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3943 add_nlist = false;
3944 } else {
3945 // This is the first entry in a N_SO that contains a
3946 // directory or a full path to the source file
3947 N_SO_index = sym_idx;
3948 }
3949 } else if ((N_SO_index == sym_idx - 1) &&
3950 ((sym_idx - 1) < num_syms)) {
3951 // This is usually the second N_SO entry that contains just the
3952 // filename, so here we combine it with the first one if we are
3953 // minimizing the symbol table
3954 const char *so_path =
3955 sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString();
3956 if (so_path && so_path[0]) {
3957 std::string full_so_path(so_path);
3958 const size_t double_slash_pos = full_so_path.find("//");
3959 if (double_slash_pos != std::string::npos) {
3960 // The linker has been generating bad N_SO entries with
3961 // doubled up paths in the format "%s%s" where the first
3962 // string in the DW_AT_comp_dir, and the second is the
3963 // directory for the source file so you end up with a path
3964 // that looks like "/tmp/src//tmp/src/"
3965 FileSpec so_dir(so_path);
3966 if (!FileSystem::Instance().Exists(so_dir)) {
3967 so_dir.SetFile(&full_so_path[double_slash_pos + 1],
3968 FileSpec::Style::native);
3969 if (FileSystem::Instance().Exists(so_dir)) {
3970 // Trim off the incorrect path
3971 full_so_path.erase(0, double_slash_pos + 1);
3972 }
3973 }
3974 }
3975 if (*full_so_path.rbegin() != '/')
3976 full_so_path += '/';
3977 full_so_path += symbol_name;
3978 sym[sym_idx - 1].GetMangled().SetValue(
3979 ConstString(full_so_path.c_str()));
3980 add_nlist = false;
3981 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1;
3982 }
3983 } else {
3984 // This could be a relative path to a N_SO
3985 N_SO_index = sym_idx;
3986 }
3987 }
3988 break;
3989
3990 case N_OSO:
3991 // object file name: name,,0,0,st_mtime
3992 type = eSymbolTypeObjectFile;
3993 break;
3994
3995 case N_LSYM:
3996 // local sym: name,,NO_SECT,type,offset
3997 type = eSymbolTypeLocal;
3998 break;
3999
4000 // INCL scopes
4001 case N_BINCL:
4002 // include file beginning: name,,NO_SECT,0,sum We use the current
4003 // number of symbols in the symbol table in lieu of using nlist_idx
4004 // in case we ever start trimming entries out
4005 N_INCL_indexes.push_back(sym_idx);
4006 type = eSymbolTypeScopeBegin;
4007 break;
4008
4009 case N_EINCL:
4010 // include file end: name,,NO_SECT,0,0
4011 // Set the size of the N_BINCL to the terminating index of this
4012 // N_EINCL so that we can always skip the entire symbol if we need
4013 // to navigate more quickly at the source level when parsing STABS
4014 if (!N_INCL_indexes.empty()) {
4015 symbol_ptr = symtab.SymbolAtIndex(N_INCL_indexes.back());
4016 symbol_ptr->SetByteSize(sym_idx + 1);
4017 symbol_ptr->SetSizeIsSibling(true);
4018 N_INCL_indexes.pop_back();
4019 }
4020 type = eSymbolTypeScopeEnd;
4021 break;
4022
4023 case N_SOL:
4024 // #included file name: name,,n_sect,0,address
4025 type = eSymbolTypeHeaderFile;
4026
4027 // We currently don't use the header files on darwin
4028 add_nlist = false;
4029 break;
4030
4031 case N_PARAMS:
4032 // compiler parameters: name,,NO_SECT,0,0
4033 type = eSymbolTypeCompiler;
4034 break;
4035
4036 case N_VERSION:
4037 // compiler version: name,,NO_SECT,0,0
4038 type = eSymbolTypeCompiler;
4039 break;
4040
4041 case N_OLEVEL:
4042 // compiler -O level: name,,NO_SECT,0,0
4043 type = eSymbolTypeCompiler;
4044 break;
4045
4046 case N_PSYM:
4047 // parameter: name,,NO_SECT,type,offset
4048 type = eSymbolTypeVariable;
4049 break;
4050
4051 case N_ENTRY:
4052 // alternate entry: name,,n_sect,linenumber,address
4053 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4054 type = eSymbolTypeLineEntry;
4055 break;
4056
4057 // Left and Right Braces
4058 case N_LBRAC:
4059 // left bracket: 0,,NO_SECT,nesting level,address We use the
4060 // current number of symbols in the symbol table in lieu of using
4061 // nlist_idx in case we ever start trimming entries out
4062 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4063 N_BRAC_indexes.push_back(sym_idx);
4064 type = eSymbolTypeScopeBegin;
4065 break;
4066
4067 case N_RBRAC:
4068 // right bracket: 0,,NO_SECT,nesting level,address Set the size of
4069 // the N_LBRAC to the terminating index of this N_RBRAC so that we
4070 // can always skip the entire symbol if we need to navigate more
4071 // quickly at the source level when parsing STABS
4072 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4073 if (!N_BRAC_indexes.empty()) {
4074 symbol_ptr = symtab.SymbolAtIndex(N_BRAC_indexes.back());
4075 symbol_ptr->SetByteSize(sym_idx + 1);
4076 symbol_ptr->SetSizeIsSibling(true);
4077 N_BRAC_indexes.pop_back();
4078 }
4079 type = eSymbolTypeScopeEnd;
4080 break;
4081
4082 case N_EXCL:
4083 // deleted include file: name,,NO_SECT,0,sum
4084 type = eSymbolTypeHeaderFile;
4085 break;
4086
4087 // COMM scopes
4088 case N_BCOMM:
4089 // begin common: name,,NO_SECT,0,0
4090 // We use the current number of symbols in the symbol table in lieu
4091 // of using nlist_idx in case we ever start trimming entries out
4092 type = eSymbolTypeScopeBegin;
4093 N_COMM_indexes.push_back(sym_idx);
4094 break;
4095
4096 case N_ECOML:
4097 // end common (local name): 0,,n_sect,0,address
4098 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4099 [[fallthrough]];
4100
4101 case N_ECOMM:
4102 // end common: name,,n_sect,0,0
4103 // Set the size of the N_BCOMM to the terminating index of this
4104 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if
4105 // we need to navigate more quickly at the source level when
4106 // parsing STABS
4107 if (!N_COMM_indexes.empty()) {
4108 symbol_ptr = symtab.SymbolAtIndex(N_COMM_indexes.back());
4109 symbol_ptr->SetByteSize(sym_idx + 1);
4110 symbol_ptr->SetSizeIsSibling(true);
4111 N_COMM_indexes.pop_back();
4112 }
4113 type = eSymbolTypeScopeEnd;
4114 break;
4115
4116 case N_LENG:
4117 // second stab entry with length information
4118 type = eSymbolTypeAdditional;
4119 break;
4120
4121 default:
4122 break;
4123 }
4124 } else {
4125 uint8_t n_type = N_TYPE & nlist.n_type;
4126 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0);
4127
4128 switch (n_type) {
4129 case N_INDR: {
4130 const char *reexport_name_cstr = strtab_data.PeekCStr(nlist.n_value);
4131 if (reexport_name_cstr && reexport_name_cstr[0] && symbol_name) {
4132 type = eSymbolTypeReExported;
4133 ConstString reexport_name(reexport_name_cstr +
4134 ((reexport_name_cstr[0] == '_') ? 1 : 0));
4135 sym[sym_idx].SetReExportedSymbolName(reexport_name);
4136 set_value = false;
4137 reexport_shlib_needs_fixup[sym_idx] = reexport_name;
4138 indirect_symbol_names.insert(
4139 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0)));
4140 } else
4141 type = eSymbolTypeUndefined;
4142 } break;
4143
4144 case N_UNDF:
4145 if (symbol_name && symbol_name[0]) {
4146 ConstString undefined_name(symbol_name +
4147 ((symbol_name[0] == '_') ? 1 : 0));
4148 undefined_name_to_desc[undefined_name] = nlist.n_desc;
4149 }
4150 [[fallthrough]];
4151
4152 case N_PBUD:
4153 type = eSymbolTypeUndefined;
4154 break;
4155
4156 case N_ABS:
4157 type = eSymbolTypeAbsolute;
4158 break;
4159
4160 case N_SECT: {
4161 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value);
4162
4163 if (!symbol_section) {
4164 // TODO: warn about this?
4165 add_nlist = false;
4166 break;
4167 }
4168
4169 if (TEXT_eh_frame_sectID == nlist.n_sect) {
4170 type = eSymbolTypeException;
4171 } else {
4172 uint32_t section_type = symbol_section->Get() & SECTION_TYPE;
4173
4174 switch (section_type) {
4175 case S_CSTRING_LITERALS:
4176 type = eSymbolTypeData;
4177 break; // section with only literal C strings
4178 case S_4BYTE_LITERALS:
4179 type = eSymbolTypeData;
4180 break; // section with only 4 byte literals
4181 case S_8BYTE_LITERALS:
4182 type = eSymbolTypeData;
4183 break; // section with only 8 byte literals
4184 case S_LITERAL_POINTERS:
4185 type = eSymbolTypeTrampoline;
4186 break; // section with only pointers to literals
4187 case S_NON_LAZY_SYMBOL_POINTERS:
4188 type = eSymbolTypeTrampoline;
4189 break; // section with only non-lazy symbol pointers
4190 case S_LAZY_SYMBOL_POINTERS:
4191 type = eSymbolTypeTrampoline;
4192 break; // section with only lazy symbol pointers
4193 case S_SYMBOL_STUBS:
4194 type = eSymbolTypeTrampoline;
4195 break; // section with only symbol stubs, byte size of stub in
4196 // the reserved2 field
4197 case S_MOD_INIT_FUNC_POINTERS:
4198 type = eSymbolTypeCode;
4199 break; // section with only function pointers for initialization
4200 case S_MOD_TERM_FUNC_POINTERS:
4201 type = eSymbolTypeCode;
4202 break; // section with only function pointers for termination
4203 case S_INTERPOSING:
4204 type = eSymbolTypeTrampoline;
4205 break; // section with only pairs of function pointers for
4206 // interposing
4207 case S_16BYTE_LITERALS:
4208 type = eSymbolTypeData;
4209 break; // section with only 16 byte literals
4210 case S_DTRACE_DOF:
4212 break;
4213 case S_LAZY_DYLIB_SYMBOL_POINTERS:
4214 type = eSymbolTypeTrampoline;
4215 break;
4216 default:
4217 switch (symbol_section->GetType()) {
4219 type = eSymbolTypeCode;
4220 break;
4221 case eSectionTypeData:
4222 case eSectionTypeDataCString: // Inlined C string data
4223 case eSectionTypeDataCStringPointers: // Pointers to C string
4224 // data
4225 case eSectionTypeDataSymbolAddress: // Address of a symbol in
4226 // the symbol table
4227 case eSectionTypeData4:
4228 case eSectionTypeData8:
4229 case eSectionTypeData16:
4230 type = eSymbolTypeData;
4231 break;
4232 default:
4233 break;
4234 }
4235 break;
4236 }
4237
4238 if (type == eSymbolTypeInvalid) {
4239 const char *symbol_sect_name =
4240 symbol_section->GetName().AsCString();
4241 if (symbol_section->IsDescendant(text_section_sp.get())) {
4242 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS |
4243 S_ATTR_SELF_MODIFYING_CODE |
4244 S_ATTR_SOME_INSTRUCTIONS))
4245 type = eSymbolTypeData;
4246 else
4247 type = eSymbolTypeCode;
4248 } else if (symbol_section->IsDescendant(data_section_sp.get()) ||
4249 symbol_section->IsDescendant(
4250 data_dirty_section_sp.get()) ||
4251 symbol_section->IsDescendant(
4252 data_const_section_sp.get())) {
4253 if (symbol_sect_name &&
4254 ::strstr(symbol_sect_name, "__objc") == symbol_sect_name) {
4255 type = eSymbolTypeRuntime;
4256
4257 if (symbol_name) {
4258 llvm::StringRef symbol_name_ref(symbol_name);
4259 if (symbol_name_ref.starts_with("_OBJC_")) {
4260 llvm::StringRef g_objc_v2_prefix_class(
4261 "_OBJC_CLASS_$_");
4262 llvm::StringRef g_objc_v2_prefix_metaclass(
4263 "_OBJC_METACLASS_$_");
4264 llvm::StringRef g_objc_v2_prefix_ivar(
4265 "_OBJC_IVAR_$_");
4266 if (symbol_name_ref.starts_with(g_objc_v2_prefix_class)) {
4267 symbol_name_non_abi_mangled = symbol_name + 1;
4268 symbol_name =
4269 symbol_name + g_objc_v2_prefix_class.size();
4270 type = eSymbolTypeObjCClass;
4271 demangled_is_synthesized = true;
4272 } else if (symbol_name_ref.starts_with(
4273 g_objc_v2_prefix_metaclass)) {
4274 symbol_name_non_abi_mangled = symbol_name + 1;
4275 symbol_name =
4276 symbol_name + g_objc_v2_prefix_metaclass.size();
4278 demangled_is_synthesized = true;
4279 } else if (symbol_name_ref.starts_with(
4280 g_objc_v2_prefix_ivar)) {
4281 symbol_name_non_abi_mangled = symbol_name + 1;
4282 symbol_name =
4283 symbol_name + g_objc_v2_prefix_ivar.size();
4284 type = eSymbolTypeObjCIVar;
4285 demangled_is_synthesized = true;
4286 }
4287 }
4288 }
4289 } else if (symbol_sect_name &&
4290 ::strstr(symbol_sect_name, "__gcc_except_tab") ==
4291 symbol_sect_name) {
4292 type = eSymbolTypeException;
4293 } else {
4294 type = eSymbolTypeData;
4295 }
4296 } else if (symbol_sect_name &&
4297 ::strstr(symbol_sect_name, "__IMPORT") ==
4298 symbol_sect_name) {
4299 type = eSymbolTypeTrampoline;
4300 } else if (symbol_section->IsDescendant(objc_section_sp.get())) {
4301 type = eSymbolTypeRuntime;
4302 if (symbol_name && symbol_name[0] == '.') {
4303 llvm::StringRef symbol_name_ref(symbol_name);
4304 llvm::StringRef g_objc_v1_prefix_class(
4305 ".objc_class_name_");
4306 if (symbol_name_ref.starts_with(g_objc_v1_prefix_class)) {
4307 symbol_name_non_abi_mangled = symbol_name;
4308 symbol_name = symbol_name + g_objc_v1_prefix_class.size();
4309 type = eSymbolTypeObjCClass;
4310 demangled_is_synthesized = true;
4311 }
4312 }
4313 }
4314 }
4315 }
4316 } break;
4317 }
4318 }
4319
4320 if (!add_nlist) {
4321 sym[sym_idx].Clear();
4322 return true;
4323 }
4324
4325 uint64_t symbol_value = nlist.n_value;
4326
4327 if (symbol_name_non_abi_mangled) {
4328 sym[sym_idx].GetMangled().SetMangledName(
4329 ConstString(symbol_name_non_abi_mangled));
4330 sym[sym_idx].GetMangled().SetDemangledName(ConstString(symbol_name));
4331 } else {
4332
4333 if (symbol_name && symbol_name[0] == '_') {
4334 symbol_name++; // Skip the leading underscore
4335 }
4336
4337 if (symbol_name) {
4338 ConstString const_symbol_name(symbol_name);
4339 sym[sym_idx].GetMangled().SetValue(const_symbol_name);
4340 }
4341 }
4342
4343 if (is_gsym) {
4344 const char *gsym_name = sym[sym_idx]
4345 .GetMangled()
4347 .GetCString();
4348 if (gsym_name)
4349 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx;
4350 }
4351
4352 if (symbol_section) {
4353 const addr_t section_file_addr = symbol_section->GetFileAddress();
4354 if (symbol_byte_size == 0 && function_starts_count > 0) {
4355 addr_t symbol_lookup_file_addr = nlist.n_value;
4356 // Do an exact address match for non-ARM addresses, else get the
4357 // closest since the symbol might be a thumb symbol which has an
4358 // address with bit zero set.
4359 FunctionStarts::Entry *func_start_entry =
4360 function_starts.FindEntry(symbol_lookup_file_addr, !is_arm);
4361 if (is_arm && func_start_entry) {
4362 // Verify that the function start address is the symbol address
4363 // (ARM) or the symbol address + 1 (thumb).
4364 if (func_start_entry->addr != symbol_lookup_file_addr &&
4365 func_start_entry->addr != (symbol_lookup_file_addr + 1)) {
4366 // Not the right entry, NULL it out...
4367 func_start_entry = nullptr;
4368 }
4369 }
4370 if (func_start_entry) {
4371 func_start_entry->data = true;
4372
4373 addr_t symbol_file_addr = func_start_entry->addr;
4374 if (is_arm)
4375 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4376
4377 const FunctionStarts::Entry *next_func_start_entry =
4378 function_starts.FindNextEntry(func_start_entry);
4379 const addr_t section_end_file_addr =
4380 section_file_addr + symbol_section->GetByteSize();
4381 if (next_func_start_entry) {
4382 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4383 // Be sure the clear the Thumb address bit when we calculate the
4384 // size from the current and next address
4385 if (is_arm)
4386 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4387 symbol_byte_size = std::min<lldb::addr_t>(
4388 next_symbol_file_addr - symbol_file_addr,
4389 section_end_file_addr - symbol_file_addr);
4390 } else {
4391 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4392 }
4393 }
4394 }
4395 symbol_value -= section_file_addr;
4396 }
4397
4398 if (!is_debug) {
4399 if (type == eSymbolTypeCode) {
4400 // See if we can find a N_FUN entry for any code symbols. If we do
4401 // find a match, and the name matches, then we can merge the two into
4402 // just the function symbol to avoid duplicate entries in the symbol
4403 // table.
4404 std::pair<ValueToSymbolIndexMap::const_iterator,
4405 ValueToSymbolIndexMap::const_iterator>
4406 range;
4407 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value);
4408 if (range.first != range.second) {
4409 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4410 pos != range.second; ++pos) {
4411 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) ==
4412 sym[pos->second].GetMangled().GetName(
4414 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4415 // We just need the flags from the linker symbol, so put these
4416 // flags into the N_FUN flags to avoid duplicate symbols in the
4417 // symbol table.
4418 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4419 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4420 if (resolver_addresses.find(nlist.n_value) !=
4421 resolver_addresses.end())
4422 sym[pos->second].SetType(eSymbolTypeResolver);
4423 sym[sym_idx].Clear();
4424 return true;
4425 }
4426 }
4427 } else {
4428 if (resolver_addresses.find(nlist.n_value) !=
4429 resolver_addresses.end())
4430 type = eSymbolTypeResolver;
4431 }
4432 } else if (type == eSymbolTypeData || type == eSymbolTypeObjCClass ||
4433 type == eSymbolTypeObjCMetaClass ||
4434 type == eSymbolTypeObjCIVar) {
4435 // See if we can find a N_STSYM entry for any data symbols. If we do
4436 // find a match, and the name matches, then we can merge the two into
4437 // just the Static symbol to avoid duplicate entries in the symbol
4438 // table.
4439 std::pair<ValueToSymbolIndexMap::const_iterator,
4440 ValueToSymbolIndexMap::const_iterator>
4441 range;
4442 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value);
4443 if (range.first != range.second) {
4444 for (ValueToSymbolIndexMap::const_iterator pos = range.first;
4445 pos != range.second; ++pos) {
4446 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) ==
4447 sym[pos->second].GetMangled().GetName(
4449 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second;
4450 // We just need the flags from the linker symbol, so put these
4451 // flags into the N_STSYM flags to avoid duplicate symbols in
4452 // the symbol table.
4453 sym[pos->second].SetExternal(sym[sym_idx].IsExternal());
4454 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4455 sym[sym_idx].Clear();
4456 return true;
4457 }
4458 }
4459 } else {
4460 // Combine N_GSYM stab entries with the non stab symbol.
4461 const char *gsym_name = sym[sym_idx]
4462 .GetMangled()
4464 .GetCString();
4465 if (gsym_name) {
4466 ConstNameToSymbolIndexMap::const_iterator pos =
4467 N_GSYM_name_to_sym_idx.find(gsym_name);
4468 if (pos != N_GSYM_name_to_sym_idx.end()) {
4469 const uint32_t GSYM_sym_idx = pos->second;
4470 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx;
4471 // Copy the address, because often the N_GSYM address has an
4472 // invalid address of zero when the global is a common symbol.
4473 sym[GSYM_sym_idx].GetAddressRef().SetSection(symbol_section);
4474 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value);
4475 add_symbol_addr(
4476 sym[GSYM_sym_idx].GetAddress().GetFileAddress());
4477 // We just need the flags from the linker symbol, so put these
4478 // flags into the N_GSYM flags to avoid duplicate symbols in
4479 // the symbol table.
4480 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4481 sym[sym_idx].Clear();
4482 return true;
4483 }
4484 }
4485 }
4486 }
4487 }
4488
4489 sym[sym_idx].SetID(nlist_idx);
4490 sym[sym_idx].SetType(type);
4491 if (set_value) {
4492 sym[sym_idx].GetAddressRef().SetSection(symbol_section);
4493 sym[sym_idx].GetAddressRef().SetOffset(symbol_value);
4494 if (symbol_section)
4495 add_symbol_addr(sym[sym_idx].GetAddress().GetFileAddress());
4496 }
4497 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc);
4498 if (nlist.n_desc & N_WEAK_REF)
4499 sym[sym_idx].SetIsWeak(true);
4500
4501 if (symbol_byte_size > 0)
4502 sym[sym_idx].SetByteSize(symbol_byte_size);
4503
4504 if (demangled_is_synthesized)
4505 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4506
4507 ++sym_idx;
4508 return true;
4509 };
4510
4511 // First parse all the nlists but don't process them yet. See the next
4512 // comment for an explanation why.
4513 std::vector<struct nlist_64> nlists;
4514 nlists.reserve(symtab_load_command.nsyms);
4515 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) {
4516 if (auto nlist =
4517 ParseNList(nlist_data, nlist_data_offset, nlist_byte_size))
4518 nlists.push_back(*nlist);
4519 else
4520 break;
4521 }
4522
4523 // Now parse all the debug symbols. This is needed to merge non-debug
4524 // symbols in the next step. Non-debug symbols are always coalesced into
4525 // the debug symbol. Doing this in one step would mean that some symbols
4526 // won't be merged.
4527 nlist_idx = 0;
4528 for (auto &nlist : nlists) {
4529 if (!ParseSymbolLambda(nlist, nlist_idx++, DebugSymbols))
4530 break;
4531 }
4532
4533 // Finally parse all the non debug symbols.
4534 nlist_idx = 0;
4535 for (auto &nlist : nlists) {
4536 if (!ParseSymbolLambda(nlist, nlist_idx++, NonDebugSymbols))
4537 break;
4538 }
4539
4540 for (const auto &pos : reexport_shlib_needs_fixup) {
4541 const auto undef_pos = undefined_name_to_desc.find(pos.second);
4542 if (undef_pos != undefined_name_to_desc.end()) {
4543 const uint8_t dylib_ordinal =
4544 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second);
4545 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize())
4546 sym[pos.first].SetReExportedSymbolSharedLibrary(
4547 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1));
4548 }
4549 }
4550 }
4551
4552 // Count how many trie symbols we'll add to the symbol table
4553 int trie_symbol_table_augment_count = 0;
4554 for (auto &e : external_sym_trie_entries) {
4555 if (!symbols_added.contains(e.entry.address))
4556 trie_symbol_table_augment_count++;
4557 }
4558
4559 if (num_syms < sym_idx + trie_symbol_table_augment_count) {
4560 num_syms = sym_idx + trie_symbol_table_augment_count;
4561 sym = symtab.Resize(num_syms);
4562 }
4563 uint32_t synthetic_sym_id = symtab_load_command.nsyms;
4564
4565 // Add symbols from the trie to the symbol table.
4566 for (auto &e : external_sym_trie_entries) {
4567 if (symbols_added.contains(e.entry.address))
4568 continue;
4569
4570 // Find the section that this trie address is in, use that to annotate
4571 // symbol type as we add the trie address and name to the symbol table.
4572 Address symbol_addr;
4573 if (module_sp->ResolveFileAddress(e.entry.address, symbol_addr)) {
4574 SectionSP symbol_section(symbol_addr.GetSection());
4575 const char *symbol_name = e.entry.name.GetCString();
4576 bool demangled_is_synthesized = false;
4577 SymbolType type =
4578 GetSymbolType(symbol_name, demangled_is_synthesized, text_section_sp,
4579 data_section_sp, data_dirty_section_sp,
4580 data_const_section_sp, symbol_section);
4581
4582 sym[sym_idx].SetType(type);
4583 if (symbol_section) {
4584 sym[sym_idx].SetID(synthetic_sym_id++);
4585 sym[sym_idx].GetMangled().SetMangledName(ConstString(symbol_name));
4586 if (demangled_is_synthesized)
4587 sym[sym_idx].SetDemangledNameIsSynthesized(true);
4588 sym[sym_idx].SetIsSynthetic(true);
4589 sym[sym_idx].SetExternal(true);
4590 sym[sym_idx].GetAddressRef() = symbol_addr;
4591 add_symbol_addr(symbol_addr.GetFileAddress());
4592 if (e.entry.flags & TRIE_SYMBOL_IS_THUMB)
4594 ++sym_idx;
4595 }
4596 }
4597 }
4598
4599 if (function_starts_count > 0) {
4600 uint32_t num_synthetic_function_symbols = 0;
4601 for (i = 0; i < function_starts_count; ++i) {
4602 if (!symbols_added.contains(function_starts.GetEntryRef(i).addr))
4603 ++num_synthetic_function_symbols;
4604 }
4605
4606 if (num_synthetic_function_symbols > 0) {
4607 if (num_syms < sym_idx + num_synthetic_function_symbols) {
4608 num_syms = sym_idx + num_synthetic_function_symbols;
4609 sym = symtab.Resize(num_syms);
4610 }
4611 for (i = 0; i < function_starts_count; ++i) {
4612 const FunctionStarts::Entry *func_start_entry =
4613 function_starts.GetEntryAtIndex(i);
4614 if (!symbols_added.contains(func_start_entry->addr)) {
4615 addr_t symbol_file_addr = func_start_entry->addr;
4616 uint32_t symbol_flags = 0;
4617 if (func_start_entry->data)
4618 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB;
4619 Address symbol_addr;
4620 if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) {
4621 SectionSP symbol_section(symbol_addr.GetSection());
4622 uint32_t symbol_byte_size = 0;
4623 if (symbol_section) {
4624 const addr_t section_file_addr = symbol_section->GetFileAddress();
4625 const FunctionStarts::Entry *next_func_start_entry =
4626 function_starts.FindNextEntry(func_start_entry);
4627 const addr_t section_end_file_addr =
4628 section_file_addr + symbol_section->GetByteSize();
4629 if (next_func_start_entry) {
4630 addr_t next_symbol_file_addr = next_func_start_entry->addr;
4631 if (is_arm)
4632 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK;
4633 symbol_byte_size = std::min<lldb::addr_t>(
4634 next_symbol_file_addr - symbol_file_addr,
4635 section_end_file_addr - symbol_file_addr);
4636 } else {
4637 symbol_byte_size = section_end_file_addr - symbol_file_addr;
4638 }
4639 sym[sym_idx].SetID(synthetic_sym_id++);
4640 // Don't set the name for any synthetic symbols, the Symbol
4641 // object will generate one if needed when the name is accessed
4642 // via accessors.
4643 sym[sym_idx].GetMangled().SetDemangledName(ConstString());
4644 sym[sym_idx].SetType(eSymbolTypeCode);
4645 sym[sym_idx].SetIsSynthetic(true);
4646 sym[sym_idx].GetAddressRef() = symbol_addr;
4647 add_symbol_addr(symbol_addr.GetFileAddress());
4648 if (symbol_flags)
4649 sym[sym_idx].SetFlags(symbol_flags);
4650 if (symbol_byte_size)
4651 sym[sym_idx].SetByteSize(symbol_byte_size);
4652 ++sym_idx;
4653 }
4654 }
4655 }
4656 }
4657 }
4658 }
4659
4660 // Trim our symbols down to just what we ended up with after removing any
4661 // symbols.
4662 if (sym_idx < num_syms) {
4663 num_syms = sym_idx;
4664 sym = symtab.Resize(num_syms);
4665 }
4666
4667 // Now synthesize indirect symbols
4668 if (m_dysymtab.nindirectsyms != 0) {
4669 if (indirect_symbol_index_data.GetByteSize()) {
4670 NListIndexToSymbolIndexMap::const_iterator end_index_pos =
4671 m_nlist_idx_to_sym_idx.end();
4672
4673 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size();
4674 ++sect_idx) {
4675 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) ==
4676 S_SYMBOL_STUBS) {
4677 uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2;
4678 if (symbol_stub_byte_size == 0)
4679 continue;
4680
4681 const uint32_t num_symbol_stubs =
4682 m_mach_sections[sect_idx].size / symbol_stub_byte_size;
4683
4684 if (num_symbol_stubs == 0)
4685 continue;
4686
4687 const uint32_t symbol_stub_index_offset =
4688 m_mach_sections[sect_idx].reserved1;
4689 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx) {
4690 const uint32_t symbol_stub_index =
4691 symbol_stub_index_offset + stub_idx;
4692 const lldb::addr_t symbol_stub_addr =
4693 m_mach_sections[sect_idx].addr +
4694 (stub_idx * symbol_stub_byte_size);
4695 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4;
4696 if (indirect_symbol_index_data.ValidOffsetForDataOfSize(
4697 symbol_stub_offset, 4)) {
4698 const uint32_t stub_sym_id =
4699 indirect_symbol_index_data.GetU32(&symbol_stub_offset);
4700 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL))
4701 continue;
4702
4703 NListIndexToSymbolIndexMap::const_iterator index_pos =
4704 m_nlist_idx_to_sym_idx.find(stub_sym_id);
4705 Symbol *stub_symbol = nullptr;
4706 if (index_pos != end_index_pos) {
4707 // We have a remapping from the original nlist index to a
4708 // current symbol index, so just look this up by index
4709 stub_symbol = symtab.SymbolAtIndex(index_pos->second);
4710 } else {
4711 // We need to lookup a symbol using the original nlist symbol
4712 // index since this index is coming from the S_SYMBOL_STUBS
4713 stub_symbol = symtab.FindSymbolByID(stub_sym_id);
4714 }
4715
4716 if (stub_symbol) {
4717 Address so_addr(symbol_stub_addr, section_list);
4718
4719 if (stub_symbol->GetType() == eSymbolTypeUndefined) {
4720 // Change the external symbol into a trampoline that makes
4721 // sense These symbols were N_UNDF N_EXT, and are useless
4722 // to us, so we can re-use them so we don't have to make up
4723 // a synthetic symbol for no good reason.
4724 if (resolver_addresses.find(symbol_stub_addr) ==
4725 resolver_addresses.end())
4726 stub_symbol->SetType(eSymbolTypeTrampoline);
4727 else
4728 stub_symbol->SetType(eSymbolTypeResolver);
4729 stub_symbol->SetExternal(false);
4730 stub_symbol->GetAddressRef() = so_addr;
4731 stub_symbol->SetByteSize(symbol_stub_byte_size);
4732 } else {
4733 // Make a synthetic symbol to describe the trampoline stub
4734 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled());
4735 if (sym_idx >= num_syms) {
4736 sym = symtab.Resize(++num_syms);
4737 stub_symbol = nullptr; // this pointer no longer valid
4738 }
4739 sym[sym_idx].SetID(synthetic_sym_id++);
4740 sym[sym_idx].GetMangled() = stub_symbol_mangled_name;
4741 if (resolver_addresses.find(symbol_stub_addr) ==
4742 resolver_addresses.end())
4743 sym[sym_idx].SetType(eSymbolTypeTrampoline);
4744 else
4745 sym[sym_idx].SetType(eSymbolTypeResolver);
4746 sym[sym_idx].SetIsSynthetic(true);
4747 sym[sym_idx].GetAddressRef() = so_addr;
4748 add_symbol_addr(so_addr.GetFileAddress());
4749 sym[sym_idx].SetByteSize(symbol_stub_byte_size);
4750 ++sym_idx;
4751 }
4752 } else {
4753 if (log)
4754 log->Warning("symbol stub referencing symbol table symbol "
4755 "%u that isn't in our minimal symbol table, "
4756 "fix this!!!",
4757 stub_sym_id);
4758 }
4759 }
4760 }
4761 }
4762 }
4763 }
4764 }
4765
4766 if (!reexport_trie_entries.empty()) {
4767 for (const auto &e : reexport_trie_entries) {
4768 if (e.entry.import_name) {
4769 // Only add indirect symbols from the Trie entries if we didn't have
4770 // a N_INDR nlist entry for this already
4771 if (indirect_symbol_names.find(e.entry.name) ==
4772 indirect_symbol_names.end()) {
4773 // Make a synthetic symbol to describe re-exported symbol.
4774 if (sym_idx >= num_syms)
4775 sym = symtab.Resize(++num_syms);
4776 sym[sym_idx].SetID(synthetic_sym_id++);
4777 sym[sym_idx].GetMangled() = Mangled(e.entry.name);
4778 sym[sym_idx].SetType(eSymbolTypeReExported);
4779 sym[sym_idx].SetIsSynthetic(true);
4780 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name);
4781 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) {
4783 dylib_files.GetFileSpecAtIndex(e.entry.other - 1));
4784 }
4785 ++sym_idx;
4786 }
4787 }
4788 }
4789 }
4790}
4791
4793 ModuleSP module_sp(GetModule());
4794 if (module_sp) {
4795 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
4796 s->Printf("%p: ", static_cast<void *>(this));
4797 s->Indent();
4798 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64)
4799 s->PutCString("ObjectFileMachO64");
4800 else
4801 s->PutCString("ObjectFileMachO32");
4802
4803 *s << ", file = '" << m_file;
4804 ModuleSpecList all_specs;
4805 ModuleSpec base_spec;
4807 base_spec, all_specs);
4808 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
4809 *s << "', triple";
4810 if (e)
4811 s->Printf("[%d]", i);
4812 *s << " = ";
4813 *s << all_specs.GetModuleSpecRefAtIndex(i)
4815 .GetTriple()
4816 .getTriple();
4817 }
4818 *s << "\n";
4819 SectionList *sections = GetSectionList();
4820 if (sections)
4821 sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
4822 UINT32_MAX);
4823
4824 if (m_symtab_up)
4825 m_symtab_up->Dump(s, nullptr, eSortOrderNone);
4826 }
4827}
4828
4829UUID ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header,
4830 const lldb_private::DataExtractor &data,
4831 lldb::offset_t lc_offset) {
4832 uint32_t i;
4833 llvm::MachO::uuid_command load_cmd;
4834
4835 lldb::offset_t offset = lc_offset;
4836 for (i = 0; i < header.ncmds; ++i) {
4837 const lldb::offset_t cmd_offset = offset;
4838 if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
4839 break;
4840
4841 if (load_cmd.cmd == LC_UUID) {
4842 const uint8_t *uuid_bytes = data.PeekData(offset, 16);
4843
4844 if (uuid_bytes) {
4845 // OpenCL on Mac OS X uses the same UUID for each of its object files.
4846 // We pretend these object files have no UUID to prevent crashing.
4847
4848 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8,
4849 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63,
4850 0xbb, 0x14, 0xf0, 0x0d};
4851
4852 if (!memcmp(uuid_bytes, opencl_uuid, 16))
4853 return UUID();
4854
4855 return UUID(uuid_bytes, 16);
4856 }
4857 return UUID();
4858 }
4859 offset = cmd_offset + load_cmd.cmdsize;
4860 }
4861 return UUID();
4862}
4863
4864static llvm::StringRef GetOSName(uint32_t cmd) {
4865 switch (cmd) {
4866 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
4867 return llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4868 case llvm::MachO::LC_VERSION_MIN_MACOSX:
4869 return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4870 case llvm::MachO::LC_VERSION_MIN_TVOS:
4871 return llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4872 case llvm::MachO::LC_VERSION_MIN_WATCHOS:
4873 return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4874 default:
4875 llvm_unreachable("unexpected LC_VERSION load command");
4876 }
4877}
4878
4879namespace {
4880struct OSEnv {
4881 llvm::StringRef os_type;
4882 llvm::StringRef environment;
4883 OSEnv(uint32_t cmd) {
4884 switch (cmd) {
4885 case llvm::MachO::PLATFORM_MACOS:
4886 os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX);
4887 return;
4888 case llvm::MachO::PLATFORM_IOS:
4889 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4890 return;
4891 case llvm::MachO::PLATFORM_TVOS:
4892 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4893 return;
4894 case llvm::MachO::PLATFORM_WATCHOS:
4895 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4896 return;
4897 case llvm::MachO::PLATFORM_BRIDGEOS:
4898 os_type = llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS);
4899 return;
4900 case llvm::MachO::PLATFORM_DRIVERKIT:
4901 os_type = llvm::Triple::getOSTypeName(llvm::Triple::DriverKit);
4902 return;
4903 case llvm::MachO::PLATFORM_MACCATALYST:
4904 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4905 environment = llvm::Triple::getEnvironmentTypeName(llvm::Triple::MacABI);
4906 return;
4907 case llvm::MachO::PLATFORM_IOSSIMULATOR:
4908 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS);
4909 environment =
4910 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4911 return;
4912 case llvm::MachO::PLATFORM_TVOSSIMULATOR:
4913 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS);
4914 environment =
4915 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4916 return;
4917 case llvm::MachO::PLATFORM_WATCHOSSIMULATOR:
4918 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS);
4919 environment =
4920 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4921 return;
4922 case llvm::MachO::PLATFORM_XROS:
4923 os_type = llvm::Triple::getOSTypeName(llvm::Triple::XROS);
4924 return;
4925 case llvm::MachO::PLATFORM_XROS_SIMULATOR:
4926 os_type = llvm::Triple::getOSTypeName(llvm::Triple::XROS);
4927 environment =
4928 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator);
4929 return;
4930 default: {
4931 Log *log(GetLog(LLDBLog::Symbols | LLDBLog::Process));
4932 LLDB_LOGF(log, "unsupported platform in LC_BUILD_VERSION");
4933 }
4934 }
4935 }
4936};
4937
4938struct MinOS {
4939 uint32_t major_version, minor_version, patch_version;
4940 MinOS(uint32_t version)
4941 : major_version(version >> 16), minor_version((version >> 8) & 0xffu),
4942 patch_version(version & 0xffu) {}
4943};
4944} // namespace
4945
4946void ObjectFileMachO::GetAllArchSpecs(const llvm::MachO::mach_header &header,
4947 const lldb_private::DataExtractor &data,
4948 lldb::offset_t lc_offset,
4949 ModuleSpec &base_spec,
4950 lldb_private::ModuleSpecList &all_specs) {
4951 auto &base_arch = base_spec.GetArchitecture();
4952 base_arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype);
4953 if (!base_arch.IsValid())
4954 return;
4955
4956 bool found_any = false;
4957 auto add_triple = [&](const llvm::Triple &triple) {
4958 auto spec = base_spec;
4959 spec.GetArchitecture().GetTriple() = triple;
4960 if (spec.GetArchitecture().IsValid()) {
4961 spec.GetUUID() = ObjectFileMachO::GetUUID(header, data, lc_offset);
4962 all_specs.Append(spec);
4963 found_any = true;
4964 }
4965 };
4966
4967 // Set OS to an unspecified unknown or a "*" so it can match any OS
4968 llvm::Triple base_triple = base_arch.GetTriple();
4969 base_triple.setOS(llvm::Triple::UnknownOS);
4970 base_triple.setOSName(llvm::StringRef());
4971
4972 if (header.filetype == MH_PRELOAD) {
4973 if (header.cputype == CPU_TYPE_ARM) {
4974 // If this is a 32-bit arm binary, and it's a standalone binary, force
4975 // the Vendor to Apple so we don't accidentally pick up the generic
4976 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the
4977 // frame pointer register; most other armv7 ABIs use a combination of
4978 // r7 and r11.
4979 base_triple.setVendor(llvm::Triple::Apple);
4980 } else {
4981 // Set vendor to an unspecified unknown or a "*" so it can match any
4982 // vendor This is required for correct behavior of EFI debugging on
4983 // x86_64
4984 base_triple.setVendor(llvm::Triple::UnknownVendor);
4985 base_triple.setVendorName(llvm::StringRef());
4986 }
4987 return add_triple(base_triple);
4988 }
4989
4990 llvm::MachO::load_command load_cmd;
4991
4992 // See if there is an LC_VERSION_MIN_* load command that can give
4993 // us the OS type.
4994 lldb::offset_t offset = lc_offset;
4995 for (uint32_t i = 0; i < header.ncmds; ++i) {
4996 const lldb::offset_t cmd_offset = offset;
4997 if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
4998 break;
4999
5000 llvm::MachO::version_min_command version_min;
5001 switch (load_cmd.cmd) {
5002 case llvm::MachO::LC_VERSION_MIN_MACOSX:
5003 case llvm::MachO::LC_VERSION_MIN_IPHONEOS:
5004 case llvm::MachO::LC_VERSION_MIN_TVOS:
5005 case llvm::MachO::LC_VERSION_MIN_WATCHOS: {
5006 if (load_cmd.cmdsize != sizeof(version_min))
5007 break;
5008 if (data.ExtractBytes(cmd_offset, sizeof(version_min),
5009 data.GetByteOrder(), &version_min) == 0)
5010 break;
5011 MinOS min_os(version_min.version);
5012 llvm::SmallString<32> os_name;
5013 llvm::raw_svector_ostream os(os_name);
5014 os << GetOSName(load_cmd.cmd) << min_os.major_version << '.'
5015 << min_os.minor_version << '.' << min_os.patch_version;
5016
5017 auto triple = base_triple;
5018 triple.setOSName(os.str());
5019
5020 // Disambiguate legacy simulator platforms.
5021 if (load_cmd.cmd != llvm::MachO::LC_VERSION_MIN_MACOSX &&
5022 (base_triple.getArch() == llvm::Triple::x86_64 ||
5023 base_triple.getArch() == llvm::Triple::x86)) {
5024 // The combination of legacy LC_VERSION_MIN load command and
5025 // x86 architecture always indicates a simulator environment.
5026 // The combination of LC_VERSION_MIN and arm architecture only
5027 // appears for native binaries. Back-deploying simulator
5028 // binaries on Apple Silicon Macs use the modern unambigous
5029 // LC_BUILD_VERSION load commands; no special handling required.
5030 triple.setEnvironment(llvm::Triple::Simulator);
5031 }
5032 add_triple(triple);
5033 break;
5034 }
5035 default:
5036 break;
5037 }
5038
5039 offset = cmd_offset + load_cmd.cmdsize;
5040 }
5041
5042 // See if there are LC_BUILD_VERSION load commands that can give
5043 // us the OS type.
5044 offset = lc_offset;
5045 for (uint32_t i = 0; i < header.ncmds; ++i) {
5046 const lldb::offset_t cmd_offset = offset;
5047 if (data.GetU32(&offset, &load_cmd, 2) == nullptr)
5048 break;
5049
5050 do {
5051 if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) {
5052 llvm::MachO::build_version_command build_version;
5053 if (load_cmd.cmdsize < sizeof(build_version)) {
5054 // Malformed load command.
5055 break;
5056 }
5057 if (data.ExtractBytes(cmd_offset, sizeof(build_version),
5058 data.GetByteOrder(), &build_version) == 0)
5059 break;
5060 MinOS min_os(build_version.minos);
5061 OSEnv os_env(build_version.platform);
5062 llvm::SmallString<16> os_name;
5063 llvm::raw_svector_ostream os(os_name);
5064 os << os_env.os_type << min_os.major_version << '.'
5065 << min_os.minor_version << '.' << min_os.patch_version;
5066 auto triple = base_triple;
5067 triple.setOSName(os.str());
5068 os_name.clear();
5069 if (!os_env.environment.empty())
5070 triple.setEnvironmentName(os_env.environment);
5071 add_triple(triple);
5072 }
5073 } while (false);
5074 offset = cmd_offset + load_cmd.cmdsize;
5075 }
5076
5077 if (!found_any) {
5078 add_triple(base_triple);
5079 }
5080}
5081
5083 ModuleSP module_sp, const llvm::MachO::mach_header &header,
5084 const lldb_private::DataExtractor &data, lldb::offset_t lc_offset) {
5085 ModuleSpecList all_specs;
5086 ModuleSpec base_spec;
5087 GetAllArchSpecs(header, data, MachHeaderSizeFromMagic(header.magic),
5088 base_spec, all_specs);
5089
5090 // If the object file offers multiple alternative load commands,
5091 // pick the one that matches the module.
5092 if (module_sp) {
5093 const ArchSpec &module_arch = module_sp->GetArchitecture();
5094 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) {
5095 ArchSpec mach_arch =
5097 if (module_arch.IsCompatibleMatch(mach_arch))
5098 return mach_arch;
5099 }
5100 }
5101
5102 // Return the first arch we found.
5103 if (all_specs.GetSize() == 0)
5104 return {};
5105 return all_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
5106}
5107
5109 ModuleSP module_sp(GetModule());
5110 if (module_sp) {
5111 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5113 return GetUUID(m_header, m_data, offset);
5114 }
5115 return UUID();
5116}
5117
5119 uint32_t count = 0;
5120 ModuleSP module_sp(GetModule());
5121 if (module_sp) {
5122 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
5123 llvm::MachO::load_command load_cmd;
5125 std::vector<std::string> rpath_paths;
5126 std::vector<std::string> rpath_relative_paths;
5127 std::vector<std::string> at_exec_relative_paths;
5128 uint32_t i;
5129 for (i = 0; i < m_header.ncmds; ++i) {
5130 const uint32_t cmd_offset = offset;
5131 if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr)
5132 break;
5133
5134 switch (load_cmd.cmd) {
5135 case LC_RPATH:
5136 case LC_LOAD_DYLIB:
5137 case LC_LOAD_WEAK_DYLIB:
5138 case LC_REEXPORT_DYLIB:
5139 case LC_LOAD_DYLINKER:
5140 case LC_LOADFVMLIB:
5141 case LC_LOAD_UPWARD_DYLIB: {
5142 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset);
5143 // For LC_LOAD_DYLIB there is an alternate encoding
5144 // which adds a uint32_t `flags` field for `DYLD_USE_*`
5145 // flags. This can be detected by a timestamp field with
5146 // the `DYLIB_USE_MARKER` constant value.
5147 bool is_delayed_init = false;
5148 uint32_t use_command_marker = m_data.GetU32(&offset);
5149 if (use_command_marker == 0x1a741800 /* DYLIB_USE_MARKER */) {
5150 offset += 4; /* uint32_t current_version */
5151 offset += 4; /* uint32_t compat_version */
5152 uint32_t flags = m_data.GetU32(&offset);
5153 // If this LC_LOAD_DYLIB is marked delay-init,
5154 // don't report it as a dependent library -- it
5155 // may be loaded in the process at some point,
5156 // but will most likely not be load at launch.
5157 if (flags & 0x08 /* DYLIB_USE_DELAYED_INIT */)
5158 is_delayed_init = true;
5159 }
5160 const char *path = m_data.PeekCStr(name_offset);
5161 if (path && !is_delayed_init) {
5162 if (load_cmd.cmd == LC_RPATH)
5163 rpath_paths.push_back(path);
5164 else {
5165 if (path[0] == '@') {
5166 if (strncmp(path, "@rpath", strlen("@rpath")) == 0)
5167 rpath_relative_paths.push_back(path + strlen("@rpath"));
5168 else if (strncmp(path, "@executable_path",
5169 strlen("@executable_path")) == 0)
5170 at_exec_relative_paths.push_back(path +
5171 strlen("@executable_path"));
5172 } else {
5173 FileSpec file_spec(path);
5174 if (files.AppendIfUnique(file_spec))
5175 count++;
5176 }
5177 }
5178 }
5179 } break;
5180
5181 default:
5182 break;
5183 }
5184 offset = cmd_offset + load_cmd.cmdsize;
5185 }
5186
5187 FileSpec this_file_spec(m_file);
5188 FileSystem::Instance().Resolve(this_file_spec);
5189
5190 if (!rpath_paths.empty()) {
5191 // Fixup all LC_RPATH values to be absolute paths
5192 std::string loader_path("@loader_path");
5193 std::string executable_path("@executable_path");
5194 for (auto &rpath : rpath_paths) {
5195 if (llvm::StringRef(rpath).starts_with(loader_path)) {
5196 rpath.erase(0, loader_path.size());
5197 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5198 } else if (llvm::StringRef(rpath).starts_with(executable_path)) {
5199 rpath.erase(0, executable_path.size());
5200 rpath.insert(0, this_file_spec.GetDirectory().GetCString());
5201 }
5202 }
5203
5204 for (const auto &rpath_relative_path : rpath_relative_paths) {
5205 for (const auto &rpath : rpath_paths) {
5206 std::string path = rpath;
5207 path += rpath_relative_path;
5208 // It is OK to resolve this path because we must find a file on disk
5209 // for us to accept it anyway if it is rpath relative.
5210 FileSpec file_spec(path);
5211 FileSystem::Instance().Resolve(file_spec);
5212 if (FileSystem::Instance().Exists(file_spec) &&
5213 files.AppendIfUnique(file_spec)) {
5214 count++;
5215 break;
5216 }
5217 }
5218 }
5219 }
5220
5221 // We may have @executable_paths but no RPATHS. Figure those out here.
5222 // Only do this if this object file is the executable. We have no way to
5223 // get back to the actual executable otherwise, so we won't get the right
5224 // path.
5225 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) {
5226 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent();
5227 for (const auto &at_exec_relative_path : at_exec_relative_paths) {
5228 FileSpec file_spec =
5229 exec_dir.CopyByAppendingPathComponent(at_exec_relative_path);
5230 if (FileSystem::Instance().Exists(file_spec) &&
5231 files.AppendIfUnique(file_spec))
5232 count++;
5233 }
5234 }
5235 }
5236 return count;
5237}
5238
5240 // If the object file is not an executable it can't hold the entry point.
5241 // m_entry_point_address is initialized to an invalid address, so we can just
5242<