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