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