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