1 //===-- VSCode.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 <stdarg.h>
10 #include <fstream>
11 #include <mutex>
12 
13 #include "LLDBUtils.h"
14 #include "VSCode.h"
15 #include "llvm/Support/FormatVariadic.h"
16 
17 #if defined(_WIN32)
18 #define NOMINMAX
19 #include <Windows.h>
20 #include <fcntl.h>
21 #include <io.h>
22 #endif
23 
24 using namespace lldb_vscode;
25 
26 namespace lldb_vscode {
27 
28 VSCode g_vsc;
29 
30 VSCode::VSCode()
31     : launch_info(nullptr), variables(), broadcaster("lldb-vscode"),
32       num_regs(0), num_locals(0), num_globals(0), log(),
33       exception_breakpoints(
34           {{"cpp_catch", "C++ Catch", lldb::eLanguageTypeC_plus_plus},
35            {"cpp_throw", "C++ Throw", lldb::eLanguageTypeC_plus_plus},
36            {"objc_catch", "Objective C Catch", lldb::eLanguageTypeObjC},
37            {"objc_throw", "Objective C Throw", lldb::eLanguageTypeObjC},
38            {"swift_catch", "Swift Catch", lldb::eLanguageTypeSwift},
39            {"swift_throw", "Swift Throw", lldb::eLanguageTypeSwift}}),
40       focus_tid(LLDB_INVALID_THREAD_ID), sent_terminated_event(false),
41       stop_at_entry(false) {
42   const char *log_file_path = getenv("LLDBVSCODE_LOG");
43 #if defined(_WIN32)
44 // Windows opens stdout and stdin in text mode which converts \n to 13,10
45 // while the value is just 10 on Darwin/Linux. Setting the file mode to binary
46 // fixes this.
47   assert(_setmode(fileno(stdout), _O_BINARY));
48   assert(_setmode(fileno(stdin), _O_BINARY));
49 #endif
50   if (log_file_path)
51     log.reset(new std::ofstream(log_file_path));
52 }
53 
54 VSCode::~VSCode() {
55 }
56 
57 int64_t VSCode::GetLineForPC(int64_t sourceReference, lldb::addr_t pc) const {
58   auto pos = source_map.find(sourceReference);
59   if (pos != source_map.end())
60     return pos->second.GetLineForPC(pc);
61   return 0;
62 }
63 
64 ExceptionBreakpoint *VSCode::GetExceptionBreakpoint(const std::string &filter) {
65   for (auto &bp : exception_breakpoints) {
66     if (bp.filter == filter)
67       return &bp;
68   }
69   return nullptr;
70 }
71 
72 ExceptionBreakpoint *
73 VSCode::GetExceptionBreakpoint(const lldb::break_id_t bp_id) {
74   for (auto &bp : exception_breakpoints) {
75     if (bp.bp.GetID() == bp_id)
76       return &bp;
77   }
78   return nullptr;
79 }
80 
81 //----------------------------------------------------------------------
82 // Send the JSON in "json_str" to the "out" stream. Correctly send the
83 // "Content-Length:" field followed by the length, followed by the raw
84 // JSON bytes.
85 //----------------------------------------------------------------------
86 void VSCode::SendJSON(const std::string &json_str) {
87   output.write_full("Content-Length: ");
88   output.write_full(llvm::utostr(json_str.size()));
89   output.write_full("\r\n\r\n");
90   output.write_full(json_str);
91 
92   if (log) {
93     *log << "<-- " << std::endl
94          << "Content-Length: " << json_str.size() << "\r\n\r\n"
95          << json_str << std::endl;
96   }
97 }
98 
99 //----------------------------------------------------------------------
100 // Serialize the JSON value into a string and send the JSON packet to
101 // the "out" stream.
102 //----------------------------------------------------------------------
103 void VSCode::SendJSON(const llvm::json::Value &json) {
104   std::string s;
105   llvm::raw_string_ostream strm(s);
106   strm << json;
107   static std::mutex mutex;
108   std::lock_guard<std::mutex> locker(mutex);
109   SendJSON(strm.str());
110 }
111 
112 //----------------------------------------------------------------------
113 // Read a JSON packet from the "in" stream.
114 //----------------------------------------------------------------------
115 std::string VSCode::ReadJSON() {
116   std::string length_str;
117   std::string json_str;
118   int length;
119 
120   if (!input.read_expected(log.get(), "Content-Length: "))
121     return json_str;
122 
123   if (!input.read_line(log.get(), length_str))
124     return json_str;
125 
126   if (!llvm::to_integer(length_str, length))
127     return json_str;
128 
129   if (!input.read_expected(log.get(), "\r\n"))
130     return json_str;
131 
132   if (!input.read_full(log.get(), length, json_str))
133     return json_str;
134 
135   return json_str;
136 }
137 
138 //----------------------------------------------------------------------
139 // "OutputEvent": {
140 //   "allOf": [ { "$ref": "#/definitions/Event" }, {
141 //     "type": "object",
142 //     "description": "Event message for 'output' event type. The event
143 //                     indicates that the target has produced some output.",
144 //     "properties": {
145 //       "event": {
146 //         "type": "string",
147 //         "enum": [ "output" ]
148 //       },
149 //       "body": {
150 //         "type": "object",
151 //         "properties": {
152 //           "category": {
153 //             "type": "string",
154 //             "description": "The output category. If not specified,
155 //                             'console' is assumed.",
156 //             "_enum": [ "console", "stdout", "stderr", "telemetry" ]
157 //           },
158 //           "output": {
159 //             "type": "string",
160 //             "description": "The output to report."
161 //           },
162 //           "variablesReference": {
163 //             "type": "number",
164 //             "description": "If an attribute 'variablesReference' exists
165 //                             and its value is > 0, the output contains
166 //                             objects which can be retrieved by passing
167 //                             variablesReference to the VariablesRequest."
168 //           },
169 //           "source": {
170 //             "$ref": "#/definitions/Source",
171 //             "description": "An optional source location where the output
172 //                             was produced."
173 //           },
174 //           "line": {
175 //             "type": "integer",
176 //             "description": "An optional source location line where the
177 //                             output was produced."
178 //           },
179 //           "column": {
180 //             "type": "integer",
181 //             "description": "An optional source location column where the
182 //                             output was produced."
183 //           },
184 //           "data": {
185 //             "type":["array","boolean","integer","null","number","object",
186 //                     "string"],
187 //             "description": "Optional data to report. For the 'telemetry'
188 //                             category the data will be sent to telemetry, for
189 //                             the other categories the data is shown in JSON
190 //                             format."
191 //           }
192 //         },
193 //         "required": ["output"]
194 //       }
195 //     },
196 //     "required": [ "event", "body" ]
197 //   }]
198 // }
199 //----------------------------------------------------------------------
200 void VSCode::SendOutput(OutputType o, const llvm::StringRef output) {
201   if (output.empty())
202     return;
203 
204   llvm::json::Object event(CreateEventObject("output"));
205   llvm::json::Object body;
206   const char *category = nullptr;
207   switch (o) {
208   case OutputType::Console:
209     category = "console";
210     break;
211   case OutputType::Stdout:
212     category = "stdout";
213     break;
214   case OutputType::Stderr:
215     category = "stderr";
216     break;
217   case OutputType::Telemetry:
218     category = "telemetry";
219     break;
220   }
221   body.try_emplace("category", category);
222   EmplaceSafeString(body, "output", output.str());
223   event.try_emplace("body", std::move(body));
224   SendJSON(llvm::json::Value(std::move(event)));
225 }
226 
227 void __attribute__((format(printf, 3, 4)))
228 VSCode::SendFormattedOutput(OutputType o, const char *format, ...) {
229   char buffer[1024];
230   va_list args;
231   va_start(args, format);
232   int actual_length = vsnprintf(buffer, sizeof(buffer), format, args);
233   va_end(args);
234   SendOutput(o, llvm::StringRef(buffer,
235                                 std::min<int>(actual_length, sizeof(buffer))));
236 }
237 
238 int64_t VSCode::GetNextSourceReference() {
239   static int64_t ref = 0;
240   return ++ref;
241 }
242 
243 ExceptionBreakpoint *
244 VSCode::GetExceptionBPFromStopReason(lldb::SBThread &thread) {
245   const auto num = thread.GetStopReasonDataCount();
246   // Check to see if have hit an exception breakpoint and change the
247   // reason to "exception", but only do so if all breakpoints that were
248   // hit are exception breakpoints.
249   ExceptionBreakpoint *exc_bp = nullptr;
250   for (size_t i = 0; i < num; i += 2) {
251     // thread.GetStopReasonDataAtIndex(i) will return the bp ID and
252     // thread.GetStopReasonDataAtIndex(i+1) will return the location
253     // within that breakpoint. We only care about the bp ID so we can
254     // see if this is an exception breakpoint that is getting hit.
255     lldb::break_id_t bp_id = thread.GetStopReasonDataAtIndex(i);
256     exc_bp = GetExceptionBreakpoint(bp_id);
257     // If any breakpoint is not an exception breakpoint, then stop and
258     // report this as a normal breakpoint
259     if (exc_bp == nullptr)
260       return nullptr;
261   }
262   return exc_bp;
263 }
264 
265 lldb::SBThread VSCode::GetLLDBThread(const llvm::json::Object &arguments) {
266   auto tid = GetSigned(arguments, "threadId", LLDB_INVALID_THREAD_ID);
267   return target.GetProcess().GetThreadByID(tid);
268 }
269 
270 lldb::SBFrame VSCode::GetLLDBFrame(const llvm::json::Object &arguments) {
271   const uint64_t frame_id = GetUnsigned(arguments, "frameId", UINT64_MAX);
272   lldb::SBProcess process = target.GetProcess();
273   // Upper 32 bits is the thread index ID
274   lldb::SBThread thread =
275       process.GetThreadByIndexID(GetLLDBThreadIndexID(frame_id));
276   // Lower 32 bits is the frame index
277   return thread.GetFrameAtIndex(GetLLDBFrameID(frame_id));
278 }
279 
280 llvm::json::Value VSCode::CreateTopLevelScopes() {
281   llvm::json::Array scopes;
282   scopes.emplace_back(CreateScope("Locals", VARREF_LOCALS, num_locals, false));
283   scopes.emplace_back(
284       CreateScope("Globals", VARREF_GLOBALS, num_globals, false));
285   scopes.emplace_back(CreateScope("Registers", VARREF_REGS, num_regs, false));
286   return llvm::json::Value(std::move(scopes));
287 }
288 
289 void VSCode::RunLLDBCommands(llvm::StringRef prefix,
290                              const std::vector<std::string> &commands) {
291   SendOutput(OutputType::Console,
292              llvm::StringRef(::RunLLDBCommands(prefix, commands)));
293 }
294 
295 void VSCode::RunInitCommands() {
296   RunLLDBCommands("Running initCommands:", init_commands);
297 }
298 
299 void VSCode::RunPreRunCommands() {
300   RunLLDBCommands("Running preRunCommands:", pre_run_commands);
301 }
302 
303 void VSCode::RunStopCommands() {
304   RunLLDBCommands("Running stopCommands:", stop_commands);
305 }
306 
307 void VSCode::RunExitCommands() {
308   RunLLDBCommands("Running exitCommands:", exit_commands);
309 }
310 
311 } // namespace lldb_vscode
312 
313