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