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