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