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