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()->IsInMemory()) { 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 LLDB_SCOPED_TIMERF("ObjectFileMachO::ParseSymtab () module = %s", 2165 m_file.GetFilename().AsCString("")); 2166 ModuleSP module_sp(GetModule()); 2167 if (!module_sp) 2168 return 0; 2169 2170 struct symtab_command symtab_load_command = {0, 0, 0, 0, 0, 0}; 2171 struct linkedit_data_command function_starts_load_command = {0, 0, 0, 0}; 2172 struct dyld_info_command dyld_info = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 2173 // The data element of type bool indicates that this entry is thumb 2174 // code. 2175 typedef AddressDataArray<lldb::addr_t, bool, 100> FunctionStarts; 2176 2177 // Record the address of every function/data that we add to the symtab. 2178 // We add symbols to the table in the order of most information (nlist 2179 // records) to least (function starts), and avoid duplicating symbols 2180 // via this set. 2181 std::set<addr_t> symbols_added; 2182 FunctionStarts function_starts; 2183 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 2184 uint32_t i; 2185 FileSpecList dylib_files; 2186 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS)); 2187 llvm::StringRef g_objc_v2_prefix_class("_OBJC_CLASS_$_"); 2188 llvm::StringRef g_objc_v2_prefix_metaclass("_OBJC_METACLASS_$_"); 2189 llvm::StringRef g_objc_v2_prefix_ivar("_OBJC_IVAR_$_"); 2190 2191 for (i = 0; i < m_header.ncmds; ++i) { 2192 const lldb::offset_t cmd_offset = offset; 2193 // Read in the load command and load command size 2194 struct load_command lc; 2195 if (m_data.GetU32(&offset, &lc, 2) == nullptr) 2196 break; 2197 // Watch for the symbol table load command 2198 switch (lc.cmd) { 2199 case LC_SYMTAB: 2200 symtab_load_command.cmd = lc.cmd; 2201 symtab_load_command.cmdsize = lc.cmdsize; 2202 // Read in the rest of the symtab load command 2203 if (m_data.GetU32(&offset, &symtab_load_command.symoff, 4) == 2204 nullptr) // fill in symoff, nsyms, stroff, strsize fields 2205 return 0; 2206 break; 2207 2208 case LC_DYLD_INFO: 2209 case LC_DYLD_INFO_ONLY: 2210 if (m_data.GetU32(&offset, &dyld_info.rebase_off, 10)) { 2211 dyld_info.cmd = lc.cmd; 2212 dyld_info.cmdsize = lc.cmdsize; 2213 } else { 2214 memset(&dyld_info, 0, sizeof(dyld_info)); 2215 } 2216 break; 2217 2218 case LC_LOAD_DYLIB: 2219 case LC_LOAD_WEAK_DYLIB: 2220 case LC_REEXPORT_DYLIB: 2221 case LC_LOADFVMLIB: 2222 case LC_LOAD_UPWARD_DYLIB: { 2223 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset); 2224 const char *path = m_data.PeekCStr(name_offset); 2225 if (path) { 2226 FileSpec file_spec(path); 2227 // Strip the path if there is @rpath, @executable, etc so we just use 2228 // the basename 2229 if (path[0] == '@') 2230 file_spec.GetDirectory().Clear(); 2231 2232 if (lc.cmd == LC_REEXPORT_DYLIB) { 2233 m_reexported_dylibs.AppendIfUnique(file_spec); 2234 } 2235 2236 dylib_files.Append(file_spec); 2237 } 2238 } break; 2239 2240 case LC_FUNCTION_STARTS: 2241 function_starts_load_command.cmd = lc.cmd; 2242 function_starts_load_command.cmdsize = lc.cmdsize; 2243 if (m_data.GetU32(&offset, &function_starts_load_command.dataoff, 2) == 2244 nullptr) // fill in symoff, nsyms, stroff, strsize fields 2245 memset(&function_starts_load_command, 0, 2246 sizeof(function_starts_load_command)); 2247 break; 2248 2249 default: 2250 break; 2251 } 2252 offset = cmd_offset + lc.cmdsize; 2253 } 2254 2255 if (!symtab_load_command.cmd) 2256 return 0; 2257 2258 Symtab *symtab = m_symtab_up.get(); 2259 SectionList *section_list = GetSectionList(); 2260 if (section_list == nullptr) 2261 return 0; 2262 2263 const uint32_t addr_byte_size = m_data.GetAddressByteSize(); 2264 const ByteOrder byte_order = m_data.GetByteOrder(); 2265 bool bit_width_32 = addr_byte_size == 4; 2266 const size_t nlist_byte_size = 2267 bit_width_32 ? sizeof(struct nlist) : sizeof(struct nlist_64); 2268 2269 DataExtractor nlist_data(nullptr, 0, byte_order, addr_byte_size); 2270 DataExtractor strtab_data(nullptr, 0, byte_order, addr_byte_size); 2271 DataExtractor function_starts_data(nullptr, 0, byte_order, addr_byte_size); 2272 DataExtractor indirect_symbol_index_data(nullptr, 0, byte_order, 2273 addr_byte_size); 2274 DataExtractor dyld_trie_data(nullptr, 0, byte_order, addr_byte_size); 2275 2276 const addr_t nlist_data_byte_size = 2277 symtab_load_command.nsyms * nlist_byte_size; 2278 const addr_t strtab_data_byte_size = symtab_load_command.strsize; 2279 addr_t strtab_addr = LLDB_INVALID_ADDRESS; 2280 2281 ProcessSP process_sp(m_process_wp.lock()); 2282 Process *process = process_sp.get(); 2283 2284 uint32_t memory_module_load_level = eMemoryModuleLoadLevelComplete; 2285 bool is_shared_cache_image = m_header.flags & MH_DYLIB_IN_CACHE; 2286 bool is_local_shared_cache_image = is_shared_cache_image && !IsInMemory(); 2287 SectionSP linkedit_section_sp( 2288 section_list->FindSectionByName(GetSegmentNameLINKEDIT())); 2289 2290 if (process && m_header.filetype != llvm::MachO::MH_OBJECT && 2291 !is_local_shared_cache_image) { 2292 Target &target = process->GetTarget(); 2293 2294 memory_module_load_level = target.GetMemoryModuleLoadLevel(); 2295 2296 // Reading mach file from memory in a process or core file... 2297 2298 if (linkedit_section_sp) { 2299 addr_t linkedit_load_addr = 2300 linkedit_section_sp->GetLoadBaseAddress(&target); 2301 if (linkedit_load_addr == LLDB_INVALID_ADDRESS) { 2302 // We might be trying to access the symbol table before the 2303 // __LINKEDIT's load address has been set in the target. We can't 2304 // fail to read the symbol table, so calculate the right address 2305 // manually 2306 linkedit_load_addr = CalculateSectionLoadAddressForMemoryImage( 2307 m_memory_addr, GetMachHeaderSection(), linkedit_section_sp.get()); 2308 } 2309 2310 const addr_t linkedit_file_offset = linkedit_section_sp->GetFileOffset(); 2311 const addr_t symoff_addr = linkedit_load_addr + 2312 symtab_load_command.symoff - 2313 linkedit_file_offset; 2314 strtab_addr = linkedit_load_addr + symtab_load_command.stroff - 2315 linkedit_file_offset; 2316 2317 // Always load dyld - the dynamic linker - from memory if we didn't 2318 // find a binary anywhere else. lldb will not register 2319 // dylib/framework/bundle loads/unloads if we don't have the dyld 2320 // symbols, we force dyld to load from memory despite the user's 2321 // target.memory-module-load-level setting. 2322 if (memory_module_load_level == eMemoryModuleLoadLevelComplete || 2323 m_header.filetype == llvm::MachO::MH_DYLINKER) { 2324 DataBufferSP nlist_data_sp( 2325 ReadMemory(process_sp, symoff_addr, nlist_data_byte_size)); 2326 if (nlist_data_sp) 2327 nlist_data.SetData(nlist_data_sp, 0, nlist_data_sp->GetByteSize()); 2328 if (m_dysymtab.nindirectsyms != 0) { 2329 const addr_t indirect_syms_addr = linkedit_load_addr + 2330 m_dysymtab.indirectsymoff - 2331 linkedit_file_offset; 2332 DataBufferSP indirect_syms_data_sp(ReadMemory( 2333 process_sp, indirect_syms_addr, m_dysymtab.nindirectsyms * 4)); 2334 if (indirect_syms_data_sp) 2335 indirect_symbol_index_data.SetData( 2336 indirect_syms_data_sp, 0, 2337 indirect_syms_data_sp->GetByteSize()); 2338 // If this binary is outside the shared cache, 2339 // cache the string table. 2340 // Binaries in the shared cache all share a giant string table, 2341 // and we can't share the string tables across multiple 2342 // ObjectFileMachO's, so we'd end up re-reading this mega-strtab 2343 // for every binary in the shared cache - it would be a big perf 2344 // problem. For binaries outside the shared cache, it's faster to 2345 // read the entire strtab at once instead of piece-by-piece as we 2346 // process the nlist records. 2347 if (!is_shared_cache_image) { 2348 DataBufferSP strtab_data_sp( 2349 ReadMemory(process_sp, strtab_addr, strtab_data_byte_size)); 2350 if (strtab_data_sp) { 2351 strtab_data.SetData(strtab_data_sp, 0, 2352 strtab_data_sp->GetByteSize()); 2353 } 2354 } 2355 } 2356 if (memory_module_load_level >= eMemoryModuleLoadLevelPartial) { 2357 if (function_starts_load_command.cmd) { 2358 const addr_t func_start_addr = 2359 linkedit_load_addr + function_starts_load_command.dataoff - 2360 linkedit_file_offset; 2361 DataBufferSP func_start_data_sp( 2362 ReadMemory(process_sp, func_start_addr, 2363 function_starts_load_command.datasize)); 2364 if (func_start_data_sp) 2365 function_starts_data.SetData(func_start_data_sp, 0, 2366 func_start_data_sp->GetByteSize()); 2367 } 2368 } 2369 } 2370 } 2371 } else { 2372 if (is_local_shared_cache_image) { 2373 // The load commands in shared cache images are relative to the 2374 // beginning of the shared cache, not the library image. The 2375 // data we get handed when creating the ObjectFileMachO starts 2376 // at the beginning of a specific library and spans to the end 2377 // of the cache to be able to reach the shared LINKEDIT 2378 // segments. We need to convert the load command offsets to be 2379 // relative to the beginning of our specific image. 2380 lldb::addr_t linkedit_offset = linkedit_section_sp->GetFileOffset(); 2381 lldb::offset_t linkedit_slide = 2382 linkedit_offset - m_linkedit_original_offset; 2383 symtab_load_command.symoff += linkedit_slide; 2384 symtab_load_command.stroff += linkedit_slide; 2385 dyld_info.export_off += linkedit_slide; 2386 m_dysymtab.indirectsymoff += linkedit_slide; 2387 function_starts_load_command.dataoff += linkedit_slide; 2388 } 2389 2390 nlist_data.SetData(m_data, symtab_load_command.symoff, 2391 nlist_data_byte_size); 2392 strtab_data.SetData(m_data, symtab_load_command.stroff, 2393 strtab_data_byte_size); 2394 2395 if (dyld_info.export_size > 0) { 2396 dyld_trie_data.SetData(m_data, dyld_info.export_off, 2397 dyld_info.export_size); 2398 } 2399 2400 if (m_dysymtab.nindirectsyms != 0) { 2401 indirect_symbol_index_data.SetData(m_data, m_dysymtab.indirectsymoff, 2402 m_dysymtab.nindirectsyms * 4); 2403 } 2404 if (function_starts_load_command.cmd) { 2405 function_starts_data.SetData(m_data, function_starts_load_command.dataoff, 2406 function_starts_load_command.datasize); 2407 } 2408 } 2409 2410 const bool have_strtab_data = strtab_data.GetByteSize() > 0; 2411 2412 ConstString g_segment_name_TEXT = GetSegmentNameTEXT(); 2413 ConstString g_segment_name_DATA = GetSegmentNameDATA(); 2414 ConstString g_segment_name_DATA_DIRTY = GetSegmentNameDATA_DIRTY(); 2415 ConstString g_segment_name_DATA_CONST = GetSegmentNameDATA_CONST(); 2416 ConstString g_segment_name_OBJC = GetSegmentNameOBJC(); 2417 ConstString g_section_name_eh_frame = GetSectionNameEHFrame(); 2418 SectionSP text_section_sp( 2419 section_list->FindSectionByName(g_segment_name_TEXT)); 2420 SectionSP data_section_sp( 2421 section_list->FindSectionByName(g_segment_name_DATA)); 2422 SectionSP data_dirty_section_sp( 2423 section_list->FindSectionByName(g_segment_name_DATA_DIRTY)); 2424 SectionSP data_const_section_sp( 2425 section_list->FindSectionByName(g_segment_name_DATA_CONST)); 2426 SectionSP objc_section_sp( 2427 section_list->FindSectionByName(g_segment_name_OBJC)); 2428 SectionSP eh_frame_section_sp; 2429 if (text_section_sp.get()) 2430 eh_frame_section_sp = text_section_sp->GetChildren().FindSectionByName( 2431 g_section_name_eh_frame); 2432 else 2433 eh_frame_section_sp = 2434 section_list->FindSectionByName(g_section_name_eh_frame); 2435 2436 const bool is_arm = (m_header.cputype == llvm::MachO::CPU_TYPE_ARM); 2437 const bool always_thumb = GetArchitecture().IsAlwaysThumbInstructions(); 2438 2439 // lldb works best if it knows the start address of all functions in a 2440 // module. Linker symbols or debug info are normally the best source of 2441 // information for start addr / size but they may be stripped in a released 2442 // binary. Two additional sources of information exist in Mach-O binaries: 2443 // LC_FUNCTION_STARTS - a list of ULEB128 encoded offsets of each 2444 // function's start address in the 2445 // binary, relative to the text section. 2446 // eh_frame - the eh_frame FDEs have the start addr & size of 2447 // each function 2448 // LC_FUNCTION_STARTS is the fastest source to read in, and is present on 2449 // all modern binaries. 2450 // Binaries built to run on older releases may need to use eh_frame 2451 // information. 2452 2453 if (text_section_sp && function_starts_data.GetByteSize()) { 2454 FunctionStarts::Entry function_start_entry; 2455 function_start_entry.data = false; 2456 lldb::offset_t function_start_offset = 0; 2457 function_start_entry.addr = text_section_sp->GetFileAddress(); 2458 uint64_t delta; 2459 while ((delta = function_starts_data.GetULEB128(&function_start_offset)) > 2460 0) { 2461 // Now append the current entry 2462 function_start_entry.addr += delta; 2463 if (is_arm) { 2464 if (function_start_entry.addr & 1) { 2465 function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK; 2466 function_start_entry.data = true; 2467 } else if (always_thumb) { 2468 function_start_entry.data = true; 2469 } 2470 } 2471 function_starts.Append(function_start_entry); 2472 } 2473 } else { 2474 // If m_type is eTypeDebugInfo, then this is a dSYM - it will have the 2475 // load command claiming an eh_frame but it doesn't actually have the 2476 // eh_frame content. And if we have a dSYM, we don't need to do any of 2477 // this fill-in-the-missing-symbols works anyway - the debug info should 2478 // give us all the functions in the module. 2479 if (text_section_sp.get() && eh_frame_section_sp.get() && 2480 m_type != eTypeDebugInfo) { 2481 DWARFCallFrameInfo eh_frame(*this, eh_frame_section_sp, 2482 DWARFCallFrameInfo::EH); 2483 DWARFCallFrameInfo::FunctionAddressAndSizeVector functions; 2484 eh_frame.GetFunctionAddressAndSizeVector(functions); 2485 addr_t text_base_addr = text_section_sp->GetFileAddress(); 2486 size_t count = functions.GetSize(); 2487 for (size_t i = 0; i < count; ++i) { 2488 const DWARFCallFrameInfo::FunctionAddressAndSizeVector::Entry *func = 2489 functions.GetEntryAtIndex(i); 2490 if (func) { 2491 FunctionStarts::Entry function_start_entry; 2492 function_start_entry.addr = func->base - text_base_addr; 2493 if (is_arm) { 2494 if (function_start_entry.addr & 1) { 2495 function_start_entry.addr &= THUMB_ADDRESS_BIT_MASK; 2496 function_start_entry.data = true; 2497 } else if (always_thumb) { 2498 function_start_entry.data = true; 2499 } 2500 } 2501 function_starts.Append(function_start_entry); 2502 } 2503 } 2504 } 2505 } 2506 2507 const size_t function_starts_count = function_starts.GetSize(); 2508 2509 // For user process binaries (executables, dylibs, frameworks, bundles), if 2510 // we don't have LC_FUNCTION_STARTS/eh_frame section in this binary, we're 2511 // going to assume the binary has been stripped. Don't allow assembly 2512 // language instruction emulation because we don't know proper function 2513 // start boundaries. 2514 // 2515 // For all other types of binaries (kernels, stand-alone bare board 2516 // binaries, kexts), they may not have LC_FUNCTION_STARTS / eh_frame 2517 // sections - we should not make any assumptions about them based on that. 2518 if (function_starts_count == 0 && CalculateStrata() == eStrataUser) { 2519 m_allow_assembly_emulation_unwind_plans = false; 2520 Log *unwind_or_symbol_log(lldb_private::GetLogIfAnyCategoriesSet( 2521 LIBLLDB_LOG_SYMBOLS | LIBLLDB_LOG_UNWIND)); 2522 2523 if (unwind_or_symbol_log) 2524 module_sp->LogMessage( 2525 unwind_or_symbol_log, 2526 "no LC_FUNCTION_STARTS, will not allow assembly profiled unwinds"); 2527 } 2528 2529 const user_id_t TEXT_eh_frame_sectID = eh_frame_section_sp.get() 2530 ? eh_frame_section_sp->GetID() 2531 : static_cast<user_id_t>(NO_SECT); 2532 2533 lldb::offset_t nlist_data_offset = 0; 2534 2535 uint32_t N_SO_index = UINT32_MAX; 2536 2537 MachSymtabSectionInfo section_info(section_list); 2538 std::vector<uint32_t> N_FUN_indexes; 2539 std::vector<uint32_t> N_NSYM_indexes; 2540 std::vector<uint32_t> N_INCL_indexes; 2541 std::vector<uint32_t> N_BRAC_indexes; 2542 std::vector<uint32_t> N_COMM_indexes; 2543 typedef std::multimap<uint64_t, uint32_t> ValueToSymbolIndexMap; 2544 typedef llvm::DenseMap<uint32_t, uint32_t> NListIndexToSymbolIndexMap; 2545 typedef llvm::DenseMap<const char *, uint32_t> ConstNameToSymbolIndexMap; 2546 ValueToSymbolIndexMap N_FUN_addr_to_sym_idx; 2547 ValueToSymbolIndexMap N_STSYM_addr_to_sym_idx; 2548 ConstNameToSymbolIndexMap N_GSYM_name_to_sym_idx; 2549 // Any symbols that get merged into another will get an entry in this map 2550 // so we know 2551 NListIndexToSymbolIndexMap m_nlist_idx_to_sym_idx; 2552 uint32_t nlist_idx = 0; 2553 Symbol *symbol_ptr = nullptr; 2554 2555 uint32_t sym_idx = 0; 2556 Symbol *sym = nullptr; 2557 size_t num_syms = 0; 2558 std::string memory_symbol_name; 2559 uint32_t unmapped_local_symbols_found = 0; 2560 2561 std::vector<TrieEntryWithOffset> reexport_trie_entries; 2562 std::vector<TrieEntryWithOffset> external_sym_trie_entries; 2563 std::set<lldb::addr_t> resolver_addresses; 2564 2565 if (dyld_trie_data.GetByteSize() > 0) { 2566 ConstString text_segment_name("__TEXT"); 2567 SectionSP text_segment_sp = 2568 GetSectionList()->FindSectionByName(text_segment_name); 2569 lldb::addr_t text_segment_file_addr = LLDB_INVALID_ADDRESS; 2570 if (text_segment_sp) 2571 text_segment_file_addr = text_segment_sp->GetFileAddress(); 2572 std::vector<llvm::StringRef> nameSlices; 2573 ParseTrieEntries(dyld_trie_data, 0, is_arm, text_segment_file_addr, 2574 nameSlices, resolver_addresses, reexport_trie_entries, 2575 external_sym_trie_entries); 2576 } 2577 2578 typedef std::set<ConstString> IndirectSymbols; 2579 IndirectSymbols indirect_symbol_names; 2580 2581 #if TARGET_OS_IPHONE 2582 2583 // Some recent builds of the dyld_shared_cache (hereafter: DSC) have been 2584 // optimized by moving LOCAL symbols out of the memory mapped portion of 2585 // the DSC. The symbol information has all been retained, but it isn't 2586 // available in the normal nlist data. However, there *are* duplicate 2587 // entries of *some* 2588 // LOCAL symbols in the normal nlist data. To handle this situation 2589 // correctly, we must first attempt 2590 // to parse any DSC unmapped symbol information. If we find any, we set a 2591 // flag that tells the normal nlist parser to ignore all LOCAL symbols. 2592 2593 if (m_header.flags & MH_DYLIB_IN_CACHE) { 2594 // Before we can start mapping the DSC, we need to make certain the 2595 // target process is actually using the cache we can find. 2596 2597 // Next we need to determine the correct path for the dyld shared cache. 2598 2599 ArchSpec header_arch = GetArchitecture(); 2600 char dsc_path[PATH_MAX]; 2601 char dsc_path_development[PATH_MAX]; 2602 2603 snprintf( 2604 dsc_path, sizeof(dsc_path), "%s%s%s", 2605 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR 2606 */ 2607 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */ 2608 header_arch.GetArchitectureName()); 2609 2610 snprintf( 2611 dsc_path_development, sizeof(dsc_path), "%s%s%s%s", 2612 "/System/Library/Caches/com.apple.dyld/", /* IPHONE_DYLD_SHARED_CACHE_DIR 2613 */ 2614 "dyld_shared_cache_", /* DYLD_SHARED_CACHE_BASE_NAME */ 2615 header_arch.GetArchitectureName(), ".development"); 2616 2617 FileSpec dsc_nondevelopment_filespec(dsc_path); 2618 FileSpec dsc_development_filespec(dsc_path_development); 2619 FileSpec dsc_filespec; 2620 2621 UUID dsc_uuid; 2622 UUID process_shared_cache_uuid; 2623 addr_t process_shared_cache_base_addr; 2624 2625 if (process) { 2626 GetProcessSharedCacheUUID(process, process_shared_cache_base_addr, 2627 process_shared_cache_uuid); 2628 } 2629 2630 // First see if we can find an exact match for the inferior process 2631 // shared cache UUID in the development or non-development shared caches 2632 // on disk. 2633 if (process_shared_cache_uuid.IsValid()) { 2634 if (FileSystem::Instance().Exists(dsc_development_filespec)) { 2635 UUID dsc_development_uuid = GetSharedCacheUUID( 2636 dsc_development_filespec, byte_order, addr_byte_size); 2637 if (dsc_development_uuid.IsValid() && 2638 dsc_development_uuid == process_shared_cache_uuid) { 2639 dsc_filespec = dsc_development_filespec; 2640 dsc_uuid = dsc_development_uuid; 2641 } 2642 } 2643 if (!dsc_uuid.IsValid() && 2644 FileSystem::Instance().Exists(dsc_nondevelopment_filespec)) { 2645 UUID dsc_nondevelopment_uuid = GetSharedCacheUUID( 2646 dsc_nondevelopment_filespec, byte_order, addr_byte_size); 2647 if (dsc_nondevelopment_uuid.IsValid() && 2648 dsc_nondevelopment_uuid == process_shared_cache_uuid) { 2649 dsc_filespec = dsc_nondevelopment_filespec; 2650 dsc_uuid = dsc_nondevelopment_uuid; 2651 } 2652 } 2653 } 2654 2655 // Failing a UUID match, prefer the development dyld_shared cache if both 2656 // are present. 2657 if (!FileSystem::Instance().Exists(dsc_filespec)) { 2658 if (FileSystem::Instance().Exists(dsc_development_filespec)) { 2659 dsc_filespec = dsc_development_filespec; 2660 } else { 2661 dsc_filespec = dsc_nondevelopment_filespec; 2662 } 2663 } 2664 2665 /* The dyld_cache_header has a pointer to the 2666 dyld_cache_local_symbols_info structure (localSymbolsOffset). 2667 The dyld_cache_local_symbols_info structure gives us three things: 2668 1. The start and count of the nlist records in the dyld_shared_cache 2669 file 2670 2. The start and size of the strings for these nlist records 2671 3. The start and count of dyld_cache_local_symbols_entry entries 2672 2673 There is one dyld_cache_local_symbols_entry per dylib/framework in the 2674 dyld shared cache. 2675 The "dylibOffset" field is the Mach-O header of this dylib/framework in 2676 the dyld shared cache. 2677 The dyld_cache_local_symbols_entry also lists the start of this 2678 dylib/framework's nlist records 2679 and the count of how many nlist records there are for this 2680 dylib/framework. 2681 */ 2682 2683 // Process the dyld shared cache header to find the unmapped symbols 2684 2685 DataBufferSP dsc_data_sp = MapFileData( 2686 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_header_v1), 0); 2687 if (!dsc_uuid.IsValid()) { 2688 dsc_uuid = GetSharedCacheUUID(dsc_filespec, byte_order, addr_byte_size); 2689 } 2690 if (dsc_data_sp) { 2691 DataExtractor dsc_header_data(dsc_data_sp, byte_order, addr_byte_size); 2692 2693 bool uuid_match = true; 2694 if (dsc_uuid.IsValid() && process) { 2695 if (process_shared_cache_uuid.IsValid() && 2696 dsc_uuid != process_shared_cache_uuid) { 2697 // The on-disk dyld_shared_cache file is not the same as the one in 2698 // this process' memory, don't use it. 2699 uuid_match = false; 2700 ModuleSP module_sp(GetModule()); 2701 if (module_sp) 2702 module_sp->ReportWarning("process shared cache does not match " 2703 "on-disk dyld_shared_cache file, some " 2704 "symbol names will be missing."); 2705 } 2706 } 2707 2708 offset = offsetof(struct lldb_copy_dyld_cache_header_v1, mappingOffset); 2709 2710 uint32_t mappingOffset = dsc_header_data.GetU32(&offset); 2711 2712 // If the mappingOffset points to a location inside the header, we've 2713 // opened an old dyld shared cache, and should not proceed further. 2714 if (uuid_match && 2715 mappingOffset >= sizeof(struct lldb_copy_dyld_cache_header_v1)) { 2716 2717 DataBufferSP dsc_mapping_info_data_sp = MapFileData( 2718 dsc_filespec, sizeof(struct lldb_copy_dyld_cache_mapping_info), 2719 mappingOffset); 2720 2721 DataExtractor dsc_mapping_info_data(dsc_mapping_info_data_sp, 2722 byte_order, addr_byte_size); 2723 offset = 0; 2724 2725 // The File addresses (from the in-memory Mach-O load commands) for 2726 // the shared libraries in the shared library cache need to be 2727 // adjusted by an offset to match up with the dylibOffset identifying 2728 // field in the dyld_cache_local_symbol_entry's. This offset is 2729 // recorded in mapping_offset_value. 2730 const uint64_t mapping_offset_value = 2731 dsc_mapping_info_data.GetU64(&offset); 2732 2733 offset = 2734 offsetof(struct lldb_copy_dyld_cache_header_v1, localSymbolsOffset); 2735 uint64_t localSymbolsOffset = dsc_header_data.GetU64(&offset); 2736 uint64_t localSymbolsSize = dsc_header_data.GetU64(&offset); 2737 2738 if (localSymbolsOffset && localSymbolsSize) { 2739 // Map the local symbols 2740 DataBufferSP dsc_local_symbols_data_sp = 2741 MapFileData(dsc_filespec, localSymbolsSize, localSymbolsOffset); 2742 2743 if (dsc_local_symbols_data_sp) { 2744 DataExtractor dsc_local_symbols_data(dsc_local_symbols_data_sp, 2745 byte_order, addr_byte_size); 2746 2747 offset = 0; 2748 2749 typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap; 2750 typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName; 2751 UndefinedNameToDescMap undefined_name_to_desc; 2752 SymbolIndexToName reexport_shlib_needs_fixup; 2753 2754 // Read the local_symbols_infos struct in one shot 2755 struct lldb_copy_dyld_cache_local_symbols_info local_symbols_info; 2756 dsc_local_symbols_data.GetU32(&offset, 2757 &local_symbols_info.nlistOffset, 6); 2758 2759 SectionSP text_section_sp( 2760 section_list->FindSectionByName(GetSegmentNameTEXT())); 2761 2762 uint32_t header_file_offset = 2763 (text_section_sp->GetFileAddress() - mapping_offset_value); 2764 2765 offset = local_symbols_info.entriesOffset; 2766 for (uint32_t entry_index = 0; 2767 entry_index < local_symbols_info.entriesCount; entry_index++) { 2768 struct lldb_copy_dyld_cache_local_symbols_entry 2769 local_symbols_entry; 2770 local_symbols_entry.dylibOffset = 2771 dsc_local_symbols_data.GetU32(&offset); 2772 local_symbols_entry.nlistStartIndex = 2773 dsc_local_symbols_data.GetU32(&offset); 2774 local_symbols_entry.nlistCount = 2775 dsc_local_symbols_data.GetU32(&offset); 2776 2777 if (header_file_offset == local_symbols_entry.dylibOffset) { 2778 unmapped_local_symbols_found = local_symbols_entry.nlistCount; 2779 2780 // The normal nlist code cannot correctly size the Symbols 2781 // array, we need to allocate it here. 2782 sym = symtab->Resize( 2783 symtab_load_command.nsyms + m_dysymtab.nindirectsyms + 2784 unmapped_local_symbols_found - m_dysymtab.nlocalsym); 2785 num_syms = symtab->GetNumSymbols(); 2786 2787 nlist_data_offset = 2788 local_symbols_info.nlistOffset + 2789 (nlist_byte_size * local_symbols_entry.nlistStartIndex); 2790 uint32_t string_table_offset = local_symbols_info.stringsOffset; 2791 2792 for (uint32_t nlist_index = 0; 2793 nlist_index < local_symbols_entry.nlistCount; 2794 nlist_index++) { 2795 ///////////////////////////// 2796 { 2797 llvm::Optional<struct nlist_64> nlist_maybe = 2798 ParseNList(dsc_local_symbols_data, nlist_data_offset, 2799 nlist_byte_size); 2800 if (!nlist_maybe) 2801 break; 2802 struct nlist_64 nlist = *nlist_maybe; 2803 2804 SymbolType type = eSymbolTypeInvalid; 2805 const char *symbol_name = dsc_local_symbols_data.PeekCStr( 2806 string_table_offset + nlist.n_strx); 2807 2808 if (symbol_name == NULL) { 2809 // No symbol should be NULL, even the symbols with no 2810 // string values should have an offset zero which 2811 // points to an empty C-string 2812 Host::SystemLog( 2813 Host::eSystemLogError, 2814 "error: DSC unmapped local symbol[%u] has invalid " 2815 "string table offset 0x%x in %s, ignoring symbol\n", 2816 entry_index, nlist.n_strx, 2817 module_sp->GetFileSpec().GetPath().c_str()); 2818 continue; 2819 } 2820 if (symbol_name[0] == '\0') 2821 symbol_name = NULL; 2822 2823 const char *symbol_name_non_abi_mangled = NULL; 2824 2825 SectionSP symbol_section; 2826 uint32_t symbol_byte_size = 0; 2827 bool add_nlist = true; 2828 bool is_debug = ((nlist.n_type & N_STAB) != 0); 2829 bool demangled_is_synthesized = false; 2830 bool is_gsym = false; 2831 bool set_value = true; 2832 2833 assert(sym_idx < num_syms); 2834 2835 sym[sym_idx].SetDebug(is_debug); 2836 2837 if (is_debug) { 2838 switch (nlist.n_type) { 2839 case N_GSYM: 2840 // global symbol: name,,NO_SECT,type,0 2841 // Sometimes the N_GSYM value contains the address. 2842 2843 // FIXME: In the .o files, we have a GSYM and a debug 2844 // symbol for all the ObjC data. They 2845 // have the same address, but we want to ensure that 2846 // we always find only the real symbol, 'cause we 2847 // don't currently correctly attribute the 2848 // GSYM one to the ObjCClass/Ivar/MetaClass 2849 // symbol type. This is a temporary hack to make 2850 // sure the ObjectiveC symbols get treated correctly. 2851 // To do this right, we should coalesce all the GSYM 2852 // & global symbols that have the same address. 2853 2854 is_gsym = true; 2855 sym[sym_idx].SetExternal(true); 2856 2857 if (symbol_name && symbol_name[0] == '_' && 2858 symbol_name[1] == 'O') { 2859 llvm::StringRef symbol_name_ref(symbol_name); 2860 if (symbol_name_ref.startswith( 2861 g_objc_v2_prefix_class)) { 2862 symbol_name_non_abi_mangled = symbol_name + 1; 2863 symbol_name = 2864 symbol_name + g_objc_v2_prefix_class.size(); 2865 type = eSymbolTypeObjCClass; 2866 demangled_is_synthesized = true; 2867 2868 } else if (symbol_name_ref.startswith( 2869 g_objc_v2_prefix_metaclass)) { 2870 symbol_name_non_abi_mangled = symbol_name + 1; 2871 symbol_name = 2872 symbol_name + g_objc_v2_prefix_metaclass.size(); 2873 type = eSymbolTypeObjCMetaClass; 2874 demangled_is_synthesized = true; 2875 } else if (symbol_name_ref.startswith( 2876 g_objc_v2_prefix_ivar)) { 2877 symbol_name_non_abi_mangled = symbol_name + 1; 2878 symbol_name = 2879 symbol_name + g_objc_v2_prefix_ivar.size(); 2880 type = eSymbolTypeObjCIVar; 2881 demangled_is_synthesized = true; 2882 } 2883 } else { 2884 if (nlist.n_value != 0) 2885 symbol_section = section_info.GetSection( 2886 nlist.n_sect, nlist.n_value); 2887 type = eSymbolTypeData; 2888 } 2889 break; 2890 2891 case N_FNAME: 2892 // procedure name (f77 kludge): name,,NO_SECT,0,0 2893 type = eSymbolTypeCompiler; 2894 break; 2895 2896 case N_FUN: 2897 // procedure: name,,n_sect,linenumber,address 2898 if (symbol_name) { 2899 type = eSymbolTypeCode; 2900 symbol_section = section_info.GetSection( 2901 nlist.n_sect, nlist.n_value); 2902 2903 N_FUN_addr_to_sym_idx.insert( 2904 std::make_pair(nlist.n_value, sym_idx)); 2905 // We use the current number of symbols in the 2906 // symbol table in lieu of using nlist_idx in case 2907 // we ever start trimming entries out 2908 N_FUN_indexes.push_back(sym_idx); 2909 } else { 2910 type = eSymbolTypeCompiler; 2911 2912 if (!N_FUN_indexes.empty()) { 2913 // Copy the size of the function into the 2914 // original 2915 // STAB entry so we don't have 2916 // to hunt for it later 2917 symtab->SymbolAtIndex(N_FUN_indexes.back()) 2918 ->SetByteSize(nlist.n_value); 2919 N_FUN_indexes.pop_back(); 2920 // We don't really need the end function STAB as 2921 // it contains the size which we already placed 2922 // with the original symbol, so don't add it if 2923 // we want a minimal symbol table 2924 add_nlist = false; 2925 } 2926 } 2927 break; 2928 2929 case N_STSYM: 2930 // static symbol: name,,n_sect,type,address 2931 N_STSYM_addr_to_sym_idx.insert( 2932 std::make_pair(nlist.n_value, sym_idx)); 2933 symbol_section = section_info.GetSection(nlist.n_sect, 2934 nlist.n_value); 2935 if (symbol_name && symbol_name[0]) { 2936 type = ObjectFile::GetSymbolTypeFromName( 2937 symbol_name + 1, eSymbolTypeData); 2938 } 2939 break; 2940 2941 case N_LCSYM: 2942 // .lcomm symbol: name,,n_sect,type,address 2943 symbol_section = section_info.GetSection(nlist.n_sect, 2944 nlist.n_value); 2945 type = eSymbolTypeCommonBlock; 2946 break; 2947 2948 case N_BNSYM: 2949 // We use the current number of symbols in the symbol 2950 // table in lieu of using nlist_idx in case we ever 2951 // start trimming entries out Skip these if we want 2952 // minimal symbol tables 2953 add_nlist = false; 2954 break; 2955 2956 case N_ENSYM: 2957 // Set the size of the N_BNSYM to the terminating 2958 // index of this N_ENSYM so that we can always skip 2959 // the entire symbol if we need to navigate more 2960 // quickly at the source level when parsing STABS 2961 // Skip these if we want minimal symbol tables 2962 add_nlist = false; 2963 break; 2964 2965 case N_OPT: 2966 // emitted with gcc2_compiled and in gcc source 2967 type = eSymbolTypeCompiler; 2968 break; 2969 2970 case N_RSYM: 2971 // register sym: name,,NO_SECT,type,register 2972 type = eSymbolTypeVariable; 2973 break; 2974 2975 case N_SLINE: 2976 // src line: 0,,n_sect,linenumber,address 2977 symbol_section = section_info.GetSection(nlist.n_sect, 2978 nlist.n_value); 2979 type = eSymbolTypeLineEntry; 2980 break; 2981 2982 case N_SSYM: 2983 // structure elt: name,,NO_SECT,type,struct_offset 2984 type = eSymbolTypeVariableType; 2985 break; 2986 2987 case N_SO: 2988 // source file name 2989 type = eSymbolTypeSourceFile; 2990 if (symbol_name == NULL) { 2991 add_nlist = false; 2992 if (N_SO_index != UINT32_MAX) { 2993 // Set the size of the N_SO to the terminating 2994 // index of this N_SO so that we can always skip 2995 // the entire N_SO if we need to navigate more 2996 // quickly at the source level when parsing STABS 2997 symbol_ptr = symtab->SymbolAtIndex(N_SO_index); 2998 symbol_ptr->SetByteSize(sym_idx); 2999 symbol_ptr->SetSizeIsSibling(true); 3000 } 3001 N_NSYM_indexes.clear(); 3002 N_INCL_indexes.clear(); 3003 N_BRAC_indexes.clear(); 3004 N_COMM_indexes.clear(); 3005 N_FUN_indexes.clear(); 3006 N_SO_index = UINT32_MAX; 3007 } else { 3008 // We use the current number of symbols in the 3009 // symbol table in lieu of using nlist_idx in case 3010 // we ever start trimming entries out 3011 const bool N_SO_has_full_path = symbol_name[0] == '/'; 3012 if (N_SO_has_full_path) { 3013 if ((N_SO_index == sym_idx - 1) && 3014 ((sym_idx - 1) < num_syms)) { 3015 // We have two consecutive N_SO entries where 3016 // the first contains a directory and the 3017 // second contains a full path. 3018 sym[sym_idx - 1].GetMangled().SetValue( 3019 ConstString(symbol_name), false); 3020 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1; 3021 add_nlist = false; 3022 } else { 3023 // This is the first entry in a N_SO that 3024 // contains a directory or 3025 // a full path to the source file 3026 N_SO_index = sym_idx; 3027 } 3028 } else if ((N_SO_index == sym_idx - 1) && 3029 ((sym_idx - 1) < num_syms)) { 3030 // This is usually the second N_SO entry that 3031 // contains just the filename, so here we combine 3032 // it with the first one if we are minimizing the 3033 // symbol table 3034 const char *so_path = sym[sym_idx - 1] 3035 .GetMangled() 3036 .GetDemangledName() 3037 .AsCString(); 3038 if (so_path && so_path[0]) { 3039 std::string full_so_path(so_path); 3040 const size_t double_slash_pos = 3041 full_so_path.find("//"); 3042 if (double_slash_pos != std::string::npos) { 3043 // The linker has been generating bad N_SO 3044 // entries with doubled up paths 3045 // in the format "%s%s" where the first 3046 // string in the DW_AT_comp_dir, and the 3047 // second is the directory for the source 3048 // file so you end up with a path that looks 3049 // like "/tmp/src//tmp/src/" 3050 FileSpec so_dir(so_path); 3051 if (!FileSystem::Instance().Exists(so_dir)) { 3052 so_dir.SetFile( 3053 &full_so_path[double_slash_pos + 1], 3054 FileSpec::Style::native); 3055 if (FileSystem::Instance().Exists(so_dir)) { 3056 // Trim off the incorrect path 3057 full_so_path.erase(0, double_slash_pos + 1); 3058 } 3059 } 3060 } 3061 if (*full_so_path.rbegin() != '/') 3062 full_so_path += '/'; 3063 full_so_path += symbol_name; 3064 sym[sym_idx - 1].GetMangled().SetValue( 3065 ConstString(full_so_path.c_str()), false); 3066 add_nlist = false; 3067 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1; 3068 } 3069 } else { 3070 // This could be a relative path to a N_SO 3071 N_SO_index = sym_idx; 3072 } 3073 } 3074 break; 3075 3076 case N_OSO: 3077 // object file name: name,,0,0,st_mtime 3078 type = eSymbolTypeObjectFile; 3079 break; 3080 3081 case N_LSYM: 3082 // local sym: name,,NO_SECT,type,offset 3083 type = eSymbolTypeLocal; 3084 break; 3085 3086 // INCL scopes 3087 case N_BINCL: 3088 // include file beginning: name,,NO_SECT,0,sum We use 3089 // the current number of symbols in the symbol table 3090 // in lieu of using nlist_idx in case we ever start 3091 // trimming entries out 3092 N_INCL_indexes.push_back(sym_idx); 3093 type = eSymbolTypeScopeBegin; 3094 break; 3095 3096 case N_EINCL: 3097 // include file end: name,,NO_SECT,0,0 3098 // Set the size of the N_BINCL to the terminating 3099 // index of this N_EINCL so that we can always skip 3100 // the entire symbol if we need to navigate more 3101 // quickly at the source level when parsing STABS 3102 if (!N_INCL_indexes.empty()) { 3103 symbol_ptr = 3104 symtab->SymbolAtIndex(N_INCL_indexes.back()); 3105 symbol_ptr->SetByteSize(sym_idx + 1); 3106 symbol_ptr->SetSizeIsSibling(true); 3107 N_INCL_indexes.pop_back(); 3108 } 3109 type = eSymbolTypeScopeEnd; 3110 break; 3111 3112 case N_SOL: 3113 // #included file name: name,,n_sect,0,address 3114 type = eSymbolTypeHeaderFile; 3115 3116 // We currently don't use the header files on darwin 3117 add_nlist = false; 3118 break; 3119 3120 case N_PARAMS: 3121 // compiler parameters: name,,NO_SECT,0,0 3122 type = eSymbolTypeCompiler; 3123 break; 3124 3125 case N_VERSION: 3126 // compiler version: name,,NO_SECT,0,0 3127 type = eSymbolTypeCompiler; 3128 break; 3129 3130 case N_OLEVEL: 3131 // compiler -O level: name,,NO_SECT,0,0 3132 type = eSymbolTypeCompiler; 3133 break; 3134 3135 case N_PSYM: 3136 // parameter: name,,NO_SECT,type,offset 3137 type = eSymbolTypeVariable; 3138 break; 3139 3140 case N_ENTRY: 3141 // alternate entry: name,,n_sect,linenumber,address 3142 symbol_section = section_info.GetSection(nlist.n_sect, 3143 nlist.n_value); 3144 type = eSymbolTypeLineEntry; 3145 break; 3146 3147 // Left and Right Braces 3148 case N_LBRAC: 3149 // left bracket: 0,,NO_SECT,nesting level,address We 3150 // use the current number of symbols in the symbol 3151 // table in lieu of using nlist_idx in case we ever 3152 // start trimming entries out 3153 symbol_section = section_info.GetSection(nlist.n_sect, 3154 nlist.n_value); 3155 N_BRAC_indexes.push_back(sym_idx); 3156 type = eSymbolTypeScopeBegin; 3157 break; 3158 3159 case N_RBRAC: 3160 // right bracket: 0,,NO_SECT,nesting level,address 3161 // Set the size of the N_LBRAC to the terminating 3162 // index of this N_RBRAC so that we can always skip 3163 // the entire symbol if we need to navigate more 3164 // quickly at the source level when parsing STABS 3165 symbol_section = section_info.GetSection(nlist.n_sect, 3166 nlist.n_value); 3167 if (!N_BRAC_indexes.empty()) { 3168 symbol_ptr = 3169 symtab->SymbolAtIndex(N_BRAC_indexes.back()); 3170 symbol_ptr->SetByteSize(sym_idx + 1); 3171 symbol_ptr->SetSizeIsSibling(true); 3172 N_BRAC_indexes.pop_back(); 3173 } 3174 type = eSymbolTypeScopeEnd; 3175 break; 3176 3177 case N_EXCL: 3178 // deleted include file: name,,NO_SECT,0,sum 3179 type = eSymbolTypeHeaderFile; 3180 break; 3181 3182 // COMM scopes 3183 case N_BCOMM: 3184 // begin common: name,,NO_SECT,0,0 3185 // We use the current number of symbols in the symbol 3186 // table in lieu of using nlist_idx in case we ever 3187 // start trimming entries out 3188 type = eSymbolTypeScopeBegin; 3189 N_COMM_indexes.push_back(sym_idx); 3190 break; 3191 3192 case N_ECOML: 3193 // end common (local name): 0,,n_sect,0,address 3194 symbol_section = section_info.GetSection(nlist.n_sect, 3195 nlist.n_value); 3196 // Fall through 3197 3198 case N_ECOMM: 3199 // end common: name,,n_sect,0,0 3200 // Set the size of the N_BCOMM to the terminating 3201 // index of this N_ECOMM/N_ECOML so that we can 3202 // always skip the entire symbol if we need to 3203 // navigate more quickly at the source level when 3204 // parsing STABS 3205 if (!N_COMM_indexes.empty()) { 3206 symbol_ptr = 3207 symtab->SymbolAtIndex(N_COMM_indexes.back()); 3208 symbol_ptr->SetByteSize(sym_idx + 1); 3209 symbol_ptr->SetSizeIsSibling(true); 3210 N_COMM_indexes.pop_back(); 3211 } 3212 type = eSymbolTypeScopeEnd; 3213 break; 3214 3215 case N_LENG: 3216 // second stab entry with length information 3217 type = eSymbolTypeAdditional; 3218 break; 3219 3220 default: 3221 break; 3222 } 3223 } else { 3224 // uint8_t n_pext = N_PEXT & nlist.n_type; 3225 uint8_t n_type = N_TYPE & nlist.n_type; 3226 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0); 3227 3228 switch (n_type) { 3229 case N_INDR: { 3230 const char *reexport_name_cstr = 3231 strtab_data.PeekCStr(nlist.n_value); 3232 if (reexport_name_cstr && reexport_name_cstr[0]) { 3233 type = eSymbolTypeReExported; 3234 ConstString reexport_name( 3235 reexport_name_cstr + 3236 ((reexport_name_cstr[0] == '_') ? 1 : 0)); 3237 sym[sym_idx].SetReExportedSymbolName(reexport_name); 3238 set_value = false; 3239 reexport_shlib_needs_fixup[sym_idx] = reexport_name; 3240 indirect_symbol_names.insert(ConstString( 3241 symbol_name + ((symbol_name[0] == '_') ? 1 : 0))); 3242 } else 3243 type = eSymbolTypeUndefined; 3244 } break; 3245 3246 case N_UNDF: 3247 if (symbol_name && symbol_name[0]) { 3248 ConstString undefined_name( 3249 symbol_name + ((symbol_name[0] == '_') ? 1 : 0)); 3250 undefined_name_to_desc[undefined_name] = nlist.n_desc; 3251 } 3252 // Fall through 3253 case N_PBUD: 3254 type = eSymbolTypeUndefined; 3255 break; 3256 3257 case N_ABS: 3258 type = eSymbolTypeAbsolute; 3259 break; 3260 3261 case N_SECT: { 3262 symbol_section = section_info.GetSection(nlist.n_sect, 3263 nlist.n_value); 3264 3265 if (symbol_section == NULL) { 3266 // TODO: warn about this? 3267 add_nlist = false; 3268 break; 3269 } 3270 3271 if (TEXT_eh_frame_sectID == nlist.n_sect) { 3272 type = eSymbolTypeException; 3273 } else { 3274 uint32_t section_type = 3275 symbol_section->Get() & SECTION_TYPE; 3276 3277 switch (section_type) { 3278 case S_CSTRING_LITERALS: 3279 type = eSymbolTypeData; 3280 break; // section with only literal C strings 3281 case S_4BYTE_LITERALS: 3282 type = eSymbolTypeData; 3283 break; // section with only 4 byte literals 3284 case S_8BYTE_LITERALS: 3285 type = eSymbolTypeData; 3286 break; // section with only 8 byte literals 3287 case S_LITERAL_POINTERS: 3288 type = eSymbolTypeTrampoline; 3289 break; // section with only pointers to literals 3290 case S_NON_LAZY_SYMBOL_POINTERS: 3291 type = eSymbolTypeTrampoline; 3292 break; // section with only non-lazy symbol 3293 // pointers 3294 case S_LAZY_SYMBOL_POINTERS: 3295 type = eSymbolTypeTrampoline; 3296 break; // section with only lazy symbol pointers 3297 case S_SYMBOL_STUBS: 3298 type = eSymbolTypeTrampoline; 3299 break; // section with only symbol stubs, byte 3300 // size of stub in the reserved2 field 3301 case S_MOD_INIT_FUNC_POINTERS: 3302 type = eSymbolTypeCode; 3303 break; // section with only function pointers for 3304 // initialization 3305 case S_MOD_TERM_FUNC_POINTERS: 3306 type = eSymbolTypeCode; 3307 break; // section with only function pointers for 3308 // termination 3309 case S_INTERPOSING: 3310 type = eSymbolTypeTrampoline; 3311 break; // section with only pairs of function 3312 // pointers for interposing 3313 case S_16BYTE_LITERALS: 3314 type = eSymbolTypeData; 3315 break; // section with only 16 byte literals 3316 case S_DTRACE_DOF: 3317 type = eSymbolTypeInstrumentation; 3318 break; 3319 case S_LAZY_DYLIB_SYMBOL_POINTERS: 3320 type = eSymbolTypeTrampoline; 3321 break; 3322 default: 3323 switch (symbol_section->GetType()) { 3324 case lldb::eSectionTypeCode: 3325 type = eSymbolTypeCode; 3326 break; 3327 case eSectionTypeData: 3328 case eSectionTypeDataCString: // Inlined C string 3329 // data 3330 case eSectionTypeDataCStringPointers: // Pointers 3331 // to C 3332 // string 3333 // data 3334 case eSectionTypeDataSymbolAddress: // Address of 3335 // a symbol in 3336 // the symbol 3337 // table 3338 case eSectionTypeData4: 3339 case eSectionTypeData8: 3340 case eSectionTypeData16: 3341 type = eSymbolTypeData; 3342 break; 3343 default: 3344 break; 3345 } 3346 break; 3347 } 3348 3349 if (type == eSymbolTypeInvalid) { 3350 const char *symbol_sect_name = 3351 symbol_section->GetName().AsCString(); 3352 if (symbol_section->IsDescendant( 3353 text_section_sp.get())) { 3354 if (symbol_section->IsClear( 3355 S_ATTR_PURE_INSTRUCTIONS | 3356 S_ATTR_SELF_MODIFYING_CODE | 3357 S_ATTR_SOME_INSTRUCTIONS)) 3358 type = eSymbolTypeData; 3359 else 3360 type = eSymbolTypeCode; 3361 } else if (symbol_section->IsDescendant( 3362 data_section_sp.get()) || 3363 symbol_section->IsDescendant( 3364 data_dirty_section_sp.get()) || 3365 symbol_section->IsDescendant( 3366 data_const_section_sp.get())) { 3367 if (symbol_sect_name && 3368 ::strstr(symbol_sect_name, "__objc") == 3369 symbol_sect_name) { 3370 type = eSymbolTypeRuntime; 3371 3372 if (symbol_name) { 3373 llvm::StringRef symbol_name_ref(symbol_name); 3374 if (symbol_name_ref.startswith("_OBJC_")) { 3375 llvm::StringRef 3376 g_objc_v2_prefix_class( 3377 "_OBJC_CLASS_$_"); 3378 llvm::StringRef 3379 g_objc_v2_prefix_metaclass( 3380 "_OBJC_METACLASS_$_"); 3381 llvm::StringRef 3382 g_objc_v2_prefix_ivar("_OBJC_IVAR_$_"); 3383 if (symbol_name_ref.startswith( 3384 g_objc_v2_prefix_class)) { 3385 symbol_name_non_abi_mangled = 3386 symbol_name + 1; 3387 symbol_name = 3388 symbol_name + 3389 g_objc_v2_prefix_class.size(); 3390 type = eSymbolTypeObjCClass; 3391 demangled_is_synthesized = true; 3392 } else if ( 3393 symbol_name_ref.startswith( 3394 g_objc_v2_prefix_metaclass)) { 3395 symbol_name_non_abi_mangled = 3396 symbol_name + 1; 3397 symbol_name = 3398 symbol_name + 3399 g_objc_v2_prefix_metaclass.size(); 3400 type = eSymbolTypeObjCMetaClass; 3401 demangled_is_synthesized = true; 3402 } else if (symbol_name_ref.startswith( 3403 g_objc_v2_prefix_ivar)) { 3404 symbol_name_non_abi_mangled = 3405 symbol_name + 1; 3406 symbol_name = 3407 symbol_name + 3408 g_objc_v2_prefix_ivar.size(); 3409 type = eSymbolTypeObjCIVar; 3410 demangled_is_synthesized = true; 3411 } 3412 } 3413 } 3414 } else if (symbol_sect_name && 3415 ::strstr(symbol_sect_name, 3416 "__gcc_except_tab") == 3417 symbol_sect_name) { 3418 type = eSymbolTypeException; 3419 } else { 3420 type = eSymbolTypeData; 3421 } 3422 } else if (symbol_sect_name && 3423 ::strstr(symbol_sect_name, "__IMPORT") == 3424 symbol_sect_name) { 3425 type = eSymbolTypeTrampoline; 3426 } else if (symbol_section->IsDescendant( 3427 objc_section_sp.get())) { 3428 type = eSymbolTypeRuntime; 3429 if (symbol_name && symbol_name[0] == '.') { 3430 llvm::StringRef symbol_name_ref(symbol_name); 3431 llvm::StringRef 3432 g_objc_v1_prefix_class(".objc_class_name_"); 3433 if (symbol_name_ref.startswith( 3434 g_objc_v1_prefix_class)) { 3435 symbol_name_non_abi_mangled = symbol_name; 3436 symbol_name = symbol_name + 3437 g_objc_v1_prefix_class.size(); 3438 type = eSymbolTypeObjCClass; 3439 demangled_is_synthesized = true; 3440 } 3441 } 3442 } 3443 } 3444 } 3445 } break; 3446 } 3447 } 3448 3449 if (add_nlist) { 3450 uint64_t symbol_value = nlist.n_value; 3451 if (symbol_name_non_abi_mangled) { 3452 sym[sym_idx].GetMangled().SetMangledName( 3453 ConstString(symbol_name_non_abi_mangled)); 3454 sym[sym_idx].GetMangled().SetDemangledName( 3455 ConstString(symbol_name)); 3456 } else { 3457 bool symbol_name_is_mangled = false; 3458 3459 if (symbol_name && symbol_name[0] == '_') { 3460 symbol_name_is_mangled = symbol_name[1] == '_'; 3461 symbol_name++; // Skip the leading underscore 3462 } 3463 3464 if (symbol_name) { 3465 ConstString const_symbol_name(symbol_name); 3466 sym[sym_idx].GetMangled().SetValue( 3467 const_symbol_name, symbol_name_is_mangled); 3468 if (is_gsym && is_debug) { 3469 const char *gsym_name = 3470 sym[sym_idx] 3471 .GetMangled() 3472 .GetName(Mangled::ePreferMangled) 3473 .GetCString(); 3474 if (gsym_name) 3475 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx; 3476 } 3477 } 3478 } 3479 if (symbol_section) { 3480 const addr_t section_file_addr = 3481 symbol_section->GetFileAddress(); 3482 if (symbol_byte_size == 0 && 3483 function_starts_count > 0) { 3484 addr_t symbol_lookup_file_addr = nlist.n_value; 3485 // Do an exact address match for non-ARM addresses, 3486 // else get the closest since the symbol might be a 3487 // thumb symbol which has an address with bit zero 3488 // set 3489 FunctionStarts::Entry *func_start_entry = 3490 function_starts.FindEntry(symbol_lookup_file_addr, 3491 !is_arm); 3492 if (is_arm && func_start_entry) { 3493 // Verify that the function start address is the 3494 // symbol address (ARM) or the symbol address + 1 3495 // (thumb) 3496 if (func_start_entry->addr != 3497 symbol_lookup_file_addr && 3498 func_start_entry->addr != 3499 (symbol_lookup_file_addr + 1)) { 3500 // Not the right entry, NULL it out... 3501 func_start_entry = NULL; 3502 } 3503 } 3504 if (func_start_entry) { 3505 func_start_entry->data = true; 3506 3507 addr_t symbol_file_addr = func_start_entry->addr; 3508 uint32_t symbol_flags = 0; 3509 if (is_arm) { 3510 if (symbol_file_addr & 1) 3511 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB; 3512 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK; 3513 } 3514 3515 const FunctionStarts::Entry *next_func_start_entry = 3516 function_starts.FindNextEntry(func_start_entry); 3517 const addr_t section_end_file_addr = 3518 section_file_addr + 3519 symbol_section->GetByteSize(); 3520 if (next_func_start_entry) { 3521 addr_t next_symbol_file_addr = 3522 next_func_start_entry->addr; 3523 // Be sure the clear the Thumb address bit when 3524 // we calculate the size from the current and 3525 // next address 3526 if (is_arm) 3527 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK; 3528 symbol_byte_size = std::min<lldb::addr_t>( 3529 next_symbol_file_addr - symbol_file_addr, 3530 section_end_file_addr - symbol_file_addr); 3531 } else { 3532 symbol_byte_size = 3533 section_end_file_addr - symbol_file_addr; 3534 } 3535 } 3536 } 3537 symbol_value -= section_file_addr; 3538 } 3539 3540 if (is_debug == false) { 3541 if (type == eSymbolTypeCode) { 3542 // See if we can find a N_FUN entry for any code 3543 // symbols. If we do find a match, and the name 3544 // matches, then we can merge the two into just the 3545 // function symbol to avoid duplicate entries in 3546 // the symbol table 3547 auto range = 3548 N_FUN_addr_to_sym_idx.equal_range(nlist.n_value); 3549 if (range.first != range.second) { 3550 bool found_it = false; 3551 for (auto pos = range.first; pos != range.second; 3552 ++pos) { 3553 if (sym[sym_idx].GetMangled().GetName( 3554 Mangled::ePreferMangled) == 3555 sym[pos->second].GetMangled().GetName( 3556 Mangled::ePreferMangled)) { 3557 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second; 3558 // We just need the flags from the linker 3559 // symbol, so put these flags 3560 // into the N_FUN flags to avoid duplicate 3561 // symbols in the symbol table 3562 sym[pos->second].SetExternal( 3563 sym[sym_idx].IsExternal()); 3564 sym[pos->second].SetFlags(nlist.n_type << 16 | 3565 nlist.n_desc); 3566 if (resolver_addresses.find(nlist.n_value) != 3567 resolver_addresses.end()) 3568 sym[pos->second].SetType(eSymbolTypeResolver); 3569 sym[sym_idx].Clear(); 3570 found_it = true; 3571 break; 3572 } 3573 } 3574 if (found_it) 3575 continue; 3576 } else { 3577 if (resolver_addresses.find(nlist.n_value) != 3578 resolver_addresses.end()) 3579 type = eSymbolTypeResolver; 3580 } 3581 } else if (type == eSymbolTypeData || 3582 type == eSymbolTypeObjCClass || 3583 type == eSymbolTypeObjCMetaClass || 3584 type == eSymbolTypeObjCIVar) { 3585 // See if we can find a N_STSYM entry for any data 3586 // symbols. If we do find a match, and the name 3587 // matches, then we can merge the two into just the 3588 // Static symbol to avoid duplicate entries in the 3589 // symbol table 3590 auto range = N_STSYM_addr_to_sym_idx.equal_range( 3591 nlist.n_value); 3592 if (range.first != range.second) { 3593 bool found_it = false; 3594 for (auto pos = range.first; pos != range.second; 3595 ++pos) { 3596 if (sym[sym_idx].GetMangled().GetName( 3597 Mangled::ePreferMangled) == 3598 sym[pos->second].GetMangled().GetName( 3599 Mangled::ePreferMangled)) { 3600 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second; 3601 // We just need the flags from the linker 3602 // symbol, so put these flags 3603 // into the N_STSYM flags to avoid duplicate 3604 // symbols in the symbol table 3605 sym[pos->second].SetExternal( 3606 sym[sym_idx].IsExternal()); 3607 sym[pos->second].SetFlags(nlist.n_type << 16 | 3608 nlist.n_desc); 3609 sym[sym_idx].Clear(); 3610 found_it = true; 3611 break; 3612 } 3613 } 3614 if (found_it) 3615 continue; 3616 } else { 3617 const char *gsym_name = 3618 sym[sym_idx] 3619 .GetMangled() 3620 .GetName(Mangled::ePreferMangled) 3621 .GetCString(); 3622 if (gsym_name) { 3623 // Combine N_GSYM stab entries with the non 3624 // stab symbol 3625 ConstNameToSymbolIndexMap::const_iterator pos = 3626 N_GSYM_name_to_sym_idx.find(gsym_name); 3627 if (pos != N_GSYM_name_to_sym_idx.end()) { 3628 const uint32_t GSYM_sym_idx = pos->second; 3629 m_nlist_idx_to_sym_idx[nlist_idx] = 3630 GSYM_sym_idx; 3631 // Copy the address, because often the N_GSYM 3632 // address has an invalid address of zero 3633 // when the global is a common symbol 3634 sym[GSYM_sym_idx].GetAddressRef().SetSection( 3635 symbol_section); 3636 sym[GSYM_sym_idx].GetAddressRef().SetOffset( 3637 symbol_value); 3638 symbols_added.insert(sym[GSYM_sym_idx] 3639 .GetAddress() 3640 .GetFileAddress()); 3641 // We just need the flags from the linker 3642 // symbol, so put these flags 3643 // into the N_GSYM flags to avoid duplicate 3644 // symbols in the symbol table 3645 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 | 3646 nlist.n_desc); 3647 sym[sym_idx].Clear(); 3648 continue; 3649 } 3650 } 3651 } 3652 } 3653 } 3654 3655 sym[sym_idx].SetID(nlist_idx); 3656 sym[sym_idx].SetType(type); 3657 if (set_value) { 3658 sym[sym_idx].GetAddressRef().SetSection(symbol_section); 3659 sym[sym_idx].GetAddressRef().SetOffset(symbol_value); 3660 symbols_added.insert( 3661 sym[sym_idx].GetAddress().GetFileAddress()); 3662 } 3663 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc); 3664 3665 if (symbol_byte_size > 0) 3666 sym[sym_idx].SetByteSize(symbol_byte_size); 3667 3668 if (demangled_is_synthesized) 3669 sym[sym_idx].SetDemangledNameIsSynthesized(true); 3670 ++sym_idx; 3671 } else { 3672 sym[sym_idx].Clear(); 3673 } 3674 } 3675 ///////////////////////////// 3676 } 3677 break; // No more entries to consider 3678 } 3679 } 3680 3681 for (const auto &pos : reexport_shlib_needs_fixup) { 3682 const auto undef_pos = undefined_name_to_desc.find(pos.second); 3683 if (undef_pos != undefined_name_to_desc.end()) { 3684 const uint8_t dylib_ordinal = 3685 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second); 3686 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize()) 3687 sym[pos.first].SetReExportedSymbolSharedLibrary( 3688 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1)); 3689 } 3690 } 3691 } 3692 } 3693 } 3694 } 3695 } 3696 3697 // Must reset this in case it was mutated above! 3698 nlist_data_offset = 0; 3699 #endif 3700 3701 if (nlist_data.GetByteSize() > 0) { 3702 3703 // If the sym array was not created while parsing the DSC unmapped 3704 // symbols, create it now. 3705 if (sym == nullptr) { 3706 sym = 3707 symtab->Resize(symtab_load_command.nsyms + m_dysymtab.nindirectsyms); 3708 num_syms = symtab->GetNumSymbols(); 3709 } 3710 3711 if (unmapped_local_symbols_found) { 3712 assert(m_dysymtab.ilocalsym == 0); 3713 nlist_data_offset += (m_dysymtab.nlocalsym * nlist_byte_size); 3714 nlist_idx = m_dysymtab.nlocalsym; 3715 } else { 3716 nlist_idx = 0; 3717 } 3718 3719 typedef llvm::DenseMap<ConstString, uint16_t> UndefinedNameToDescMap; 3720 typedef llvm::DenseMap<uint32_t, ConstString> SymbolIndexToName; 3721 UndefinedNameToDescMap undefined_name_to_desc; 3722 SymbolIndexToName reexport_shlib_needs_fixup; 3723 3724 // Symtab parsing is a huge mess. Everything is entangled and the code 3725 // requires access to a ridiculous amount of variables. LLDB depends 3726 // heavily on the proper merging of symbols and to get that right we need 3727 // to make sure we have parsed all the debug symbols first. Therefore we 3728 // invoke the lambda twice, once to parse only the debug symbols and then 3729 // once more to parse the remaining symbols. 3730 auto ParseSymbolLambda = [&](struct nlist_64 &nlist, uint32_t nlist_idx, 3731 bool debug_only) { 3732 const bool is_debug = ((nlist.n_type & N_STAB) != 0); 3733 if (is_debug != debug_only) 3734 return true; 3735 3736 const char *symbol_name_non_abi_mangled = nullptr; 3737 const char *symbol_name = nullptr; 3738 3739 if (have_strtab_data) { 3740 symbol_name = strtab_data.PeekCStr(nlist.n_strx); 3741 3742 if (symbol_name == nullptr) { 3743 // No symbol should be NULL, even the symbols with no string values 3744 // should have an offset zero which points to an empty C-string 3745 Host::SystemLog(Host::eSystemLogError, 3746 "error: symbol[%u] has invalid string table offset " 3747 "0x%x in %s, ignoring symbol\n", 3748 nlist_idx, nlist.n_strx, 3749 module_sp->GetFileSpec().GetPath().c_str()); 3750 return true; 3751 } 3752 if (symbol_name[0] == '\0') 3753 symbol_name = nullptr; 3754 } else { 3755 const addr_t str_addr = strtab_addr + nlist.n_strx; 3756 Status str_error; 3757 if (process->ReadCStringFromMemory(str_addr, memory_symbol_name, 3758 str_error)) 3759 symbol_name = memory_symbol_name.c_str(); 3760 } 3761 3762 SymbolType type = eSymbolTypeInvalid; 3763 SectionSP symbol_section; 3764 lldb::addr_t symbol_byte_size = 0; 3765 bool add_nlist = true; 3766 bool is_gsym = false; 3767 bool demangled_is_synthesized = false; 3768 bool set_value = true; 3769 3770 assert(sym_idx < num_syms); 3771 sym[sym_idx].SetDebug(is_debug); 3772 3773 if (is_debug) { 3774 switch (nlist.n_type) { 3775 case N_GSYM: 3776 // global symbol: name,,NO_SECT,type,0 3777 // Sometimes the N_GSYM value contains the address. 3778 3779 // FIXME: In the .o files, we have a GSYM and a debug symbol for all 3780 // the ObjC data. They 3781 // have the same address, but we want to ensure that we always find 3782 // only the real symbol, 'cause we don't currently correctly 3783 // attribute the GSYM one to the ObjCClass/Ivar/MetaClass symbol 3784 // type. This is a temporary hack to make sure the ObjectiveC 3785 // symbols get treated correctly. To do this right, we should 3786 // coalesce all the GSYM & global symbols that have the same 3787 // address. 3788 is_gsym = true; 3789 sym[sym_idx].SetExternal(true); 3790 3791 if (symbol_name && symbol_name[0] == '_' && symbol_name[1] == 'O') { 3792 llvm::StringRef symbol_name_ref(symbol_name); 3793 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) { 3794 symbol_name_non_abi_mangled = symbol_name + 1; 3795 symbol_name = symbol_name + g_objc_v2_prefix_class.size(); 3796 type = eSymbolTypeObjCClass; 3797 demangled_is_synthesized = true; 3798 3799 } else if (symbol_name_ref.startswith(g_objc_v2_prefix_metaclass)) { 3800 symbol_name_non_abi_mangled = symbol_name + 1; 3801 symbol_name = symbol_name + g_objc_v2_prefix_metaclass.size(); 3802 type = eSymbolTypeObjCMetaClass; 3803 demangled_is_synthesized = true; 3804 } else if (symbol_name_ref.startswith(g_objc_v2_prefix_ivar)) { 3805 symbol_name_non_abi_mangled = symbol_name + 1; 3806 symbol_name = symbol_name + g_objc_v2_prefix_ivar.size(); 3807 type = eSymbolTypeObjCIVar; 3808 demangled_is_synthesized = true; 3809 } 3810 } else { 3811 if (nlist.n_value != 0) 3812 symbol_section = 3813 section_info.GetSection(nlist.n_sect, nlist.n_value); 3814 type = eSymbolTypeData; 3815 } 3816 break; 3817 3818 case N_FNAME: 3819 // procedure name (f77 kludge): name,,NO_SECT,0,0 3820 type = eSymbolTypeCompiler; 3821 break; 3822 3823 case N_FUN: 3824 // procedure: name,,n_sect,linenumber,address 3825 if (symbol_name) { 3826 type = eSymbolTypeCode; 3827 symbol_section = 3828 section_info.GetSection(nlist.n_sect, nlist.n_value); 3829 3830 N_FUN_addr_to_sym_idx.insert( 3831 std::make_pair(nlist.n_value, sym_idx)); 3832 // We use the current number of symbols in the symbol table in 3833 // lieu of using nlist_idx in case we ever start trimming entries 3834 // out 3835 N_FUN_indexes.push_back(sym_idx); 3836 } else { 3837 type = eSymbolTypeCompiler; 3838 3839 if (!N_FUN_indexes.empty()) { 3840 // Copy the size of the function into the original STAB entry 3841 // so we don't have to hunt for it later 3842 symtab->SymbolAtIndex(N_FUN_indexes.back()) 3843 ->SetByteSize(nlist.n_value); 3844 N_FUN_indexes.pop_back(); 3845 // We don't really need the end function STAB as it contains 3846 // the size which we already placed with the original symbol, 3847 // so don't add it if we want a minimal symbol table 3848 add_nlist = false; 3849 } 3850 } 3851 break; 3852 3853 case N_STSYM: 3854 // static symbol: name,,n_sect,type,address 3855 N_STSYM_addr_to_sym_idx.insert( 3856 std::make_pair(nlist.n_value, sym_idx)); 3857 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value); 3858 if (symbol_name && symbol_name[0]) { 3859 type = ObjectFile::GetSymbolTypeFromName(symbol_name + 1, 3860 eSymbolTypeData); 3861 } 3862 break; 3863 3864 case N_LCSYM: 3865 // .lcomm symbol: name,,n_sect,type,address 3866 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value); 3867 type = eSymbolTypeCommonBlock; 3868 break; 3869 3870 case N_BNSYM: 3871 // We use the current number of symbols in the symbol table in lieu 3872 // of using nlist_idx in case we ever start trimming entries out 3873 // Skip these if we want minimal symbol tables 3874 add_nlist = false; 3875 break; 3876 3877 case N_ENSYM: 3878 // Set the size of the N_BNSYM to the terminating index of this 3879 // N_ENSYM so that we can always skip the entire symbol if we need 3880 // to navigate more quickly at the source level when parsing STABS 3881 // Skip these if we want minimal symbol tables 3882 add_nlist = false; 3883 break; 3884 3885 case N_OPT: 3886 // emitted with gcc2_compiled and in gcc source 3887 type = eSymbolTypeCompiler; 3888 break; 3889 3890 case N_RSYM: 3891 // register sym: name,,NO_SECT,type,register 3892 type = eSymbolTypeVariable; 3893 break; 3894 3895 case N_SLINE: 3896 // src line: 0,,n_sect,linenumber,address 3897 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value); 3898 type = eSymbolTypeLineEntry; 3899 break; 3900 3901 case N_SSYM: 3902 // structure elt: name,,NO_SECT,type,struct_offset 3903 type = eSymbolTypeVariableType; 3904 break; 3905 3906 case N_SO: 3907 // source file name 3908 type = eSymbolTypeSourceFile; 3909 if (symbol_name == nullptr) { 3910 add_nlist = false; 3911 if (N_SO_index != UINT32_MAX) { 3912 // Set the size of the N_SO to the terminating index of this 3913 // N_SO so that we can always skip the entire N_SO if we need 3914 // to navigate more quickly at the source level when parsing 3915 // STABS 3916 symbol_ptr = symtab->SymbolAtIndex(N_SO_index); 3917 symbol_ptr->SetByteSize(sym_idx); 3918 symbol_ptr->SetSizeIsSibling(true); 3919 } 3920 N_NSYM_indexes.clear(); 3921 N_INCL_indexes.clear(); 3922 N_BRAC_indexes.clear(); 3923 N_COMM_indexes.clear(); 3924 N_FUN_indexes.clear(); 3925 N_SO_index = UINT32_MAX; 3926 } else { 3927 // We use the current number of symbols in the symbol table in 3928 // lieu of using nlist_idx in case we ever start trimming entries 3929 // out 3930 const bool N_SO_has_full_path = symbol_name[0] == '/'; 3931 if (N_SO_has_full_path) { 3932 if ((N_SO_index == sym_idx - 1) && ((sym_idx - 1) < num_syms)) { 3933 // We have two consecutive N_SO entries where the first 3934 // contains a directory and the second contains a full path. 3935 sym[sym_idx - 1].GetMangled().SetValue(ConstString(symbol_name), 3936 false); 3937 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1; 3938 add_nlist = false; 3939 } else { 3940 // This is the first entry in a N_SO that contains a 3941 // directory or a full path to the source file 3942 N_SO_index = sym_idx; 3943 } 3944 } else if ((N_SO_index == sym_idx - 1) && 3945 ((sym_idx - 1) < num_syms)) { 3946 // This is usually the second N_SO entry that contains just the 3947 // filename, so here we combine it with the first one if we are 3948 // minimizing the symbol table 3949 const char *so_path = 3950 sym[sym_idx - 1].GetMangled().GetDemangledName().AsCString(); 3951 if (so_path && so_path[0]) { 3952 std::string full_so_path(so_path); 3953 const size_t double_slash_pos = full_so_path.find("//"); 3954 if (double_slash_pos != std::string::npos) { 3955 // The linker has been generating bad N_SO entries with 3956 // doubled up paths in the format "%s%s" where the first 3957 // string in the DW_AT_comp_dir, and the second is the 3958 // directory for the source file so you end up with a path 3959 // that looks like "/tmp/src//tmp/src/" 3960 FileSpec so_dir(so_path); 3961 if (!FileSystem::Instance().Exists(so_dir)) { 3962 so_dir.SetFile(&full_so_path[double_slash_pos + 1], 3963 FileSpec::Style::native); 3964 if (FileSystem::Instance().Exists(so_dir)) { 3965 // Trim off the incorrect path 3966 full_so_path.erase(0, double_slash_pos + 1); 3967 } 3968 } 3969 } 3970 if (*full_so_path.rbegin() != '/') 3971 full_so_path += '/'; 3972 full_so_path += symbol_name; 3973 sym[sym_idx - 1].GetMangled().SetValue( 3974 ConstString(full_so_path.c_str()), false); 3975 add_nlist = false; 3976 m_nlist_idx_to_sym_idx[nlist_idx] = sym_idx - 1; 3977 } 3978 } else { 3979 // This could be a relative path to a N_SO 3980 N_SO_index = sym_idx; 3981 } 3982 } 3983 break; 3984 3985 case N_OSO: 3986 // object file name: name,,0,0,st_mtime 3987 type = eSymbolTypeObjectFile; 3988 break; 3989 3990 case N_LSYM: 3991 // local sym: name,,NO_SECT,type,offset 3992 type = eSymbolTypeLocal; 3993 break; 3994 3995 // INCL scopes 3996 case N_BINCL: 3997 // include file beginning: name,,NO_SECT,0,sum We use the current 3998 // number of symbols in the symbol table in lieu of using nlist_idx 3999 // in case we ever start trimming entries out 4000 N_INCL_indexes.push_back(sym_idx); 4001 type = eSymbolTypeScopeBegin; 4002 break; 4003 4004 case N_EINCL: 4005 // include file end: name,,NO_SECT,0,0 4006 // Set the size of the N_BINCL to the terminating index of this 4007 // N_EINCL so that we can always skip the entire symbol if we need 4008 // to navigate more quickly at the source level when parsing STABS 4009 if (!N_INCL_indexes.empty()) { 4010 symbol_ptr = symtab->SymbolAtIndex(N_INCL_indexes.back()); 4011 symbol_ptr->SetByteSize(sym_idx + 1); 4012 symbol_ptr->SetSizeIsSibling(true); 4013 N_INCL_indexes.pop_back(); 4014 } 4015 type = eSymbolTypeScopeEnd; 4016 break; 4017 4018 case N_SOL: 4019 // #included file name: name,,n_sect,0,address 4020 type = eSymbolTypeHeaderFile; 4021 4022 // We currently don't use the header files on darwin 4023 add_nlist = false; 4024 break; 4025 4026 case N_PARAMS: 4027 // compiler parameters: name,,NO_SECT,0,0 4028 type = eSymbolTypeCompiler; 4029 break; 4030 4031 case N_VERSION: 4032 // compiler version: name,,NO_SECT,0,0 4033 type = eSymbolTypeCompiler; 4034 break; 4035 4036 case N_OLEVEL: 4037 // compiler -O level: name,,NO_SECT,0,0 4038 type = eSymbolTypeCompiler; 4039 break; 4040 4041 case N_PSYM: 4042 // parameter: name,,NO_SECT,type,offset 4043 type = eSymbolTypeVariable; 4044 break; 4045 4046 case N_ENTRY: 4047 // alternate entry: name,,n_sect,linenumber,address 4048 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value); 4049 type = eSymbolTypeLineEntry; 4050 break; 4051 4052 // Left and Right Braces 4053 case N_LBRAC: 4054 // left bracket: 0,,NO_SECT,nesting level,address We use the 4055 // current number of symbols in the symbol table in lieu of using 4056 // nlist_idx in case we ever start trimming entries out 4057 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value); 4058 N_BRAC_indexes.push_back(sym_idx); 4059 type = eSymbolTypeScopeBegin; 4060 break; 4061 4062 case N_RBRAC: 4063 // right bracket: 0,,NO_SECT,nesting level,address Set the size of 4064 // the N_LBRAC to the terminating index of this N_RBRAC so that we 4065 // can always skip the entire symbol if we need to navigate more 4066 // quickly at the source level when parsing STABS 4067 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value); 4068 if (!N_BRAC_indexes.empty()) { 4069 symbol_ptr = symtab->SymbolAtIndex(N_BRAC_indexes.back()); 4070 symbol_ptr->SetByteSize(sym_idx + 1); 4071 symbol_ptr->SetSizeIsSibling(true); 4072 N_BRAC_indexes.pop_back(); 4073 } 4074 type = eSymbolTypeScopeEnd; 4075 break; 4076 4077 case N_EXCL: 4078 // deleted include file: name,,NO_SECT,0,sum 4079 type = eSymbolTypeHeaderFile; 4080 break; 4081 4082 // COMM scopes 4083 case N_BCOMM: 4084 // begin common: name,,NO_SECT,0,0 4085 // We use the current number of symbols in the symbol table in lieu 4086 // of using nlist_idx in case we ever start trimming entries out 4087 type = eSymbolTypeScopeBegin; 4088 N_COMM_indexes.push_back(sym_idx); 4089 break; 4090 4091 case N_ECOML: 4092 // end common (local name): 0,,n_sect,0,address 4093 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value); 4094 LLVM_FALLTHROUGH; 4095 4096 case N_ECOMM: 4097 // end common: name,,n_sect,0,0 4098 // Set the size of the N_BCOMM to the terminating index of this 4099 // N_ECOMM/N_ECOML so that we can always skip the entire symbol if 4100 // we need to navigate more quickly at the source level when 4101 // parsing STABS 4102 if (!N_COMM_indexes.empty()) { 4103 symbol_ptr = symtab->SymbolAtIndex(N_COMM_indexes.back()); 4104 symbol_ptr->SetByteSize(sym_idx + 1); 4105 symbol_ptr->SetSizeIsSibling(true); 4106 N_COMM_indexes.pop_back(); 4107 } 4108 type = eSymbolTypeScopeEnd; 4109 break; 4110 4111 case N_LENG: 4112 // second stab entry with length information 4113 type = eSymbolTypeAdditional; 4114 break; 4115 4116 default: 4117 break; 4118 } 4119 } else { 4120 uint8_t n_type = N_TYPE & nlist.n_type; 4121 sym[sym_idx].SetExternal((N_EXT & nlist.n_type) != 0); 4122 4123 switch (n_type) { 4124 case N_INDR: { 4125 const char *reexport_name_cstr = strtab_data.PeekCStr(nlist.n_value); 4126 if (reexport_name_cstr && reexport_name_cstr[0]) { 4127 type = eSymbolTypeReExported; 4128 ConstString reexport_name(reexport_name_cstr + 4129 ((reexport_name_cstr[0] == '_') ? 1 : 0)); 4130 sym[sym_idx].SetReExportedSymbolName(reexport_name); 4131 set_value = false; 4132 reexport_shlib_needs_fixup[sym_idx] = reexport_name; 4133 indirect_symbol_names.insert( 4134 ConstString(symbol_name + ((symbol_name[0] == '_') ? 1 : 0))); 4135 } else 4136 type = eSymbolTypeUndefined; 4137 } break; 4138 4139 case N_UNDF: 4140 if (symbol_name && symbol_name[0]) { 4141 ConstString undefined_name(symbol_name + 4142 ((symbol_name[0] == '_') ? 1 : 0)); 4143 undefined_name_to_desc[undefined_name] = nlist.n_desc; 4144 } 4145 LLVM_FALLTHROUGH; 4146 4147 case N_PBUD: 4148 type = eSymbolTypeUndefined; 4149 break; 4150 4151 case N_ABS: 4152 type = eSymbolTypeAbsolute; 4153 break; 4154 4155 case N_SECT: { 4156 symbol_section = section_info.GetSection(nlist.n_sect, nlist.n_value); 4157 4158 if (!symbol_section) { 4159 // TODO: warn about this? 4160 add_nlist = false; 4161 break; 4162 } 4163 4164 if (TEXT_eh_frame_sectID == nlist.n_sect) { 4165 type = eSymbolTypeException; 4166 } else { 4167 uint32_t section_type = symbol_section->Get() & SECTION_TYPE; 4168 4169 switch (section_type) { 4170 case S_CSTRING_LITERALS: 4171 type = eSymbolTypeData; 4172 break; // section with only literal C strings 4173 case S_4BYTE_LITERALS: 4174 type = eSymbolTypeData; 4175 break; // section with only 4 byte literals 4176 case S_8BYTE_LITERALS: 4177 type = eSymbolTypeData; 4178 break; // section with only 8 byte literals 4179 case S_LITERAL_POINTERS: 4180 type = eSymbolTypeTrampoline; 4181 break; // section with only pointers to literals 4182 case S_NON_LAZY_SYMBOL_POINTERS: 4183 type = eSymbolTypeTrampoline; 4184 break; // section with only non-lazy symbol pointers 4185 case S_LAZY_SYMBOL_POINTERS: 4186 type = eSymbolTypeTrampoline; 4187 break; // section with only lazy symbol pointers 4188 case S_SYMBOL_STUBS: 4189 type = eSymbolTypeTrampoline; 4190 break; // section with only symbol stubs, byte size of stub in 4191 // the reserved2 field 4192 case S_MOD_INIT_FUNC_POINTERS: 4193 type = eSymbolTypeCode; 4194 break; // section with only function pointers for initialization 4195 case S_MOD_TERM_FUNC_POINTERS: 4196 type = eSymbolTypeCode; 4197 break; // section with only function pointers for termination 4198 case S_INTERPOSING: 4199 type = eSymbolTypeTrampoline; 4200 break; // section with only pairs of function pointers for 4201 // interposing 4202 case S_16BYTE_LITERALS: 4203 type = eSymbolTypeData; 4204 break; // section with only 16 byte literals 4205 case S_DTRACE_DOF: 4206 type = eSymbolTypeInstrumentation; 4207 break; 4208 case S_LAZY_DYLIB_SYMBOL_POINTERS: 4209 type = eSymbolTypeTrampoline; 4210 break; 4211 default: 4212 switch (symbol_section->GetType()) { 4213 case lldb::eSectionTypeCode: 4214 type = eSymbolTypeCode; 4215 break; 4216 case eSectionTypeData: 4217 case eSectionTypeDataCString: // Inlined C string data 4218 case eSectionTypeDataCStringPointers: // Pointers to C string 4219 // data 4220 case eSectionTypeDataSymbolAddress: // Address of a symbol in 4221 // the symbol table 4222 case eSectionTypeData4: 4223 case eSectionTypeData8: 4224 case eSectionTypeData16: 4225 type = eSymbolTypeData; 4226 break; 4227 default: 4228 break; 4229 } 4230 break; 4231 } 4232 4233 if (type == eSymbolTypeInvalid) { 4234 const char *symbol_sect_name = 4235 symbol_section->GetName().AsCString(); 4236 if (symbol_section->IsDescendant(text_section_sp.get())) { 4237 if (symbol_section->IsClear(S_ATTR_PURE_INSTRUCTIONS | 4238 S_ATTR_SELF_MODIFYING_CODE | 4239 S_ATTR_SOME_INSTRUCTIONS)) 4240 type = eSymbolTypeData; 4241 else 4242 type = eSymbolTypeCode; 4243 } else if (symbol_section->IsDescendant(data_section_sp.get()) || 4244 symbol_section->IsDescendant( 4245 data_dirty_section_sp.get()) || 4246 symbol_section->IsDescendant( 4247 data_const_section_sp.get())) { 4248 if (symbol_sect_name && 4249 ::strstr(symbol_sect_name, "__objc") == symbol_sect_name) { 4250 type = eSymbolTypeRuntime; 4251 4252 if (symbol_name) { 4253 llvm::StringRef symbol_name_ref(symbol_name); 4254 if (symbol_name_ref.startswith("_OBJC_")) { 4255 llvm::StringRef g_objc_v2_prefix_class( 4256 "_OBJC_CLASS_$_"); 4257 llvm::StringRef g_objc_v2_prefix_metaclass( 4258 "_OBJC_METACLASS_$_"); 4259 llvm::StringRef g_objc_v2_prefix_ivar( 4260 "_OBJC_IVAR_$_"); 4261 if (symbol_name_ref.startswith(g_objc_v2_prefix_class)) { 4262 symbol_name_non_abi_mangled = symbol_name + 1; 4263 symbol_name = 4264 symbol_name + g_objc_v2_prefix_class.size(); 4265 type = eSymbolTypeObjCClass; 4266 demangled_is_synthesized = true; 4267 } else if (symbol_name_ref.startswith( 4268 g_objc_v2_prefix_metaclass)) { 4269 symbol_name_non_abi_mangled = symbol_name + 1; 4270 symbol_name = 4271 symbol_name + g_objc_v2_prefix_metaclass.size(); 4272 type = eSymbolTypeObjCMetaClass; 4273 demangled_is_synthesized = true; 4274 } else if (symbol_name_ref.startswith( 4275 g_objc_v2_prefix_ivar)) { 4276 symbol_name_non_abi_mangled = symbol_name + 1; 4277 symbol_name = 4278 symbol_name + g_objc_v2_prefix_ivar.size(); 4279 type = eSymbolTypeObjCIVar; 4280 demangled_is_synthesized = true; 4281 } 4282 } 4283 } 4284 } else if (symbol_sect_name && 4285 ::strstr(symbol_sect_name, "__gcc_except_tab") == 4286 symbol_sect_name) { 4287 type = eSymbolTypeException; 4288 } else { 4289 type = eSymbolTypeData; 4290 } 4291 } else if (symbol_sect_name && 4292 ::strstr(symbol_sect_name, "__IMPORT") == 4293 symbol_sect_name) { 4294 type = eSymbolTypeTrampoline; 4295 } else if (symbol_section->IsDescendant(objc_section_sp.get())) { 4296 type = eSymbolTypeRuntime; 4297 if (symbol_name && symbol_name[0] == '.') { 4298 llvm::StringRef symbol_name_ref(symbol_name); 4299 llvm::StringRef g_objc_v1_prefix_class( 4300 ".objc_class_name_"); 4301 if (symbol_name_ref.startswith(g_objc_v1_prefix_class)) { 4302 symbol_name_non_abi_mangled = symbol_name; 4303 symbol_name = symbol_name + g_objc_v1_prefix_class.size(); 4304 type = eSymbolTypeObjCClass; 4305 demangled_is_synthesized = true; 4306 } 4307 } 4308 } 4309 } 4310 } 4311 } break; 4312 } 4313 } 4314 4315 if (!add_nlist) { 4316 sym[sym_idx].Clear(); 4317 return true; 4318 } 4319 4320 uint64_t symbol_value = nlist.n_value; 4321 4322 if (symbol_name_non_abi_mangled) { 4323 sym[sym_idx].GetMangled().SetMangledName( 4324 ConstString(symbol_name_non_abi_mangled)); 4325 sym[sym_idx].GetMangled().SetDemangledName(ConstString(symbol_name)); 4326 } else { 4327 bool symbol_name_is_mangled = false; 4328 4329 if (symbol_name && symbol_name[0] == '_') { 4330 symbol_name_is_mangled = symbol_name[1] == '_'; 4331 symbol_name++; // Skip the leading underscore 4332 } 4333 4334 if (symbol_name) { 4335 ConstString const_symbol_name(symbol_name); 4336 sym[sym_idx].GetMangled().SetValue(const_symbol_name, 4337 symbol_name_is_mangled); 4338 } 4339 } 4340 4341 if (is_gsym) { 4342 const char *gsym_name = sym[sym_idx] 4343 .GetMangled() 4344 .GetName(Mangled::ePreferMangled) 4345 .GetCString(); 4346 if (gsym_name) 4347 N_GSYM_name_to_sym_idx[gsym_name] = sym_idx; 4348 } 4349 4350 if (symbol_section) { 4351 const addr_t section_file_addr = symbol_section->GetFileAddress(); 4352 if (symbol_byte_size == 0 && function_starts_count > 0) { 4353 addr_t symbol_lookup_file_addr = nlist.n_value; 4354 // Do an exact address match for non-ARM addresses, else get the 4355 // closest since the symbol might be a thumb symbol which has an 4356 // address with bit zero set. 4357 FunctionStarts::Entry *func_start_entry = 4358 function_starts.FindEntry(symbol_lookup_file_addr, !is_arm); 4359 if (is_arm && func_start_entry) { 4360 // Verify that the function start address is the symbol address 4361 // (ARM) or the symbol address + 1 (thumb). 4362 if (func_start_entry->addr != symbol_lookup_file_addr && 4363 func_start_entry->addr != (symbol_lookup_file_addr + 1)) { 4364 // Not the right entry, NULL it out... 4365 func_start_entry = nullptr; 4366 } 4367 } 4368 if (func_start_entry) { 4369 func_start_entry->data = true; 4370 4371 addr_t symbol_file_addr = func_start_entry->addr; 4372 if (is_arm) 4373 symbol_file_addr &= THUMB_ADDRESS_BIT_MASK; 4374 4375 const FunctionStarts::Entry *next_func_start_entry = 4376 function_starts.FindNextEntry(func_start_entry); 4377 const addr_t section_end_file_addr = 4378 section_file_addr + symbol_section->GetByteSize(); 4379 if (next_func_start_entry) { 4380 addr_t next_symbol_file_addr = next_func_start_entry->addr; 4381 // Be sure the clear the Thumb address bit when we calculate the 4382 // size from the current and next address 4383 if (is_arm) 4384 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK; 4385 symbol_byte_size = std::min<lldb::addr_t>( 4386 next_symbol_file_addr - symbol_file_addr, 4387 section_end_file_addr - symbol_file_addr); 4388 } else { 4389 symbol_byte_size = section_end_file_addr - symbol_file_addr; 4390 } 4391 } 4392 } 4393 symbol_value -= section_file_addr; 4394 } 4395 4396 if (!is_debug) { 4397 if (type == eSymbolTypeCode) { 4398 // See if we can find a N_FUN entry for any code symbols. If we do 4399 // find a match, and the name matches, then we can merge the two into 4400 // just the function symbol to avoid duplicate entries in the symbol 4401 // table. 4402 std::pair<ValueToSymbolIndexMap::const_iterator, 4403 ValueToSymbolIndexMap::const_iterator> 4404 range; 4405 range = N_FUN_addr_to_sym_idx.equal_range(nlist.n_value); 4406 if (range.first != range.second) { 4407 for (ValueToSymbolIndexMap::const_iterator pos = range.first; 4408 pos != range.second; ++pos) { 4409 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == 4410 sym[pos->second].GetMangled().GetName( 4411 Mangled::ePreferMangled)) { 4412 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second; 4413 // We just need the flags from the linker symbol, so put these 4414 // flags into the N_FUN flags to avoid duplicate symbols in the 4415 // symbol table. 4416 sym[pos->second].SetExternal(sym[sym_idx].IsExternal()); 4417 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc); 4418 if (resolver_addresses.find(nlist.n_value) != 4419 resolver_addresses.end()) 4420 sym[pos->second].SetType(eSymbolTypeResolver); 4421 sym[sym_idx].Clear(); 4422 return true; 4423 } 4424 } 4425 } else { 4426 if (resolver_addresses.find(nlist.n_value) != 4427 resolver_addresses.end()) 4428 type = eSymbolTypeResolver; 4429 } 4430 } else if (type == eSymbolTypeData || type == eSymbolTypeObjCClass || 4431 type == eSymbolTypeObjCMetaClass || 4432 type == eSymbolTypeObjCIVar) { 4433 // See if we can find a N_STSYM entry for any data symbols. If we do 4434 // find a match, and the name matches, then we can merge the two into 4435 // just the Static symbol to avoid duplicate entries in the symbol 4436 // table. 4437 std::pair<ValueToSymbolIndexMap::const_iterator, 4438 ValueToSymbolIndexMap::const_iterator> 4439 range; 4440 range = N_STSYM_addr_to_sym_idx.equal_range(nlist.n_value); 4441 if (range.first != range.second) { 4442 for (ValueToSymbolIndexMap::const_iterator pos = range.first; 4443 pos != range.second; ++pos) { 4444 if (sym[sym_idx].GetMangled().GetName(Mangled::ePreferMangled) == 4445 sym[pos->second].GetMangled().GetName( 4446 Mangled::ePreferMangled)) { 4447 m_nlist_idx_to_sym_idx[nlist_idx] = pos->second; 4448 // We just need the flags from the linker symbol, so put these 4449 // flags into the N_STSYM flags to avoid duplicate symbols in 4450 // the symbol table. 4451 sym[pos->second].SetExternal(sym[sym_idx].IsExternal()); 4452 sym[pos->second].SetFlags(nlist.n_type << 16 | nlist.n_desc); 4453 sym[sym_idx].Clear(); 4454 return true; 4455 } 4456 } 4457 } else { 4458 // Combine N_GSYM stab entries with the non stab symbol. 4459 const char *gsym_name = sym[sym_idx] 4460 .GetMangled() 4461 .GetName(Mangled::ePreferMangled) 4462 .GetCString(); 4463 if (gsym_name) { 4464 ConstNameToSymbolIndexMap::const_iterator pos = 4465 N_GSYM_name_to_sym_idx.find(gsym_name); 4466 if (pos != N_GSYM_name_to_sym_idx.end()) { 4467 const uint32_t GSYM_sym_idx = pos->second; 4468 m_nlist_idx_to_sym_idx[nlist_idx] = GSYM_sym_idx; 4469 // Copy the address, because often the N_GSYM address has an 4470 // invalid address of zero when the global is a common symbol. 4471 sym[GSYM_sym_idx].GetAddressRef().SetSection(symbol_section); 4472 sym[GSYM_sym_idx].GetAddressRef().SetOffset(symbol_value); 4473 symbols_added.insert( 4474 sym[GSYM_sym_idx].GetAddress().GetFileAddress()); 4475 // We just need the flags from the linker symbol, so put these 4476 // flags into the N_GSYM flags to avoid duplicate symbols in 4477 // the symbol table. 4478 sym[GSYM_sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc); 4479 sym[sym_idx].Clear(); 4480 return true; 4481 } 4482 } 4483 } 4484 } 4485 } 4486 4487 sym[sym_idx].SetID(nlist_idx); 4488 sym[sym_idx].SetType(type); 4489 if (set_value) { 4490 sym[sym_idx].GetAddressRef().SetSection(symbol_section); 4491 sym[sym_idx].GetAddressRef().SetOffset(symbol_value); 4492 symbols_added.insert(sym[sym_idx].GetAddress().GetFileAddress()); 4493 } 4494 sym[sym_idx].SetFlags(nlist.n_type << 16 | nlist.n_desc); 4495 if (nlist.n_desc & N_WEAK_REF) 4496 sym[sym_idx].SetIsWeak(true); 4497 4498 if (symbol_byte_size > 0) 4499 sym[sym_idx].SetByteSize(symbol_byte_size); 4500 4501 if (demangled_is_synthesized) 4502 sym[sym_idx].SetDemangledNameIsSynthesized(true); 4503 4504 ++sym_idx; 4505 return true; 4506 }; 4507 4508 // First parse all the nlists but don't process them yet. See the next 4509 // comment for an explanation why. 4510 std::vector<struct nlist_64> nlists; 4511 nlists.reserve(symtab_load_command.nsyms); 4512 for (; nlist_idx < symtab_load_command.nsyms; ++nlist_idx) { 4513 if (auto nlist = 4514 ParseNList(nlist_data, nlist_data_offset, nlist_byte_size)) 4515 nlists.push_back(*nlist); 4516 else 4517 break; 4518 } 4519 4520 // Now parse all the debug symbols. This is needed to merge non-debug 4521 // symbols in the next step. Non-debug symbols are always coalesced into 4522 // the debug symbol. Doing this in one step would mean that some symbols 4523 // won't be merged. 4524 nlist_idx = 0; 4525 for (auto &nlist : nlists) { 4526 if (!ParseSymbolLambda(nlist, nlist_idx++, DebugSymbols)) 4527 break; 4528 } 4529 4530 // Finally parse all the non debug symbols. 4531 nlist_idx = 0; 4532 for (auto &nlist : nlists) { 4533 if (!ParseSymbolLambda(nlist, nlist_idx++, NonDebugSymbols)) 4534 break; 4535 } 4536 4537 for (const auto &pos : reexport_shlib_needs_fixup) { 4538 const auto undef_pos = undefined_name_to_desc.find(pos.second); 4539 if (undef_pos != undefined_name_to_desc.end()) { 4540 const uint8_t dylib_ordinal = 4541 llvm::MachO::GET_LIBRARY_ORDINAL(undef_pos->second); 4542 if (dylib_ordinal > 0 && dylib_ordinal < dylib_files.GetSize()) 4543 sym[pos.first].SetReExportedSymbolSharedLibrary( 4544 dylib_files.GetFileSpecAtIndex(dylib_ordinal - 1)); 4545 } 4546 } 4547 } 4548 4549 // Count how many trie symbols we'll add to the symbol table 4550 int trie_symbol_table_augment_count = 0; 4551 for (auto &e : external_sym_trie_entries) { 4552 if (symbols_added.find(e.entry.address) == symbols_added.end()) 4553 trie_symbol_table_augment_count++; 4554 } 4555 4556 if (num_syms < sym_idx + trie_symbol_table_augment_count) { 4557 num_syms = sym_idx + trie_symbol_table_augment_count; 4558 sym = symtab->Resize(num_syms); 4559 } 4560 uint32_t synthetic_sym_id = symtab_load_command.nsyms; 4561 4562 // Add symbols from the trie to the symbol table. 4563 for (auto &e : external_sym_trie_entries) { 4564 if (symbols_added.find(e.entry.address) != symbols_added.end()) 4565 continue; 4566 4567 // Find the section that this trie address is in, use that to annotate 4568 // symbol type as we add the trie address and name to the symbol table. 4569 Address symbol_addr; 4570 if (module_sp->ResolveFileAddress(e.entry.address, symbol_addr)) { 4571 SectionSP symbol_section(symbol_addr.GetSection()); 4572 const char *symbol_name = e.entry.name.GetCString(); 4573 bool demangled_is_synthesized = false; 4574 SymbolType type = 4575 GetSymbolType(symbol_name, demangled_is_synthesized, text_section_sp, 4576 data_section_sp, data_dirty_section_sp, 4577 data_const_section_sp, symbol_section); 4578 4579 sym[sym_idx].SetType(type); 4580 if (symbol_section) { 4581 sym[sym_idx].SetID(synthetic_sym_id++); 4582 sym[sym_idx].GetMangled().SetMangledName(ConstString(symbol_name)); 4583 if (demangled_is_synthesized) 4584 sym[sym_idx].SetDemangledNameIsSynthesized(true); 4585 sym[sym_idx].SetIsSynthetic(true); 4586 sym[sym_idx].SetExternal(true); 4587 sym[sym_idx].GetAddressRef() = symbol_addr; 4588 symbols_added.insert(symbol_addr.GetFileAddress()); 4589 if (e.entry.flags & TRIE_SYMBOL_IS_THUMB) 4590 sym[sym_idx].SetFlags(MACHO_NLIST_ARM_SYMBOL_IS_THUMB); 4591 ++sym_idx; 4592 } 4593 } 4594 } 4595 4596 if (function_starts_count > 0) { 4597 uint32_t num_synthetic_function_symbols = 0; 4598 for (i = 0; i < function_starts_count; ++i) { 4599 if (symbols_added.find(function_starts.GetEntryRef(i).addr) == 4600 symbols_added.end()) 4601 ++num_synthetic_function_symbols; 4602 } 4603 4604 if (num_synthetic_function_symbols > 0) { 4605 if (num_syms < sym_idx + num_synthetic_function_symbols) { 4606 num_syms = sym_idx + num_synthetic_function_symbols; 4607 sym = symtab->Resize(num_syms); 4608 } 4609 for (i = 0; i < function_starts_count; ++i) { 4610 const FunctionStarts::Entry *func_start_entry = 4611 function_starts.GetEntryAtIndex(i); 4612 if (symbols_added.find(func_start_entry->addr) == symbols_added.end()) { 4613 addr_t symbol_file_addr = func_start_entry->addr; 4614 uint32_t symbol_flags = 0; 4615 if (func_start_entry->data) 4616 symbol_flags = MACHO_NLIST_ARM_SYMBOL_IS_THUMB; 4617 Address symbol_addr; 4618 if (module_sp->ResolveFileAddress(symbol_file_addr, symbol_addr)) { 4619 SectionSP symbol_section(symbol_addr.GetSection()); 4620 uint32_t symbol_byte_size = 0; 4621 if (symbol_section) { 4622 const addr_t section_file_addr = symbol_section->GetFileAddress(); 4623 const FunctionStarts::Entry *next_func_start_entry = 4624 function_starts.FindNextEntry(func_start_entry); 4625 const addr_t section_end_file_addr = 4626 section_file_addr + symbol_section->GetByteSize(); 4627 if (next_func_start_entry) { 4628 addr_t next_symbol_file_addr = next_func_start_entry->addr; 4629 if (is_arm) 4630 next_symbol_file_addr &= THUMB_ADDRESS_BIT_MASK; 4631 symbol_byte_size = std::min<lldb::addr_t>( 4632 next_symbol_file_addr - symbol_file_addr, 4633 section_end_file_addr - symbol_file_addr); 4634 } else { 4635 symbol_byte_size = section_end_file_addr - symbol_file_addr; 4636 } 4637 sym[sym_idx].SetID(synthetic_sym_id++); 4638 sym[sym_idx].GetMangled().SetDemangledName( 4639 GetNextSyntheticSymbolName()); 4640 sym[sym_idx].SetType(eSymbolTypeCode); 4641 sym[sym_idx].SetIsSynthetic(true); 4642 sym[sym_idx].GetAddressRef() = symbol_addr; 4643 symbols_added.insert(symbol_addr.GetFileAddress()); 4644 if (symbol_flags) 4645 sym[sym_idx].SetFlags(symbol_flags); 4646 if (symbol_byte_size) 4647 sym[sym_idx].SetByteSize(symbol_byte_size); 4648 ++sym_idx; 4649 } 4650 } 4651 } 4652 } 4653 } 4654 } 4655 4656 // Trim our symbols down to just what we ended up with after removing any 4657 // symbols. 4658 if (sym_idx < num_syms) { 4659 num_syms = sym_idx; 4660 sym = symtab->Resize(num_syms); 4661 } 4662 4663 // Now synthesize indirect symbols 4664 if (m_dysymtab.nindirectsyms != 0) { 4665 if (indirect_symbol_index_data.GetByteSize()) { 4666 NListIndexToSymbolIndexMap::const_iterator end_index_pos = 4667 m_nlist_idx_to_sym_idx.end(); 4668 4669 for (uint32_t sect_idx = 1; sect_idx < m_mach_sections.size(); 4670 ++sect_idx) { 4671 if ((m_mach_sections[sect_idx].flags & SECTION_TYPE) == 4672 S_SYMBOL_STUBS) { 4673 uint32_t symbol_stub_byte_size = m_mach_sections[sect_idx].reserved2; 4674 if (symbol_stub_byte_size == 0) 4675 continue; 4676 4677 const uint32_t num_symbol_stubs = 4678 m_mach_sections[sect_idx].size / symbol_stub_byte_size; 4679 4680 if (num_symbol_stubs == 0) 4681 continue; 4682 4683 const uint32_t symbol_stub_index_offset = 4684 m_mach_sections[sect_idx].reserved1; 4685 for (uint32_t stub_idx = 0; stub_idx < num_symbol_stubs; ++stub_idx) { 4686 const uint32_t symbol_stub_index = 4687 symbol_stub_index_offset + stub_idx; 4688 const lldb::addr_t symbol_stub_addr = 4689 m_mach_sections[sect_idx].addr + 4690 (stub_idx * symbol_stub_byte_size); 4691 lldb::offset_t symbol_stub_offset = symbol_stub_index * 4; 4692 if (indirect_symbol_index_data.ValidOffsetForDataOfSize( 4693 symbol_stub_offset, 4)) { 4694 const uint32_t stub_sym_id = 4695 indirect_symbol_index_data.GetU32(&symbol_stub_offset); 4696 if (stub_sym_id & (INDIRECT_SYMBOL_ABS | INDIRECT_SYMBOL_LOCAL)) 4697 continue; 4698 4699 NListIndexToSymbolIndexMap::const_iterator index_pos = 4700 m_nlist_idx_to_sym_idx.find(stub_sym_id); 4701 Symbol *stub_symbol = nullptr; 4702 if (index_pos != end_index_pos) { 4703 // We have a remapping from the original nlist index to a 4704 // current symbol index, so just look this up by index 4705 stub_symbol = symtab->SymbolAtIndex(index_pos->second); 4706 } else { 4707 // We need to lookup a symbol using the original nlist symbol 4708 // index since this index is coming from the S_SYMBOL_STUBS 4709 stub_symbol = symtab->FindSymbolByID(stub_sym_id); 4710 } 4711 4712 if (stub_symbol) { 4713 Address so_addr(symbol_stub_addr, section_list); 4714 4715 if (stub_symbol->GetType() == eSymbolTypeUndefined) { 4716 // Change the external symbol into a trampoline that makes 4717 // sense These symbols were N_UNDF N_EXT, and are useless 4718 // to us, so we can re-use them so we don't have to make up 4719 // a synthetic symbol for no good reason. 4720 if (resolver_addresses.find(symbol_stub_addr) == 4721 resolver_addresses.end()) 4722 stub_symbol->SetType(eSymbolTypeTrampoline); 4723 else 4724 stub_symbol->SetType(eSymbolTypeResolver); 4725 stub_symbol->SetExternal(false); 4726 stub_symbol->GetAddressRef() = so_addr; 4727 stub_symbol->SetByteSize(symbol_stub_byte_size); 4728 } else { 4729 // Make a synthetic symbol to describe the trampoline stub 4730 Mangled stub_symbol_mangled_name(stub_symbol->GetMangled()); 4731 if (sym_idx >= num_syms) { 4732 sym = symtab->Resize(++num_syms); 4733 stub_symbol = nullptr; // this pointer no longer valid 4734 } 4735 sym[sym_idx].SetID(synthetic_sym_id++); 4736 sym[sym_idx].GetMangled() = stub_symbol_mangled_name; 4737 if (resolver_addresses.find(symbol_stub_addr) == 4738 resolver_addresses.end()) 4739 sym[sym_idx].SetType(eSymbolTypeTrampoline); 4740 else 4741 sym[sym_idx].SetType(eSymbolTypeResolver); 4742 sym[sym_idx].SetIsSynthetic(true); 4743 sym[sym_idx].GetAddressRef() = so_addr; 4744 symbols_added.insert(so_addr.GetFileAddress()); 4745 sym[sym_idx].SetByteSize(symbol_stub_byte_size); 4746 ++sym_idx; 4747 } 4748 } else { 4749 if (log) 4750 log->Warning("symbol stub referencing symbol table symbol " 4751 "%u that isn't in our minimal symbol table, " 4752 "fix this!!!", 4753 stub_sym_id); 4754 } 4755 } 4756 } 4757 } 4758 } 4759 } 4760 } 4761 4762 if (!reexport_trie_entries.empty()) { 4763 for (const auto &e : reexport_trie_entries) { 4764 if (e.entry.import_name) { 4765 // Only add indirect symbols from the Trie entries if we didn't have 4766 // a N_INDR nlist entry for this already 4767 if (indirect_symbol_names.find(e.entry.name) == 4768 indirect_symbol_names.end()) { 4769 // Make a synthetic symbol to describe re-exported symbol. 4770 if (sym_idx >= num_syms) 4771 sym = symtab->Resize(++num_syms); 4772 sym[sym_idx].SetID(synthetic_sym_id++); 4773 sym[sym_idx].GetMangled() = Mangled(e.entry.name); 4774 sym[sym_idx].SetType(eSymbolTypeReExported); 4775 sym[sym_idx].SetIsSynthetic(true); 4776 sym[sym_idx].SetReExportedSymbolName(e.entry.import_name); 4777 if (e.entry.other > 0 && e.entry.other <= dylib_files.GetSize()) { 4778 sym[sym_idx].SetReExportedSymbolSharedLibrary( 4779 dylib_files.GetFileSpecAtIndex(e.entry.other - 1)); 4780 } 4781 ++sym_idx; 4782 } 4783 } 4784 } 4785 } 4786 4787 // StreamFile s(stdout, false); 4788 // s.Printf ("Symbol table before CalculateSymbolSizes():\n"); 4789 // symtab->Dump(&s, NULL, eSortOrderNone); 4790 // Set symbol byte sizes correctly since mach-o nlist entries don't have 4791 // sizes 4792 symtab->CalculateSymbolSizes(); 4793 4794 // s.Printf ("Symbol table after CalculateSymbolSizes():\n"); 4795 // symtab->Dump(&s, NULL, eSortOrderNone); 4796 4797 return symtab->GetNumSymbols(); 4798 } 4799 4800 void ObjectFileMachO::Dump(Stream *s) { 4801 ModuleSP module_sp(GetModule()); 4802 if (module_sp) { 4803 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 4804 s->Printf("%p: ", static_cast<void *>(this)); 4805 s->Indent(); 4806 if (m_header.magic == MH_MAGIC_64 || m_header.magic == MH_CIGAM_64) 4807 s->PutCString("ObjectFileMachO64"); 4808 else 4809 s->PutCString("ObjectFileMachO32"); 4810 4811 *s << ", file = '" << m_file; 4812 ModuleSpecList all_specs; 4813 ModuleSpec base_spec; 4814 GetAllArchSpecs(m_header, m_data, MachHeaderSizeFromMagic(m_header.magic), 4815 base_spec, all_specs); 4816 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) { 4817 *s << "', triple"; 4818 if (e) 4819 s->Printf("[%d]", i); 4820 *s << " = "; 4821 *s << all_specs.GetModuleSpecRefAtIndex(i) 4822 .GetArchitecture() 4823 .GetTriple() 4824 .getTriple(); 4825 } 4826 *s << "\n"; 4827 SectionList *sections = GetSectionList(); 4828 if (sections) 4829 sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true, 4830 UINT32_MAX); 4831 4832 if (m_symtab_up) 4833 m_symtab_up->Dump(s, nullptr, eSortOrderNone); 4834 } 4835 } 4836 4837 UUID ObjectFileMachO::GetUUID(const llvm::MachO::mach_header &header, 4838 const lldb_private::DataExtractor &data, 4839 lldb::offset_t lc_offset) { 4840 uint32_t i; 4841 struct uuid_command load_cmd; 4842 4843 lldb::offset_t offset = lc_offset; 4844 for (i = 0; i < header.ncmds; ++i) { 4845 const lldb::offset_t cmd_offset = offset; 4846 if (data.GetU32(&offset, &load_cmd, 2) == nullptr) 4847 break; 4848 4849 if (load_cmd.cmd == LC_UUID) { 4850 const uint8_t *uuid_bytes = data.PeekData(offset, 16); 4851 4852 if (uuid_bytes) { 4853 // OpenCL on Mac OS X uses the same UUID for each of its object files. 4854 // We pretend these object files have no UUID to prevent crashing. 4855 4856 const uint8_t opencl_uuid[] = {0x8c, 0x8e, 0xb3, 0x9b, 0x3b, 0xa8, 4857 0x4b, 0x16, 0xb6, 0xa4, 0x27, 0x63, 4858 0xbb, 0x14, 0xf0, 0x0d}; 4859 4860 if (!memcmp(uuid_bytes, opencl_uuid, 16)) 4861 return UUID(); 4862 4863 return UUID::fromOptionalData(uuid_bytes, 16); 4864 } 4865 return UUID(); 4866 } 4867 offset = cmd_offset + load_cmd.cmdsize; 4868 } 4869 return UUID(); 4870 } 4871 4872 static llvm::StringRef GetOSName(uint32_t cmd) { 4873 switch (cmd) { 4874 case llvm::MachO::LC_VERSION_MIN_IPHONEOS: 4875 return llvm::Triple::getOSTypeName(llvm::Triple::IOS); 4876 case llvm::MachO::LC_VERSION_MIN_MACOSX: 4877 return llvm::Triple::getOSTypeName(llvm::Triple::MacOSX); 4878 case llvm::MachO::LC_VERSION_MIN_TVOS: 4879 return llvm::Triple::getOSTypeName(llvm::Triple::TvOS); 4880 case llvm::MachO::LC_VERSION_MIN_WATCHOS: 4881 return llvm::Triple::getOSTypeName(llvm::Triple::WatchOS); 4882 default: 4883 llvm_unreachable("unexpected LC_VERSION load command"); 4884 } 4885 } 4886 4887 namespace { 4888 struct OSEnv { 4889 llvm::StringRef os_type; 4890 llvm::StringRef environment; 4891 OSEnv(uint32_t cmd) { 4892 switch (cmd) { 4893 case llvm::MachO::PLATFORM_MACOS: 4894 os_type = llvm::Triple::getOSTypeName(llvm::Triple::MacOSX); 4895 return; 4896 case llvm::MachO::PLATFORM_IOS: 4897 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS); 4898 return; 4899 case llvm::MachO::PLATFORM_TVOS: 4900 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS); 4901 return; 4902 case llvm::MachO::PLATFORM_WATCHOS: 4903 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS); 4904 return; 4905 // NEED_BRIDGEOS_TRIPLE case llvm::MachO::PLATFORM_BRIDGEOS: 4906 // NEED_BRIDGEOS_TRIPLE os_type = 4907 // llvm::Triple::getOSTypeName(llvm::Triple::BridgeOS); 4908 // NEED_BRIDGEOS_TRIPLE return; 4909 case llvm::MachO::PLATFORM_MACCATALYST: 4910 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS); 4911 environment = llvm::Triple::getEnvironmentTypeName(llvm::Triple::MacABI); 4912 return; 4913 case llvm::MachO::PLATFORM_IOSSIMULATOR: 4914 os_type = llvm::Triple::getOSTypeName(llvm::Triple::IOS); 4915 environment = 4916 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator); 4917 return; 4918 case llvm::MachO::PLATFORM_TVOSSIMULATOR: 4919 os_type = llvm::Triple::getOSTypeName(llvm::Triple::TvOS); 4920 environment = 4921 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator); 4922 return; 4923 case llvm::MachO::PLATFORM_WATCHOSSIMULATOR: 4924 os_type = llvm::Triple::getOSTypeName(llvm::Triple::WatchOS); 4925 environment = 4926 llvm::Triple::getEnvironmentTypeName(llvm::Triple::Simulator); 4927 return; 4928 default: { 4929 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | 4930 LIBLLDB_LOG_PROCESS)); 4931 LLDB_LOGF(log, "unsupported platform in LC_BUILD_VERSION"); 4932 } 4933 } 4934 } 4935 }; 4936 4937 struct MinOS { 4938 uint32_t major_version, minor_version, patch_version; 4939 MinOS(uint32_t version) 4940 : major_version(version >> 16), minor_version((version >> 8) & 0xffu), 4941 patch_version(version & 0xffu) {} 4942 }; 4943 } // namespace 4944 4945 void ObjectFileMachO::GetAllArchSpecs(const llvm::MachO::mach_header &header, 4946 const lldb_private::DataExtractor &data, 4947 lldb::offset_t lc_offset, 4948 ModuleSpec &base_spec, 4949 lldb_private::ModuleSpecList &all_specs) { 4950 auto &base_arch = base_spec.GetArchitecture(); 4951 base_arch.SetArchitecture(eArchTypeMachO, header.cputype, header.cpusubtype); 4952 if (!base_arch.IsValid()) 4953 return; 4954 4955 bool found_any = false; 4956 auto add_triple = [&](const llvm::Triple &triple) { 4957 auto spec = base_spec; 4958 spec.GetArchitecture().GetTriple() = triple; 4959 if (spec.GetArchitecture().IsValid()) { 4960 spec.GetUUID() = ObjectFileMachO::GetUUID(header, data, lc_offset); 4961 all_specs.Append(spec); 4962 found_any = true; 4963 } 4964 }; 4965 4966 // Set OS to an unspecified unknown or a "*" so it can match any OS 4967 llvm::Triple base_triple = base_arch.GetTriple(); 4968 base_triple.setOS(llvm::Triple::UnknownOS); 4969 base_triple.setOSName(llvm::StringRef()); 4970 4971 if (header.filetype == MH_PRELOAD) { 4972 if (header.cputype == CPU_TYPE_ARM) { 4973 // If this is a 32-bit arm binary, and it's a standalone binary, force 4974 // the Vendor to Apple so we don't accidentally pick up the generic 4975 // armv7 ABI at runtime. Apple's armv7 ABI always uses r7 for the 4976 // frame pointer register; most other armv7 ABIs use a combination of 4977 // r7 and r11. 4978 base_triple.setVendor(llvm::Triple::Apple); 4979 } else { 4980 // Set vendor to an unspecified unknown or a "*" so it can match any 4981 // vendor This is required for correct behavior of EFI debugging on 4982 // x86_64 4983 base_triple.setVendor(llvm::Triple::UnknownVendor); 4984 base_triple.setVendorName(llvm::StringRef()); 4985 } 4986 return add_triple(base_triple); 4987 } 4988 4989 struct load_command load_cmd; 4990 4991 // See if there is an LC_VERSION_MIN_* load command that can give 4992 // us the OS type. 4993 lldb::offset_t offset = lc_offset; 4994 for (uint32_t i = 0; i < header.ncmds; ++i) { 4995 const lldb::offset_t cmd_offset = offset; 4996 if (data.GetU32(&offset, &load_cmd, 2) == NULL) 4997 break; 4998 4999 struct version_min_command version_min; 5000 switch (load_cmd.cmd) { 5001 case llvm::MachO::LC_VERSION_MIN_MACOSX: 5002 case llvm::MachO::LC_VERSION_MIN_IPHONEOS: 5003 case llvm::MachO::LC_VERSION_MIN_TVOS: 5004 case llvm::MachO::LC_VERSION_MIN_WATCHOS: { 5005 if (load_cmd.cmdsize != sizeof(version_min)) 5006 break; 5007 if (data.ExtractBytes(cmd_offset, sizeof(version_min), 5008 data.GetByteOrder(), &version_min) == 0) 5009 break; 5010 MinOS min_os(version_min.version); 5011 llvm::SmallString<32> os_name; 5012 llvm::raw_svector_ostream os(os_name); 5013 os << GetOSName(load_cmd.cmd) << min_os.major_version << '.' 5014 << min_os.minor_version << '.' << min_os.patch_version; 5015 5016 auto triple = base_triple; 5017 triple.setOSName(os.str()); 5018 5019 // Disambiguate legacy simulator platforms. 5020 if (load_cmd.cmd != llvm::MachO::LC_VERSION_MIN_MACOSX && 5021 (base_triple.getArch() == llvm::Triple::x86_64 || 5022 base_triple.getArch() == llvm::Triple::x86)) { 5023 // The combination of legacy LC_VERSION_MIN load command and 5024 // x86 architecture always indicates a simulator environment. 5025 // The combination of LC_VERSION_MIN and arm architecture only 5026 // appears for native binaries. Back-deploying simulator 5027 // binaries on Apple Silicon Macs use the modern unambigous 5028 // LC_BUILD_VERSION load commands; no special handling required. 5029 triple.setEnvironment(llvm::Triple::Simulator); 5030 } 5031 add_triple(triple); 5032 break; 5033 } 5034 default: 5035 break; 5036 } 5037 5038 offset = cmd_offset + load_cmd.cmdsize; 5039 } 5040 5041 // See if there are LC_BUILD_VERSION load commands that can give 5042 // us the OS type. 5043 offset = lc_offset; 5044 for (uint32_t i = 0; i < header.ncmds; ++i) { 5045 const lldb::offset_t cmd_offset = offset; 5046 if (data.GetU32(&offset, &load_cmd, 2) == NULL) 5047 break; 5048 5049 do { 5050 if (load_cmd.cmd == llvm::MachO::LC_BUILD_VERSION) { 5051 struct build_version_command build_version; 5052 if (load_cmd.cmdsize < sizeof(build_version)) { 5053 // Malformed load command. 5054 break; 5055 } 5056 if (data.ExtractBytes(cmd_offset, sizeof(build_version), 5057 data.GetByteOrder(), &build_version) == 0) 5058 break; 5059 MinOS min_os(build_version.minos); 5060 OSEnv os_env(build_version.platform); 5061 llvm::SmallString<16> os_name; 5062 llvm::raw_svector_ostream os(os_name); 5063 os << os_env.os_type << min_os.major_version << '.' 5064 << min_os.minor_version << '.' << min_os.patch_version; 5065 auto triple = base_triple; 5066 triple.setOSName(os.str()); 5067 os_name.clear(); 5068 if (!os_env.environment.empty()) 5069 triple.setEnvironmentName(os_env.environment); 5070 add_triple(triple); 5071 } 5072 } while (0); 5073 offset = cmd_offset + load_cmd.cmdsize; 5074 } 5075 5076 if (!found_any) { 5077 if (header.filetype == MH_KEXT_BUNDLE) { 5078 base_triple.setVendor(llvm::Triple::Apple); 5079 add_triple(base_triple); 5080 } else { 5081 // We didn't find a LC_VERSION_MIN load command and this isn't a KEXT 5082 // so lets not say our Vendor is Apple, leave it as an unspecified 5083 // unknown. 5084 base_triple.setVendor(llvm::Triple::UnknownVendor); 5085 base_triple.setVendorName(llvm::StringRef()); 5086 add_triple(base_triple); 5087 } 5088 } 5089 } 5090 5091 ArchSpec ObjectFileMachO::GetArchitecture( 5092 ModuleSP module_sp, const llvm::MachO::mach_header &header, 5093 const lldb_private::DataExtractor &data, lldb::offset_t lc_offset) { 5094 ModuleSpecList all_specs; 5095 ModuleSpec base_spec; 5096 GetAllArchSpecs(header, data, MachHeaderSizeFromMagic(header.magic), 5097 base_spec, all_specs); 5098 5099 // If the object file offers multiple alternative load commands, 5100 // pick the one that matches the module. 5101 if (module_sp) { 5102 const ArchSpec &module_arch = module_sp->GetArchitecture(); 5103 for (unsigned i = 0, e = all_specs.GetSize(); i != e; ++i) { 5104 ArchSpec mach_arch = 5105 all_specs.GetModuleSpecRefAtIndex(i).GetArchitecture(); 5106 if (module_arch.IsCompatibleMatch(mach_arch)) 5107 return mach_arch; 5108 } 5109 } 5110 5111 // Return the first arch we found. 5112 if (all_specs.GetSize() == 0) 5113 return {}; 5114 return all_specs.GetModuleSpecRefAtIndex(0).GetArchitecture(); 5115 } 5116 5117 UUID ObjectFileMachO::GetUUID() { 5118 ModuleSP module_sp(GetModule()); 5119 if (module_sp) { 5120 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 5121 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 5122 return GetUUID(m_header, m_data, offset); 5123 } 5124 return UUID(); 5125 } 5126 5127 uint32_t ObjectFileMachO::GetDependentModules(FileSpecList &files) { 5128 uint32_t count = 0; 5129 ModuleSP module_sp(GetModule()); 5130 if (module_sp) { 5131 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 5132 struct load_command load_cmd; 5133 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 5134 std::vector<std::string> rpath_paths; 5135 std::vector<std::string> rpath_relative_paths; 5136 std::vector<std::string> at_exec_relative_paths; 5137 uint32_t i; 5138 for (i = 0; i < m_header.ncmds; ++i) { 5139 const uint32_t cmd_offset = offset; 5140 if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr) 5141 break; 5142 5143 switch (load_cmd.cmd) { 5144 case LC_RPATH: 5145 case LC_LOAD_DYLIB: 5146 case LC_LOAD_WEAK_DYLIB: 5147 case LC_REEXPORT_DYLIB: 5148 case LC_LOAD_DYLINKER: 5149 case LC_LOADFVMLIB: 5150 case LC_LOAD_UPWARD_DYLIB: { 5151 uint32_t name_offset = cmd_offset + m_data.GetU32(&offset); 5152 const char *path = m_data.PeekCStr(name_offset); 5153 if (path) { 5154 if (load_cmd.cmd == LC_RPATH) 5155 rpath_paths.push_back(path); 5156 else { 5157 if (path[0] == '@') { 5158 if (strncmp(path, "@rpath", strlen("@rpath")) == 0) 5159 rpath_relative_paths.push_back(path + strlen("@rpath")); 5160 else if (strncmp(path, "@executable_path", 5161 strlen("@executable_path")) == 0) 5162 at_exec_relative_paths.push_back(path + 5163 strlen("@executable_path")); 5164 } else { 5165 FileSpec file_spec(path); 5166 if (files.AppendIfUnique(file_spec)) 5167 count++; 5168 } 5169 } 5170 } 5171 } break; 5172 5173 default: 5174 break; 5175 } 5176 offset = cmd_offset + load_cmd.cmdsize; 5177 } 5178 5179 FileSpec this_file_spec(m_file); 5180 FileSystem::Instance().Resolve(this_file_spec); 5181 5182 if (!rpath_paths.empty()) { 5183 // Fixup all LC_RPATH values to be absolute paths 5184 std::string loader_path("@loader_path"); 5185 std::string executable_path("@executable_path"); 5186 for (auto &rpath : rpath_paths) { 5187 if (llvm::StringRef(rpath).startswith(loader_path)) { 5188 rpath.erase(0, loader_path.size()); 5189 rpath.insert(0, this_file_spec.GetDirectory().GetCString()); 5190 } else if (llvm::StringRef(rpath).startswith(executable_path)) { 5191 rpath.erase(0, executable_path.size()); 5192 rpath.insert(0, this_file_spec.GetDirectory().GetCString()); 5193 } 5194 } 5195 5196 for (const auto &rpath_relative_path : rpath_relative_paths) { 5197 for (const auto &rpath : rpath_paths) { 5198 std::string path = rpath; 5199 path += rpath_relative_path; 5200 // It is OK to resolve this path because we must find a file on disk 5201 // for us to accept it anyway if it is rpath relative. 5202 FileSpec file_spec(path); 5203 FileSystem::Instance().Resolve(file_spec); 5204 if (FileSystem::Instance().Exists(file_spec) && 5205 files.AppendIfUnique(file_spec)) { 5206 count++; 5207 break; 5208 } 5209 } 5210 } 5211 } 5212 5213 // We may have @executable_paths but no RPATHS. Figure those out here. 5214 // Only do this if this object file is the executable. We have no way to 5215 // get back to the actual executable otherwise, so we won't get the right 5216 // path. 5217 if (!at_exec_relative_paths.empty() && CalculateType() == eTypeExecutable) { 5218 FileSpec exec_dir = this_file_spec.CopyByRemovingLastPathComponent(); 5219 for (const auto &at_exec_relative_path : at_exec_relative_paths) { 5220 FileSpec file_spec = 5221 exec_dir.CopyByAppendingPathComponent(at_exec_relative_path); 5222 if (FileSystem::Instance().Exists(file_spec) && 5223 files.AppendIfUnique(file_spec)) 5224 count++; 5225 } 5226 } 5227 } 5228 return count; 5229 } 5230 5231 lldb_private::Address ObjectFileMachO::GetEntryPointAddress() { 5232 // If the object file is not an executable it can't hold the entry point. 5233 // m_entry_point_address is initialized to an invalid address, so we can just 5234 // return that. If m_entry_point_address is valid it means we've found it 5235 // already, so return the cached value. 5236 5237 if ((!IsExecutable() && !IsDynamicLoader()) || 5238 m_entry_point_address.IsValid()) { 5239 return m_entry_point_address; 5240 } 5241 5242 // Otherwise, look for the UnixThread or Thread command. The data for the 5243 // Thread command is given in /usr/include/mach-o.h, but it is basically: 5244 // 5245 // uint32_t flavor - this is the flavor argument you would pass to 5246 // thread_get_state 5247 // uint32_t count - this is the count of longs in the thread state data 5248 // struct XXX_thread_state state - this is the structure from 5249 // <machine/thread_status.h> corresponding to the flavor. 5250 // <repeat this trio> 5251 // 5252 // So we just keep reading the various register flavors till we find the GPR 5253 // one, then read the PC out of there. 5254 // FIXME: We will need to have a "RegisterContext data provider" class at some 5255 // point that can get all the registers 5256 // out of data in this form & attach them to a given thread. That should 5257 // underlie the MacOS X User process plugin, and we'll also need it for the 5258 // MacOS X Core File process plugin. When we have that we can also use it 5259 // here. 5260 // 5261 // For now we hard-code the offsets and flavors we need: 5262 // 5263 // 5264 5265 ModuleSP module_sp(GetModule()); 5266 if (module_sp) { 5267 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 5268 struct load_command load_cmd; 5269 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 5270 uint32_t i; 5271 lldb::addr_t start_address = LLDB_INVALID_ADDRESS; 5272 bool done = false; 5273 5274 for (i = 0; i < m_header.ncmds; ++i) { 5275 const lldb::offset_t cmd_offset = offset; 5276 if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr) 5277 break; 5278 5279 switch (load_cmd.cmd) { 5280 case LC_UNIXTHREAD: 5281 case LC_THREAD: { 5282 while (offset < cmd_offset + load_cmd.cmdsize) { 5283 uint32_t flavor = m_data.GetU32(&offset); 5284 uint32_t count = m_data.GetU32(&offset); 5285 if (count == 0) { 5286 // We've gotten off somehow, log and exit; 5287 return m_entry_point_address; 5288 } 5289 5290 switch (m_header.cputype) { 5291 case llvm::MachO::CPU_TYPE_ARM: 5292 if (flavor == 1 || 5293 flavor == 9) // ARM_THREAD_STATE/ARM_THREAD_STATE32 5294 // from mach/arm/thread_status.h 5295 { 5296 offset += 60; // This is the offset of pc in the GPR thread state 5297 // data structure. 5298 start_address = m_data.GetU32(&offset); 5299 done = true; 5300 } 5301 break; 5302 case llvm::MachO::CPU_TYPE_ARM64: 5303 case llvm::MachO::CPU_TYPE_ARM64_32: 5304 if (flavor == 6) // ARM_THREAD_STATE64 from mach/arm/thread_status.h 5305 { 5306 offset += 256; // This is the offset of pc in the GPR thread state 5307 // data structure. 5308 start_address = m_data.GetU64(&offset); 5309 done = true; 5310 } 5311 break; 5312 case llvm::MachO::CPU_TYPE_I386: 5313 if (flavor == 5314 1) // x86_THREAD_STATE32 from mach/i386/thread_status.h 5315 { 5316 offset += 40; // This is the offset of eip in the GPR thread state 5317 // data structure. 5318 start_address = m_data.GetU32(&offset); 5319 done = true; 5320 } 5321 break; 5322 case llvm::MachO::CPU_TYPE_X86_64: 5323 if (flavor == 5324 4) // x86_THREAD_STATE64 from mach/i386/thread_status.h 5325 { 5326 offset += 16 * 8; // This is the offset of rip in the GPR thread 5327 // state data structure. 5328 start_address = m_data.GetU64(&offset); 5329 done = true; 5330 } 5331 break; 5332 default: 5333 return m_entry_point_address; 5334 } 5335 // Haven't found the GPR flavor yet, skip over the data for this 5336 // flavor: 5337 if (done) 5338 break; 5339 offset += count * 4; 5340 } 5341 } break; 5342 case LC_MAIN: { 5343 ConstString text_segment_name("__TEXT"); 5344 uint64_t entryoffset = m_data.GetU64(&offset); 5345 SectionSP text_segment_sp = 5346 GetSectionList()->FindSectionByName(text_segment_name); 5347 if (text_segment_sp) { 5348 done = true; 5349 start_address = text_segment_sp->GetFileAddress() + entryoffset; 5350 } 5351 } break; 5352 5353 default: 5354 break; 5355 } 5356 if (done) 5357 break; 5358 5359 // Go to the next load command: 5360 offset = cmd_offset + load_cmd.cmdsize; 5361 } 5362 5363 if (start_address == LLDB_INVALID_ADDRESS && IsDynamicLoader()) { 5364 if (GetSymtab()) { 5365 Symbol *dyld_start_sym = GetSymtab()->FindFirstSymbolWithNameAndType( 5366 ConstString("_dyld_start"), SymbolType::eSymbolTypeCode, 5367 Symtab::eDebugAny, Symtab::eVisibilityAny); 5368 if (dyld_start_sym && dyld_start_sym->GetAddress().IsValid()) { 5369 start_address = dyld_start_sym->GetAddress().GetFileAddress(); 5370 } 5371 } 5372 } 5373 5374 if (start_address != LLDB_INVALID_ADDRESS) { 5375 // We got the start address from the load commands, so now resolve that 5376 // address in the sections of this ObjectFile: 5377 if (!m_entry_point_address.ResolveAddressUsingFileSections( 5378 start_address, GetSectionList())) { 5379 m_entry_point_address.Clear(); 5380 } 5381 } else { 5382 // We couldn't read the UnixThread load command - maybe it wasn't there. 5383 // As a fallback look for the "start" symbol in the main executable. 5384 5385 ModuleSP module_sp(GetModule()); 5386 5387 if (module_sp) { 5388 SymbolContextList contexts; 5389 SymbolContext context; 5390 module_sp->FindSymbolsWithNameAndType(ConstString("start"), 5391 eSymbolTypeCode, contexts); 5392 if (contexts.GetSize()) { 5393 if (contexts.GetContextAtIndex(0, context)) 5394 m_entry_point_address = context.symbol->GetAddress(); 5395 } 5396 } 5397 } 5398 } 5399 5400 return m_entry_point_address; 5401 } 5402 5403 lldb_private::Address ObjectFileMachO::GetBaseAddress() { 5404 lldb_private::Address header_addr; 5405 SectionList *section_list = GetSectionList(); 5406 if (section_list) { 5407 SectionSP text_segment_sp( 5408 section_list->FindSectionByName(GetSegmentNameTEXT())); 5409 if (text_segment_sp) { 5410 header_addr.SetSection(text_segment_sp); 5411 header_addr.SetOffset(0); 5412 } 5413 } 5414 return header_addr; 5415 } 5416 5417 uint32_t ObjectFileMachO::GetNumThreadContexts() { 5418 ModuleSP module_sp(GetModule()); 5419 if (module_sp) { 5420 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 5421 if (!m_thread_context_offsets_valid) { 5422 m_thread_context_offsets_valid = true; 5423 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 5424 FileRangeArray::Entry file_range; 5425 thread_command thread_cmd; 5426 for (uint32_t i = 0; i < m_header.ncmds; ++i) { 5427 const uint32_t cmd_offset = offset; 5428 if (m_data.GetU32(&offset, &thread_cmd, 2) == nullptr) 5429 break; 5430 5431 if (thread_cmd.cmd == LC_THREAD) { 5432 file_range.SetRangeBase(offset); 5433 file_range.SetByteSize(thread_cmd.cmdsize - 8); 5434 m_thread_context_offsets.Append(file_range); 5435 } 5436 offset = cmd_offset + thread_cmd.cmdsize; 5437 } 5438 } 5439 } 5440 return m_thread_context_offsets.GetSize(); 5441 } 5442 5443 std::string ObjectFileMachO::GetIdentifierString() { 5444 std::string result; 5445 ModuleSP module_sp(GetModule()); 5446 if (module_sp) { 5447 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 5448 5449 // First, look over the load commands for an LC_NOTE load command with 5450 // data_owner string "kern ver str" & use that if found. 5451 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 5452 for (uint32_t i = 0; i < m_header.ncmds; ++i) { 5453 const uint32_t cmd_offset = offset; 5454 load_command lc; 5455 if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) 5456 break; 5457 if (lc.cmd == LC_NOTE) { 5458 char data_owner[17]; 5459 m_data.CopyData(offset, 16, data_owner); 5460 data_owner[16] = '\0'; 5461 offset += 16; 5462 uint64_t fileoff = m_data.GetU64_unchecked(&offset); 5463 uint64_t size = m_data.GetU64_unchecked(&offset); 5464 5465 // "kern ver str" has a uint32_t version and then a nul terminated 5466 // c-string. 5467 if (strcmp("kern ver str", data_owner) == 0) { 5468 offset = fileoff; 5469 uint32_t version; 5470 if (m_data.GetU32(&offset, &version, 1) != nullptr) { 5471 if (version == 1) { 5472 uint32_t strsize = size - sizeof(uint32_t); 5473 char *buf = (char *)malloc(strsize); 5474 if (buf) { 5475 m_data.CopyData(offset, strsize, buf); 5476 buf[strsize - 1] = '\0'; 5477 result = buf; 5478 if (buf) 5479 free(buf); 5480 return result; 5481 } 5482 } 5483 } 5484 } 5485 } 5486 offset = cmd_offset + lc.cmdsize; 5487 } 5488 5489 // Second, make a pass over the load commands looking for an obsolete 5490 // LC_IDENT load command. 5491 offset = MachHeaderSizeFromMagic(m_header.magic); 5492 for (uint32_t i = 0; i < m_header.ncmds; ++i) { 5493 const uint32_t cmd_offset = offset; 5494 struct ident_command ident_command; 5495 if (m_data.GetU32(&offset, &ident_command, 2) == nullptr) 5496 break; 5497 if (ident_command.cmd == LC_IDENT && ident_command.cmdsize != 0) { 5498 char *buf = (char *)malloc(ident_command.cmdsize); 5499 if (buf != nullptr && m_data.CopyData(offset, ident_command.cmdsize, 5500 buf) == ident_command.cmdsize) { 5501 buf[ident_command.cmdsize - 1] = '\0'; 5502 result = buf; 5503 } 5504 if (buf) 5505 free(buf); 5506 } 5507 offset = cmd_offset + ident_command.cmdsize; 5508 } 5509 } 5510 return result; 5511 } 5512 5513 bool ObjectFileMachO::GetCorefileMainBinaryInfo(addr_t &address, UUID &uuid, 5514 ObjectFile::BinaryType &type) { 5515 address = LLDB_INVALID_ADDRESS; 5516 uuid.Clear(); 5517 ModuleSP module_sp(GetModule()); 5518 if (module_sp) { 5519 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 5520 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 5521 for (uint32_t i = 0; i < m_header.ncmds; ++i) { 5522 const uint32_t cmd_offset = offset; 5523 load_command lc; 5524 if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) 5525 break; 5526 if (lc.cmd == LC_NOTE) { 5527 char data_owner[17]; 5528 memset(data_owner, 0, sizeof(data_owner)); 5529 m_data.CopyData(offset, 16, data_owner); 5530 offset += 16; 5531 uint64_t fileoff = m_data.GetU64_unchecked(&offset); 5532 uint64_t size = m_data.GetU64_unchecked(&offset); 5533 5534 // "main bin spec" (main binary specification) data payload is 5535 // formatted: 5536 // uint32_t version [currently 1] 5537 // uint32_t type [0 == unspecified, 1 == kernel, 5538 // 2 == user process, 3 == firmware ] 5539 // uint64_t address [ UINT64_MAX if address not specified ] 5540 // uuid_t uuid [ all zero's if uuid not specified ] 5541 // uint32_t log2_pagesize [ process page size in log base 5542 // 2, e.g. 4k pages are 12. 5543 // 0 for unspecified ] 5544 // uint32_t unused [ for alignment ] 5545 5546 if (strcmp("main bin spec", data_owner) == 0 && size >= 32) { 5547 offset = fileoff; 5548 uint32_t version; 5549 if (m_data.GetU32(&offset, &version, 1) != nullptr && version == 1) { 5550 uint32_t binspec_type = 0; 5551 uuid_t raw_uuid; 5552 memset(raw_uuid, 0, sizeof(uuid_t)); 5553 5554 if (m_data.GetU32(&offset, &binspec_type, 1) && 5555 m_data.GetU64(&offset, &address, 1) && 5556 m_data.CopyData(offset, sizeof(uuid_t), raw_uuid) != 0) { 5557 uuid = UUID::fromOptionalData(raw_uuid, sizeof(uuid_t)); 5558 // convert the "main bin spec" type into our 5559 // ObjectFile::BinaryType enum 5560 switch (binspec_type) { 5561 case 0: 5562 type = eBinaryTypeUnknown; 5563 break; 5564 case 1: 5565 type = eBinaryTypeKernel; 5566 break; 5567 case 2: 5568 type = eBinaryTypeUser; 5569 break; 5570 case 3: 5571 type = eBinaryTypeStandalone; 5572 break; 5573 } 5574 return true; 5575 } 5576 } 5577 } 5578 } 5579 offset = cmd_offset + lc.cmdsize; 5580 } 5581 } 5582 return false; 5583 } 5584 5585 lldb::RegisterContextSP 5586 ObjectFileMachO::GetThreadContextAtIndex(uint32_t idx, 5587 lldb_private::Thread &thread) { 5588 lldb::RegisterContextSP reg_ctx_sp; 5589 5590 ModuleSP module_sp(GetModule()); 5591 if (module_sp) { 5592 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 5593 if (!m_thread_context_offsets_valid) 5594 GetNumThreadContexts(); 5595 5596 const FileRangeArray::Entry *thread_context_file_range = 5597 m_thread_context_offsets.GetEntryAtIndex(idx); 5598 if (thread_context_file_range) { 5599 5600 DataExtractor data(m_data, thread_context_file_range->GetRangeBase(), 5601 thread_context_file_range->GetByteSize()); 5602 5603 switch (m_header.cputype) { 5604 case llvm::MachO::CPU_TYPE_ARM64: 5605 case llvm::MachO::CPU_TYPE_ARM64_32: 5606 reg_ctx_sp = 5607 std::make_shared<RegisterContextDarwin_arm64_Mach>(thread, data); 5608 break; 5609 5610 case llvm::MachO::CPU_TYPE_ARM: 5611 reg_ctx_sp = 5612 std::make_shared<RegisterContextDarwin_arm_Mach>(thread, data); 5613 break; 5614 5615 case llvm::MachO::CPU_TYPE_I386: 5616 reg_ctx_sp = 5617 std::make_shared<RegisterContextDarwin_i386_Mach>(thread, data); 5618 break; 5619 5620 case llvm::MachO::CPU_TYPE_X86_64: 5621 reg_ctx_sp = 5622 std::make_shared<RegisterContextDarwin_x86_64_Mach>(thread, data); 5623 break; 5624 } 5625 } 5626 } 5627 return reg_ctx_sp; 5628 } 5629 5630 ObjectFile::Type ObjectFileMachO::CalculateType() { 5631 switch (m_header.filetype) { 5632 case MH_OBJECT: // 0x1u 5633 if (GetAddressByteSize() == 4) { 5634 // 32 bit kexts are just object files, but they do have a valid 5635 // UUID load command. 5636 if (GetUUID()) { 5637 // this checking for the UUID load command is not enough we could 5638 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as 5639 // this is required of kexts 5640 if (m_strata == eStrataInvalid) 5641 m_strata = eStrataKernel; 5642 return eTypeSharedLibrary; 5643 } 5644 } 5645 return eTypeObjectFile; 5646 5647 case MH_EXECUTE: 5648 return eTypeExecutable; // 0x2u 5649 case MH_FVMLIB: 5650 return eTypeSharedLibrary; // 0x3u 5651 case MH_CORE: 5652 return eTypeCoreFile; // 0x4u 5653 case MH_PRELOAD: 5654 return eTypeSharedLibrary; // 0x5u 5655 case MH_DYLIB: 5656 return eTypeSharedLibrary; // 0x6u 5657 case MH_DYLINKER: 5658 return eTypeDynamicLinker; // 0x7u 5659 case MH_BUNDLE: 5660 return eTypeSharedLibrary; // 0x8u 5661 case MH_DYLIB_STUB: 5662 return eTypeStubLibrary; // 0x9u 5663 case MH_DSYM: 5664 return eTypeDebugInfo; // 0xAu 5665 case MH_KEXT_BUNDLE: 5666 return eTypeSharedLibrary; // 0xBu 5667 default: 5668 break; 5669 } 5670 return eTypeUnknown; 5671 } 5672 5673 ObjectFile::Strata ObjectFileMachO::CalculateStrata() { 5674 switch (m_header.filetype) { 5675 case MH_OBJECT: // 0x1u 5676 { 5677 // 32 bit kexts are just object files, but they do have a valid 5678 // UUID load command. 5679 if (GetUUID()) { 5680 // this checking for the UUID load command is not enough we could 5681 // eventually look for the symbol named "OSKextGetCurrentIdentifier" as 5682 // this is required of kexts 5683 if (m_type == eTypeInvalid) 5684 m_type = eTypeSharedLibrary; 5685 5686 return eStrataKernel; 5687 } 5688 } 5689 return eStrataUnknown; 5690 5691 case MH_EXECUTE: // 0x2u 5692 // Check for the MH_DYLDLINK bit in the flags 5693 if (m_header.flags & MH_DYLDLINK) { 5694 return eStrataUser; 5695 } else { 5696 SectionList *section_list = GetSectionList(); 5697 if (section_list) { 5698 static ConstString g_kld_section_name("__KLD"); 5699 if (section_list->FindSectionByName(g_kld_section_name)) 5700 return eStrataKernel; 5701 } 5702 } 5703 return eStrataRawImage; 5704 5705 case MH_FVMLIB: 5706 return eStrataUser; // 0x3u 5707 case MH_CORE: 5708 return eStrataUnknown; // 0x4u 5709 case MH_PRELOAD: 5710 return eStrataRawImage; // 0x5u 5711 case MH_DYLIB: 5712 return eStrataUser; // 0x6u 5713 case MH_DYLINKER: 5714 return eStrataUser; // 0x7u 5715 case MH_BUNDLE: 5716 return eStrataUser; // 0x8u 5717 case MH_DYLIB_STUB: 5718 return eStrataUser; // 0x9u 5719 case MH_DSYM: 5720 return eStrataUnknown; // 0xAu 5721 case MH_KEXT_BUNDLE: 5722 return eStrataKernel; // 0xBu 5723 default: 5724 break; 5725 } 5726 return eStrataUnknown; 5727 } 5728 5729 llvm::VersionTuple ObjectFileMachO::GetVersion() { 5730 ModuleSP module_sp(GetModule()); 5731 if (module_sp) { 5732 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 5733 struct dylib_command load_cmd; 5734 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 5735 uint32_t version_cmd = 0; 5736 uint64_t version = 0; 5737 uint32_t i; 5738 for (i = 0; i < m_header.ncmds; ++i) { 5739 const lldb::offset_t cmd_offset = offset; 5740 if (m_data.GetU32(&offset, &load_cmd, 2) == nullptr) 5741 break; 5742 5743 if (load_cmd.cmd == LC_ID_DYLIB) { 5744 if (version_cmd == 0) { 5745 version_cmd = load_cmd.cmd; 5746 if (m_data.GetU32(&offset, &load_cmd.dylib, 4) == nullptr) 5747 break; 5748 version = load_cmd.dylib.current_version; 5749 } 5750 break; // Break for now unless there is another more complete version 5751 // number load command in the future. 5752 } 5753 offset = cmd_offset + load_cmd.cmdsize; 5754 } 5755 5756 if (version_cmd == LC_ID_DYLIB) { 5757 unsigned major = (version & 0xFFFF0000ull) >> 16; 5758 unsigned minor = (version & 0x0000FF00ull) >> 8; 5759 unsigned subminor = (version & 0x000000FFull); 5760 return llvm::VersionTuple(major, minor, subminor); 5761 } 5762 } 5763 return llvm::VersionTuple(); 5764 } 5765 5766 ArchSpec ObjectFileMachO::GetArchitecture() { 5767 ModuleSP module_sp(GetModule()); 5768 ArchSpec arch; 5769 if (module_sp) { 5770 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex()); 5771 5772 return GetArchitecture(module_sp, m_header, m_data, 5773 MachHeaderSizeFromMagic(m_header.magic)); 5774 } 5775 return arch; 5776 } 5777 5778 void ObjectFileMachO::GetProcessSharedCacheUUID(Process *process, 5779 addr_t &base_addr, UUID &uuid) { 5780 uuid.Clear(); 5781 base_addr = LLDB_INVALID_ADDRESS; 5782 if (process && process->GetDynamicLoader()) { 5783 DynamicLoader *dl = process->GetDynamicLoader(); 5784 LazyBool using_shared_cache; 5785 LazyBool private_shared_cache; 5786 dl->GetSharedCacheInformation(base_addr, uuid, using_shared_cache, 5787 private_shared_cache); 5788 } 5789 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | 5790 LIBLLDB_LOG_PROCESS)); 5791 LLDB_LOGF( 5792 log, 5793 "inferior process shared cache has a UUID of %s, base address 0x%" PRIx64, 5794 uuid.GetAsString().c_str(), base_addr); 5795 } 5796 5797 // From dyld SPI header dyld_process_info.h 5798 typedef void *dyld_process_info; 5799 struct lldb_copy__dyld_process_cache_info { 5800 uuid_t cacheUUID; // UUID of cache used by process 5801 uint64_t cacheBaseAddress; // load address of dyld shared cache 5802 bool noCache; // process is running without a dyld cache 5803 bool privateCache; // process is using a private copy of its dyld cache 5804 }; 5805 5806 // #including mach/mach.h pulls in machine.h & CPU_TYPE_ARM etc conflicts with 5807 // llvm enum definitions llvm::MachO::CPU_TYPE_ARM turning them into compile 5808 // errors. So we need to use the actual underlying types of task_t and 5809 // kern_return_t below. 5810 extern "C" unsigned int /*task_t*/ mach_task_self(); 5811 5812 void ObjectFileMachO::GetLLDBSharedCacheUUID(addr_t &base_addr, UUID &uuid) { 5813 uuid.Clear(); 5814 base_addr = LLDB_INVALID_ADDRESS; 5815 5816 #if defined(__APPLE__) 5817 uint8_t *(*dyld_get_all_image_infos)(void); 5818 dyld_get_all_image_infos = 5819 (uint8_t * (*)()) dlsym(RTLD_DEFAULT, "_dyld_get_all_image_infos"); 5820 if (dyld_get_all_image_infos) { 5821 uint8_t *dyld_all_image_infos_address = dyld_get_all_image_infos(); 5822 if (dyld_all_image_infos_address) { 5823 uint32_t *version = (uint32_t *) 5824 dyld_all_image_infos_address; // version <mach-o/dyld_images.h> 5825 if (*version >= 13) { 5826 uuid_t *sharedCacheUUID_address = 0; 5827 int wordsize = sizeof(uint8_t *); 5828 if (wordsize == 8) { 5829 sharedCacheUUID_address = 5830 (uuid_t *)((uint8_t *)dyld_all_image_infos_address + 5831 160); // sharedCacheUUID <mach-o/dyld_images.h> 5832 if (*version >= 15) 5833 base_addr = 5834 *(uint64_t 5835 *)((uint8_t *)dyld_all_image_infos_address + 5836 176); // sharedCacheBaseAddress <mach-o/dyld_images.h> 5837 } else { 5838 sharedCacheUUID_address = 5839 (uuid_t *)((uint8_t *)dyld_all_image_infos_address + 5840 84); // sharedCacheUUID <mach-o/dyld_images.h> 5841 if (*version >= 15) { 5842 base_addr = 0; 5843 base_addr = 5844 *(uint32_t 5845 *)((uint8_t *)dyld_all_image_infos_address + 5846 100); // sharedCacheBaseAddress <mach-o/dyld_images.h> 5847 } 5848 } 5849 uuid = UUID::fromOptionalData(sharedCacheUUID_address, sizeof(uuid_t)); 5850 } 5851 } 5852 } else { 5853 // Exists in macOS 10.12 and later, iOS 10.0 and later - dyld SPI 5854 dyld_process_info (*dyld_process_info_create)( 5855 unsigned int /* task_t */ task, uint64_t timestamp, 5856 unsigned int /*kern_return_t*/ *kernelError); 5857 void (*dyld_process_info_get_cache)(void *info, void *cacheInfo); 5858 void (*dyld_process_info_release)(dyld_process_info info); 5859 5860 dyld_process_info_create = (void *(*)(unsigned int /* task_t */, uint64_t, 5861 unsigned int /*kern_return_t*/ *)) 5862 dlsym(RTLD_DEFAULT, "_dyld_process_info_create"); 5863 dyld_process_info_get_cache = (void (*)(void *, void *))dlsym( 5864 RTLD_DEFAULT, "_dyld_process_info_get_cache"); 5865 dyld_process_info_release = 5866 (void (*)(void *))dlsym(RTLD_DEFAULT, "_dyld_process_info_release"); 5867 5868 if (dyld_process_info_create && dyld_process_info_get_cache) { 5869 unsigned int /*kern_return_t */ kern_ret; 5870 dyld_process_info process_info = 5871 dyld_process_info_create(::mach_task_self(), 0, &kern_ret); 5872 if (process_info) { 5873 struct lldb_copy__dyld_process_cache_info sc_info; 5874 memset(&sc_info, 0, sizeof(struct lldb_copy__dyld_process_cache_info)); 5875 dyld_process_info_get_cache(process_info, &sc_info); 5876 if (sc_info.cacheBaseAddress != 0) { 5877 base_addr = sc_info.cacheBaseAddress; 5878 uuid = UUID::fromOptionalData(sc_info.cacheUUID, sizeof(uuid_t)); 5879 } 5880 dyld_process_info_release(process_info); 5881 } 5882 } 5883 } 5884 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS | 5885 LIBLLDB_LOG_PROCESS)); 5886 if (log && uuid.IsValid()) 5887 LLDB_LOGF(log, 5888 "lldb's in-memory shared cache has a UUID of %s base address of " 5889 "0x%" PRIx64, 5890 uuid.GetAsString().c_str(), base_addr); 5891 #endif 5892 } 5893 5894 llvm::VersionTuple ObjectFileMachO::GetMinimumOSVersion() { 5895 if (!m_min_os_version) { 5896 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 5897 for (uint32_t i = 0; i < m_header.ncmds; ++i) { 5898 const lldb::offset_t load_cmd_offset = offset; 5899 5900 version_min_command lc; 5901 if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) 5902 break; 5903 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX || 5904 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS || 5905 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS || 5906 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) { 5907 if (m_data.GetU32(&offset, &lc.version, 5908 (sizeof(lc) / sizeof(uint32_t)) - 2)) { 5909 const uint32_t xxxx = lc.version >> 16; 5910 const uint32_t yy = (lc.version >> 8) & 0xffu; 5911 const uint32_t zz = lc.version & 0xffu; 5912 if (xxxx) { 5913 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz); 5914 break; 5915 } 5916 } 5917 } else if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) { 5918 // struct build_version_command { 5919 // uint32_t cmd; /* LC_BUILD_VERSION */ 5920 // uint32_t cmdsize; /* sizeof(struct 5921 // build_version_command) plus */ 5922 // /* ntools * sizeof(struct 5923 // build_tool_version) */ 5924 // uint32_t platform; /* platform */ 5925 // uint32_t minos; /* X.Y.Z is encoded in nibbles 5926 // xxxx.yy.zz */ uint32_t sdk; /* X.Y.Z is encoded in 5927 // nibbles xxxx.yy.zz */ uint32_t ntools; /* number of 5928 // tool entries following this */ 5929 // }; 5930 5931 offset += 4; // skip platform 5932 uint32_t minos = m_data.GetU32(&offset); 5933 5934 const uint32_t xxxx = minos >> 16; 5935 const uint32_t yy = (minos >> 8) & 0xffu; 5936 const uint32_t zz = minos & 0xffu; 5937 if (xxxx) { 5938 m_min_os_version = llvm::VersionTuple(xxxx, yy, zz); 5939 break; 5940 } 5941 } 5942 5943 offset = load_cmd_offset + lc.cmdsize; 5944 } 5945 5946 if (!m_min_os_version) { 5947 // Set version to an empty value so we don't keep trying to 5948 m_min_os_version = llvm::VersionTuple(); 5949 } 5950 } 5951 5952 return *m_min_os_version; 5953 } 5954 5955 llvm::VersionTuple ObjectFileMachO::GetSDKVersion() { 5956 if (!m_sdk_versions.hasValue()) { 5957 lldb::offset_t offset = MachHeaderSizeFromMagic(m_header.magic); 5958 for (uint32_t i = 0; i < m_header.ncmds; ++i) { 5959 const lldb::offset_t load_cmd_offset = offset; 5960 5961 version_min_command lc; 5962 if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) 5963 break; 5964 if (lc.cmd == llvm::MachO::LC_VERSION_MIN_MACOSX || 5965 lc.cmd == llvm::MachO::LC_VERSION_MIN_IPHONEOS || 5966 lc.cmd == llvm::MachO::LC_VERSION_MIN_TVOS || 5967 lc.cmd == llvm::MachO::LC_VERSION_MIN_WATCHOS) { 5968 if (m_data.GetU32(&offset, &lc.version, 5969 (sizeof(lc) / sizeof(uint32_t)) - 2)) { 5970 const uint32_t xxxx = lc.sdk >> 16; 5971 const uint32_t yy = (lc.sdk >> 8) & 0xffu; 5972 const uint32_t zz = lc.sdk & 0xffu; 5973 if (xxxx) { 5974 m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz); 5975 break; 5976 } else { 5977 GetModule()->ReportWarning("minimum OS version load command with " 5978 "invalid (0) version found."); 5979 } 5980 } 5981 } 5982 offset = load_cmd_offset + lc.cmdsize; 5983 } 5984 5985 if (!m_sdk_versions.hasValue()) { 5986 offset = MachHeaderSizeFromMagic(m_header.magic); 5987 for (uint32_t i = 0; i < m_header.ncmds; ++i) { 5988 const lldb::offset_t load_cmd_offset = offset; 5989 5990 version_min_command lc; 5991 if (m_data.GetU32(&offset, &lc.cmd, 2) == nullptr) 5992 break; 5993 if (lc.cmd == llvm::MachO::LC_BUILD_VERSION) { 5994 // struct build_version_command { 5995 // uint32_t cmd; /* LC_BUILD_VERSION */ 5996 // uint32_t cmdsize; /* sizeof(struct 5997 // build_version_command) plus */ 5998 // /* ntools * sizeof(struct 5999 // build_tool_version) */ 6000 // uint32_t platform; /* platform */ 6001 // uint32_t minos; /* X.Y.Z is encoded in nibbles 6002 // xxxx.yy.zz */ uint32_t sdk; /* X.Y.Z is encoded 6003 // in nibbles xxxx.yy.zz */ uint32_t ntools; /* number 6004 // of tool entries following this */ 6005 // }; 6006 6007 offset += 4; // skip platform 6008 uint32_t minos = m_data.GetU32(&offset); 6009 6010 const uint32_t xxxx = minos >> 16; 6011 const uint32_t yy = (minos >> 8) & 0xffu; 6012 const uint32_t zz = minos & 0xffu; 6013 if (xxxx) { 6014 m_sdk_versions = llvm::VersionTuple(xxxx, yy, zz); 6015 break; 6016 } 6017 } 6018 offset = load_cmd_offset + lc.cmdsize; 6019 } 6020 } 6021 6022 if (!m_sdk_versions.hasValue()) 6023 m_sdk_versions = llvm::VersionTuple(); 6024 } 6025 6026 return m_sdk_versions.getValue(); 6027 } 6028 6029 bool ObjectFileMachO::GetIsDynamicLinkEditor() { 6030 return m_header.filetype == llvm::MachO::MH_DYLINKER; 6031 } 6032 6033 bool ObjectFileMachO::AllowAssemblyEmulationUnwindPlans() { 6034 return m_allow_assembly_emulation_unwind_plans; 6035 } 6036 6037 // PluginInterface protocol 6038 lldb_private::ConstString ObjectFileMachO::GetPluginName() { 6039 return GetPluginNameStatic(); 6040 } 6041 6042 uint32_t ObjectFileMachO::GetPluginVersion() { return 1; } 6043 6044 Section *ObjectFileMachO::GetMachHeaderSection() { 6045 // Find the first address of the mach header which is the first non-zero file 6046 // sized section whose file offset is zero. This is the base file address of 6047 // the mach-o file which can be subtracted from the vmaddr of the other 6048 // segments found in memory and added to the load address 6049 ModuleSP module_sp = GetModule(); 6050 if (!module_sp) 6051 return nullptr; 6052 SectionList *section_list = GetSectionList(); 6053 if (!section_list) 6054 return nullptr; 6055 const size_t num_sections = section_list->GetSize(); 6056 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) { 6057 Section *section = section_list->GetSectionAtIndex(sect_idx).get(); 6058 if (section->GetFileOffset() == 0 && SectionIsLoadable(section)) 6059 return section; 6060 } 6061 return nullptr; 6062 } 6063 6064 bool ObjectFileMachO::SectionIsLoadable(const Section *section) { 6065 if (!section) 6066 return false; 6067 const bool is_dsym = (m_header.filetype == MH_DSYM); 6068 if (section->GetFileSize() == 0 && !is_dsym) 6069 return false; 6070 if (section->IsThreadSpecific()) 6071 return false; 6072 if (GetModule().get() != section->GetModule().get()) 6073 return false; 6074 // Be careful with __LINKEDIT and __DWARF segments 6075 if (section->GetName() == GetSegmentNameLINKEDIT() || 6076 section->GetName() == GetSegmentNameDWARF()) { 6077 // Only map __LINKEDIT and __DWARF if we have an in memory image and 6078 // this isn't a kernel binary like a kext or mach_kernel. 6079 const bool is_memory_image = (bool)m_process_wp.lock(); 6080 const Strata strata = GetStrata(); 6081 if (is_memory_image == false || strata == eStrataKernel) 6082 return false; 6083 } 6084 return true; 6085 } 6086 6087 lldb::addr_t ObjectFileMachO::CalculateSectionLoadAddressForMemoryImage( 6088 lldb::addr_t header_load_address, const Section *header_section, 6089 const Section *section) { 6090 ModuleSP module_sp = GetModule(); 6091 if (module_sp && header_section && section && 6092 header_load_address != LLDB_INVALID_ADDRESS) { 6093 lldb::addr_t file_addr = header_section->GetFileAddress(); 6094 if (file_addr != LLDB_INVALID_ADDRESS && SectionIsLoadable(section)) 6095 return section->GetFileAddress() - file_addr + header_load_address; 6096 } 6097 return LLDB_INVALID_ADDRESS; 6098 } 6099 6100 bool ObjectFileMachO::SetLoadAddress(Target &target, lldb::addr_t value, 6101 bool value_is_offset) { 6102 ModuleSP module_sp = GetModule(); 6103 if (!module_sp) 6104 return false; 6105 6106 SectionList *section_list = GetSectionList(); 6107 if (!section_list) 6108 return false; 6109 6110 size_t num_loaded_sections = 0; 6111 const size_t num_sections = section_list->GetSize(); 6112 6113 if (value_is_offset) { 6114 // "value" is an offset to apply to each top level segment 6115 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) { 6116 // Iterate through the object file sections to find all of the 6117 // sections that size on disk (to avoid __PAGEZERO) and load them 6118 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx)); 6119 if (SectionIsLoadable(section_sp.get())) 6120 if (target.GetSectionLoadList().SetSectionLoadAddress( 6121 section_sp, section_sp->GetFileAddress() + value)) 6122 ++num_loaded_sections; 6123 } 6124 } else { 6125 // "value" is the new base address of the mach_header, adjust each 6126 // section accordingly 6127 6128 Section *mach_header_section = GetMachHeaderSection(); 6129 if (mach_header_section) { 6130 for (size_t sect_idx = 0; sect_idx < num_sections; ++sect_idx) { 6131 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx)); 6132 6133 lldb::addr_t section_load_addr = 6134 CalculateSectionLoadAddressForMemoryImage( 6135 value, mach_header_section, section_sp.get()); 6136 if (section_load_addr != LLDB_INVALID_ADDRESS) { 6137 if (target.GetSectionLoadList().SetSectionLoadAddress( 6138 section_sp, section_load_addr)) 6139 ++num_loaded_sections; 6140 } 6141 } 6142 } 6143 } 6144 return num_loaded_sections > 0; 6145 } 6146 6147 bool ObjectFileMachO::SaveCore(const lldb::ProcessSP &process_sp, 6148 const FileSpec &outfile, Status &error) { 6149 if (!process_sp) 6150 return false; 6151 6152 Target &target = process_sp->GetTarget(); 6153 const ArchSpec target_arch = target.GetArchitecture(); 6154 const llvm::Triple &target_triple = target_arch.GetTriple(); 6155 if (target_triple.getVendor() == llvm::Triple::Apple && 6156 (target_triple.getOS() == llvm::Triple::MacOSX || 6157 target_triple.getOS() == llvm::Triple::IOS || 6158 target_triple.getOS() == llvm::Triple::WatchOS || 6159 target_triple.getOS() == llvm::Triple::TvOS)) { 6160 // NEED_BRIDGEOS_TRIPLE target_triple.getOS() == llvm::Triple::BridgeOS)) 6161 // { 6162 bool make_core = false; 6163 switch (target_arch.GetMachine()) { 6164 case llvm::Triple::aarch64: 6165 case llvm::Triple::aarch64_32: 6166 case llvm::Triple::arm: 6167 case llvm::Triple::thumb: 6168 case llvm::Triple::x86: 6169 case llvm::Triple::x86_64: 6170 make_core = true; 6171 break; 6172 default: 6173 error.SetErrorStringWithFormat("unsupported core architecture: %s", 6174 target_triple.str().c_str()); 6175 break; 6176 } 6177 6178 if (make_core) { 6179 std::vector<segment_command_64> segment_load_commands; 6180 // uint32_t range_info_idx = 0; 6181 MemoryRegionInfo range_info; 6182 Status range_error = process_sp->GetMemoryRegionInfo(0, range_info); 6183 const uint32_t addr_byte_size = target_arch.GetAddressByteSize(); 6184 const ByteOrder byte_order = target_arch.GetByteOrder(); 6185 if (range_error.Success()) { 6186 while (range_info.GetRange().GetRangeBase() != LLDB_INVALID_ADDRESS) { 6187 const addr_t addr = range_info.GetRange().GetRangeBase(); 6188 const addr_t size = range_info.GetRange().GetByteSize(); 6189 6190 if (size == 0) 6191 break; 6192 6193 // Calculate correct protections 6194 uint32_t prot = 0; 6195 if (range_info.GetReadable() == MemoryRegionInfo::eYes) 6196 prot |= VM_PROT_READ; 6197 if (range_info.GetWritable() == MemoryRegionInfo::eYes) 6198 prot |= VM_PROT_WRITE; 6199 if (range_info.GetExecutable() == MemoryRegionInfo::eYes) 6200 prot |= VM_PROT_EXECUTE; 6201 6202 if (prot != 0) { 6203 uint32_t cmd_type = LC_SEGMENT_64; 6204 uint32_t segment_size = sizeof(segment_command_64); 6205 if (addr_byte_size == 4) { 6206 cmd_type = LC_SEGMENT; 6207 segment_size = sizeof(segment_command); 6208 } 6209 segment_command_64 segment = { 6210 cmd_type, // uint32_t cmd; 6211 segment_size, // uint32_t cmdsize; 6212 {0}, // char segname[16]; 6213 addr, // uint64_t vmaddr; // uint32_t for 32-bit Mach-O 6214 size, // uint64_t vmsize; // uint32_t for 32-bit Mach-O 6215 0, // uint64_t fileoff; // uint32_t for 32-bit Mach-O 6216 size, // uint64_t filesize; // uint32_t for 32-bit Mach-O 6217 prot, // uint32_t maxprot; 6218 prot, // uint32_t initprot; 6219 0, // uint32_t nsects; 6220 0}; // uint32_t flags; 6221 segment_load_commands.push_back(segment); 6222 } else { 6223 // No protections and a size of 1 used to be returned from old 6224 // debugservers when we asked about a region that was past the 6225 // last memory region and it indicates the end... 6226 if (size == 1) 6227 break; 6228 } 6229 6230 range_error = process_sp->GetMemoryRegionInfo( 6231 range_info.GetRange().GetRangeEnd(), range_info); 6232 if (range_error.Fail()) 6233 break; 6234 } 6235 6236 StreamString buffer(Stream::eBinary, addr_byte_size, byte_order); 6237 6238 mach_header_64 mach_header; 6239 if (addr_byte_size == 8) { 6240 mach_header.magic = MH_MAGIC_64; 6241 } else { 6242 mach_header.magic = MH_MAGIC; 6243 } 6244 mach_header.cputype = target_arch.GetMachOCPUType(); 6245 mach_header.cpusubtype = target_arch.GetMachOCPUSubType(); 6246 mach_header.filetype = MH_CORE; 6247 mach_header.ncmds = segment_load_commands.size(); 6248 mach_header.flags = 0; 6249 mach_header.reserved = 0; 6250 ThreadList &thread_list = process_sp->GetThreadList(); 6251 const uint32_t num_threads = thread_list.GetSize(); 6252 6253 // Make an array of LC_THREAD data items. Each one contains the 6254 // contents of the LC_THREAD load command. The data doesn't contain 6255 // the load command + load command size, we will add the load command 6256 // and load command size as we emit the data. 6257 std::vector<StreamString> LC_THREAD_datas(num_threads); 6258 for (auto &LC_THREAD_data : LC_THREAD_datas) { 6259 LC_THREAD_data.GetFlags().Set(Stream::eBinary); 6260 LC_THREAD_data.SetAddressByteSize(addr_byte_size); 6261 LC_THREAD_data.SetByteOrder(byte_order); 6262 } 6263 for (uint32_t thread_idx = 0; thread_idx < num_threads; ++thread_idx) { 6264 ThreadSP thread_sp(thread_list.GetThreadAtIndex(thread_idx)); 6265 if (thread_sp) { 6266 switch (mach_header.cputype) { 6267 case llvm::MachO::CPU_TYPE_ARM64: 6268 case llvm::MachO::CPU_TYPE_ARM64_32: 6269 RegisterContextDarwin_arm64_Mach::Create_LC_THREAD( 6270 thread_sp.get(), LC_THREAD_datas[thread_idx]); 6271 break; 6272 6273 case llvm::MachO::CPU_TYPE_ARM: 6274 RegisterContextDarwin_arm_Mach::Create_LC_THREAD( 6275 thread_sp.get(), LC_THREAD_datas[thread_idx]); 6276 break; 6277 6278 case llvm::MachO::CPU_TYPE_I386: 6279 RegisterContextDarwin_i386_Mach::Create_LC_THREAD( 6280 thread_sp.get(), LC_THREAD_datas[thread_idx]); 6281 break; 6282 6283 case llvm::MachO::CPU_TYPE_X86_64: 6284 RegisterContextDarwin_x86_64_Mach::Create_LC_THREAD( 6285 thread_sp.get(), LC_THREAD_datas[thread_idx]); 6286 break; 6287 } 6288 } 6289 } 6290 6291 // The size of the load command is the size of the segments... 6292 if (addr_byte_size == 8) { 6293 mach_header.sizeofcmds = 6294 segment_load_commands.size() * sizeof(struct segment_command_64); 6295 } else { 6296 mach_header.sizeofcmds = 6297 segment_load_commands.size() * sizeof(struct segment_command); 6298 } 6299 6300 // and the size of all LC_THREAD load command 6301 for (const auto &LC_THREAD_data : LC_THREAD_datas) { 6302 ++mach_header.ncmds; 6303 mach_header.sizeofcmds += 8 + LC_THREAD_data.GetSize(); 6304 } 6305 6306 // Write the mach header 6307 buffer.PutHex32(mach_header.magic); 6308 buffer.PutHex32(mach_header.cputype); 6309 buffer.PutHex32(mach_header.cpusubtype); 6310 buffer.PutHex32(mach_header.filetype); 6311 buffer.PutHex32(mach_header.ncmds); 6312 buffer.PutHex32(mach_header.sizeofcmds); 6313 buffer.PutHex32(mach_header.flags); 6314 if (addr_byte_size == 8) { 6315 buffer.PutHex32(mach_header.reserved); 6316 } 6317 6318 // Skip the mach header and all load commands and align to the next 6319 // 0x1000 byte boundary 6320 addr_t file_offset = buffer.GetSize() + mach_header.sizeofcmds; 6321 if (file_offset & 0x00000fff) { 6322 file_offset += 0x00001000ull; 6323 file_offset &= (~0x00001000ull + 1); 6324 } 6325 6326 for (auto &segment : segment_load_commands) { 6327 segment.fileoff = file_offset; 6328 file_offset += segment.filesize; 6329 } 6330 6331 // Write out all of the LC_THREAD load commands 6332 for (const auto &LC_THREAD_data : LC_THREAD_datas) { 6333 const size_t LC_THREAD_data_size = LC_THREAD_data.GetSize(); 6334 buffer.PutHex32(LC_THREAD); 6335 buffer.PutHex32(8 + LC_THREAD_data_size); // cmd + cmdsize + data 6336 buffer.Write(LC_THREAD_data.GetString().data(), LC_THREAD_data_size); 6337 } 6338 6339 // Write out all of the segment load commands 6340 for (const auto &segment : segment_load_commands) { 6341 printf("0x%8.8x 0x%8.8x [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 6342 ") [0x%16.16" PRIx64 " 0x%16.16" PRIx64 6343 ") 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x]\n", 6344 segment.cmd, segment.cmdsize, segment.vmaddr, 6345 segment.vmaddr + segment.vmsize, segment.fileoff, 6346 segment.filesize, segment.maxprot, segment.initprot, 6347 segment.nsects, segment.flags); 6348 6349 buffer.PutHex32(segment.cmd); 6350 buffer.PutHex32(segment.cmdsize); 6351 buffer.PutRawBytes(segment.segname, sizeof(segment.segname)); 6352 if (addr_byte_size == 8) { 6353 buffer.PutHex64(segment.vmaddr); 6354 buffer.PutHex64(segment.vmsize); 6355 buffer.PutHex64(segment.fileoff); 6356 buffer.PutHex64(segment.filesize); 6357 } else { 6358 buffer.PutHex32(static_cast<uint32_t>(segment.vmaddr)); 6359 buffer.PutHex32(static_cast<uint32_t>(segment.vmsize)); 6360 buffer.PutHex32(static_cast<uint32_t>(segment.fileoff)); 6361 buffer.PutHex32(static_cast<uint32_t>(segment.filesize)); 6362 } 6363 buffer.PutHex32(segment.maxprot); 6364 buffer.PutHex32(segment.initprot); 6365 buffer.PutHex32(segment.nsects); 6366 buffer.PutHex32(segment.flags); 6367 } 6368 6369 std::string core_file_path(outfile.GetPath()); 6370 auto core_file = FileSystem::Instance().Open( 6371 outfile, File::eOpenOptionWrite | File::eOpenOptionTruncate | 6372 File::eOpenOptionCanCreate); 6373 if (!core_file) { 6374 error = core_file.takeError(); 6375 } else { 6376 // Read 1 page at a time 6377 uint8_t bytes[0x1000]; 6378 // Write the mach header and load commands out to the core file 6379 size_t bytes_written = buffer.GetString().size(); 6380 error = 6381 core_file.get()->Write(buffer.GetString().data(), bytes_written); 6382 if (error.Success()) { 6383 // Now write the file data for all memory segments in the process 6384 for (const auto &segment : segment_load_commands) { 6385 if (core_file.get()->SeekFromStart(segment.fileoff) == -1) { 6386 error.SetErrorStringWithFormat( 6387 "unable to seek to offset 0x%" PRIx64 " in '%s'", 6388 segment.fileoff, core_file_path.c_str()); 6389 break; 6390 } 6391 6392 printf("Saving %" PRId64 6393 " bytes of data for memory region at 0x%" PRIx64 "\n", 6394 segment.vmsize, segment.vmaddr); 6395 addr_t bytes_left = segment.vmsize; 6396 addr_t addr = segment.vmaddr; 6397 Status memory_read_error; 6398 while (bytes_left > 0 && error.Success()) { 6399 const size_t bytes_to_read = 6400 bytes_left > sizeof(bytes) ? sizeof(bytes) : bytes_left; 6401 6402 // In a savecore setting, we don't really care about caching, 6403 // as the data is dumped and very likely never read again, 6404 // so we call ReadMemoryFromInferior to bypass it. 6405 const size_t bytes_read = process_sp->ReadMemoryFromInferior( 6406 addr, bytes, bytes_to_read, memory_read_error); 6407 6408 if (bytes_read == bytes_to_read) { 6409 size_t bytes_written = bytes_read; 6410 error = core_file.get()->Write(bytes, bytes_written); 6411 bytes_left -= bytes_read; 6412 addr += bytes_read; 6413 } else { 6414 // Some pages within regions are not readable, those should 6415 // be zero filled 6416 memset(bytes, 0, bytes_to_read); 6417 size_t bytes_written = bytes_to_read; 6418 error = core_file.get()->Write(bytes, bytes_written); 6419 bytes_left -= bytes_to_read; 6420 addr += bytes_to_read; 6421 } 6422 } 6423 } 6424 } 6425 } 6426 } else { 6427 error.SetErrorString( 6428 "process doesn't support getting memory region info"); 6429 } 6430 } 6431 return true; // This is the right plug to handle saving core files for 6432 // this process 6433 } 6434 return false; 6435 } 6436