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