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