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