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