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