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