180814287SRaphael Isemann //===-- DynamicLoaderMacOS.cpp --------------------------------------------===//
29ab5dc24SJason Molenda //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
69ab5dc24SJason Molenda //
79ab5dc24SJason Molenda //===----------------------------------------------------------------------===//
89ab5dc24SJason Molenda 
99ab5dc24SJason Molenda #include "lldb/Breakpoint/StoppointCallbackContext.h"
109ab5dc24SJason Molenda #include "lldb/Core/Debugger.h"
119ab5dc24SJason Molenda #include "lldb/Core/Module.h"
129ab5dc24SJason Molenda #include "lldb/Core/PluginManager.h"
139ab5dc24SJason Molenda #include "lldb/Core/Section.h"
149ab5dc24SJason Molenda #include "lldb/Symbol/ObjectFile.h"
15b9c1b51eSKate Stone #include "lldb/Symbol/SymbolVendor.h"
169ab5dc24SJason Molenda #include "lldb/Target/ABI.h"
17*8d5a6007SJason Molenda #include "lldb/Target/SectionLoadList.h"
18b9c1b51eSKate Stone #include "lldb/Target/StackFrame.h"
199ab5dc24SJason Molenda #include "lldb/Target/Target.h"
209ab5dc24SJason Molenda #include "lldb/Target/Thread.h"
21c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
226f9e6901SZachary Turner #include "lldb/Utility/Log.h"
23d821c997SPavel Labath #include "lldb/Utility/State.h"
249ab5dc24SJason Molenda 
259ab5dc24SJason Molenda #include "DynamicLoaderDarwin.h"
26b9c1b51eSKate Stone #include "DynamicLoaderMacOS.h"
279ab5dc24SJason Molenda 
288be30215SAlex Langford #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
298be30215SAlex Langford 
309ab5dc24SJason Molenda using namespace lldb;
319ab5dc24SJason Molenda using namespace lldb_private;
329ab5dc24SJason Molenda 
3305097246SAdrian Prantl // Create an instance of this class. This function is filled into the plugin
3405097246SAdrian Prantl // info class that gets handed out by the plugin factory and allows the lldb to
3505097246SAdrian Prantl // instantiate an instance of this class.
CreateInstance(Process * process,bool force)36b9c1b51eSKate Stone DynamicLoader *DynamicLoaderMacOS::CreateInstance(Process *process,
37b9c1b51eSKate Stone                                                   bool force) {
389ab5dc24SJason Molenda   bool create = force;
39b9c1b51eSKate Stone   if (!create) {
409ab5dc24SJason Molenda     create = true;
419ab5dc24SJason Molenda     Module *exe_module = process->GetTarget().GetExecutableModulePointer();
42b9c1b51eSKate Stone     if (exe_module) {
439ab5dc24SJason Molenda       ObjectFile *object_file = exe_module->GetObjectFile();
44b9c1b51eSKate Stone       if (object_file) {
459ab5dc24SJason Molenda         create = (object_file->GetStrata() == ObjectFile::eStrataUser);
469ab5dc24SJason Molenda       }
479ab5dc24SJason Molenda     }
489ab5dc24SJason Molenda 
49b9c1b51eSKate Stone     if (create) {
50b9c1b51eSKate Stone       const llvm::Triple &triple_ref =
51b9c1b51eSKate Stone           process->GetTarget().GetArchitecture().GetTriple();
52b9c1b51eSKate Stone       switch (triple_ref.getOS()) {
539ab5dc24SJason Molenda       case llvm::Triple::Darwin:
549ab5dc24SJason Molenda       case llvm::Triple::MacOSX:
559ab5dc24SJason Molenda       case llvm::Triple::IOS:
569ab5dc24SJason Molenda       case llvm::Triple::TvOS:
579ab5dc24SJason Molenda       case llvm::Triple::WatchOS:
5832762fd2SJason Molenda       // NEED_BRIDGEOS_TRIPLE case llvm::Triple::BridgeOS:
599ab5dc24SJason Molenda         create = triple_ref.getVendor() == llvm::Triple::Apple;
609ab5dc24SJason Molenda         break;
619ab5dc24SJason Molenda       default:
629ab5dc24SJason Molenda         create = false;
639ab5dc24SJason Molenda         break;
649ab5dc24SJason Molenda       }
659ab5dc24SJason Molenda     }
669ab5dc24SJason Molenda   }
679ab5dc24SJason Molenda 
68a6682a41SJonas Devlieghere   if (!UseDYLDSPI(process)) {
699ab5dc24SJason Molenda     create = false;
709ab5dc24SJason Molenda   }
719ab5dc24SJason Molenda 
729ab5dc24SJason Molenda   if (create)
739ab5dc24SJason Molenda     return new DynamicLoaderMacOS(process);
74248a1305SKonrad Kleine   return nullptr;
759ab5dc24SJason Molenda }
769ab5dc24SJason Molenda 
779ab5dc24SJason Molenda // Constructor
DynamicLoaderMacOS(Process * process)78b9c1b51eSKate Stone DynamicLoaderMacOS::DynamicLoaderMacOS(Process *process)
79b9c1b51eSKate Stone     : DynamicLoaderDarwin(process), m_image_infos_stop_id(UINT32_MAX),
80*8d5a6007SJason Molenda       m_break_id(LLDB_INVALID_BREAK_ID),
81*8d5a6007SJason Molenda       m_dyld_handover_break_id(LLDB_INVALID_BREAK_ID), m_mutex(),
8229ae6594SJim Ingham       m_maybe_image_infos_address(LLDB_INVALID_ADDRESS) {}
839ab5dc24SJason Molenda 
849ab5dc24SJason Molenda // Destructor
~DynamicLoaderMacOS()85b9c1b51eSKate Stone DynamicLoaderMacOS::~DynamicLoaderMacOS() {
869ab5dc24SJason Molenda   if (LLDB_BREAK_ID_IS_VALID(m_break_id))
879ab5dc24SJason Molenda     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
88*8d5a6007SJason Molenda   if (LLDB_BREAK_ID_IS_VALID(m_dyld_handover_break_id))
89*8d5a6007SJason Molenda     m_process->GetTarget().RemoveBreakpointByID(m_dyld_handover_break_id);
909ab5dc24SJason Molenda }
919ab5dc24SJason Molenda 
ProcessDidExec()92b9c1b51eSKate Stone bool DynamicLoaderMacOS::ProcessDidExec() {
939ab5dc24SJason Molenda   std::lock_guard<std::recursive_mutex> baseclass_guard(GetMutex());
949ab5dc24SJason Molenda   bool did_exec = false;
95b9c1b51eSKate Stone   if (m_process) {
969ab5dc24SJason Molenda     // If we are stopped after an exec, we will have only one thread...
97b9c1b51eSKate Stone     if (m_process->GetThreadList().GetSize() == 1) {
9829ae6594SJim Ingham       // Maybe we still have an image infos address around?  If so see
9929ae6594SJim Ingham       // if that has changed, and if so we have exec'ed.
10029ae6594SJim Ingham       if (m_maybe_image_infos_address != LLDB_INVALID_ADDRESS) {
10129ae6594SJim Ingham         lldb::addr_t image_infos_address = m_process->GetImageInfoAddress();
10229ae6594SJim Ingham         if (image_infos_address != m_maybe_image_infos_address) {
10329ae6594SJim Ingham           // We don't really have to reset this here, since we are going to
10429ae6594SJim Ingham           // call DoInitialImageFetch right away to handle the exec.  But in
10529ae6594SJim Ingham           // case anybody looks at it in the meantime, it can't hurt.
10629ae6594SJim Ingham           m_maybe_image_infos_address = image_infos_address;
10729ae6594SJim Ingham           did_exec = true;
10829ae6594SJim Ingham         }
10929ae6594SJim Ingham       }
11029ae6594SJim Ingham 
11129ae6594SJim Ingham       if (!did_exec) {
1129ab5dc24SJason Molenda         // See if we are stopped at '_dyld_start'
1139ab5dc24SJason Molenda         ThreadSP thread_sp(m_process->GetThreadList().GetThreadAtIndex(0));
114b9c1b51eSKate Stone         if (thread_sp) {
1159ab5dc24SJason Molenda           lldb::StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
116b9c1b51eSKate Stone           if (frame_sp) {
117b9c1b51eSKate Stone             const Symbol *symbol =
118b9c1b51eSKate Stone                 frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol;
119b9c1b51eSKate Stone             if (symbol) {
12005cfdb0eSRaphael Isemann               if (symbol->GetName() == "_dyld_start")
1219ab5dc24SJason Molenda                 did_exec = true;
1229ab5dc24SJason Molenda             }
1239ab5dc24SJason Molenda           }
1249ab5dc24SJason Molenda         }
1259ab5dc24SJason Molenda       }
1269ab5dc24SJason Molenda     }
12729ae6594SJim Ingham   }
1289ab5dc24SJason Molenda 
129b9c1b51eSKate Stone   if (did_exec) {
1309ab5dc24SJason Molenda     m_libpthread_module_wp.reset();
1319ab5dc24SJason Molenda     m_pthread_getspecific_addr.Clear();
1329ab5dc24SJason Molenda   }
1339ab5dc24SJason Molenda   return did_exec;
1349ab5dc24SJason Molenda }
1359ab5dc24SJason Molenda 
1369ab5dc24SJason Molenda // Clear out the state of this class.
DoClear()137b9c1b51eSKate Stone void DynamicLoaderMacOS::DoClear() {
1389ab5dc24SJason Molenda   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1399ab5dc24SJason Molenda 
1409ab5dc24SJason Molenda   if (LLDB_BREAK_ID_IS_VALID(m_break_id))
1419ab5dc24SJason Molenda     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
142*8d5a6007SJason Molenda   if (LLDB_BREAK_ID_IS_VALID(m_dyld_handover_break_id))
143*8d5a6007SJason Molenda     m_process->GetTarget().RemoveBreakpointByID(m_dyld_handover_break_id);
1449ab5dc24SJason Molenda 
1459ab5dc24SJason Molenda   m_break_id = LLDB_INVALID_BREAK_ID;
146*8d5a6007SJason Molenda   m_dyld_handover_break_id = LLDB_INVALID_BREAK_ID;
1479ab5dc24SJason Molenda }
1489ab5dc24SJason Molenda 
1499ab5dc24SJason Molenda // Check if we have found DYLD yet
DidSetNotificationBreakpoint()150b9c1b51eSKate Stone bool DynamicLoaderMacOS::DidSetNotificationBreakpoint() {
1519ab5dc24SJason Molenda   return LLDB_BREAK_ID_IS_VALID(m_break_id);
1529ab5dc24SJason Molenda }
1539ab5dc24SJason Molenda 
ClearNotificationBreakpoint()154b9c1b51eSKate Stone void DynamicLoaderMacOS::ClearNotificationBreakpoint() {
155b9c1b51eSKate Stone   if (LLDB_BREAK_ID_IS_VALID(m_break_id)) {
1569ab5dc24SJason Molenda     m_process->GetTarget().RemoveBreakpointByID(m_break_id);
157777fcecfSJason Molenda     m_break_id = LLDB_INVALID_BREAK_ID;
1589ab5dc24SJason Molenda   }
1599ab5dc24SJason Molenda }
1609ab5dc24SJason Molenda 
16105097246SAdrian Prantl // Try and figure out where dyld is by first asking the Process if it knows
16205097246SAdrian Prantl // (which currently calls down in the lldb::Process to get the DYLD info
16305097246SAdrian Prantl // (available on SnowLeopard only). If that fails, then check in the default
16405097246SAdrian Prantl // addresses.
DoInitialImageFetch()165b9c1b51eSKate Stone void DynamicLoaderMacOS::DoInitialImageFetch() {
166a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::DynamicLoader);
1679ab5dc24SJason Molenda 
16805097246SAdrian Prantl   // Remove any binaries we pre-loaded in the Target before
16905097246SAdrian Prantl   // launching/attaching. If the same binaries are present in the process,
17005097246SAdrian Prantl   // we'll get them from the shared module cache, we won't need to re-load them
17105097246SAdrian Prantl   // from disk.
172848c7be0SJason Molenda   UnloadAllImages();
173848c7be0SJason Molenda 
174b9c1b51eSKate Stone   StructuredData::ObjectSP all_image_info_json_sp(
175b9c1b51eSKate Stone       m_process->GetLoadedDynamicLibrariesInfos());
1769ab5dc24SJason Molenda   ImageInfo::collection image_infos;
177b9c1b51eSKate Stone   if (all_image_info_json_sp.get() &&
178b9c1b51eSKate Stone       all_image_info_json_sp->GetAsDictionary() &&
179b9c1b51eSKate Stone       all_image_info_json_sp->GetAsDictionary()->HasKey("images") &&
180b9c1b51eSKate Stone       all_image_info_json_sp->GetAsDictionary()
181b9c1b51eSKate Stone           ->GetValueForKey("images")
182b9c1b51eSKate Stone           ->GetAsArray()) {
183b9c1b51eSKate Stone     if (JSONImageInformationIntoImageInfo(all_image_info_json_sp,
184b9c1b51eSKate Stone                                           image_infos)) {
18563e5fb76SJonas Devlieghere       LLDB_LOGF(log, "Initial module fetch:  Adding %" PRId64 " modules.\n",
186b9c1b51eSKate Stone                 (uint64_t)image_infos.size());
1879ab5dc24SJason Molenda 
1889ab5dc24SJason Molenda       UpdateSpecialBinariesFromNewImageInfos(image_infos);
1899ab5dc24SJason Molenda       AddModulesUsingImageInfos(image_infos);
1909ab5dc24SJason Molenda     }
1919ab5dc24SJason Molenda   }
1929ab5dc24SJason Molenda 
1939ab5dc24SJason Molenda   m_dyld_image_infos_stop_id = m_process->GetStopID();
19429ae6594SJim Ingham   m_maybe_image_infos_address = m_process->GetImageInfoAddress();
1959ab5dc24SJason Molenda }
1969ab5dc24SJason Molenda 
NeedToDoInitialImageFetch()197b9c1b51eSKate Stone bool DynamicLoaderMacOS::NeedToDoInitialImageFetch() { return true; }
1989ab5dc24SJason Molenda 
1999ab5dc24SJason Molenda // Static callback function that gets called when our DYLD notification
20005097246SAdrian Prantl // breakpoint gets hit. We update all of our image infos and then let our super
20105097246SAdrian Prantl // class DynamicLoader class decide if we should stop or not (based on global
20205097246SAdrian Prantl // preference).
NotifyBreakpointHit(void * baton,StoppointCallbackContext * context,lldb::user_id_t break_id,lldb::user_id_t break_loc_id)203b9c1b51eSKate Stone bool DynamicLoaderMacOS::NotifyBreakpointHit(void *baton,
2049ab5dc24SJason Molenda                                              StoppointCallbackContext *context,
2059ab5dc24SJason Molenda                                              lldb::user_id_t break_id,
206b9c1b51eSKate Stone                                              lldb::user_id_t break_loc_id) {
2079ab5dc24SJason Molenda   // Let the event know that the images have changed
2089ab5dc24SJason Molenda   // DYLD passes three arguments to the notification breakpoint.
20905097246SAdrian Prantl   // Arg1: enum dyld_notify_mode mode - 0 = adding, 1 = removing, 2 = remove
21005097246SAdrian Prantl   // all Arg2: unsigned long icount        - Number of shared libraries
21105097246SAdrian Prantl   // added/removed Arg3: uint64_t mach_headers[]     - Array of load addresses
21205097246SAdrian Prantl   // of binaries added/removed
2139ab5dc24SJason Molenda 
2149ab5dc24SJason Molenda   DynamicLoaderMacOS *dyld_instance = (DynamicLoaderMacOS *)baton;
2159ab5dc24SJason Molenda 
2169ab5dc24SJason Molenda   ExecutionContext exe_ctx(context->exe_ctx_ref);
2179ab5dc24SJason Molenda   Process *process = exe_ctx.GetProcessPtr();
2189ab5dc24SJason Molenda 
219b9c1b51eSKate Stone   // This is a sanity check just in case this dyld_instance is an old dyld
220b9c1b51eSKate Stone   // plugin's breakpoint still lying around.
2219ab5dc24SJason Molenda   if (process != dyld_instance->m_process)
2229ab5dc24SJason Molenda     return false;
2239ab5dc24SJason Molenda 
224b9c1b51eSKate Stone   if (dyld_instance->m_image_infos_stop_id != UINT32_MAX &&
225b9c1b51eSKate Stone       process->GetStopID() < dyld_instance->m_image_infos_stop_id) {
2269ab5dc24SJason Molenda     return false;
2279ab5dc24SJason Molenda   }
2289ab5dc24SJason Molenda 
2299ab5dc24SJason Molenda   const lldb::ABISP &abi = process->GetABI();
230b9c1b51eSKate Stone   if (abi) {
231b9c1b51eSKate Stone     // Build up the value array to store the three arguments given above, then
232b9c1b51eSKate Stone     // get the values from the ABI:
2339ab5dc24SJason Molenda 
2346e3b0cc2SRaphael Isemann     TypeSystemClang *clang_ast_context =
235594308c7SRaphael Isemann         ScratchTypeSystemClang::GetForTarget(process->GetTarget());
2363031818aSAlex Langford     if (!clang_ast_context)
2373031818aSAlex Langford       return false;
2383031818aSAlex Langford 
2399ab5dc24SJason Molenda     ValueList argument_values;
2409ab5dc24SJason Molenda 
241b9c1b51eSKate Stone     Value mode_value;    // enum dyld_notify_mode { dyld_notify_adding=0,
242b9c1b51eSKate Stone                          // dyld_notify_removing=1, dyld_notify_remove_all=2 };
2439ab5dc24SJason Molenda     Value count_value;   // unsigned long count
2449ab5dc24SJason Molenda     Value headers_value; // uint64_t machHeaders[] (aka void*)
2459ab5dc24SJason Molenda 
246b9c1b51eSKate Stone     CompilerType clang_void_ptr_type =
247b9c1b51eSKate Stone         clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
248b9c1b51eSKate Stone     CompilerType clang_uint32_type =
249b9c1b51eSKate Stone         clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
250b9c1b51eSKate Stone             lldb::eEncodingUint, 32);
251b9c1b51eSKate Stone     CompilerType clang_uint64_type =
252b9c1b51eSKate Stone         clang_ast_context->GetBuiltinTypeForEncodingAndBitSize(
253b9c1b51eSKate Stone             lldb::eEncodingUint, 32);
2549ab5dc24SJason Molenda 
255057efa99SAdrian Prantl     mode_value.SetValueType(Value::ValueType::Scalar);
2569ab5dc24SJason Molenda     mode_value.SetCompilerType(clang_uint32_type);
2579ab5dc24SJason Molenda 
258b9c1b51eSKate Stone     if (process->GetTarget().GetArchitecture().GetAddressByteSize() == 4) {
259057efa99SAdrian Prantl       count_value.SetValueType(Value::ValueType::Scalar);
2609ab5dc24SJason Molenda       count_value.SetCompilerType(clang_uint32_type);
261b9c1b51eSKate Stone     } else {
262057efa99SAdrian Prantl       count_value.SetValueType(Value::ValueType::Scalar);
2639ab5dc24SJason Molenda       count_value.SetCompilerType(clang_uint64_type);
2649ab5dc24SJason Molenda     }
2659ab5dc24SJason Molenda 
266057efa99SAdrian Prantl     headers_value.SetValueType(Value::ValueType::Scalar);
2679ab5dc24SJason Molenda     headers_value.SetCompilerType(clang_void_ptr_type);
2689ab5dc24SJason Molenda 
2699ab5dc24SJason Molenda     argument_values.PushValue(mode_value);
2709ab5dc24SJason Molenda     argument_values.PushValue(count_value);
2719ab5dc24SJason Molenda     argument_values.PushValue(headers_value);
2729ab5dc24SJason Molenda 
273b9c1b51eSKate Stone     if (abi->GetArgumentValues(exe_ctx.GetThreadRef(), argument_values)) {
274b9c1b51eSKate Stone       uint32_t dyld_mode =
275b9c1b51eSKate Stone           argument_values.GetValueAtIndex(0)->GetScalar().UInt(-1);
276b9c1b51eSKate Stone       if (dyld_mode != static_cast<uint32_t>(-1)) {
277b9c1b51eSKate Stone         // Okay the mode was right, now get the number of elements, and the
278b9c1b51eSKate Stone         // array of new elements...
279b9c1b51eSKate Stone         uint32_t image_infos_count =
280b9c1b51eSKate Stone             argument_values.GetValueAtIndex(1)->GetScalar().UInt(-1);
281b9c1b51eSKate Stone         if (image_infos_count != static_cast<uint32_t>(-1)) {
282b9c1b51eSKate Stone           addr_t header_array =
283b9c1b51eSKate Stone               argument_values.GetValueAtIndex(2)->GetScalar().ULongLong(-1);
284b9c1b51eSKate Stone           if (header_array != static_cast<uint64_t>(-1)) {
2859ab5dc24SJason Molenda             std::vector<addr_t> image_load_addresses;
286b9c1b51eSKate Stone             for (uint64_t i = 0; i < image_infos_count; i++) {
28797206d57SZachary Turner               Status error;
288b9c1b51eSKate Stone               addr_t addr = process->ReadUnsignedIntegerFromMemory(
289b9c1b51eSKate Stone                   header_array + (8 * i), 8, LLDB_INVALID_ADDRESS, error);
290b9c1b51eSKate Stone               if (addr != LLDB_INVALID_ADDRESS) {
2919ab5dc24SJason Molenda                 image_load_addresses.push_back(addr);
2929ab5dc24SJason Molenda               }
2939ab5dc24SJason Molenda             }
294b9c1b51eSKate Stone             if (dyld_mode == 0) {
2959ab5dc24SJason Molenda               // dyld_notify_adding
296*8d5a6007SJason Molenda               if (process->GetTarget().GetImages().GetSize() == 0) {
297*8d5a6007SJason Molenda                 // When all images have been removed, we're doing the
298*8d5a6007SJason Molenda                 // dyld handover from a launch-dyld to a shared-cache-dyld,
299*8d5a6007SJason Molenda                 // and we've just hit our one-shot address breakpoint in
300*8d5a6007SJason Molenda                 // the sc-dyld.  Note that the image addresses passed to
301*8d5a6007SJason Molenda                 // this function are inferior sizeof(void*) not uint64_t's
302*8d5a6007SJason Molenda                 // like our normal notification, so don't even look at
303*8d5a6007SJason Molenda                 // image_load_addresses.
304*8d5a6007SJason Molenda 
305*8d5a6007SJason Molenda                 dyld_instance->ClearDYLDHandoverBreakpoint();
306*8d5a6007SJason Molenda 
307*8d5a6007SJason Molenda                 dyld_instance->DoInitialImageFetch();
308*8d5a6007SJason Molenda                 dyld_instance->SetNotificationBreakpoint();
309*8d5a6007SJason Molenda               } else {
3109ab5dc24SJason Molenda                 dyld_instance->AddBinaries(image_load_addresses);
311*8d5a6007SJason Molenda               }
312b9c1b51eSKate Stone             } else if (dyld_mode == 1) {
3139ab5dc24SJason Molenda               // dyld_notify_removing
3149ab5dc24SJason Molenda               dyld_instance->UnloadImages(image_load_addresses);
315b9c1b51eSKate Stone             } else if (dyld_mode == 2) {
3169ab5dc24SJason Molenda               // dyld_notify_remove_all
3179ab5dc24SJason Molenda               dyld_instance->UnloadAllImages();
318*8d5a6007SJason Molenda             } else if (dyld_mode == 3 && image_infos_count == 1) {
319*8d5a6007SJason Molenda               // dyld_image_dyld_moved
320*8d5a6007SJason Molenda 
321*8d5a6007SJason Molenda               dyld_instance->ClearNotificationBreakpoint();
322*8d5a6007SJason Molenda               dyld_instance->UnloadAllImages();
323*8d5a6007SJason Molenda               dyld_instance->ClearDYLDModule();
324*8d5a6007SJason Molenda               process->GetTarget().GetImages().Clear();
325*8d5a6007SJason Molenda               process->GetTarget().GetSectionLoadList().Clear();
326*8d5a6007SJason Molenda 
327*8d5a6007SJason Molenda               addr_t all_image_infos = process->GetImageInfoAddress();
328*8d5a6007SJason Molenda               int addr_size =
329*8d5a6007SJason Molenda                   process->GetTarget().GetArchitecture().GetAddressByteSize();
330*8d5a6007SJason Molenda               addr_t notification_location = all_image_infos + 4 + // version
331*8d5a6007SJason Molenda                                              4 +        // infoArrayCount
332*8d5a6007SJason Molenda                                              addr_size; // infoArray
333*8d5a6007SJason Molenda               Status error;
334*8d5a6007SJason Molenda               addr_t notification_addr =
335*8d5a6007SJason Molenda                   process->ReadPointerFromMemory(notification_location, error);
336*8d5a6007SJason Molenda               if (ABISP abi_sp = process->GetABI())
337*8d5a6007SJason Molenda                 notification_addr = abi_sp->FixCodeAddress(notification_addr);
338*8d5a6007SJason Molenda 
339*8d5a6007SJason Molenda               dyld_instance->SetDYLDHandoverBreakpoint(notification_addr);
3409ab5dc24SJason Molenda             }
3419ab5dc24SJason Molenda           }
3429ab5dc24SJason Molenda         }
3439ab5dc24SJason Molenda       }
3449ab5dc24SJason Molenda     }
345b9c1b51eSKate Stone   } else {
3462fc38b2bSJonas Devlieghere     Target &target = process->GetTarget();
3472fc38b2bSJonas Devlieghere     Debugger::ReportWarning(
3482fc38b2bSJonas Devlieghere         "no ABI plugin located for triple " +
3492fc38b2bSJonas Devlieghere             target.GetArchitecture().GetTriple().getTriple() +
3502fc38b2bSJonas Devlieghere             ": shared libraries will not be registered",
3512fc38b2bSJonas Devlieghere         target.GetDebugger().GetID());
3529ab5dc24SJason Molenda   }
3539ab5dc24SJason Molenda 
3549ab5dc24SJason Molenda   // Return true to stop the target, false to just let the target run
3559ab5dc24SJason Molenda   return dyld_instance->GetStopWhenImagesChange();
3569ab5dc24SJason Molenda }
3579ab5dc24SJason Molenda 
AddBinaries(const std::vector<lldb::addr_t> & load_addresses)358b9c1b51eSKate Stone void DynamicLoaderMacOS::AddBinaries(
359b9c1b51eSKate Stone     const std::vector<lldb::addr_t> &load_addresses) {
360a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::DynamicLoader);
3619ab5dc24SJason Molenda   ImageInfo::collection image_infos;
3629ab5dc24SJason Molenda 
36363e5fb76SJonas Devlieghere   LLDB_LOGF(log, "Adding %" PRId64 " modules.",
36463e5fb76SJonas Devlieghere             (uint64_t)load_addresses.size());
365b9c1b51eSKate Stone   StructuredData::ObjectSP binaries_info_sp =
366b9c1b51eSKate Stone       m_process->GetLoadedDynamicLibrariesInfos(load_addresses);
367b9c1b51eSKate Stone   if (binaries_info_sp.get() && binaries_info_sp->GetAsDictionary() &&
368b9c1b51eSKate Stone       binaries_info_sp->GetAsDictionary()->HasKey("images") &&
369b9c1b51eSKate Stone       binaries_info_sp->GetAsDictionary()
370b9c1b51eSKate Stone           ->GetValueForKey("images")
371b9c1b51eSKate Stone           ->GetAsArray() &&
372b9c1b51eSKate Stone       binaries_info_sp->GetAsDictionary()
373b9c1b51eSKate Stone               ->GetValueForKey("images")
374b9c1b51eSKate Stone               ->GetAsArray()
375b9c1b51eSKate Stone               ->GetSize() == load_addresses.size()) {
376b9c1b51eSKate Stone     if (JSONImageInformationIntoImageInfo(binaries_info_sp, image_infos)) {
3779ab5dc24SJason Molenda       UpdateSpecialBinariesFromNewImageInfos(image_infos);
3789ab5dc24SJason Molenda       AddModulesUsingImageInfos(image_infos);
3799ab5dc24SJason Molenda     }
3809ab5dc24SJason Molenda     m_dyld_image_infos_stop_id = m_process->GetStopID();
3819ab5dc24SJason Molenda   }
3829ab5dc24SJason Molenda }
3839ab5dc24SJason Molenda 
38405097246SAdrian Prantl // Dump the _dyld_all_image_infos members and all current image infos that we
38505097246SAdrian Prantl // have parsed to the file handle provided.
PutToLog(Log * log) const386b9c1b51eSKate Stone void DynamicLoaderMacOS::PutToLog(Log *log) const {
387248a1305SKonrad Kleine   if (log == nullptr)
3889ab5dc24SJason Molenda     return;
3899ab5dc24SJason Molenda }
3909ab5dc24SJason Molenda 
SetNotificationBreakpoint()391b9c1b51eSKate Stone bool DynamicLoaderMacOS::SetNotificationBreakpoint() {
392b9c1b51eSKate Stone   if (m_break_id == LLDB_INVALID_BREAK_ID) {
3939ab5dc24SJason Molenda     ModuleSP dyld_sp(GetDYLDModule());
394b9c1b51eSKate Stone     if (dyld_sp) {
3959ab5dc24SJason Molenda       bool internal = true;
3969ab5dc24SJason Molenda       bool hardware = false;
3976fca1895SJason Molenda       LazyBool skip_prologue = eLazyBoolNo;
3986fca1895SJason Molenda       FileSpecList *source_files = nullptr;
3996fca1895SJason Molenda       FileSpecList dyld_filelist;
40035d71014SJason Molenda       dyld_filelist.Append(dyld_sp->GetFileSpec());
4016fca1895SJason Molenda 
402b9c1b51eSKate Stone       Breakpoint *breakpoint =
403b9c1b51eSKate Stone           m_process->GetTarget()
4046fca1895SJason Molenda               .CreateBreakpoint(&dyld_filelist, source_files,
4056fca1895SJason Molenda                                 "_dyld_debugger_notification",
4066fca1895SJason Molenda                                 eFunctionNameTypeFull, eLanguageTypeC, 0,
4076fca1895SJason Molenda                                 skip_prologue, internal, hardware)
408b9c1b51eSKate Stone               .get();
409b9c1b51eSKate Stone       breakpoint->SetCallback(DynamicLoaderMacOS::NotifyBreakpointHit, this,
410b9c1b51eSKate Stone                               true);
4119ab5dc24SJason Molenda       breakpoint->SetBreakpointKind("shared-library-event");
4129ab5dc24SJason Molenda       m_break_id = breakpoint->GetID();
4139ab5dc24SJason Molenda     }
4149ab5dc24SJason Molenda   }
4159ab5dc24SJason Molenda   return m_break_id != LLDB_INVALID_BREAK_ID;
4169ab5dc24SJason Molenda }
4179ab5dc24SJason Molenda 
SetDYLDHandoverBreakpoint(addr_t notification_address)418*8d5a6007SJason Molenda bool DynamicLoaderMacOS::SetDYLDHandoverBreakpoint(
419*8d5a6007SJason Molenda     addr_t notification_address) {
420*8d5a6007SJason Molenda   if (m_dyld_handover_break_id == LLDB_INVALID_BREAK_ID) {
421*8d5a6007SJason Molenda     BreakpointSP dyld_handover_bp = m_process->GetTarget().CreateBreakpoint(
422*8d5a6007SJason Molenda         notification_address, true, false);
423*8d5a6007SJason Molenda     dyld_handover_bp->SetCallback(DynamicLoaderMacOS::NotifyBreakpointHit, this,
424*8d5a6007SJason Molenda                                   true);
425*8d5a6007SJason Molenda     dyld_handover_bp->SetOneShot(true);
426*8d5a6007SJason Molenda     m_dyld_handover_break_id = dyld_handover_bp->GetID();
427*8d5a6007SJason Molenda     return true;
428*8d5a6007SJason Molenda   }
429*8d5a6007SJason Molenda   return false;
430*8d5a6007SJason Molenda }
431*8d5a6007SJason Molenda 
ClearDYLDHandoverBreakpoint()432*8d5a6007SJason Molenda void DynamicLoaderMacOS::ClearDYLDHandoverBreakpoint() {
433*8d5a6007SJason Molenda   if (LLDB_BREAK_ID_IS_VALID(m_dyld_handover_break_id))
434*8d5a6007SJason Molenda     m_process->GetTarget().RemoveBreakpointByID(m_dyld_handover_break_id);
435*8d5a6007SJason Molenda   m_dyld_handover_break_id = LLDB_INVALID_BREAK_ID;
436*8d5a6007SJason Molenda }
437*8d5a6007SJason Molenda 
4389ab5dc24SJason Molenda addr_t
GetDyldLockVariableAddressFromModule(Module * module)439b9c1b51eSKate Stone DynamicLoaderMacOS::GetDyldLockVariableAddressFromModule(Module *module) {
4409ab5dc24SJason Molenda   SymbolContext sc;
4419ab5dc24SJason Molenda   Target &target = m_process->GetTarget();
442d5d47a35SPavel Labath   if (Symtab *symtab = module->GetSymtab()) {
4439ab5dc24SJason Molenda     std::vector<uint32_t> match_indexes;
4449ab5dc24SJason Molenda     ConstString g_symbol_name("_dyld_global_lock_held");
4459ab5dc24SJason Molenda     uint32_t num_matches = 0;
446b9c1b51eSKate Stone     num_matches =
447b9c1b51eSKate Stone         symtab->AppendSymbolIndexesWithName(g_symbol_name, match_indexes);
448b9c1b51eSKate Stone     if (num_matches == 1) {
4499ab5dc24SJason Molenda       Symbol *symbol = symtab->SymbolAtIndex(match_indexes[0]);
450b9c1b51eSKate Stone       if (symbol &&
451b9c1b51eSKate Stone           (symbol->ValueIsAddress() || symbol->GetAddressRef().IsValid())) {
4529ab5dc24SJason Molenda         return symbol->GetAddressRef().GetOpcodeLoadAddress(&target);
4539ab5dc24SJason Molenda       }
4549ab5dc24SJason Molenda     }
4559ab5dc24SJason Molenda   }
4569ab5dc24SJason Molenda   return LLDB_INVALID_ADDRESS;
4579ab5dc24SJason Molenda }
4589ab5dc24SJason Molenda 
4599ab5dc24SJason Molenda //  Look for this symbol:
4609ab5dc24SJason Molenda //
461b9c1b51eSKate Stone //  int __attribute__((visibility("hidden")))           _dyld_global_lock_held =
462b9c1b51eSKate Stone //  0;
4639ab5dc24SJason Molenda //
4649ab5dc24SJason Molenda //  in libdyld.dylib.
CanLoadImage()46597206d57SZachary Turner Status DynamicLoaderMacOS::CanLoadImage() {
46697206d57SZachary Turner   Status error;
4679ab5dc24SJason Molenda   addr_t symbol_address = LLDB_INVALID_ADDRESS;
468f2e05855SJonas Devlieghere   ConstString g_libdyld_name("libdyld.dylib");
4699ab5dc24SJason Molenda   Target &target = m_process->GetTarget();
4709ab5dc24SJason Molenda   const ModuleList &target_modules = target.GetImages();
4719ab5dc24SJason Molenda   std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
4729ab5dc24SJason Molenda 
4739ab5dc24SJason Molenda   // Find any modules named "libdyld.dylib" and look for the symbol there first
474f2e05855SJonas Devlieghere   for (ModuleSP module_sp : target.GetImages().ModulesNoLocking()) {
475f2e05855SJonas Devlieghere     if (module_sp) {
476f2e05855SJonas Devlieghere       if (module_sp->GetFileSpec().GetFilename() == g_libdyld_name) {
477f2e05855SJonas Devlieghere         symbol_address = GetDyldLockVariableAddressFromModule(module_sp.get());
4789ab5dc24SJason Molenda         if (symbol_address != LLDB_INVALID_ADDRESS)
4799ab5dc24SJason Molenda           break;
4809ab5dc24SJason Molenda       }
4819ab5dc24SJason Molenda     }
4829ab5dc24SJason Molenda   }
4839ab5dc24SJason Molenda 
4849ab5dc24SJason Molenda   // Search through all modules looking for the symbol in them
485b9c1b51eSKate Stone   if (symbol_address == LLDB_INVALID_ADDRESS) {
486f2e05855SJonas Devlieghere     for (ModuleSP module_sp : target.GetImages().Modules()) {
487f2e05855SJonas Devlieghere       if (module_sp) {
488b9c1b51eSKate Stone         addr_t symbol_address =
489f2e05855SJonas Devlieghere             GetDyldLockVariableAddressFromModule(module_sp.get());
4909ab5dc24SJason Molenda         if (symbol_address != LLDB_INVALID_ADDRESS)
4919ab5dc24SJason Molenda           break;
4929ab5dc24SJason Molenda       }
4939ab5dc24SJason Molenda     }
4949ab5dc24SJason Molenda   }
4959ab5dc24SJason Molenda 
49605097246SAdrian Prantl   // Default assumption is that it is OK to load images. Only say that we
49705097246SAdrian Prantl   // cannot load images if we find the symbol in libdyld and it indicates that
49805097246SAdrian Prantl   // we cannot.
4999ab5dc24SJason Molenda 
500b9c1b51eSKate Stone   if (symbol_address != LLDB_INVALID_ADDRESS) {
5019ab5dc24SJason Molenda     {
502b9c1b51eSKate Stone       int lock_held =
503b9c1b51eSKate Stone           m_process->ReadUnsignedIntegerFromMemory(symbol_address, 4, 0, error);
504b9c1b51eSKate Stone       if (lock_held != 0) {
505abc5d72fSJim Ingham         error.SetErrorString("dyld lock held - unsafe to load images.");
5069ab5dc24SJason Molenda       }
5079ab5dc24SJason Molenda     }
508b9c1b51eSKate Stone   } else {
50905097246SAdrian Prantl     // If we were unable to find _dyld_global_lock_held in any modules, or it
51005097246SAdrian Prantl     // is not loaded into memory yet, we may be at process startup (sitting  at
51105097246SAdrian Prantl     // _dyld_start) - so we should not allow dlopen calls. But if we found more
51205097246SAdrian Prantl     // than one module then we are clearly past _dyld_start so in that case
51305097246SAdrian Prantl     // we'll default to "it's safe".
514f2e05855SJonas Devlieghere     if (target.GetImages().GetSize() <= 1)
515abc5d72fSJim Ingham       error.SetErrorString("could not find the dyld library or "
516abc5d72fSJim Ingham                            "the dyld lock symbol");
51737397353SJason Molenda   }
5189ab5dc24SJason Molenda   return error;
5199ab5dc24SJason Molenda }
5209ab5dc24SJason Molenda 
GetSharedCacheInformation(lldb::addr_t & base_address,UUID & uuid,LazyBool & using_shared_cache,LazyBool & private_shared_cache)521b9c1b51eSKate Stone bool DynamicLoaderMacOS::GetSharedCacheInformation(
522b9c1b51eSKate Stone     lldb::addr_t &base_address, UUID &uuid, LazyBool &using_shared_cache,
523b9c1b51eSKate Stone     LazyBool &private_shared_cache) {
52413becd4fSJason Molenda   base_address = LLDB_INVALID_ADDRESS;
52513becd4fSJason Molenda   uuid.Clear();
52613becd4fSJason Molenda   using_shared_cache = eLazyBoolCalculate;
52713becd4fSJason Molenda   private_shared_cache = eLazyBoolCalculate;
52813becd4fSJason Molenda 
529b9c1b51eSKate Stone   if (m_process) {
53013becd4fSJason Molenda     StructuredData::ObjectSP info = m_process->GetSharedCacheInfo();
53113becd4fSJason Molenda     StructuredData::Dictionary *info_dict = nullptr;
532b9c1b51eSKate Stone     if (info.get() && info->GetAsDictionary()) {
53313becd4fSJason Molenda       info_dict = info->GetAsDictionary();
53413becd4fSJason Molenda     }
53513becd4fSJason Molenda 
53605097246SAdrian Prantl     // {"shared_cache_base_address":140735683125248,"shared_cache_uuid
53705097246SAdrian Prantl     // ":"DDB8D70C-
53805097246SAdrian Prantl     // C9A2-3561-B2C8-BE48A4F33F96","no_shared_cache":false,"shared_cache_private_cache":false}
53913becd4fSJason Molenda 
540b9c1b51eSKate Stone     if (info_dict && info_dict->HasKey("shared_cache_uuid") &&
541b9c1b51eSKate Stone         info_dict->HasKey("no_shared_cache") &&
542b9c1b51eSKate Stone         info_dict->HasKey("shared_cache_base_address")) {
543b9c1b51eSKate Stone       base_address = info_dict->GetValueForKey("shared_cache_base_address")
544b9c1b51eSKate Stone                          ->GetIntegerValue(LLDB_INVALID_ADDRESS);
545adcd0268SBenjamin Kramer       std::string uuid_str = std::string(
546adcd0268SBenjamin Kramer           info_dict->GetValueForKey("shared_cache_uuid")->GetStringValue());
54713becd4fSJason Molenda       if (!uuid_str.empty())
548a174bcbfSPavel Labath         uuid.SetFromStringRef(uuid_str);
549a6682a41SJonas Devlieghere       if (!info_dict->GetValueForKey("no_shared_cache")->GetBooleanValue())
55013becd4fSJason Molenda         using_shared_cache = eLazyBoolYes;
55113becd4fSJason Molenda       else
55213becd4fSJason Molenda         using_shared_cache = eLazyBoolNo;
553b9c1b51eSKate Stone       if (info_dict->GetValueForKey("shared_cache_private_cache")
554b9c1b51eSKate Stone               ->GetBooleanValue())
55513becd4fSJason Molenda         private_shared_cache = eLazyBoolYes;
55613becd4fSJason Molenda       else
55713becd4fSJason Molenda         private_shared_cache = eLazyBoolNo;
55813becd4fSJason Molenda 
55913becd4fSJason Molenda       return true;
56013becd4fSJason Molenda     }
56113becd4fSJason Molenda   }
56213becd4fSJason Molenda   return false;
56313becd4fSJason Molenda }
56413becd4fSJason Molenda 
Initialize()565b9c1b51eSKate Stone void DynamicLoaderMacOS::Initialize() {
5669ab5dc24SJason Molenda   PluginManager::RegisterPlugin(GetPluginNameStatic(),
567b9c1b51eSKate Stone                                 GetPluginDescriptionStatic(), CreateInstance);
5689ab5dc24SJason Molenda }
5699ab5dc24SJason Molenda 
Terminate()570b9c1b51eSKate Stone void DynamicLoaderMacOS::Terminate() {
5719ab5dc24SJason Molenda   PluginManager::UnregisterPlugin(CreateInstance);
5729ab5dc24SJason Molenda }
5739ab5dc24SJason Molenda 
GetPluginDescriptionStatic()5746fa1b4ffSPavel Labath llvm::StringRef DynamicLoaderMacOS::GetPluginDescriptionStatic() {
575b9c1b51eSKate Stone   return "Dynamic loader plug-in that watches for shared library loads/unloads "
576b9c1b51eSKate Stone          "in MacOSX user processes.";
5779ab5dc24SJason Molenda }
578