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