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