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     Target &target = process->GetTarget();
303     Debugger::ReportWarning(
304         "no ABI plugin located for triple " +
305             target.GetArchitecture().GetTriple().getTriple() +
306             ": shared libraries will not be registered",
307         target.GetDebugger().GetID());
308   }
309 
310   // Return true to stop the target, false to just let the target run
311   return dyld_instance->GetStopWhenImagesChange();
312 }
313 
314 void DynamicLoaderMacOS::AddBinaries(
315     const std::vector<lldb::addr_t> &load_addresses) {
316   Log *log = GetLog(LLDBLog::DynamicLoader);
317   ImageInfo::collection image_infos;
318 
319   LLDB_LOGF(log, "Adding %" PRId64 " modules.",
320             (uint64_t)load_addresses.size());
321   StructuredData::ObjectSP binaries_info_sp =
322       m_process->GetLoadedDynamicLibrariesInfos(load_addresses);
323   if (binaries_info_sp.get() && binaries_info_sp->GetAsDictionary() &&
324       binaries_info_sp->GetAsDictionary()->HasKey("images") &&
325       binaries_info_sp->GetAsDictionary()
326           ->GetValueForKey("images")
327           ->GetAsArray() &&
328       binaries_info_sp->GetAsDictionary()
329               ->GetValueForKey("images")
330               ->GetAsArray()
331               ->GetSize() == load_addresses.size()) {
332     if (JSONImageInformationIntoImageInfo(binaries_info_sp, image_infos)) {
333       UpdateSpecialBinariesFromNewImageInfos(image_infos);
334       AddModulesUsingImageInfos(image_infos);
335     }
336     m_dyld_image_infos_stop_id = m_process->GetStopID();
337   }
338 }
339 
340 // Dump the _dyld_all_image_infos members and all current image infos that we
341 // have parsed to the file handle provided.
342 void DynamicLoaderMacOS::PutToLog(Log *log) const {
343   if (log == nullptr)
344     return;
345 }
346 
347 bool DynamicLoaderMacOS::SetNotificationBreakpoint() {
348   if (m_break_id == LLDB_INVALID_BREAK_ID) {
349     ModuleSP dyld_sp(GetDYLDModule());
350     if (dyld_sp) {
351       bool internal = true;
352       bool hardware = false;
353       LazyBool skip_prologue = eLazyBoolNo;
354       FileSpecList *source_files = nullptr;
355       FileSpecList dyld_filelist;
356       dyld_filelist.Append(dyld_sp->GetFileSpec());
357 
358       Breakpoint *breakpoint =
359           m_process->GetTarget()
360               .CreateBreakpoint(&dyld_filelist, source_files,
361                                 "_dyld_debugger_notification",
362                                 eFunctionNameTypeFull, eLanguageTypeC, 0,
363                                 skip_prologue, internal, hardware)
364               .get();
365       breakpoint->SetCallback(DynamicLoaderMacOS::NotifyBreakpointHit, this,
366                               true);
367       breakpoint->SetBreakpointKind("shared-library-event");
368       m_break_id = breakpoint->GetID();
369     }
370   }
371   return m_break_id != LLDB_INVALID_BREAK_ID;
372 }
373 
374 addr_t
375 DynamicLoaderMacOS::GetDyldLockVariableAddressFromModule(Module *module) {
376   SymbolContext sc;
377   Target &target = m_process->GetTarget();
378   if (Symtab *symtab = module->GetSymtab()) {
379     std::vector<uint32_t> match_indexes;
380     ConstString g_symbol_name("_dyld_global_lock_held");
381     uint32_t num_matches = 0;
382     num_matches =
383         symtab->AppendSymbolIndexesWithName(g_symbol_name, match_indexes);
384     if (num_matches == 1) {
385       Symbol *symbol = symtab->SymbolAtIndex(match_indexes[0]);
386       if (symbol &&
387           (symbol->ValueIsAddress() || symbol->GetAddressRef().IsValid())) {
388         return symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
389       }
390     }
391   }
392   return LLDB_INVALID_ADDRESS;
393 }
394 
395 //  Look for this symbol:
396 //
397 //  int __attribute__((visibility("hidden")))           _dyld_global_lock_held =
398 //  0;
399 //
400 //  in libdyld.dylib.
401 Status DynamicLoaderMacOS::CanLoadImage() {
402   Status error;
403   addr_t symbol_address = LLDB_INVALID_ADDRESS;
404   ConstString g_libdyld_name("libdyld.dylib");
405   Target &target = m_process->GetTarget();
406   const ModuleList &target_modules = target.GetImages();
407   std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
408 
409   // Find any modules named "libdyld.dylib" and look for the symbol there first
410   for (ModuleSP module_sp : target.GetImages().ModulesNoLocking()) {
411     if (module_sp) {
412       if (module_sp->GetFileSpec().GetFilename() == g_libdyld_name) {
413         symbol_address = GetDyldLockVariableAddressFromModule(module_sp.get());
414         if (symbol_address != LLDB_INVALID_ADDRESS)
415           break;
416       }
417     }
418   }
419 
420   // Search through all modules looking for the symbol in them
421   if (symbol_address == LLDB_INVALID_ADDRESS) {
422     for (ModuleSP module_sp : target.GetImages().Modules()) {
423       if (module_sp) {
424         addr_t symbol_address =
425             GetDyldLockVariableAddressFromModule(module_sp.get());
426         if (symbol_address != LLDB_INVALID_ADDRESS)
427           break;
428       }
429     }
430   }
431 
432   // Default assumption is that it is OK to load images. Only say that we
433   // cannot load images if we find the symbol in libdyld and it indicates that
434   // we cannot.
435 
436   if (symbol_address != LLDB_INVALID_ADDRESS) {
437     {
438       int lock_held =
439           m_process->ReadUnsignedIntegerFromMemory(symbol_address, 4, 0, error);
440       if (lock_held != 0) {
441         error.SetErrorString("dyld lock held - unsafe to load images.");
442       }
443     }
444   } else {
445     // If we were unable to find _dyld_global_lock_held in any modules, or it
446     // is not loaded into memory yet, we may be at process startup (sitting  at
447     // _dyld_start) - so we should not allow dlopen calls. But if we found more
448     // than one module then we are clearly past _dyld_start so in that case
449     // we'll default to "it's safe".
450     if (target.GetImages().GetSize() <= 1)
451       error.SetErrorString("could not find the dyld library or "
452                            "the dyld lock symbol");
453   }
454   return error;
455 }
456 
457 bool DynamicLoaderMacOS::GetSharedCacheInformation(
458     lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
459     LazyBool &private_shared_cache) {
460   base_address = LLDB_INVALID_ADDRESS;
461   uuid.Clear();
462   using_shared_cache = eLazyBoolCalculate;
463   private_shared_cache = eLazyBoolCalculate;
464 
465   if (m_process) {
466     StructuredData::ObjectSP info = m_process->GetSharedCacheInfo();
467     StructuredData::Dictionary *info_dict = nullptr;
468     if (info.get() && info->GetAsDictionary()) {
469       info_dict = info->GetAsDictionary();
470     }
471 
472     // {"shared_cache_base_address":140735683125248,"shared_cache_uuid
473     // ":"DDB8D70C-
474     // C9A2-3561-B2C8-BE48A4F33F96","no_shared_cache":false,"shared_cache_private_cache":false}
475 
476     if (info_dict && info_dict->HasKey("shared_cache_uuid") &&
477         info_dict->HasKey("no_shared_cache") &&
478         info_dict->HasKey("shared_cache_base_address")) {
479       base_address = info_dict->GetValueForKey("shared_cache_base_address")
480                          ->GetIntegerValue(LLDB_INVALID_ADDRESS);
481       std::string uuid_str = std::string(
482           info_dict->GetValueForKey("shared_cache_uuid")->GetStringValue());
483       if (!uuid_str.empty())
484         uuid.SetFromStringRef(uuid_str);
485       if (!info_dict->GetValueForKey("no_shared_cache")->GetBooleanValue())
486         using_shared_cache = eLazyBoolYes;
487       else
488         using_shared_cache = eLazyBoolNo;
489       if (info_dict->GetValueForKey("shared_cache_private_cache")
490               ->GetBooleanValue())
491         private_shared_cache = eLazyBoolYes;
492       else
493         private_shared_cache = eLazyBoolNo;
494 
495       return true;
496     }
497   }
498   return false;
499 }
500 
501 void DynamicLoaderMacOS::Initialize() {
502   PluginManager::RegisterPlugin(GetPluginNameStatic(),
503                                 GetPluginDescriptionStatic(), CreateInstance);
504 }
505 
506 void DynamicLoaderMacOS::Terminate() {
507   PluginManager::UnregisterPlugin(CreateInstance);
508 }
509 
510 llvm::StringRef DynamicLoaderMacOS::GetPluginDescriptionStatic() {
511   return "Dynamic loader plug-in that watches for shared library loads/unloads "
512          "in MacOSX user processes.";
513 }
514