1 //===-- LLDBUtils.cpp -------------------------------------------*- C++ -*-===//
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 "LLDBUtils.h"
10 #include "VSCode.h"
11 
12 namespace lldb_vscode {
13 
14 void RunLLDBCommands(llvm::StringRef prefix,
15                      const llvm::ArrayRef<std::string> &commands,
16                      llvm::raw_ostream &strm) {
17   if (commands.empty())
18     return;
19   lldb::SBCommandInterpreter interp = g_vsc.debugger.GetCommandInterpreter();
20   if (!prefix.empty())
21     strm << prefix << "\n";
22   for (const auto &command : commands) {
23     lldb::SBCommandReturnObject result;
24     strm << "(lldb) " << command << "\n";
25     interp.HandleCommand(command.c_str(), result);
26     auto output_len = result.GetOutputSize();
27     if (output_len) {
28       const char *output = result.GetOutput();
29       strm << output;
30     }
31     auto error_len = result.GetErrorSize();
32     if (error_len) {
33       const char *error = result.GetError();
34       strm << error;
35     }
36   }
37 }
38 
39 std::string RunLLDBCommands(llvm::StringRef prefix,
40                             const llvm::ArrayRef<std::string> &commands) {
41   std::string s;
42   llvm::raw_string_ostream strm(s);
43   RunLLDBCommands(prefix, commands, strm);
44   strm.flush();
45   return s;
46 }
47 
48 bool ThreadHasStopReason(lldb::SBThread &thread) {
49   switch (thread.GetStopReason()) {
50   case lldb::eStopReasonTrace:
51   case lldb::eStopReasonPlanComplete:
52   case lldb::eStopReasonBreakpoint:
53   case lldb::eStopReasonWatchpoint:
54   case lldb::eStopReasonInstrumentation:
55   case lldb::eStopReasonSignal:
56   case lldb::eStopReasonException:
57   case lldb::eStopReasonExec:
58   case lldb::eStopReasonProcessorTrace:
59     return true;
60   case lldb::eStopReasonThreadExiting:
61   case lldb::eStopReasonInvalid:
62   case lldb::eStopReasonNone:
63     break;
64   }
65   return false;
66 }
67 
68 static uint32_t constexpr THREAD_INDEX_SHIFT = 19;
69 
70 uint32_t GetLLDBThreadIndexID(uint64_t dap_frame_id) {
71   return dap_frame_id >> THREAD_INDEX_SHIFT;
72 }
73 
74 uint32_t GetLLDBFrameID(uint64_t dap_frame_id) {
75   return dap_frame_id & ((1u << THREAD_INDEX_SHIFT) - 1);
76 }
77 
78 int64_t MakeVSCodeFrameID(lldb::SBFrame &frame) {
79   return (int64_t)(frame.GetThread().GetIndexID() << THREAD_INDEX_SHIFT |
80                    frame.GetFrameID());
81 }
82 
83 } // namespace lldb_vscode
84