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