1 //===-- DynamicLoaderDarwinKernel.h -----------------------------*- 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 #ifndef liblldb_DynamicLoaderDarwinKernel_h_
11 #define liblldb_DynamicLoaderDarwinKernel_h_
12 
13 #include <mutex>
14 #include <string>
15 #include <vector>
16 
17 
18 #include "lldb/Host/SafeMachO.h"
19 
20 #include "lldb/Target/DynamicLoader.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Utility/FileSpec.h"
23 #include "lldb/Utility/UUID.h"
24 
25 class DynamicLoaderDarwinKernel : public lldb_private::DynamicLoader {
26 public:
27   DynamicLoaderDarwinKernel(lldb_private::Process *process,
28                             lldb::addr_t kernel_addr);
29 
30   ~DynamicLoaderDarwinKernel() override;
31 
32   //------------------------------------------------------------------
33   // Static Functions
34   //------------------------------------------------------------------
35   static void Initialize();
36 
37   static void Terminate();
38 
39   static lldb_private::ConstString GetPluginNameStatic();
40 
41   static const char *GetPluginDescriptionStatic();
42 
43   static lldb_private::DynamicLoader *
44   CreateInstance(lldb_private::Process *process, bool force);
45 
46   static void DebuggerInitialize(lldb_private::Debugger &debugger);
47 
48   static lldb::addr_t SearchForDarwinKernel(lldb_private::Process *process);
49 
50   //------------------------------------------------------------------
51   /// Called after attaching a process.
52   ///
53   /// Allow DynamicLoader plug-ins to execute some code after
54   /// attaching to a process.
55   //------------------------------------------------------------------
56   void DidAttach() override;
57 
58   void DidLaunch() override;
59 
60   lldb::ThreadPlanSP GetStepThroughTrampolinePlan(lldb_private::Thread &thread,
61                                                   bool stop_others) override;
62 
63   lldb_private::Status CanLoadImage() override;
64 
65   //------------------------------------------------------------------
66   // PluginInterface protocol
67   //------------------------------------------------------------------
68   lldb_private::ConstString GetPluginName() override;
69 
70   uint32_t GetPluginVersion() override;
71 
72 protected:
73   void PrivateInitialize(lldb_private::Process *process);
74 
75   void PrivateProcessStateChanged(lldb_private::Process *process,
76                                   lldb::StateType state);
77 
78   void UpdateIfNeeded();
79 
80   void LoadKernelModuleIfNeeded();
81 
82   void Clear(bool clear_process);
83 
84   void PutToLog(lldb_private::Log *log) const;
85 
86   static bool
87   BreakpointHitCallback(void *baton,
88                         lldb_private::StoppointCallbackContext *context,
89                         lldb::user_id_t break_id, lldb::user_id_t break_loc_id);
90 
91   bool BreakpointHit(lldb_private::StoppointCallbackContext *context,
92                      lldb::user_id_t break_id, lldb::user_id_t break_loc_id);
93   uint32_t GetAddrByteSize() { return m_kernel.GetAddressByteSize(); }
94 
95   static lldb::ByteOrder GetByteOrderFromMagic(uint32_t magic);
96 
97   enum {
98     KERNEL_MODULE_MAX_NAME = 64u,
99     // Versions less than 2 didn't have an entry size,
100     // they had a 64 bit name, 16 byte UUID, 8 byte addr,
101     // 8 byte size, 8 byte version, 4 byte load tag, and
102     // 4 byte flags
103     KERNEL_MODULE_ENTRY_SIZE_VERSION_1 = 64u + 16u + 8u + 8u + 8u + 4u + 4u
104   };
105 
106   // class KextImageInfo represents a single kext or kernel binary image.
107   // The class was designed to hold the information from the
108   // OSKextLoadedKextSummary
109   // structure (in libkern/libkern/OSKextLibPrivate.h from xnu).  The kernel
110   // maintains
111   // a list of loded kexts in memory (the OSKextLoadedKextSummaryHeader
112   // structure,
113   // which points to an array of OSKextLoadedKextSummary's).
114   //
115   // A KextImageInfos may have -
116   //
117   // 1. The load address, name, UUID, and size of a kext/kernel binary in memory
118   //    (read straight out of the kernel's list-of-kexts loaded)
119   // 2. A ModuleSP based on a MemoryModule read out of the kernel's memory
120   //    (very unlikely to have any symbolic information)
121   // 3. A ModuleSP for an on-disk copy of the kext binary, possibly with debug
122   // info
123   //    or a dSYM
124   //
125   // For performance reasons, the developer may prefer that lldb not load the
126   // kexts out
127   // of memory at the start of a kernel session.  But we should build up /
128   // maintain a
129   // list of kexts that the kernel has told us about so we can relocate a kext
130   // module
131   // later if the user explicitly adds it to the target.
132 
133   class KextImageInfo {
134   public:
135     KextImageInfo()
136         : m_name(), m_module_sp(), m_memory_module_sp(),
137           m_load_process_stop_id(UINT32_MAX), m_uuid(),
138           m_load_address(LLDB_INVALID_ADDRESS), m_size(0),
139           m_kernel_image(false) {}
140 
141     void Clear() {
142       m_load_address = LLDB_INVALID_ADDRESS;
143       m_size = 0;
144       m_name.clear();
145       m_uuid.Clear();
146       m_module_sp.reset();
147       m_memory_module_sp.reset();
148       m_load_process_stop_id = UINT32_MAX;
149     }
150 
151     bool LoadImageAtFileAddress(lldb_private::Process *process);
152 
153     bool LoadImageUsingMemoryModule(lldb_private::Process *process);
154 
155     bool IsLoaded() { return m_load_process_stop_id != UINT32_MAX; }
156 
157     void SetLoadAddress(
158         lldb::addr_t load_addr); // Address of the Mach-O header for this binary
159 
160     lldb::addr_t
161     GetLoadAddress() const; // Address of the Mach-O header for this binary
162 
163     lldb_private::UUID GetUUID() const;
164 
165     void SetUUID(const lldb_private::UUID &uuid);
166 
167     void SetName(const char *);
168 
169     std::string GetName() const;
170 
171     void SetModule(lldb::ModuleSP module);
172 
173     lldb::ModuleSP GetModule();
174 
175     // try to fill in m_memory_module_sp from memory based on the m_load_address
176     bool ReadMemoryModule(lldb_private::Process *process);
177 
178     bool IsKernel()
179         const; // true if this is the mach_kernel; false if this is a kext
180 
181     void SetIsKernel(bool is_kernel);
182 
183     uint64_t GetSize() const;
184 
185     void SetSize(uint64_t size);
186 
187     uint32_t
188     GetProcessStopId() const; // the stop-id when this binary was first noticed
189 
190     void SetProcessStopId(uint32_t stop_id);
191 
192     bool operator==(const KextImageInfo &rhs);
193 
194     uint32_t GetAddressByteSize(); // as determined by Mach-O header
195 
196     lldb::ByteOrder GetByteOrder(); // as determined by Mach-O header
197 
198     lldb_private::ArchSpec
199     GetArchitecture() const; // as determined by Mach-O header
200 
201     void PutToLog(lldb_private::Log *log) const;
202 
203     typedef std::vector<KextImageInfo> collection;
204     typedef collection::iterator iterator;
205     typedef collection::const_iterator const_iterator;
206 
207   private:
208     std::string m_name;
209     lldb::ModuleSP m_module_sp;
210     lldb::ModuleSP m_memory_module_sp;
211     uint32_t m_load_process_stop_id; // the stop-id when this module was added
212                                      // to the Target
213     lldb_private::UUID
214         m_uuid; // UUID for this dylib if it has one, else all zeros
215     lldb::addr_t m_load_address;
216     uint64_t m_size;
217     bool m_kernel_image; // true if this is the kernel, false if this is a kext
218   };
219 
220   struct OSKextLoadedKextSummaryHeader {
221     uint32_t version;
222     uint32_t entry_size;
223     uint32_t entry_count;
224     lldb::addr_t image_infos_addr;
225 
226     OSKextLoadedKextSummaryHeader()
227         : version(0), entry_size(0), entry_count(0),
228           image_infos_addr(LLDB_INVALID_ADDRESS) {}
229 
230     uint32_t GetSize() {
231       switch (version) {
232       case 0:
233         return 0; // Can't know the size without a valid version
234       case 1:
235         return 8; // Version 1 only had a version + entry_count
236       default:
237         break;
238       }
239       // Version 2 and above has version, entry_size, entry_count, and reserved
240       return 16;
241     }
242 
243     void Clear() {
244       version = 0;
245       entry_size = 0;
246       entry_count = 0;
247       image_infos_addr = LLDB_INVALID_ADDRESS;
248     }
249 
250     bool IsValid() const { return version >= 1 || version <= 2; }
251   };
252 
253   void RegisterNotificationCallbacks();
254 
255   void UnregisterNotificationCallbacks();
256 
257   void SetNotificationBreakpointIfNeeded();
258 
259   bool ReadAllKextSummaries();
260 
261   bool ReadKextSummaryHeader();
262 
263   bool ParseKextSummaries(const lldb_private::Address &kext_summary_addr,
264                           uint32_t count);
265 
266   void
267   UpdateImageInfosHeaderAndLoadCommands(KextImageInfo::collection &image_infos,
268                                         uint32_t infos_count,
269                                         bool update_executable);
270 
271   uint32_t ReadKextSummaries(const lldb_private::Address &kext_summary_addr,
272                              uint32_t image_infos_count,
273                              KextImageInfo::collection &image_infos);
274 
275   static lldb::addr_t
276   SearchForKernelAtSameLoadAddr(lldb_private::Process *process);
277 
278   static lldb::addr_t
279   SearchForKernelWithDebugHints(lldb_private::Process *process);
280 
281   static lldb::addr_t SearchForKernelNearPC(lldb_private::Process *process);
282 
283   static lldb::addr_t
284   SearchForKernelViaExhaustiveSearch(lldb_private::Process *process);
285 
286   static bool
287   ReadMachHeader(lldb::addr_t addr, lldb_private::Process *process, llvm::MachO::mach_header &mh);
288 
289   static lldb_private::UUID
290   CheckForKernelImageAtAddress(lldb::addr_t addr,
291                                lldb_private::Process *process);
292 
293   lldb::addr_t m_kernel_load_address;
294   KextImageInfo m_kernel; // Info about the current kernel image being used
295 
296   lldb_private::Address m_kext_summary_header_ptr_addr;
297   lldb_private::Address m_kext_summary_header_addr;
298   OSKextLoadedKextSummaryHeader m_kext_summary_header;
299   KextImageInfo::collection m_known_kexts;
300   mutable std::recursive_mutex m_mutex;
301   lldb::user_id_t m_break_id;
302 
303 private:
304   DISALLOW_COPY_AND_ASSIGN(DynamicLoaderDarwinKernel);
305 };
306 
307 #endif // liblldb_DynamicLoaderDarwinKernel_h_
308