1202 lines · cpp
1//===-- DynamicLoaderMacOSXDYLD.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-exception6//7//===----------------------------------------------------------------------===//8 9#include "DynamicLoaderMacOSXDYLD.h"10#include "DynamicLoaderDarwin.h"11#include "DynamicLoaderMacOS.h"12#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"13#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"14#include "lldb/Breakpoint/StoppointCallbackContext.h"15#include "lldb/Core/Debugger.h"16#include "lldb/Core/Module.h"17#include "lldb/Core/ModuleSpec.h"18#include "lldb/Core/PluginManager.h"19#include "lldb/Core/Section.h"20#include "lldb/Symbol/Function.h"21#include "lldb/Symbol/ObjectFile.h"22#include "lldb/Target/ABI.h"23#include "lldb/Target/RegisterContext.h"24#include "lldb/Target/StackFrame.h"25#include "lldb/Target/Target.h"26#include "lldb/Target/Thread.h"27#include "lldb/Target/ThreadPlanRunToAddress.h"28#include "lldb/Utility/DataBuffer.h"29#include "lldb/Utility/DataBufferHeap.h"30#include "lldb/Utility/LLDBLog.h"31#include "lldb/Utility/Log.h"32#include "lldb/Utility/State.h"33 34//#define ENABLE_DEBUG_PRINTF // COMMENT THIS LINE OUT PRIOR TO CHECKIN35#ifdef ENABLE_DEBUG_PRINTF36#include <cstdio>37#define DEBUG_PRINTF(fmt, ...) printf(fmt, ##__VA_ARGS__)38#else39#define DEBUG_PRINTF(fmt, ...)40#endif41 42#ifndef __APPLE__43#include "lldb/Utility/AppleUuidCompatibility.h"44#else45#include <uuid/uuid.h>46#endif47 48using namespace lldb;49using namespace lldb_private;50 51LLDB_PLUGIN_DEFINE(DynamicLoaderMacOSXDYLD)52 53// Create an instance of this class. This function is filled into the plugin54// info class that gets handed out by the plugin factory and allows the lldb to55// instantiate an instance of this class.56DynamicLoader *DynamicLoaderMacOSXDYLD::CreateInstance(Process *process,57 bool force) {58 bool create = force;59 if (!create) {60 create = true;61 Module *exe_module = process->GetTarget().GetExecutableModulePointer();62 if (exe_module) {63 ObjectFile *object_file = exe_module->GetObjectFile();64 if (object_file) {65 create = (object_file->GetStrata() == ObjectFile::eStrataUser);66 }67 }68 69 if (create) {70 const llvm::Triple &triple_ref =71 process->GetTarget().GetArchitecture().GetTriple();72 switch (triple_ref.getOS()) {73 case llvm::Triple::Darwin:74 case llvm::Triple::MacOSX:75 case llvm::Triple::IOS:76 case llvm::Triple::TvOS:77 case llvm::Triple::WatchOS:78 case llvm::Triple::BridgeOS:79 case llvm::Triple::DriverKit:80 case llvm::Triple::XROS:81 create = triple_ref.getVendor() == llvm::Triple::Apple;82 break;83 default:84 create = false;85 break;86 }87 }88 }89 90 if (UseDYLDSPI(process)) {91 create = false;92 }93 94 if (create)95 return new DynamicLoaderMacOSXDYLD(process);96 return nullptr;97}98 99// Constructor100DynamicLoaderMacOSXDYLD::DynamicLoaderMacOSXDYLD(Process *process)101 : DynamicLoaderDarwin(process),102 m_dyld_all_image_infos_addr(LLDB_INVALID_ADDRESS),103 m_dyld_all_image_infos(), m_dyld_all_image_infos_stop_id(UINT32_MAX),104 m_break_id(LLDB_INVALID_BREAK_ID), m_mutex(),105 m_process_image_addr_is_all_images_infos(false) {}106 107// Destructor108DynamicLoaderMacOSXDYLD::~DynamicLoaderMacOSXDYLD() {109 if (LLDB_BREAK_ID_IS_VALID(m_break_id))110 m_process->GetTarget().RemoveBreakpointByID(m_break_id);111}112 113bool DynamicLoaderMacOSXDYLD::ProcessDidExec() {114 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());115 bool did_exec = false;116 if (m_process) {117 // If we are stopped after an exec, we will have only one thread...118 if (m_process->GetThreadList().GetSize() == 1) {119 // We know if a process has exec'ed if our "m_dyld_all_image_infos_addr"120 // value differs from the Process' image info address. When a process121 // execs itself it might cause a change if ASLR is enabled.122 const addr_t shlib_addr = m_process->GetImageInfoAddress();123 if (m_process_image_addr_is_all_images_infos &&124 shlib_addr != m_dyld_all_image_infos_addr) {125 // The image info address from the process is the126 // 'dyld_all_image_infos' address and it has changed.127 did_exec = true;128 } else if (!m_process_image_addr_is_all_images_infos &&129 shlib_addr == m_dyld.address) {130 // The image info address from the process is the mach_header address131 // for dyld and it has changed.132 did_exec = true;133 } else {134 // ASLR might be disabled and dyld could have ended up in the same135 // location. We should try and detect if we are stopped at136 // '_dyld_start'137 ThreadSP thread_sp(m_process->GetThreadList().GetThreadAtIndex(0));138 if (thread_sp) {139 lldb::StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));140 if (frame_sp) {141 const Symbol *symbol =142 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol;143 if (symbol) {144 if (symbol->GetName() == "_dyld_start")145 did_exec = true;146 }147 }148 }149 }150 151 if (did_exec) {152 m_libpthread_module_wp.reset();153 m_pthread_getspecific_addr.Clear();154 }155 }156 }157 return did_exec;158}159 160// Clear out the state of this class.161void DynamicLoaderMacOSXDYLD::DoClear() {162 std::lock_guard<std::recursive_mutex> guard(m_mutex);163 164 if (LLDB_BREAK_ID_IS_VALID(m_break_id))165 m_process->GetTarget().RemoveBreakpointByID(m_break_id);166 167 m_dyld_all_image_infos_addr = LLDB_INVALID_ADDRESS;168 m_dyld_all_image_infos.Clear();169 m_break_id = LLDB_INVALID_BREAK_ID;170}171 172// Check if we have found DYLD yet173bool DynamicLoaderMacOSXDYLD::DidSetNotificationBreakpoint() {174 return LLDB_BREAK_ID_IS_VALID(m_break_id);175}176 177void DynamicLoaderMacOSXDYLD::ClearNotificationBreakpoint() {178 if (LLDB_BREAK_ID_IS_VALID(m_break_id)) {179 m_process->GetTarget().RemoveBreakpointByID(m_break_id);180 }181}182 183// Try and figure out where dyld is by first asking the Process if it knows184// (which currently calls down in the lldb::Process to get the DYLD info185// (available on SnowLeopard only). If that fails, then check in the default186// addresses.187void DynamicLoaderMacOSXDYLD::DoInitialImageFetch() {188 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS) {189 // Check the image info addr as it might point to the mach header for dyld,190 // or it might point to the dyld_all_image_infos struct191 const addr_t shlib_addr = m_process->GetImageInfoAddress();192 if (shlib_addr != LLDB_INVALID_ADDRESS) {193 ByteOrder byte_order =194 m_process->GetTarget().GetArchitecture().GetByteOrder();195 uint8_t buf[4];196 DataExtractor data(buf, sizeof(buf), byte_order, 4);197 Status error;198 if (m_process->ReadMemory(shlib_addr, buf, 4, error) == 4) {199 lldb::offset_t offset = 0;200 uint32_t magic = data.GetU32(&offset);201 switch (magic) {202 case llvm::MachO::MH_MAGIC:203 case llvm::MachO::MH_MAGIC_64:204 case llvm::MachO::MH_CIGAM:205 case llvm::MachO::MH_CIGAM_64:206 m_process_image_addr_is_all_images_infos = false;207 ReadDYLDInfoFromMemoryAndSetNotificationCallback(shlib_addr);208 return;209 210 default:211 break;212 }213 }214 // Maybe it points to the all image infos?215 m_dyld_all_image_infos_addr = shlib_addr;216 m_process_image_addr_is_all_images_infos = true;217 }218 }219 220 if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {221 if (ReadAllImageInfosStructure()) {222 if (m_dyld_all_image_infos.dyldImageLoadAddress != LLDB_INVALID_ADDRESS)223 ReadDYLDInfoFromMemoryAndSetNotificationCallback(224 m_dyld_all_image_infos.dyldImageLoadAddress);225 else226 ReadDYLDInfoFromMemoryAndSetNotificationCallback(227 m_dyld_all_image_infos_addr & 0xfffffffffff00000ull);228 return;229 }230 }231 232 // Check some default values233 Module *executable = m_process->GetTarget().GetExecutableModulePointer();234 235 if (executable) {236 const ArchSpec &exe_arch = executable->GetArchitecture();237 if (exe_arch.GetAddressByteSize() == 8) {238 ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x7fff5fc00000ull);239 } else if (exe_arch.GetMachine() == llvm::Triple::arm ||240 exe_arch.GetMachine() == llvm::Triple::thumb ||241 exe_arch.GetMachine() == llvm::Triple::aarch64 ||242 exe_arch.GetMachine() == llvm::Triple::aarch64_32) {243 ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x2fe00000);244 } else {245 ReadDYLDInfoFromMemoryAndSetNotificationCallback(0x8fe00000);246 }247 }248}249 250// Assume that dyld is in memory at ADDR and try to parse it's load commands251bool DynamicLoaderMacOSXDYLD::ReadDYLDInfoFromMemoryAndSetNotificationCallback(252 lldb::addr_t addr) {253 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());254 DataExtractor data; // Load command data255 static ConstString g_dyld_all_image_infos("dyld_all_image_infos");256 static ConstString g_new_dyld_all_image_infos("dyld4::dyld_all_image_infos");257 if (ReadMachHeader(addr, &m_dyld.header, &data)) {258 if (m_dyld.header.filetype == llvm::MachO::MH_DYLINKER) {259 m_dyld.address = addr;260 ModuleSP dyld_module_sp;261 if (ParseLoadCommands(data, m_dyld, &m_dyld.file_spec)) {262 if (m_dyld.file_spec) {263 if (!UpdateDYLDImageInfoFromNewImageInfo(m_dyld))264 return false;265 }266 }267 dyld_module_sp = GetDYLDModule();268 if (!dyld_module_sp)269 return false;270 271 Target &target = m_process->GetTarget();272 273 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS &&274 dyld_module_sp.get()) {275 const Symbol *symbol = dyld_module_sp->FindFirstSymbolWithNameAndType(276 g_dyld_all_image_infos, eSymbolTypeData);277 if (!symbol) {278 symbol = dyld_module_sp->FindFirstSymbolWithNameAndType(279 g_new_dyld_all_image_infos, eSymbolTypeData);280 }281 if (symbol)282 m_dyld_all_image_infos_addr = symbol->GetLoadAddress(&target);283 }284 285 if (m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS) {286 ConstString g_sect_name("__all_image_info");287 SectionSP dyld_aii_section_sp =288 dyld_module_sp->GetSectionList()->FindSectionByName(g_sect_name);289 if (dyld_aii_section_sp) {290 Address dyld_aii_addr(dyld_aii_section_sp, 0);291 m_dyld_all_image_infos_addr = dyld_aii_addr.GetLoadAddress(&target);292 }293 }294 295 // Update all image infos296 InitializeFromAllImageInfos();297 298 // If we didn't have an executable before, but now we do, then the dyld299 // module shared pointer might be unique and we may need to add it again300 // (since Target::SetExecutableModule() will clear the images). So append301 // the dyld module back to the list if it is302 /// unique!303 if (dyld_module_sp) {304 target.GetImages().AppendIfNeeded(dyld_module_sp);305 306 // At this point we should have read in dyld's module, and so we should307 // set breakpoints in it:308 ModuleList modules;309 modules.Append(dyld_module_sp);310 target.ModulesDidLoad(modules);311 SetDYLDModule(dyld_module_sp);312 }313 314 return true;315 }316 }317 return false;318}319 320bool DynamicLoaderMacOSXDYLD::NeedToDoInitialImageFetch() {321 return m_dyld_all_image_infos_addr == LLDB_INVALID_ADDRESS;322}323 324// Static callback function that gets called when our DYLD notification325// breakpoint gets hit. We update all of our image infos and then let our super326// class DynamicLoader class decide if we should stop or not (based on global327// preference).328bool DynamicLoaderMacOSXDYLD::NotifyBreakpointHit(329 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,330 lldb::user_id_t break_loc_id) {331 // Let the event know that the images have changed332 // DYLD passes three arguments to the notification breakpoint.333 // Arg1: enum dyld_image_mode mode - 0 = adding, 1 = removing Arg2: uint32_t334 // infoCount - Number of shared libraries added Arg3: dyld_image_info335 // info[] - Array of structs of the form:336 // const struct mach_header337 // *imageLoadAddress338 // const char *imageFilePath339 // uintptr_t imageFileModDate (a time_t)340 341 DynamicLoaderMacOSXDYLD *dyld_instance = (DynamicLoaderMacOSXDYLD *)baton;342 343 // First step is to see if we've already initialized the all image infos. If344 // we haven't then this function will do so and return true. In the course345 // of initializing the all_image_infos it will read the complete current346 // state, so we don't need to figure out what has changed from the data347 // passed in to us.348 349 ExecutionContext exe_ctx(context->exe_ctx_ref);350 Process *process = exe_ctx.GetProcessPtr();351 352 // This is a sanity check just in case this dyld_instance is an old dyld353 // plugin's breakpoint still lying around.354 if (process != dyld_instance->m_process)355 return false;356 357 if (dyld_instance->InitializeFromAllImageInfos())358 return dyld_instance->GetStopWhenImagesChange();359 360 const lldb::ABISP &abi = process->GetABI();361 if (abi) {362 // Build up the value array to store the three arguments given above, then363 // get the values from the ABI:364 365 TypeSystemClangSP scratch_ts_sp =366 ScratchTypeSystemClang::GetForTarget(process->GetTarget());367 if (!scratch_ts_sp)368 return false;369 370 ValueList argument_values;371 Value input_value;372 373 CompilerType clang_void_ptr_type =374 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();375 CompilerType clang_uint32_type =376 scratch_ts_sp->GetBuiltinTypeForEncodingAndBitSize(lldb::eEncodingUint,377 32);378 input_value.SetValueType(Value::ValueType::Scalar);379 input_value.SetCompilerType(clang_uint32_type);380 // input_value.SetContext (Value::eContextTypeClangType,381 // clang_uint32_type);382 argument_values.PushValue(input_value);383 argument_values.PushValue(input_value);384 input_value.SetCompilerType(clang_void_ptr_type);385 // input_value.SetContext (Value::eContextTypeClangType,386 // clang_void_ptr_type);387 argument_values.PushValue(input_value);388 389 if (abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values)) {390 uint32_t dyld_mode =391 argument_values.GetValueAtIndex(0)->GetScalar().UInt(-1);392 if (dyld_mode != static_cast<uint32_t>(-1)) {393 // Okay the mode was right, now get the number of elements, and the394 // array of new elements...395 uint32_t image_infos_count =396 argument_values.GetValueAtIndex(1)->GetScalar().UInt(-1);397 if (image_infos_count != static_cast<uint32_t>(-1)) {398 // Got the number added, now go through the array of added elements,399 // putting out the mach header address, and adding the image. Note,400 // I'm not putting in logging here, since the AddModules &401 // RemoveModules functions do all the logging internally.402 403 lldb::addr_t image_infos_addr =404 argument_values.GetValueAtIndex(2)->GetScalar().ULongLong();405 if (dyld_mode == 0) {406 // This is add:407 dyld_instance->AddModulesUsingImageInfosAddress(image_infos_addr,408 image_infos_count);409 } else {410 // This is remove:411 dyld_instance->RemoveModulesUsingImageInfosAddress(412 image_infos_addr, image_infos_count);413 }414 }415 }416 }417 } else {418 Target &target = process->GetTarget();419 Debugger::ReportWarning(420 "no ABI plugin located for triple " +421 target.GetArchitecture().GetTriple().getTriple() +422 ": shared libraries will not be registered",423 target.GetDebugger().GetID());424 }425 426 // Return true to stop the target, false to just let the target run427 return dyld_instance->GetStopWhenImagesChange();428}429 430bool DynamicLoaderMacOSXDYLD::ReadAllImageInfosStructure() {431 std::lock_guard<std::recursive_mutex> guard(m_mutex);432 433 // the all image infos is already valid for this process stop ID434 if (m_process->GetStopID() == m_dyld_all_image_infos_stop_id)435 return true;436 437 m_dyld_all_image_infos.Clear();438 if (m_dyld_all_image_infos_addr != LLDB_INVALID_ADDRESS) {439 ByteOrder byte_order =440 m_process->GetTarget().GetArchitecture().GetByteOrder();441 uint32_t addr_size =442 m_process->GetTarget().GetArchitecture().GetAddressByteSize();443 444 uint8_t buf[256];445 DataExtractor data(buf, sizeof(buf), byte_order, addr_size);446 lldb::offset_t offset = 0;447 448 const size_t count_v2 = sizeof(uint32_t) + // version449 sizeof(uint32_t) + // infoArrayCount450 addr_size + // infoArray451 addr_size + // notification452 addr_size + // processDetachedFromSharedRegion +453 // libSystemInitialized + pad454 addr_size; // dyldImageLoadAddress455 const size_t count_v11 = count_v2 + addr_size + // jitInfo456 addr_size + // dyldVersion457 addr_size + // errorMessage458 addr_size + // terminationFlags459 addr_size + // coreSymbolicationShmPage460 addr_size + // systemOrderFlag461 addr_size + // uuidArrayCount462 addr_size + // uuidArray463 addr_size + // dyldAllImageInfosAddress464 addr_size + // initialImageCount465 addr_size + // errorKind466 addr_size + // errorClientOfDylibPath467 addr_size + // errorTargetDylibPath468 addr_size; // errorSymbol469 const size_t count_v13 = count_v11 + addr_size + // sharedCacheSlide470 sizeof(uuid_t); // sharedCacheUUID471 UNUSED_IF_ASSERT_DISABLED(count_v13);472 assert(sizeof(buf) >= count_v13);473 474 Status error;475 if (m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, 4, error) ==476 4) {477 m_dyld_all_image_infos.version = data.GetU32(&offset);478 // If anything in the high byte is set, we probably got the byte order479 // incorrect (the process might not have it set correctly yet due to480 // attaching to a program without a specified file).481 if (m_dyld_all_image_infos.version & 0xff000000) {482 // We have guessed the wrong byte order. Swap it and try reading the483 // version again.484 if (byte_order == eByteOrderLittle)485 byte_order = eByteOrderBig;486 else487 byte_order = eByteOrderLittle;488 489 data.SetByteOrder(byte_order);490 offset = 0;491 m_dyld_all_image_infos.version = data.GetU32(&offset);492 }493 } else {494 return false;495 }496 497 const size_t count =498 (m_dyld_all_image_infos.version >= 11) ? count_v11 : count_v2;499 500 const size_t bytes_read =501 m_process->ReadMemory(m_dyld_all_image_infos_addr, buf, count, error);502 if (bytes_read == count) {503 offset = 0;504 m_dyld_all_image_infos.version = data.GetU32(&offset);505 m_dyld_all_image_infos.dylib_info_count = data.GetU32(&offset);506 m_dyld_all_image_infos.dylib_info_addr = data.GetAddress(&offset);507 m_dyld_all_image_infos.notification = data.GetAddress(&offset);508 m_dyld_all_image_infos.processDetachedFromSharedRegion =509 data.GetU8(&offset);510 m_dyld_all_image_infos.libSystemInitialized = data.GetU8(&offset);511 // Adjust for padding.512 offset += addr_size - 2;513 m_dyld_all_image_infos.dyldImageLoadAddress = data.GetAddress(&offset);514 if (m_dyld_all_image_infos.version >= 11) {515 offset += addr_size * 8;516 uint64_t dyld_all_image_infos_addr = data.GetAddress(&offset);517 518 // When we started, we were given the actual address of the519 // all_image_infos struct (probably via TASK_DYLD_INFO) in memory -520 // this address is stored in m_dyld_all_image_infos_addr and is the521 // most accurate address we have.522 523 // We read the dyld_all_image_infos struct from memory; it contains its524 // own address. If the address in the struct does not match the actual525 // address, the dyld we're looking at has been loaded at a different526 // location (slid) from where it intended to load. The addresses in527 // the dyld_all_image_infos struct are the original, non-slid528 // addresses, and need to be adjusted. Most importantly the address of529 // dyld and the notification address need to be adjusted.530 531 if (dyld_all_image_infos_addr != m_dyld_all_image_infos_addr) {532 uint64_t image_infos_offset =533 dyld_all_image_infos_addr -534 m_dyld_all_image_infos.dyldImageLoadAddress;535 uint64_t notification_offset =536 m_dyld_all_image_infos.notification -537 m_dyld_all_image_infos.dyldImageLoadAddress;538 m_dyld_all_image_infos.dyldImageLoadAddress =539 m_dyld_all_image_infos_addr - image_infos_offset;540 m_dyld_all_image_infos.notification =541 m_dyld_all_image_infos.dyldImageLoadAddress + notification_offset;542 }543 }544 m_dyld_all_image_infos_stop_id = m_process->GetStopID();545 return true;546 }547 }548 return false;549}550 551bool DynamicLoaderMacOSXDYLD::AddModulesUsingImageInfosAddress(552 lldb::addr_t image_infos_addr, uint32_t image_infos_count) {553 ImageInfo::collection image_infos;554 Log *log = GetLog(LLDBLog::DynamicLoader);555 LLDB_LOGF(log, "Adding %d modules.\n", image_infos_count);556 557 std::lock_guard<std::recursive_mutex> guard(m_mutex);558 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());559 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)560 return true;561 562 StructuredData::ObjectSP image_infos_json_sp =563 m_process->GetLoadedDynamicLibrariesInfos(image_infos_addr,564 image_infos_count);565 if (image_infos_json_sp.get() && image_infos_json_sp->GetAsDictionary() &&566 image_infos_json_sp->GetAsDictionary()->HasKey("images") &&567 image_infos_json_sp->GetAsDictionary()568 ->GetValueForKey("images")569 ->GetAsArray() &&570 image_infos_json_sp->GetAsDictionary()571 ->GetValueForKey("images")572 ->GetAsArray()573 ->GetSize() == image_infos_count) {574 bool return_value = false;575 if (JSONImageInformationIntoImageInfo(image_infos_json_sp, image_infos)) {576 auto images = PreloadModulesFromImageInfos(image_infos);577 UpdateSpecialBinariesFromPreloadedModules(images);578 return_value = AddModulesUsingPreloadedModules(images);579 }580 m_dyld_image_infos_stop_id = m_process->GetStopID();581 return return_value;582 }583 584 if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos))585 return false;586 587 UpdateImageInfosHeaderAndLoadCommands(image_infos, image_infos_count, false);588 bool return_value = AddModulesUsingImageInfos(image_infos);589 m_dyld_image_infos_stop_id = m_process->GetStopID();590 return return_value;591}592 593bool DynamicLoaderMacOSXDYLD::RemoveModulesUsingImageInfosAddress(594 lldb::addr_t image_infos_addr, uint32_t image_infos_count) {595 ImageInfo::collection image_infos;596 Log *log = GetLog(LLDBLog::DynamicLoader);597 598 std::lock_guard<std::recursive_mutex> guard(m_mutex);599 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());600 if (m_process->GetStopID() == m_dyld_image_infos_stop_id)601 return true;602 603 // First read in the image_infos for the removed modules, and their headers &604 // load commands.605 if (!ReadImageInfos(image_infos_addr, image_infos_count, image_infos)) {606 if (log)607 log->PutCString("Failed reading image infos array.");608 return false;609 }610 611 LLDB_LOGF(log, "Removing %d modules.", image_infos_count);612 613 ModuleList unloaded_module_list;614 for (uint32_t idx = 0; idx < image_infos.size(); ++idx) {615 if (log) {616 LLDB_LOGF(log, "Removing module at address=0x%16.16" PRIx64 ".",617 image_infos[idx].address);618 image_infos[idx].PutToLog(log);619 }620 621 // Remove this image_infos from the m_all_image_infos. We do the622 // comparison by address rather than by file spec because we can have many623 // modules with the same "file spec" in the case that they are modules624 // loaded from memory.625 //626 // Also copy over the uuid from the old entry to the removed entry so we627 // can use it to lookup the module in the module list.628 629 bool found = false;630 631 for (ImageInfo::collection::iterator pos = m_dyld_image_infos.begin();632 pos != m_dyld_image_infos.end(); pos++) {633 if (image_infos[idx].address == (*pos).address) {634 image_infos[idx].uuid = (*pos).uuid;635 636 // Add the module from this image_info to the "unloaded_module_list".637 // We'll remove them all at one go later on.638 639 ModuleSP unload_image_module_sp(640 FindTargetModuleForImageInfo(image_infos[idx], false, nullptr));641 if (unload_image_module_sp.get()) {642 // When we unload, be sure to use the image info from the old list,643 // since that has sections correctly filled in.644 UnloadModuleSections(unload_image_module_sp.get(), *pos);645 unloaded_module_list.AppendIfNeeded(unload_image_module_sp);646 } else {647 if (log) {648 LLDB_LOGF(log, "Could not find module for unloading info entry:");649 image_infos[idx].PutToLog(log);650 }651 }652 653 // Then remove it from the m_dyld_image_infos:654 655 m_dyld_image_infos.erase(pos);656 found = true;657 break;658 }659 }660 661 if (!found) {662 if (log) {663 LLDB_LOGF(log, "Could not find image_info entry for unloading image:");664 image_infos[idx].PutToLog(log);665 }666 }667 }668 if (unloaded_module_list.GetSize() > 0) {669 if (log) {670 log->PutCString("Unloaded:");671 unloaded_module_list.LogUUIDAndPaths(672 log, "DynamicLoaderMacOSXDYLD::ModulesDidUnload");673 }674 m_process->GetTarget().GetImages().Remove(unloaded_module_list);675 }676 m_dyld_image_infos_stop_id = m_process->GetStopID();677 return true;678}679 680bool DynamicLoaderMacOSXDYLD::ReadImageInfos(681 lldb::addr_t image_infos_addr, uint32_t image_infos_count,682 ImageInfo::collection &image_infos) {683 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());684 const ByteOrder endian = GetByteOrderFromMagic(m_dyld.header.magic);685 const uint32_t addr_size = m_dyld.GetAddressByteSize();686 687 image_infos.resize(image_infos_count);688 const size_t count = image_infos.size() * 3 * addr_size;689 DataBufferHeap info_data(count, 0);690 Status error;691 const size_t bytes_read = m_process->ReadMemory(692 image_infos_addr, info_data.GetBytes(), info_data.GetByteSize(), error);693 if (bytes_read == count) {694 lldb::offset_t info_data_offset = 0;695 DataExtractor info_data_ref(info_data.GetBytes(), info_data.GetByteSize(),696 endian, addr_size);697 for (size_t i = 0;698 i < image_infos.size() && info_data_ref.ValidOffset(info_data_offset);699 i++) {700 image_infos[i].address = info_data_ref.GetAddress(&info_data_offset);701 lldb::addr_t path_addr = info_data_ref.GetAddress(&info_data_offset);702 info_data_ref.GetAddress(&info_data_offset); // mod_date, unused */703 704 char raw_path[PATH_MAX];705 m_process->ReadCStringFromMemory(path_addr, raw_path, sizeof(raw_path),706 error);707 // don't resolve the path708 if (error.Success()) {709 image_infos[i].file_spec.SetFile(raw_path, FileSpec::Style::native);710 }711 }712 return true;713 } else {714 return false;715 }716}717 718// If we have found where the "_dyld_all_image_infos" lives in memory, read the719// current info from it, and then update all image load addresses (or lack720// thereof). Only do this if this is the first time we're reading the dyld721// infos. Return true if we actually read anything, and false otherwise.722bool DynamicLoaderMacOSXDYLD::InitializeFromAllImageInfos() {723 Log *log = GetLog(LLDBLog::DynamicLoader);724 725 std::lock_guard<std::recursive_mutex> guard(m_mutex);726 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());727 if (m_process->GetStopID() == m_dyld_image_infos_stop_id ||728 m_dyld_image_infos.size() != 0)729 return false;730 731 if (ReadAllImageInfosStructure()) {732 // Nothing to load or unload?733 if (m_dyld_all_image_infos.dylib_info_count == 0)734 return true;735 736 if (m_dyld_all_image_infos.dylib_info_addr == 0) {737 // DYLD is updating the images now. So we should say we have no images,738 // and then we'll739 // figure it out when we hit the added breakpoint.740 return false;741 } else {742 if (!AddModulesUsingImageInfosAddress(743 m_dyld_all_image_infos.dylib_info_addr,744 m_dyld_all_image_infos.dylib_info_count)) {745 DEBUG_PRINTF("%s", "unable to read all data for all_dylib_infos.");746 m_dyld_image_infos.clear();747 }748 }749 750 // Now we have one more bit of business. If there is a library left in the751 // images for our target that doesn't have a load address, then it must be752 // something that we were expecting to load (for instance we read a load753 // command for it) but it didn't in fact load - probably because754 // DYLD_*_PATH pointed to an equivalent version. We don't want it to stay755 // in the target's module list or it will confuse us, so unload it here.756 Target &target = m_process->GetTarget();757 ModuleList not_loaded_modules;758 for (ModuleSP module_sp : target.GetImages().Modules()) {759 if (!module_sp->IsLoadedInTarget(&target)) {760 if (log) {761 StreamString s;762 module_sp->GetDescription(s.AsRawOstream());763 LLDB_LOGF(log, "Unloading pre-run module: %s.", s.GetData());764 }765 not_loaded_modules.Append(module_sp);766 }767 }768 769 if (not_loaded_modules.GetSize() != 0) {770 target.GetImages().Remove(not_loaded_modules);771 }772 773 return true;774 } else775 return false;776}777 778// Read a mach_header at ADDR into HEADER, and also fill in the load command779// data into LOAD_COMMAND_DATA if it is non-NULL.780//781// Returns true if we succeed, false if we fail for any reason.782bool DynamicLoaderMacOSXDYLD::ReadMachHeader(lldb::addr_t addr,783 llvm::MachO::mach_header *header,784 DataExtractor *load_command_data) {785 DataBufferHeap header_bytes(sizeof(llvm::MachO::mach_header), 0);786 Status error;787 size_t bytes_read = m_process->ReadMemory(addr, header_bytes.GetBytes(),788 header_bytes.GetByteSize(), error);789 if (bytes_read == sizeof(llvm::MachO::mach_header)) {790 lldb::offset_t offset = 0;791 ::memset(header, 0, sizeof(llvm::MachO::mach_header));792 793 // Get the magic byte unswapped so we can figure out what we are dealing794 // with795 DataExtractor data(header_bytes.GetBytes(), header_bytes.GetByteSize(),796 endian::InlHostByteOrder(), 4);797 header->magic = data.GetU32(&offset);798 lldb::addr_t load_cmd_addr = addr;799 data.SetByteOrder(800 DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(header->magic));801 switch (header->magic) {802 case llvm::MachO::MH_MAGIC:803 case llvm::MachO::MH_CIGAM:804 data.SetAddressByteSize(4);805 load_cmd_addr += sizeof(llvm::MachO::mach_header);806 break;807 808 case llvm::MachO::MH_MAGIC_64:809 case llvm::MachO::MH_CIGAM_64:810 data.SetAddressByteSize(8);811 load_cmd_addr += sizeof(llvm::MachO::mach_header_64);812 break;813 814 default:815 return false;816 }817 818 // Read the rest of dyld's mach header819 if (data.GetU32(&offset, &header->cputype,820 (sizeof(llvm::MachO::mach_header) / sizeof(uint32_t)) -821 1)) {822 if (load_command_data == nullptr)823 return true; // We were able to read the mach_header and weren't asked824 // to read the load command bytes825 826 WritableDataBufferSP load_cmd_data_sp(827 new DataBufferHeap(header->sizeofcmds, 0));828 829 size_t load_cmd_bytes_read =830 m_process->ReadMemory(load_cmd_addr, load_cmd_data_sp->GetBytes(),831 load_cmd_data_sp->GetByteSize(), error);832 833 if (load_cmd_bytes_read == header->sizeofcmds) {834 // Set the load command data and also set the correct endian swap835 // settings and the correct address size836 load_command_data->SetData(load_cmd_data_sp, 0, header->sizeofcmds);837 load_command_data->SetByteOrder(data.GetByteOrder());838 load_command_data->SetAddressByteSize(data.GetAddressByteSize());839 return true; // We successfully read the mach_header and the load840 // command data841 }842 843 return false; // We weren't able to read the load command data844 }845 }846 return false; // We failed the read the mach_header847}848 849// Parse the load commands for an image850uint32_t DynamicLoaderMacOSXDYLD::ParseLoadCommands(const DataExtractor &data,851 ImageInfo &dylib_info,852 FileSpec *lc_id_dylinker) {853 lldb::offset_t offset = 0;854 uint32_t cmd_idx;855 Segment segment;856 dylib_info.Clear(true);857 858 for (cmd_idx = 0; cmd_idx < dylib_info.header.ncmds; cmd_idx++) {859 // Clear out any load command specific data from DYLIB_INFO since we are860 // about to read it.861 862 if (data.ValidOffsetForDataOfSize(offset,863 sizeof(llvm::MachO::load_command))) {864 llvm::MachO::load_command load_cmd;865 lldb::offset_t load_cmd_offset = offset;866 load_cmd.cmd = data.GetU32(&offset);867 load_cmd.cmdsize = data.GetU32(&offset);868 switch (load_cmd.cmd) {869 case llvm::MachO::LC_SEGMENT: {870 segment.name.SetTrimmedCStringWithLength(871 (const char *)data.GetData(&offset, 16), 16);872 // We are putting 4 uint32_t values 4 uint64_t values so we have to use873 // multiple 32 bit gets below.874 segment.vmaddr = data.GetU32(&offset);875 segment.vmsize = data.GetU32(&offset);876 segment.fileoff = data.GetU32(&offset);877 segment.filesize = data.GetU32(&offset);878 // Extract maxprot, initprot, nsects and flags all at once879 data.GetU32(&offset, &segment.maxprot, 4);880 dylib_info.segments.push_back(segment);881 } break;882 883 case llvm::MachO::LC_SEGMENT_64: {884 segment.name.SetTrimmedCStringWithLength(885 (const char *)data.GetData(&offset, 16), 16);886 // Extract vmaddr, vmsize, fileoff, and filesize all at once887 data.GetU64(&offset, &segment.vmaddr, 4);888 // Extract maxprot, initprot, nsects and flags all at once889 data.GetU32(&offset, &segment.maxprot, 4);890 dylib_info.segments.push_back(segment);891 } break;892 893 case llvm::MachO::LC_ID_DYLINKER:894 if (lc_id_dylinker) {895 const lldb::offset_t name_offset =896 load_cmd_offset + data.GetU32(&offset);897 const char *path = data.PeekCStr(name_offset);898 lc_id_dylinker->SetFile(path, FileSpec::Style::native);899 FileSystem::Instance().Resolve(*lc_id_dylinker);900 }901 break;902 903 case llvm::MachO::LC_UUID:904 dylib_info.uuid = UUID(data.GetData(&offset, 16), 16);905 break;906 907 default:908 break;909 }910 // Set offset to be the beginning of the next load command.911 offset = load_cmd_offset + load_cmd.cmdsize;912 }913 }914 915 // All sections listed in the dyld image info structure will all either be916 // fixed up already, or they will all be off by a single slide amount that is917 // determined by finding the first segment that is at file offset zero which918 // also has bytes (a file size that is greater than zero) in the object file.919 920 // Determine the slide amount (if any)921 const size_t num_sections = dylib_info.segments.size();922 for (size_t i = 0; i < num_sections; ++i) {923 // Iterate through the object file sections to find the first section that924 // starts of file offset zero and that has bytes in the file...925 if ((dylib_info.segments[i].fileoff == 0 &&926 dylib_info.segments[i].filesize > 0) ||927 (dylib_info.segments[i].name == "__TEXT")) {928 dylib_info.slide = dylib_info.address - dylib_info.segments[i].vmaddr;929 // We have found the slide amount, so we can exit this for loop.930 break;931 }932 }933 return cmd_idx;934}935 936// Read the mach_header and load commands for each image that the937// _dyld_all_image_infos structure points to and cache the results.938 939void DynamicLoaderMacOSXDYLD::UpdateImageInfosHeaderAndLoadCommands(940 ImageInfo::collection &image_infos, uint32_t infos_count,941 bool update_executable) {942 uint32_t exe_idx = UINT32_MAX;943 // Read any UUID values that we can get944 for (uint32_t i = 0; i < infos_count; i++) {945 if (!image_infos[i].UUIDValid()) {946 DataExtractor data; // Load command data947 if (!ReadMachHeader(image_infos[i].address, &image_infos[i].header,948 &data))949 continue;950 951 ParseLoadCommands(data, image_infos[i], nullptr);952 953 if (image_infos[i].header.filetype == llvm::MachO::MH_EXECUTE)954 exe_idx = i;955 }956 }957 958 Target &target = m_process->GetTarget();959 960 if (exe_idx < image_infos.size()) {961 const bool can_create = true;962 ModuleSP exe_module_sp(FindTargetModuleForImageInfo(image_infos[exe_idx],963 can_create, nullptr));964 965 if (exe_module_sp) {966 UpdateImageLoadAddress(exe_module_sp.get(), image_infos[exe_idx]);967 968 if (exe_module_sp.get() != target.GetExecutableModulePointer()) {969 // Don't load dependent images since we are in dyld where we will know970 // and find out about all images that are loaded. Also when setting the971 // executable module, it will clear the targets module list, and if we972 // have an in memory dyld module, it will get removed from the list so973 // we will need to add it back after setting the executable module, so974 // we first try and see if we already have a weak pointer to the dyld975 // module, make it into a shared pointer, then add the executable, then976 // re-add it back to make sure it is always in the list.977 ModuleSP dyld_module_sp(GetDYLDModule());978 979 m_process->GetTarget().SetExecutableModule(exe_module_sp,980 eLoadDependentsNo);981 982 if (dyld_module_sp) {983 if (target.GetImages().AppendIfNeeded(dyld_module_sp)) {984 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());985 986 // Also add it to the section list.987 UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);988 }989 }990 }991 }992 }993}994 995// Dump the _dyld_all_image_infos members and all current image infos that we996// have parsed to the file handle provided.997void DynamicLoaderMacOSXDYLD::PutToLog(Log *log) const {998 if (log == nullptr)999 return;1000 1001 std::lock_guard<std::recursive_mutex> guard(m_mutex);1002 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());1003 LLDB_LOGF(log,1004 "dyld_all_image_infos = { version=%d, count=%d, addr=0x%8.8" PRIx641005 ", notify=0x%8.8" PRIx64 " }",1006 m_dyld_all_image_infos.version,1007 m_dyld_all_image_infos.dylib_info_count,1008 (uint64_t)m_dyld_all_image_infos.dylib_info_addr,1009 (uint64_t)m_dyld_all_image_infos.notification);1010 size_t i;1011 const size_t count = m_dyld_image_infos.size();1012 if (count > 0) {1013 log->PutCString("Loaded:");1014 for (i = 0; i < count; i++)1015 m_dyld_image_infos[i].PutToLog(log);1016 }1017}1018 1019bool DynamicLoaderMacOSXDYLD::SetNotificationBreakpoint() {1020 DEBUG_PRINTF("DynamicLoaderMacOSXDYLD::%s() process state = %s\n",1021 __FUNCTION__, StateAsCString(m_process->GetState()));1022 if (m_break_id == LLDB_INVALID_BREAK_ID) {1023 if (m_dyld_all_image_infos.notification != LLDB_INVALID_ADDRESS) {1024 Address so_addr;1025 // Set the notification breakpoint and install a breakpoint callback1026 // function that will get called each time the breakpoint gets hit. We1027 // will use this to track when shared libraries get loaded/unloaded.1028 bool resolved = m_process->GetTarget().ResolveLoadAddress(1029 m_dyld_all_image_infos.notification, so_addr);1030 if (!resolved) {1031 ModuleSP dyld_module_sp = GetDYLDModule();1032 if (dyld_module_sp) {1033 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());1034 1035 UpdateImageLoadAddress(dyld_module_sp.get(), m_dyld);1036 resolved = m_process->GetTarget().ResolveLoadAddress(1037 m_dyld_all_image_infos.notification, so_addr);1038 }1039 }1040 1041 if (resolved) {1042 Breakpoint *dyld_break =1043 m_process->GetTarget().CreateBreakpoint(so_addr, true, false).get();1044 dyld_break->SetCallback(DynamicLoaderMacOSXDYLD::NotifyBreakpointHit,1045 this, true);1046 dyld_break->SetBreakpointKind("shared-library-event");1047 m_break_id = dyld_break->GetID();1048 }1049 }1050 }1051 return m_break_id != LLDB_INVALID_BREAK_ID;1052}1053 1054Status DynamicLoaderMacOSXDYLD::CanLoadImage() {1055 Status error;1056 // In order for us to tell if we can load a shared library we verify that the1057 // dylib_info_addr isn't zero (which means no shared libraries have been set1058 // yet, or dyld is currently mucking with the shared library list).1059 if (ReadAllImageInfosStructure()) {1060 // TODO: also check the _dyld_global_lock_held variable in1061 // libSystem.B.dylib?1062 // TODO: check the malloc lock?1063 // TODO: check the objective C lock?1064 if (m_dyld_all_image_infos.dylib_info_addr != 0)1065 return error; // Success1066 }1067 1068 error = Status::FromErrorString("unsafe to load or unload shared libraries");1069 return error;1070}1071 1072bool DynamicLoaderMacOSXDYLD::GetSharedCacheInformation(1073 lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,1074 LazyBool &private_shared_cache) {1075 base_address = LLDB_INVALID_ADDRESS;1076 uuid.Clear();1077 using_shared_cache = eLazyBoolCalculate;1078 private_shared_cache = eLazyBoolCalculate;1079 1080 if (m_process) {1081 addr_t all_image_infos = m_process->GetImageInfoAddress();1082 1083 // The address returned by GetImageInfoAddress may be the address of dyld1084 // (don't want) or it may be the address of the dyld_all_image_infos1085 // structure (want). The first four bytes will be either the version field1086 // (all_image_infos) or a Mach-O file magic constant. Version 13 and higher1087 // of dyld_all_image_infos is required to get the sharedCacheUUID field.1088 1089 Status err;1090 uint32_t version_or_magic =1091 m_process->ReadUnsignedIntegerFromMemory(all_image_infos, 4, -1, err);1092 if (version_or_magic != static_cast<uint32_t>(-1) &&1093 version_or_magic != llvm::MachO::MH_MAGIC &&1094 version_or_magic != llvm::MachO::MH_CIGAM &&1095 version_or_magic != llvm::MachO::MH_MAGIC_64 &&1096 version_or_magic != llvm::MachO::MH_CIGAM_64 &&1097 version_or_magic >= 13) {1098 addr_t sharedCacheUUID_address = LLDB_INVALID_ADDRESS;1099 int wordsize = m_process->GetAddressByteSize();1100 if (wordsize == 8) {1101 sharedCacheUUID_address =1102 all_image_infos + 160; // sharedCacheUUID <mach-o/dyld_images.h>1103 }1104 if (wordsize == 4) {1105 sharedCacheUUID_address =1106 all_image_infos + 84; // sharedCacheUUID <mach-o/dyld_images.h>1107 }1108 if (sharedCacheUUID_address != LLDB_INVALID_ADDRESS) {1109 uuid_t shared_cache_uuid;1110 if (m_process->ReadMemory(sharedCacheUUID_address, shared_cache_uuid,1111 sizeof(uuid_t), err) == sizeof(uuid_t)) {1112 uuid = UUID(shared_cache_uuid, 16);1113 if (uuid.IsValid()) {1114 using_shared_cache = eLazyBoolYes;1115 }1116 }1117 1118 if (version_or_magic >= 15) {1119 // The sharedCacheBaseAddress field is the next one in the1120 // dyld_all_image_infos struct.1121 addr_t sharedCacheBaseAddr_address = sharedCacheUUID_address + 16;1122 Status error;1123 base_address = m_process->ReadUnsignedIntegerFromMemory(1124 sharedCacheBaseAddr_address, wordsize, LLDB_INVALID_ADDRESS,1125 error);1126 if (error.Fail())1127 base_address = LLDB_INVALID_ADDRESS;1128 }1129 1130 return true;1131 }1132 1133 //1134 // add1135 // NB: sharedCacheBaseAddress is the next field in dyld_all_image_infos1136 // after1137 // sharedCacheUUID -- that is, 16 bytes after it, if we wanted to fetch1138 // it.1139 }1140 }1141 return false;1142}1143 1144bool DynamicLoaderMacOSXDYLD::IsFullyInitialized() {1145 if (ReadAllImageInfosStructure())1146 return m_dyld_all_image_infos.libSystemInitialized;1147 return false;1148}1149 1150void DynamicLoaderMacOSXDYLD::Initialize() {1151 PluginManager::RegisterPlugin(GetPluginNameStatic(),1152 GetPluginDescriptionStatic(), CreateInstance);1153 DynamicLoaderMacOS::Initialize();1154}1155 1156void DynamicLoaderMacOSXDYLD::Terminate() {1157 DynamicLoaderMacOS::Terminate();1158 PluginManager::UnregisterPlugin(CreateInstance);1159}1160 1161llvm::StringRef DynamicLoaderMacOSXDYLD::GetPluginDescriptionStatic() {1162 return "Dynamic loader plug-in that watches for shared library loads/unloads "1163 "in MacOSX user processes.";1164}1165 1166uint32_t DynamicLoaderMacOSXDYLD::AddrByteSize() {1167 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());1168 1169 switch (m_dyld.header.magic) {1170 case llvm::MachO::MH_MAGIC:1171 case llvm::MachO::MH_CIGAM:1172 return 4;1173 1174 case llvm::MachO::MH_MAGIC_64:1175 case llvm::MachO::MH_CIGAM_64:1176 return 8;1177 1178 default:1179 break;1180 }1181 return 0;1182}1183 1184lldb::ByteOrder DynamicLoaderMacOSXDYLD::GetByteOrderFromMagic(uint32_t magic) {1185 switch (magic) {1186 case llvm::MachO::MH_MAGIC:1187 case llvm::MachO::MH_MAGIC_64:1188 return endian::InlHostByteOrder();1189 1190 case llvm::MachO::MH_CIGAM:1191 case llvm::MachO::MH_CIGAM_64:1192 if (endian::InlHostByteOrder() == lldb::eByteOrderBig)1193 return lldb::eByteOrderLittle;1194 else1195 return lldb::eByteOrderBig;1196 1197 default:1198 break;1199 }1200 return lldb::eByteOrderInvalid;1201}1202