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