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