1 //===-- DynamicLoaderMacOS.cpp -----------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "lldb/Breakpoint/StoppointCallbackContext.h" 11 #include "lldb/Core/Debugger.h" 12 #include "lldb/Core/Log.h" 13 #include "lldb/Core/Module.h" 14 #include "lldb/Core/PluginManager.h" 15 #include "lldb/Core/Section.h" 16 #include "lldb/Core/State.h" 17 #include "lldb/Symbol/ClangASTContext.h" 18 #include "lldb/Symbol/ObjectFile.h" 19 #include "lldb/Symbol/SymbolVendor.h" 20 #include "lldb/Target/ABI.h" 21 #include "lldb/Target/StackFrame.h" 22 #include "lldb/Target/Target.h" 23 #include "lldb/Target/Thread.h" 24 25 #include "DynamicLoaderDarwin.h" 26 #include "DynamicLoaderMacOS.h" 27 28 using namespace lldb; 29 using namespace lldb_private; 30 31 //---------------------------------------------------------------------- 32 // Create an instance of this class. This function is filled into 33 // the plugin info class that gets handed out by the plugin factory and 34 // allows the lldb to instantiate an instance of this class. 35 //---------------------------------------------------------------------- 36 DynamicLoader *DynamicLoaderMacOS::CreateInstance(Process *process, 37 bool force) { 38 bool create = force; 39 if (!create) { 40 create = true; 41 Module *exe_module = process->GetTarget().GetExecutableModulePointer(); 42 if (exe_module) { 43 ObjectFile *object_file = exe_module->GetObjectFile(); 44 if (object_file) { 45 create = (object_file->GetStrata() == ObjectFile::eStrataUser); 46 } 47 } 48 49 if (create) { 50 const llvm::Triple &triple_ref = 51 process->GetTarget().GetArchitecture().GetTriple(); 52 switch (triple_ref.getOS()) { 53 case llvm::Triple::Darwin: 54 case llvm::Triple::MacOSX: 55 case llvm::Triple::IOS: 56 case llvm::Triple::TvOS: 57 case llvm::Triple::WatchOS: 58 create = triple_ref.getVendor() == llvm::Triple::Apple; 59 break; 60 default: 61 create = false; 62 break; 63 } 64 } 65 } 66 67 if (UseDYLDSPI(process) == false) { 68 create = false; 69 } 70 71 if (create) 72 return new DynamicLoaderMacOS(process); 73 return NULL; 74 } 75 76 //---------------------------------------------------------------------- 77 // Constructor 78 //---------------------------------------------------------------------- 79 DynamicLoaderMacOS::DynamicLoaderMacOS(Process *process) 80 : DynamicLoaderDarwin(process), m_image_infos_stop_id(UINT32_MAX), 81 m_break_id(LLDB_INVALID_BREAK_ID), m_mutex() {} 82 83 //---------------------------------------------------------------------- 84 // Destructor 85 //---------------------------------------------------------------------- 86 DynamicLoaderMacOS::~DynamicLoaderMacOS() { 87 if (LLDB_BREAK_ID_IS_VALID(m_break_id)) 88 m_process->GetTarget().RemoveBreakpointByID(m_break_id); 89 } 90 91 bool DynamicLoaderMacOS::ProcessDidExec() { 92 std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex()); 93 bool did_exec = false; 94 if (m_process) { 95 // If we are stopped after an exec, we will have only one thread... 96 if (m_process->GetThreadList().GetSize() == 1) { 97 // See if we are stopped at '_dyld_start' 98 ThreadSP thread_sp(m_process->GetThreadList().GetThreadAtIndex(0)); 99 if (thread_sp) { 100 lldb::StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0)); 101 if (frame_sp) { 102 const Symbol *symbol = 103 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol; 104 if (symbol) { 105 if (symbol->GetName() == ConstString("_dyld_start")) 106 did_exec = true; 107 } 108 } 109 } 110 } 111 } 112 113 if (did_exec) { 114 m_libpthread_module_wp.reset(); 115 m_pthread_getspecific_addr.Clear(); 116 } 117 return did_exec; 118 } 119 120 //---------------------------------------------------------------------- 121 // Clear out the state of this class. 122 //---------------------------------------------------------------------- 123 void DynamicLoaderMacOS::DoClear() { 124 std::lock_guard<std::recursive_mutex> guard(m_mutex); 125 126 if (LLDB_BREAK_ID_IS_VALID(m_break_id)) 127 m_process->GetTarget().RemoveBreakpointByID(m_break_id); 128 129 m_break_id = LLDB_INVALID_BREAK_ID; 130 } 131 132 //---------------------------------------------------------------------- 133 // Check if we have found DYLD yet 134 //---------------------------------------------------------------------- 135 bool DynamicLoaderMacOS::DidSetNotificationBreakpoint() { 136 return LLDB_BREAK_ID_IS_VALID(m_break_id); 137 } 138 139 void DynamicLoaderMacOS::ClearNotificationBreakpoint() { 140 if (LLDB_BREAK_ID_IS_VALID(m_break_id)) { 141 m_process->GetTarget().RemoveBreakpointByID(m_break_id); 142 } 143 } 144 145 //---------------------------------------------------------------------- 146 // Try and figure out where dyld is by first asking the Process 147 // if it knows (which currently calls down in the lldb::Process 148 // to get the DYLD info (available on SnowLeopard only). If that fails, 149 // then check in the default addresses. 150 //---------------------------------------------------------------------- 151 void DynamicLoaderMacOS::DoInitialImageFetch() { 152 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 153 154 StructuredData::ObjectSP all_image_info_json_sp( 155 m_process->GetLoadedDynamicLibrariesInfos()); 156 ImageInfo::collection image_infos; 157 if (all_image_info_json_sp.get() && 158 all_image_info_json_sp->GetAsDictionary() && 159 all_image_info_json_sp->GetAsDictionary()->HasKey("images") && 160 all_image_info_json_sp->GetAsDictionary() 161 ->GetValueForKey("images") 162 ->GetAsArray()) { 163 if (JSONImageInformationIntoImageInfo(all_image_info_json_sp, 164 image_infos)) { 165 if (log) 166 log->Printf("Initial module fetch: Adding %" PRId64 " modules.\n", 167 (uint64_t)image_infos.size()); 168 169 UpdateSpecialBinariesFromNewImageInfos(image_infos); 170 AddModulesUsingImageInfos(image_infos); 171 } 172 } 173 174 m_dyld_image_infos_stop_id = m_process->GetStopID(); 175 } 176 177 bool DynamicLoaderMacOS::NeedToDoInitialImageFetch() { return true; } 178 179 //---------------------------------------------------------------------- 180 // Static callback function that gets called when our DYLD notification 181 // breakpoint gets hit. We update all of our image infos and then 182 // let our super class DynamicLoader class decide if we should stop 183 // or not (based on global preference). 184 //---------------------------------------------------------------------- 185 bool DynamicLoaderMacOS::NotifyBreakpointHit(void *baton, 186 StoppointCallbackContext *context, 187 lldb::user_id_t break_id, 188 lldb::user_id_t break_loc_id) { 189 // Let the event know that the images have changed 190 // DYLD passes three arguments to the notification breakpoint. 191 // Arg1: enum dyld_notify_mode mode - 0 = adding, 1 = removing, 2 = remove all 192 // Arg2: unsigned long icount - Number of shared libraries 193 // added/removed 194 // Arg3: uint64_t mach_headers[] - Array of load addresses of binaries 195 // added/removed 196 197 DynamicLoaderMacOS *dyld_instance = (DynamicLoaderMacOS *)baton; 198 199 ExecutionContext exe_ctx(context->exe_ctx_ref); 200 Process *process = exe_ctx.GetProcessPtr(); 201 202 // This is a sanity check just in case this dyld_instance is an old dyld 203 // plugin's breakpoint still lying around. 204 if (process != dyld_instance->m_process) 205 return false; 206 207 if (dyld_instance->m_image_infos_stop_id != UINT32_MAX && 208 process->GetStopID() < dyld_instance->m_image_infos_stop_id) { 209 return false; 210 } 211 212 const lldb::ABISP &abi = process->GetABI(); 213 if (abi) { 214 // Build up the value array to store the three arguments given above, then 215 // get the values from the ABI: 216 217 ClangASTContext *clang_ast_context = 218 process->GetTarget().GetScratchClangASTContext(); 219 ValueList argument_values; 220 221 Value mode_value; // enum dyld_notify_mode { dyld_notify_adding=0, 222 // dyld_notify_removing=1, dyld_notify_remove_all=2 }; 223 Value count_value; // unsigned long count 224 Value headers_value; // uint64_t machHeaders[] (aka void*) 225 226 CompilerType clang_void_ptr_type = 227 clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType(); 228 CompilerType clang_uint32_type = 229 clang_ast_context->GetBuiltinTypeForEncodingAndBitSize( 230 lldb::eEncodingUint, 32); 231 CompilerType clang_uint64_type = 232 clang_ast_context->GetBuiltinTypeForEncodingAndBitSize( 233 lldb::eEncodingUint, 32); 234 235 mode_value.SetValueType(Value::eValueTypeScalar); 236 mode_value.SetCompilerType(clang_uint32_type); 237 238 if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 4) { 239 count_value.SetValueType(Value::eValueTypeScalar); 240 count_value.SetCompilerType(clang_uint32_type); 241 } else { 242 count_value.SetValueType(Value::eValueTypeScalar); 243 count_value.SetCompilerType(clang_uint64_type); 244 } 245 246 headers_value.SetValueType(Value::eValueTypeScalar); 247 headers_value.SetCompilerType(clang_void_ptr_type); 248 249 argument_values.PushValue(mode_value); 250 argument_values.PushValue(count_value); 251 argument_values.PushValue(headers_value); 252 253 if (abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values)) { 254 uint32_t dyld_mode = 255 argument_values.GetValueAtIndex(0)->GetScalar().UInt(-1); 256 if (dyld_mode != static_cast<uint32_t>(-1)) { 257 // Okay the mode was right, now get the number of elements, and the 258 // array of new elements... 259 uint32_t image_infos_count = 260 argument_values.GetValueAtIndex(1)->GetScalar().UInt(-1); 261 if (image_infos_count != static_cast<uint32_t>(-1)) { 262 addr_t header_array = 263 argument_values.GetValueAtIndex(2)->GetScalar().ULongLong(-1); 264 if (header_array != static_cast<uint64_t>(-1)) { 265 std::vector<addr_t> image_load_addresses; 266 for (uint64_t i = 0; i < image_infos_count; i++) { 267 Error error; 268 addr_t addr = process->ReadUnsignedIntegerFromMemory( 269 header_array + (8 * i), 8, LLDB_INVALID_ADDRESS, error); 270 if (addr != LLDB_INVALID_ADDRESS) { 271 image_load_addresses.push_back(addr); 272 } 273 } 274 if (dyld_mode == 0) { 275 // dyld_notify_adding 276 dyld_instance->AddBinaries(image_load_addresses); 277 } else if (dyld_mode == 1) { 278 // dyld_notify_removing 279 dyld_instance->UnloadImages(image_load_addresses); 280 } else if (dyld_mode == 2) { 281 // dyld_notify_remove_all 282 dyld_instance->UnloadAllImages(); 283 } 284 } 285 } 286 } 287 } 288 } else { 289 process->GetTarget().GetDebugger().GetAsyncErrorStream()->Printf( 290 "No ABI plugin located for triple %s -- shared libraries will not be " 291 "registered!\n", 292 process->GetTarget().GetArchitecture().GetTriple().getTriple().c_str()); 293 } 294 295 // Return true to stop the target, false to just let the target run 296 return dyld_instance->GetStopWhenImagesChange(); 297 } 298 299 void DynamicLoaderMacOS::AddBinaries( 300 const std::vector<lldb::addr_t> &load_addresses) { 301 Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_DYNAMIC_LOADER)); 302 ImageInfo::collection image_infos; 303 304 if (log) 305 log->Printf("Adding %" PRId64 " modules.", (uint64_t)load_addresses.size()); 306 StructuredData::ObjectSP binaries_info_sp = 307 m_process->GetLoadedDynamicLibrariesInfos(load_addresses); 308 if (binaries_info_sp.get() && binaries_info_sp->GetAsDictionary() && 309 binaries_info_sp->GetAsDictionary()->HasKey("images") && 310 binaries_info_sp->GetAsDictionary() 311 ->GetValueForKey("images") 312 ->GetAsArray() && 313 binaries_info_sp->GetAsDictionary() 314 ->GetValueForKey("images") 315 ->GetAsArray() 316 ->GetSize() == load_addresses.size()) { 317 if (JSONImageInformationIntoImageInfo(binaries_info_sp, image_infos)) { 318 UpdateSpecialBinariesFromNewImageInfos(image_infos); 319 AddModulesUsingImageInfos(image_infos); 320 } 321 m_dyld_image_infos_stop_id = m_process->GetStopID(); 322 } 323 } 324 325 // Dump the _dyld_all_image_infos members and all current image infos 326 // that we have parsed to the file handle provided. 327 //---------------------------------------------------------------------- 328 void DynamicLoaderMacOS::PutToLog(Log *log) const { 329 if (log == NULL) 330 return; 331 } 332 333 bool DynamicLoaderMacOS::SetNotificationBreakpoint() { 334 if (m_break_id == LLDB_INVALID_BREAK_ID) { 335 ConstString g_symbol_name("_dyld_debugger_notification"); 336 const Symbol *symbol = nullptr; 337 ModuleSP dyld_sp(GetDYLDModule()); 338 if (dyld_sp) { 339 symbol = dyld_sp->FindFirstSymbolWithNameAndType(g_symbol_name, 340 eSymbolTypeCode); 341 } 342 if (symbol && 343 (symbol->ValueIsAddress() || symbol->GetAddressRef().IsValid())) { 344 addr_t symbol_address = 345 symbol->GetAddressRef().GetOpcodeLoadAddress(&m_process->GetTarget()); 346 if (symbol_address != LLDB_INVALID_ADDRESS) { 347 bool internal = true; 348 bool hardware = false; 349 Breakpoint *breakpoint = 350 m_process->GetTarget() 351 .CreateBreakpoint(symbol_address, internal, hardware) 352 .get(); 353 breakpoint->SetCallback(DynamicLoaderMacOS::NotifyBreakpointHit, this, 354 true); 355 breakpoint->SetBreakpointKind("shared-library-event"); 356 m_break_id = breakpoint->GetID(); 357 } 358 } 359 } 360 return m_break_id != LLDB_INVALID_BREAK_ID; 361 } 362 363 addr_t 364 DynamicLoaderMacOS::GetDyldLockVariableAddressFromModule(Module *module) { 365 SymbolContext sc; 366 SymbolVendor *sym_vendor = module->GetSymbolVendor(); 367 Target &target = m_process->GetTarget(); 368 if (sym_vendor) { 369 Symtab *symtab = sym_vendor->GetSymtab(); 370 if (symtab) { 371 std::vector<uint32_t> match_indexes; 372 ConstString g_symbol_name("_dyld_global_lock_held"); 373 uint32_t num_matches = 0; 374 num_matches = 375 symtab->AppendSymbolIndexesWithName(g_symbol_name, match_indexes); 376 if (num_matches == 1) { 377 Symbol *symbol = symtab->SymbolAtIndex(match_indexes[0]); 378 if (symbol && 379 (symbol->ValueIsAddress() || symbol->GetAddressRef().IsValid())) { 380 return symbol->GetAddressRef().GetOpcodeLoadAddress(&target); 381 } 382 } 383 } 384 } 385 return LLDB_INVALID_ADDRESS; 386 } 387 388 // Look for this symbol: 389 // 390 // int __attribute__((visibility("hidden"))) _dyld_global_lock_held = 391 // 0; 392 // 393 // in libdyld.dylib. 394 Error DynamicLoaderMacOS::CanLoadImage() { 395 Error error; 396 addr_t symbol_address = LLDB_INVALID_ADDRESS; 397 Target &target = m_process->GetTarget(); 398 const ModuleList &target_modules = target.GetImages(); 399 std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex()); 400 const size_t num_modules = target_modules.GetSize(); 401 ConstString g_libdyld_name("libdyld.dylib"); 402 403 // Find any modules named "libdyld.dylib" and look for the symbol there first 404 for (size_t i = 0; i < num_modules; i++) { 405 Module *module_pointer = target_modules.GetModulePointerAtIndexUnlocked(i); 406 if (module_pointer) { 407 if (module_pointer->GetFileSpec().GetFilename() == g_libdyld_name) { 408 symbol_address = GetDyldLockVariableAddressFromModule(module_pointer); 409 if (symbol_address != LLDB_INVALID_ADDRESS) 410 break; 411 } 412 } 413 } 414 415 // Search through all modules looking for the symbol in them 416 if (symbol_address == LLDB_INVALID_ADDRESS) { 417 for (size_t i = 0; i < num_modules; i++) { 418 Module *module_pointer = 419 target_modules.GetModulePointerAtIndexUnlocked(i); 420 if (module_pointer) { 421 addr_t symbol_address = 422 GetDyldLockVariableAddressFromModule(module_pointer); 423 if (symbol_address != LLDB_INVALID_ADDRESS) 424 break; 425 } 426 } 427 } 428 429 // Default assumption is that it is OK to load images. 430 // Only say that we cannot load images if we find the symbol in libdyld and it 431 // indicates that 432 // we cannot. 433 434 if (symbol_address != LLDB_INVALID_ADDRESS) { 435 { 436 int lock_held = 437 m_process->ReadUnsignedIntegerFromMemory(symbol_address, 4, 0, error); 438 if (lock_held != 0) { 439 error.SetErrorToGenericError(); 440 } 441 } 442 } else { 443 // If we were unable to find _dyld_global_lock_held in any modules, or it is 444 // not loaded into 445 // memory yet, we may be at process startup (sitting at _dyld_start) - so we 446 // should not allow 447 // dlopen calls. 448 error.SetErrorToGenericError(); 449 } 450 return error; 451 } 452 453 bool DynamicLoaderMacOS::GetSharedCacheInformation( 454 lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache, 455 LazyBool &private_shared_cache) { 456 base_address = LLDB_INVALID_ADDRESS; 457 uuid.Clear(); 458 using_shared_cache = eLazyBoolCalculate; 459 private_shared_cache = eLazyBoolCalculate; 460 461 if (m_process) { 462 StructuredData::ObjectSP info = m_process->GetSharedCacheInfo(); 463 StructuredData::Dictionary *info_dict = nullptr; 464 if (info.get() && info->GetAsDictionary()) { 465 info_dict = info->GetAsDictionary(); 466 } 467 468 // {"shared_cache_base_address":140735683125248,"shared_cache_uuid":"DDB8D70C-C9A2-3561-B2C8-BE48A4F33F96","no_shared_cache":false,"shared_cache_private_cache":false} 469 470 if (info_dict && info_dict->HasKey("shared_cache_uuid") && 471 info_dict->HasKey("no_shared_cache") && 472 info_dict->HasKey("shared_cache_base_address")) { 473 base_address = info_dict->GetValueForKey("shared_cache_base_address") 474 ->GetIntegerValue(LLDB_INVALID_ADDRESS); 475 std::string uuid_str = info_dict->GetValueForKey("shared_cache_uuid") 476 ->GetStringValue() 477 .c_str(); 478 if (!uuid_str.empty()) 479 uuid.SetFromCString(uuid_str.c_str()); 480 if (info_dict->GetValueForKey("no_shared_cache")->GetBooleanValue() == 481 false) 482 using_shared_cache = eLazyBoolYes; 483 else 484 using_shared_cache = eLazyBoolNo; 485 if (info_dict->GetValueForKey("shared_cache_private_cache") 486 ->GetBooleanValue()) 487 private_shared_cache = eLazyBoolYes; 488 else 489 private_shared_cache = eLazyBoolNo; 490 491 return true; 492 } 493 } 494 return false; 495 } 496 497 void DynamicLoaderMacOS::Initialize() { 498 PluginManager::RegisterPlugin(GetPluginNameStatic(), 499 GetPluginDescriptionStatic(), CreateInstance); 500 } 501 502 void DynamicLoaderMacOS::Terminate() { 503 PluginManager::UnregisterPlugin(CreateInstance); 504 } 505 506 lldb_private::ConstString DynamicLoaderMacOS::GetPluginNameStatic() { 507 static ConstString g_name("macos-dyld"); 508 return g_name; 509 } 510 511 const char *DynamicLoaderMacOS::GetPluginDescriptionStatic() { 512 return "Dynamic loader plug-in that watches for shared library loads/unloads " 513 "in MacOSX user processes."; 514 } 515 516 //------------------------------------------------------------------ 517 // PluginInterface protocol 518 //------------------------------------------------------------------ 519 lldb_private::ConstString DynamicLoaderMacOS::GetPluginName() { 520 return GetPluginNameStatic(); 521 } 522 523 uint32_t DynamicLoaderMacOS::GetPluginVersion() { return 1; } 524