1 //===-- AppleGetItemInfoHandler.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 "AppleGetItemInfoHandler.h"
10 
11 #include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/Value.h"
14 #include "lldb/Expression/DiagnosticManager.h"
15 #include "lldb/Expression/FunctionCaller.h"
16 #include "lldb/Expression/UtilityFunction.h"
17 #include "lldb/Symbol/Symbol.h"
18 #include "lldb/Target/ExecutionContext.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Target/Target.h"
21 #include "lldb/Target/Thread.h"
22 #include "lldb/Utility/ConstString.h"
23 #include "lldb/Utility/Log.h"
24 #include "lldb/Utility/StreamString.h"
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 
29 const char *AppleGetItemInfoHandler::g_get_item_info_function_name =
30     "__lldb_backtrace_recording_get_item_info";
31 const char *AppleGetItemInfoHandler::g_get_item_info_function_code =
32     "                                  \n\
33 extern \"C\"                                                                                                    \n\
34 {                                                                                                               \n\
35     /*                                                                                                          \n\
36      * mach defines                                                                                             \n\
37      */                                                                                                         \n\
38                                                                                                                 \n\
39     typedef unsigned int uint32_t;                                                                              \n\
40     typedef unsigned long long uint64_t;                                                                        \n\
41     typedef uint32_t mach_port_t;                                                                               \n\
42     typedef mach_port_t vm_map_t;                                                                               \n\
43     typedef int kern_return_t;                                                                                  \n\
44     typedef uint64_t mach_vm_address_t;                                                                         \n\
45     typedef uint64_t mach_vm_size_t;                                                                            \n\
46                                                                                                                 \n\
47     mach_port_t mach_task_self ();                                                                              \n\
48     kern_return_t mach_vm_deallocate (vm_map_t target, mach_vm_address_t address, mach_vm_size_t size);         \n\
49                                                                                                                 \n\
50     /*                                                                                                          \n\
51      * libBacktraceRecording defines                                                                            \n\
52      */                                                                                                         \n\
53                                                                                                                 \n\
54     typedef uint32_t queue_list_scope_t;                                                                        \n\
55     typedef void *dispatch_queue_t;                                                                             \n\
56     typedef void *introspection_dispatch_queue_info_t;                                                          \n\
57     typedef void *introspection_dispatch_item_info_ref;                                                         \n\
58                                                                                                                 \n\
59     extern uint64_t __introspection_dispatch_queue_item_get_info (introspection_dispatch_item_info_ref item_info_ref, \n\
60                                                  introspection_dispatch_item_info_ref *returned_queues_buffer,  \n\
61                                                  uint64_t *returned_queues_buffer_size);                        \n\
62     extern int printf(const char *format, ...);                                                                 \n\
63                                                                                                                 \n\
64     /*                                                                                                          \n\
65      * return type define                                                                                       \n\
66      */                                                                                                         \n\
67                                                                                                                 \n\
68     struct get_item_info_return_values                                                                      \n\
69     {                                                                                                           \n\
70         uint64_t item_info_buffer_ptr;    /* the address of the items buffer from libBacktraceRecording */  \n\
71         uint64_t item_info_buffer_size;   /* the size of the items buffer from libBacktraceRecording */     \n\
72     };                                                                                                          \n\
73                                                                                                                 \n\
74     void  __lldb_backtrace_recording_get_item_info                                                          \n\
75                                                (struct get_item_info_return_values *return_buffer,          \n\
76                                                 int debug,                                                      \n\
77                                                 uint64_t /* introspection_dispatch_item_info_ref item_info_ref */ item, \n\
78                                                 void *page_to_free,                                             \n\
79                                                 uint64_t page_to_free_size)                                     \n\
80 {                                                                                                               \n\
81     if (debug)                                                                                                  \n\
82       printf (\"entering get_item_info with args return_buffer == %p, debug == %d, item == 0x%llx, page_to_free == %p, page_to_free_size == 0x%llx\\n\", return_buffer, debug, item, page_to_free, page_to_free_size); \n\
83     if (page_to_free != 0)                                                                                      \n\
84     {                                                                                                           \n\
85         mach_vm_deallocate (mach_task_self(), (mach_vm_address_t) page_to_free, (mach_vm_size_t) page_to_free_size); \n\
86     }                                                                                                           \n\
87                                                                                                                 \n\
88     __introspection_dispatch_queue_item_get_info ((void*) item,                                                 \n\
89                                                   (void**)&return_buffer->item_info_buffer_ptr,                 \n\
90                                                   &return_buffer->item_info_buffer_size);                       \n\
91 }                                                                                                               \n\
92 }                                                                                                               \n\
93 ";
94 
95 AppleGetItemInfoHandler::AppleGetItemInfoHandler(Process *process)
96     : m_process(process), m_get_item_info_impl_code(),
97       m_get_item_info_function_mutex(),
98       m_get_item_info_return_buffer_addr(LLDB_INVALID_ADDRESS),
99       m_get_item_info_retbuffer_mutex() {}
100 
101 AppleGetItemInfoHandler::~AppleGetItemInfoHandler() {}
102 
103 void AppleGetItemInfoHandler::Detach() {
104 
105   if (m_process && m_process->IsAlive() &&
106       m_get_item_info_return_buffer_addr != LLDB_INVALID_ADDRESS) {
107     std::unique_lock<std::mutex> lock(m_get_item_info_retbuffer_mutex,
108                                       std::defer_lock);
109     (void)lock.try_lock(); // Even if we don't get the lock, deallocate the buffer
110     m_process->DeallocateMemory(m_get_item_info_return_buffer_addr);
111   }
112 }
113 
114 // Compile our __lldb_backtrace_recording_get_item_info() function (from the
115 // source above in g_get_item_info_function_code) if we don't find that
116 // function in the inferior already with USE_BUILTIN_FUNCTION defined.  (e.g.
117 // this would be the case for testing.)
118 //
119 // Insert the __lldb_backtrace_recording_get_item_info into the inferior
120 // process if needed.
121 //
122 // Write the get_item_info_arglist into the inferior's memory space to prepare
123 // for the call.
124 //
125 // Returns the address of the arguments written down in the inferior process,
126 // which can be used to make the function call.
127 
128 lldb::addr_t AppleGetItemInfoHandler::SetupGetItemInfoFunction(
129     Thread &thread, ValueList &get_item_info_arglist) {
130   ExecutionContext exe_ctx(thread.shared_from_this());
131   DiagnosticManager diagnostics;
132   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
133   lldb::addr_t args_addr = LLDB_INVALID_ADDRESS;
134   FunctionCaller *get_item_info_caller = nullptr;
135 
136   // Scope for mutex locker:
137   {
138     std::lock_guard<std::mutex> guard(m_get_item_info_function_mutex);
139 
140     // First stage is to make the UtilityFunction to hold our injected
141     // function:
142 
143     if (!m_get_item_info_impl_code) {
144       if (g_get_item_info_function_code != nullptr) {
145         Status error;
146         m_get_item_info_impl_code.reset(
147             exe_ctx.GetTargetRef().GetUtilityFunctionForLanguage(
148                 g_get_item_info_function_code, eLanguageTypeObjC,
149                 g_get_item_info_function_name, error));
150         if (error.Fail()) {
151           LLDB_LOGF(log, "Failed to get utility function: %s.",
152                     error.AsCString());
153           return args_addr;
154         }
155 
156         if (!m_get_item_info_impl_code->Install(diagnostics, exe_ctx)) {
157           if (log) {
158             LLDB_LOGF(log, "Failed to install get-item-info introspection.");
159             diagnostics.Dump(log);
160           }
161           m_get_item_info_impl_code.reset();
162           return args_addr;
163         }
164       } else {
165         LLDB_LOGF(log, "No get-item-info introspection code found.");
166         return LLDB_INVALID_ADDRESS;
167       }
168 
169       // Next make the runner function for our implementation utility function.
170       auto type_system_or_err =
171           thread.GetProcess()->GetTarget().GetScratchTypeSystemForLanguage(
172               eLanguageTypeC);
173       if (auto err = type_system_or_err.takeError()) {
174         LLDB_LOG_ERROR(log, std::move(err),
175                        "Error inseting get-item-info function");
176         return args_addr;
177       }
178       CompilerType get_item_info_return_type =
179           type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid)
180               .GetPointerType();
181 
182       Status error;
183       get_item_info_caller = m_get_item_info_impl_code->MakeFunctionCaller(
184           get_item_info_return_type, get_item_info_arglist,
185           thread.shared_from_this(), error);
186       if (error.Fail() || get_item_info_caller == nullptr) {
187         LLDB_LOGF(log, "Error Inserting get-item-info function: \"%s\".",
188                   error.AsCString());
189         return args_addr;
190       }
191     } else {
192       // If it's already made, then we can just retrieve the caller:
193       get_item_info_caller = m_get_item_info_impl_code->GetFunctionCaller();
194       if (!get_item_info_caller) {
195         LLDB_LOGF(log, "Failed to get get-item-info introspection caller.");
196         m_get_item_info_impl_code.reset();
197         return args_addr;
198       }
199     }
200   }
201 
202   diagnostics.Clear();
203 
204   // Now write down the argument values for this particular call.  This looks
205   // like it might be a race condition if other threads were calling into here,
206   // but actually it isn't because we allocate a new args structure for this
207   // call by passing args_addr = LLDB_INVALID_ADDRESS...
208 
209   if (!get_item_info_caller->WriteFunctionArguments(
210           exe_ctx, args_addr, get_item_info_arglist, diagnostics)) {
211     if (log) {
212       LLDB_LOGF(log, "Error writing get-item-info function arguments.");
213       diagnostics.Dump(log);
214     }
215 
216     return args_addr;
217   }
218 
219   return args_addr;
220 }
221 
222 AppleGetItemInfoHandler::GetItemInfoReturnInfo
223 AppleGetItemInfoHandler::GetItemInfo(Thread &thread, uint64_t item,
224                                      addr_t page_to_free,
225                                      uint64_t page_to_free_size,
226                                      Status &error) {
227   lldb::StackFrameSP thread_cur_frame = thread.GetStackFrameAtIndex(0);
228   ProcessSP process_sp(thread.CalculateProcess());
229   TargetSP target_sp(thread.CalculateTarget());
230   TypeSystemClang *clang_ast_context = TypeSystemClang::GetScratch(*target_sp);
231   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYSTEM_RUNTIME));
232 
233   GetItemInfoReturnInfo return_value;
234   return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
235   return_value.item_buffer_size = 0;
236 
237   error.Clear();
238 
239   if (!thread.SafeToCallFunctions()) {
240     LLDB_LOGF(log, "Not safe to call functions on thread 0x%" PRIx64,
241               thread.GetID());
242     error.SetErrorString("Not safe to call functions on this thread.");
243     return return_value;
244   }
245 
246   // Set up the arguments for a call to
247 
248   // struct get_item_info_return_values
249   // {
250   //     uint64_t item_info_buffer_ptr;    /* the address of the items buffer
251   //     from libBacktraceRecording */
252   //     uint64_t item_info_buffer_size;   /* the size of the items buffer from
253   //     libBacktraceRecording */
254   // };
255   //
256   // void  __lldb_backtrace_recording_get_item_info
257   //                                            (struct
258   //                                            get_item_info_return_values
259   //                                            *return_buffer,
260   //                                             int debug,
261   //                                             uint64_t item,
262   //                                             void *page_to_free,
263   //                                             uint64_t page_to_free_size)
264 
265   // Where the return_buffer argument points to a 24 byte region of memory
266   // already allocated by lldb in the inferior process.
267 
268   CompilerType clang_void_ptr_type =
269       clang_ast_context->GetBasicType(eBasicTypeVoid).GetPointerType();
270   Value return_buffer_ptr_value;
271   return_buffer_ptr_value.SetValueType(Value::eValueTypeScalar);
272   return_buffer_ptr_value.SetCompilerType(clang_void_ptr_type);
273 
274   CompilerType clang_int_type = clang_ast_context->GetBasicType(eBasicTypeInt);
275   Value debug_value;
276   debug_value.SetValueType(Value::eValueTypeScalar);
277   debug_value.SetCompilerType(clang_int_type);
278 
279   CompilerType clang_uint64_type =
280       clang_ast_context->GetBasicType(eBasicTypeUnsignedLongLong);
281   Value item_value;
282   item_value.SetValueType(Value::eValueTypeScalar);
283   item_value.SetCompilerType(clang_uint64_type);
284 
285   Value page_to_free_value;
286   page_to_free_value.SetValueType(Value::eValueTypeScalar);
287   page_to_free_value.SetCompilerType(clang_void_ptr_type);
288 
289   Value page_to_free_size_value;
290   page_to_free_size_value.SetValueType(Value::eValueTypeScalar);
291   page_to_free_size_value.SetCompilerType(clang_uint64_type);
292 
293   std::lock_guard<std::mutex> guard(m_get_item_info_retbuffer_mutex);
294   if (m_get_item_info_return_buffer_addr == LLDB_INVALID_ADDRESS) {
295     addr_t bufaddr = process_sp->AllocateMemory(
296         32, ePermissionsReadable | ePermissionsWritable, error);
297     if (!error.Success() || bufaddr == LLDB_INVALID_ADDRESS) {
298       LLDB_LOGF(log, "Failed to allocate memory for return buffer for get "
299                      "current queues func call");
300       return return_value;
301     }
302     m_get_item_info_return_buffer_addr = bufaddr;
303   }
304 
305   ValueList argument_values;
306 
307   return_buffer_ptr_value.GetScalar() = m_get_item_info_return_buffer_addr;
308   argument_values.PushValue(return_buffer_ptr_value);
309 
310   debug_value.GetScalar() = 0;
311   argument_values.PushValue(debug_value);
312 
313   item_value.GetScalar() = item;
314   argument_values.PushValue(item_value);
315 
316   if (page_to_free != LLDB_INVALID_ADDRESS)
317     page_to_free_value.GetScalar() = page_to_free;
318   else
319     page_to_free_value.GetScalar() = 0;
320   argument_values.PushValue(page_to_free_value);
321 
322   page_to_free_size_value.GetScalar() = page_to_free_size;
323   argument_values.PushValue(page_to_free_size_value);
324 
325   addr_t args_addr = SetupGetItemInfoFunction(thread, argument_values);
326 
327   DiagnosticManager diagnostics;
328   ExecutionContext exe_ctx;
329   EvaluateExpressionOptions options;
330   options.SetUnwindOnError(true);
331   options.SetIgnoreBreakpoints(true);
332   options.SetStopOthers(true);
333 #if __has_feature(address_sanitizer)
334   options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
335 #else
336   options.SetTimeout(std::chrono::milliseconds(500));
337 #endif
338   options.SetTimeout(process_sp->GetUtilityExpressionTimeout());
339   options.SetTryAllThreads(false);
340   options.SetIsForUtilityExpr(true);
341   thread.CalculateExecutionContext(exe_ctx);
342 
343   if (!m_get_item_info_impl_code) {
344     error.SetErrorString("Unable to compile function to call "
345                          "__introspection_dispatch_queue_item_get_info");
346     return return_value;
347   }
348 
349   ExpressionResults func_call_ret;
350   Value results;
351   FunctionCaller *func_caller = m_get_item_info_impl_code->GetFunctionCaller();
352   if (!func_caller) {
353     LLDB_LOGF(log, "Could not retrieve function caller for "
354                    "__introspection_dispatch_queue_item_get_info.");
355     error.SetErrorString("Could not retrieve function caller for "
356                          "__introspection_dispatch_queue_item_get_info.");
357     return return_value;
358   }
359 
360   func_call_ret = func_caller->ExecuteFunction(exe_ctx, &args_addr, options,
361                                                diagnostics, results);
362   if (func_call_ret != eExpressionCompleted || !error.Success()) {
363     LLDB_LOGF(log,
364               "Unable to call "
365               "__introspection_dispatch_queue_item_get_info(), got "
366               "ExpressionResults %d, error contains %s",
367               func_call_ret, error.AsCString(""));
368     error.SetErrorString("Unable to call "
369                          "__introspection_dispatch_queue_get_item_info() for "
370                          "list of queues");
371     return return_value;
372   }
373 
374   return_value.item_buffer_ptr = m_process->ReadUnsignedIntegerFromMemory(
375       m_get_item_info_return_buffer_addr, 8, LLDB_INVALID_ADDRESS, error);
376   if (!error.Success() ||
377       return_value.item_buffer_ptr == LLDB_INVALID_ADDRESS) {
378     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
379     return return_value;
380   }
381 
382   return_value.item_buffer_size = m_process->ReadUnsignedIntegerFromMemory(
383       m_get_item_info_return_buffer_addr + 8, 8, 0, error);
384 
385   if (!error.Success()) {
386     return_value.item_buffer_ptr = LLDB_INVALID_ADDRESS;
387     return return_value;
388   }
389   LLDB_LOGF(log,
390             "AppleGetItemInfoHandler called "
391             "__introspection_dispatch_queue_item_get_info (page_to_free == "
392             "0x%" PRIx64 ", size = %" PRId64 "), returned page is at 0x%" PRIx64
393             ", size %" PRId64,
394             page_to_free, page_to_free_size, return_value.item_buffer_ptr,
395             return_value.item_buffer_size);
396 
397   return return_value;
398 }
399