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