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