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