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