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