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