Coverage Report

Created: 2022-01-22 13:19

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