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