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