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