Coverage Report

Created: 2023-09-30 09:22

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