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