xref: /openbsd-src/gnu/llvm/lldb/tools/lldb-vscode/JSONUtils.cpp (revision 5a38ef86d0b61900239c7913d24a05e7b88a58f0)
1 //===-- JSONUtils.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 <algorithm>
10 #include <iomanip>
11 #include <sstream>
12 
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/Support/FormatAdapters.h"
15 #include "llvm/Support/Path.h"
16 #include "llvm/Support/ScopedPrinter.h"
17 
18 #include "lldb/API/SBBreakpoint.h"
19 #include "lldb/API/SBBreakpointLocation.h"
20 #include "lldb/API/SBDeclaration.h"
21 #include "lldb/API/SBValue.h"
22 #include "lldb/Host/PosixApi.h"
23 
24 #include "ExceptionBreakpoint.h"
25 #include "JSONUtils.h"
26 #include "LLDBUtils.h"
27 #include "VSCode.h"
28 
29 namespace lldb_vscode {
30 
31 void EmplaceSafeString(llvm::json::Object &obj, llvm::StringRef key,
32                        llvm::StringRef str) {
33   if (LLVM_LIKELY(llvm::json::isUTF8(str)))
34     obj.try_emplace(key, str.str());
35   else
36     obj.try_emplace(key, llvm::json::fixUTF8(str));
37 }
38 
39 llvm::StringRef GetAsString(const llvm::json::Value &value) {
40   if (auto s = value.getAsString())
41     return *s;
42   return llvm::StringRef();
43 }
44 
45 // Gets a string from a JSON object using the key, or returns an empty string.
46 llvm::StringRef GetString(const llvm::json::Object &obj, llvm::StringRef key) {
47   if (llvm::Optional<llvm::StringRef> value = obj.getString(key))
48     return *value;
49   return llvm::StringRef();
50 }
51 
52 llvm::StringRef GetString(const llvm::json::Object *obj, llvm::StringRef key) {
53   if (obj == nullptr)
54     return llvm::StringRef();
55   return GetString(*obj, key);
56 }
57 
58 // Gets an unsigned integer from a JSON object using the key, or returns the
59 // specified fail value.
60 uint64_t GetUnsigned(const llvm::json::Object &obj, llvm::StringRef key,
61                      uint64_t fail_value) {
62   if (auto value = obj.getInteger(key))
63     return (uint64_t)*value;
64   return fail_value;
65 }
66 
67 uint64_t GetUnsigned(const llvm::json::Object *obj, llvm::StringRef key,
68                      uint64_t fail_value) {
69   if (obj == nullptr)
70     return fail_value;
71   return GetUnsigned(*obj, key, fail_value);
72 }
73 
74 bool GetBoolean(const llvm::json::Object &obj, llvm::StringRef key,
75                 bool fail_value) {
76   if (auto value = obj.getBoolean(key))
77     return *value;
78   if (auto value = obj.getInteger(key))
79     return *value != 0;
80   return fail_value;
81 }
82 
83 bool GetBoolean(const llvm::json::Object *obj, llvm::StringRef key,
84                 bool fail_value) {
85   if (obj == nullptr)
86     return fail_value;
87   return GetBoolean(*obj, key, fail_value);
88 }
89 
90 int64_t GetSigned(const llvm::json::Object &obj, llvm::StringRef key,
91                   int64_t fail_value) {
92   if (auto value = obj.getInteger(key))
93     return *value;
94   return fail_value;
95 }
96 
97 int64_t GetSigned(const llvm::json::Object *obj, llvm::StringRef key,
98                   int64_t fail_value) {
99   if (obj == nullptr)
100     return fail_value;
101   return GetSigned(*obj, key, fail_value);
102 }
103 
104 bool ObjectContainsKey(const llvm::json::Object &obj, llvm::StringRef key) {
105   return obj.find(key) != obj.end();
106 }
107 
108 std::vector<std::string> GetStrings(const llvm::json::Object *obj,
109                                     llvm::StringRef key) {
110   std::vector<std::string> strs;
111   auto json_array = obj->getArray(key);
112   if (!json_array)
113     return strs;
114   for (const auto &value : *json_array) {
115     switch (value.kind()) {
116     case llvm::json::Value::String:
117       strs.push_back(value.getAsString()->str());
118       break;
119     case llvm::json::Value::Number:
120     case llvm::json::Value::Boolean:
121       strs.push_back(llvm::to_string(value));
122       break;
123     case llvm::json::Value::Null:
124     case llvm::json::Value::Object:
125     case llvm::json::Value::Array:
126       break;
127     }
128   }
129   return strs;
130 }
131 
132 void SetValueForKey(lldb::SBValue &v, llvm::json::Object &object,
133                     llvm::StringRef key) {
134 
135   llvm::StringRef value = v.GetValue();
136   llvm::StringRef summary = v.GetSummary();
137   llvm::StringRef type_name = v.GetType().GetDisplayTypeName();
138 
139   std::string result;
140   llvm::raw_string_ostream strm(result);
141   if (!value.empty()) {
142     strm << value;
143     if (!summary.empty())
144       strm << ' ' << summary;
145   } else if (!summary.empty()) {
146     strm << ' ' << summary;
147   } else if (!type_name.empty()) {
148     strm << type_name;
149     lldb::addr_t address = v.GetLoadAddress();
150     if (address != LLDB_INVALID_ADDRESS)
151       strm << " @ " << llvm::format_hex(address, 0);
152   }
153   strm.flush();
154   EmplaceSafeString(object, key, result);
155 }
156 
157 void FillResponse(const llvm::json::Object &request,
158                   llvm::json::Object &response) {
159   // Fill in all of the needed response fields to a "request" and set "success"
160   // to true by default.
161   response.try_emplace("type", "response");
162   response.try_emplace("seq", (int64_t)0);
163   EmplaceSafeString(response, "command", GetString(request, "command"));
164   const int64_t seq = GetSigned(request, "seq", 0);
165   response.try_emplace("request_seq", seq);
166   response.try_emplace("success", true);
167 }
168 
169 // "Scope": {
170 //   "type": "object",
171 //   "description": "A Scope is a named container for variables. Optionally
172 //                   a scope can map to a source or a range within a source.",
173 //   "properties": {
174 //     "name": {
175 //       "type": "string",
176 //       "description": "Name of the scope such as 'Arguments', 'Locals'."
177 //     },
178 //     "variablesReference": {
179 //       "type": "integer",
180 //       "description": "The variables of this scope can be retrieved by
181 //                       passing the value of variablesReference to the
182 //                       VariablesRequest."
183 //     },
184 //     "namedVariables": {
185 //       "type": "integer",
186 //       "description": "The number of named variables in this scope. The
187 //                       client can use this optional information to present
188 //                       the variables in a paged UI and fetch them in chunks."
189 //     },
190 //     "indexedVariables": {
191 //       "type": "integer",
192 //       "description": "The number of indexed variables in this scope. The
193 //                       client can use this optional information to present
194 //                       the variables in a paged UI and fetch them in chunks."
195 //     },
196 //     "expensive": {
197 //       "type": "boolean",
198 //       "description": "If true, the number of variables in this scope is
199 //                       large or expensive to retrieve."
200 //     },
201 //     "source": {
202 //       "$ref": "#/definitions/Source",
203 //       "description": "Optional source for this scope."
204 //     },
205 //     "line": {
206 //       "type": "integer",
207 //       "description": "Optional start line of the range covered by this
208 //                       scope."
209 //     },
210 //     "column": {
211 //       "type": "integer",
212 //       "description": "Optional start column of the range covered by this
213 //                       scope."
214 //     },
215 //     "endLine": {
216 //       "type": "integer",
217 //       "description": "Optional end line of the range covered by this scope."
218 //     },
219 //     "endColumn": {
220 //       "type": "integer",
221 //       "description": "Optional end column of the range covered by this
222 //                       scope."
223 //     }
224 //   },
225 //   "required": [ "name", "variablesReference", "expensive" ]
226 // }
227 llvm::json::Value CreateScope(const llvm::StringRef name,
228                               int64_t variablesReference,
229                               int64_t namedVariables, bool expensive) {
230   llvm::json::Object object;
231   EmplaceSafeString(object, "name", name.str());
232   object.try_emplace("variablesReference", variablesReference);
233   object.try_emplace("expensive", expensive);
234   object.try_emplace("namedVariables", namedVariables);
235   return llvm::json::Value(std::move(object));
236 }
237 
238 // "Breakpoint": {
239 //   "type": "object",
240 //   "description": "Information about a Breakpoint created in setBreakpoints
241 //                   or setFunctionBreakpoints.",
242 //   "properties": {
243 //     "id": {
244 //       "type": "integer",
245 //       "description": "An optional unique identifier for the breakpoint."
246 //     },
247 //     "verified": {
248 //       "type": "boolean",
249 //       "description": "If true breakpoint could be set (but not necessarily
250 //                       at the desired location)."
251 //     },
252 //     "message": {
253 //       "type": "string",
254 //       "description": "An optional message about the state of the breakpoint.
255 //                       This is shown to the user and can be used to explain
256 //                       why a breakpoint could not be verified."
257 //     },
258 //     "source": {
259 //       "$ref": "#/definitions/Source",
260 //       "description": "The source where the breakpoint is located."
261 //     },
262 //     "line": {
263 //       "type": "integer",
264 //       "description": "The start line of the actual range covered by the
265 //                       breakpoint."
266 //     },
267 //     "column": {
268 //       "type": "integer",
269 //       "description": "An optional start column of the actual range covered
270 //                       by the breakpoint."
271 //     },
272 //     "endLine": {
273 //       "type": "integer",
274 //       "description": "An optional end line of the actual range covered by
275 //                       the breakpoint."
276 //     },
277 //     "endColumn": {
278 //       "type": "integer",
279 //       "description": "An optional end column of the actual range covered by
280 //                       the breakpoint. If no end line is given, then the end
281 //                       column is assumed to be in the start line."
282 //     }
283 //   },
284 //   "required": [ "verified" ]
285 // }
286 llvm::json::Value CreateBreakpoint(lldb::SBBreakpoint &bp,
287                                    llvm::Optional<llvm::StringRef> request_path,
288                                    llvm::Optional<uint32_t> request_line) {
289   // Each breakpoint location is treated as a separate breakpoint for VS code.
290   // They don't have the notion of a single breakpoint with multiple locations.
291   llvm::json::Object object;
292   if (!bp.IsValid())
293     return llvm::json::Value(std::move(object));
294 
295   object.try_emplace("verified", bp.GetNumResolvedLocations() > 0);
296   object.try_emplace("id", bp.GetID());
297   // VS Code DAP doesn't currently allow one breakpoint to have multiple
298   // locations so we just report the first one. If we report all locations
299   // then the IDE starts showing the wrong line numbers and locations for
300   // other source file and line breakpoints in the same file.
301 
302   // Below we search for the first resolved location in a breakpoint and report
303   // this as the breakpoint location since it will have a complete location
304   // that is at least loaded in the current process.
305   lldb::SBBreakpointLocation bp_loc;
306   const auto num_locs = bp.GetNumLocations();
307   for (size_t i = 0; i < num_locs; ++i) {
308     bp_loc = bp.GetLocationAtIndex(i);
309     if (bp_loc.IsResolved())
310       break;
311   }
312   // If not locations are resolved, use the first location.
313   if (!bp_loc.IsResolved())
314     bp_loc = bp.GetLocationAtIndex(0);
315   auto bp_addr = bp_loc.GetAddress();
316 
317   if (request_path)
318     object.try_emplace("source", CreateSource(*request_path));
319 
320   if (bp_addr.IsValid()) {
321     auto line_entry = bp_addr.GetLineEntry();
322     const auto line = line_entry.GetLine();
323     if (line != UINT32_MAX)
324       object.try_emplace("line", line);
325     object.try_emplace("source", CreateSource(line_entry));
326   }
327   // We try to add request_line as a fallback
328   if (request_line)
329     object.try_emplace("line", *request_line);
330   return llvm::json::Value(std::move(object));
331 }
332 
333 static uint64_t GetDebugInfoSizeInSection(lldb::SBSection section) {
334   uint64_t debug_info_size = 0;
335   llvm::StringRef section_name(section.GetName());
336   if (section_name.startswith(".debug") || section_name.startswith("__debug") ||
337       section_name.startswith(".apple") || section_name.startswith("__apple"))
338     debug_info_size += section.GetFileByteSize();
339   size_t num_sub_sections = section.GetNumSubSections();
340   for (size_t i = 0; i < num_sub_sections; i++) {
341     debug_info_size +=
342         GetDebugInfoSizeInSection(section.GetSubSectionAtIndex(i));
343   }
344   return debug_info_size;
345 }
346 
347 static uint64_t GetDebugInfoSize(lldb::SBModule module) {
348   uint64_t debug_info_size = 0;
349   size_t num_sections = module.GetNumSections();
350   for (size_t i = 0; i < num_sections; i++) {
351     debug_info_size += GetDebugInfoSizeInSection(module.GetSectionAtIndex(i));
352   }
353   return debug_info_size;
354 }
355 
356 static std::string ConvertDebugInfoSizeToString(uint64_t debug_info) {
357   std::ostringstream oss;
358   oss << std::fixed << std::setprecision(1);
359   if (debug_info < 1024) {
360     oss << debug_info << "B";
361   } else if (debug_info < 1024 * 1024) {
362     double kb = double(debug_info) / 1024.0;
363     oss << kb << "KB";
364   } else if (debug_info < 1024 * 1024 * 1024) {
365     double mb = double(debug_info) / (1024.0 * 1024.0);
366     oss << mb << "MB";
367   } else {
368     double gb = double(debug_info) / (1024.0 * 1024.0 * 1024.0);
369     oss << gb << "GB";
370   }
371   return oss.str();
372 }
373 llvm::json::Value CreateModule(lldb::SBModule &module) {
374   llvm::json::Object object;
375   if (!module.IsValid())
376     return llvm::json::Value(std::move(object));
377   const char *uuid = module.GetUUIDString();
378   object.try_emplace("id", uuid ? std::string(uuid) : std::string(""));
379   object.try_emplace("name", std::string(module.GetFileSpec().GetFilename()));
380   char module_path_arr[PATH_MAX];
381   module.GetFileSpec().GetPath(module_path_arr, sizeof(module_path_arr));
382   std::string module_path(module_path_arr);
383   object.try_emplace("path", module_path);
384   if (module.GetNumCompileUnits() > 0) {
385     std::string symbol_str = "Symbols loaded.";
386     std::string debug_info_size;
387     uint64_t debug_info = GetDebugInfoSize(module);
388     if (debug_info > 0) {
389       debug_info_size = ConvertDebugInfoSizeToString(debug_info);
390     }
391     object.try_emplace("symbolStatus", symbol_str);
392     object.try_emplace("debugInfoSize", debug_info_size);
393     char symbol_path_arr[PATH_MAX];
394     module.GetSymbolFileSpec().GetPath(symbol_path_arr,
395                                        sizeof(symbol_path_arr));
396     std::string symbol_path(symbol_path_arr);
397     object.try_emplace("symbolFilePath", symbol_path);
398   } else {
399     object.try_emplace("symbolStatus", "Symbols not found.");
400   }
401   std::string loaded_addr = std::to_string(
402       module.GetObjectFileHeaderAddress().GetLoadAddress(g_vsc.target));
403   object.try_emplace("addressRange", loaded_addr);
404   std::string version_str;
405   uint32_t version_nums[3];
406   uint32_t num_versions =
407       module.GetVersion(version_nums, sizeof(version_nums) / sizeof(uint32_t));
408   for (uint32_t i = 0; i < num_versions; ++i) {
409     if (!version_str.empty())
410       version_str += ".";
411     version_str += std::to_string(version_nums[i]);
412   }
413   if (!version_str.empty())
414     object.try_emplace("version", version_str);
415   return llvm::json::Value(std::move(object));
416 }
417 
418 void AppendBreakpoint(lldb::SBBreakpoint &bp, llvm::json::Array &breakpoints,
419                       llvm::Optional<llvm::StringRef> request_path,
420                       llvm::Optional<uint32_t> request_line) {
421   breakpoints.emplace_back(CreateBreakpoint(bp, request_path, request_line));
422 }
423 
424 // "Event": {
425 //   "allOf": [ { "$ref": "#/definitions/ProtocolMessage" }, {
426 //     "type": "object",
427 //     "description": "Server-initiated event.",
428 //     "properties": {
429 //       "type": {
430 //         "type": "string",
431 //         "enum": [ "event" ]
432 //       },
433 //       "event": {
434 //         "type": "string",
435 //         "description": "Type of event."
436 //       },
437 //       "body": {
438 //         "type": [ "array", "boolean", "integer", "null", "number" ,
439 //                   "object", "string" ],
440 //         "description": "Event-specific information."
441 //       }
442 //     },
443 //     "required": [ "type", "event" ]
444 //   }]
445 // },
446 // "ProtocolMessage": {
447 //   "type": "object",
448 //   "description": "Base class of requests, responses, and events.",
449 //   "properties": {
450 //         "seq": {
451 //           "type": "integer",
452 //           "description": "Sequence number."
453 //         },
454 //         "type": {
455 //           "type": "string",
456 //           "description": "Message type.",
457 //           "_enum": [ "request", "response", "event" ]
458 //         }
459 //   },
460 //   "required": [ "seq", "type" ]
461 // }
462 llvm::json::Object CreateEventObject(const llvm::StringRef event_name) {
463   llvm::json::Object event;
464   event.try_emplace("seq", 0);
465   event.try_emplace("type", "event");
466   EmplaceSafeString(event, "event", event_name);
467   return event;
468 }
469 
470 // "ExceptionBreakpointsFilter": {
471 //   "type": "object",
472 //   "description": "An ExceptionBreakpointsFilter is shown in the UI as an
473 //                   option for configuring how exceptions are dealt with.",
474 //   "properties": {
475 //     "filter": {
476 //       "type": "string",
477 //       "description": "The internal ID of the filter. This value is passed
478 //                       to the setExceptionBreakpoints request."
479 //     },
480 //     "label": {
481 //       "type": "string",
482 //       "description": "The name of the filter. This will be shown in the UI."
483 //     },
484 //     "default": {
485 //       "type": "boolean",
486 //       "description": "Initial value of the filter. If not specified a value
487 //                       'false' is assumed."
488 //     }
489 //   },
490 //   "required": [ "filter", "label" ]
491 // }
492 llvm::json::Value
493 CreateExceptionBreakpointFilter(const ExceptionBreakpoint &bp) {
494   llvm::json::Object object;
495   EmplaceSafeString(object, "filter", bp.filter);
496   EmplaceSafeString(object, "label", bp.label);
497   object.try_emplace("default", bp.default_value);
498   return llvm::json::Value(std::move(object));
499 }
500 
501 // "Source": {
502 //   "type": "object",
503 //   "description": "A Source is a descriptor for source code. It is returned
504 //                   from the debug adapter as part of a StackFrame and it is
505 //                   used by clients when specifying breakpoints.",
506 //   "properties": {
507 //     "name": {
508 //       "type": "string",
509 //       "description": "The short name of the source. Every source returned
510 //                       from the debug adapter has a name. When sending a
511 //                       source to the debug adapter this name is optional."
512 //     },
513 //     "path": {
514 //       "type": "string",
515 //       "description": "The path of the source to be shown in the UI. It is
516 //                       only used to locate and load the content of the
517 //                       source if no sourceReference is specified (or its
518 //                       value is 0)."
519 //     },
520 //     "sourceReference": {
521 //       "type": "number",
522 //       "description": "If sourceReference > 0 the contents of the source must
523 //                       be retrieved through the SourceRequest (even if a path
524 //                       is specified). A sourceReference is only valid for a
525 //                       session, so it must not be used to persist a source."
526 //     },
527 //     "presentationHint": {
528 //       "type": "string",
529 //       "description": "An optional hint for how to present the source in the
530 //                       UI. A value of 'deemphasize' can be used to indicate
531 //                       that the source is not available or that it is
532 //                       skipped on stepping.",
533 //       "enum": [ "normal", "emphasize", "deemphasize" ]
534 //     },
535 //     "origin": {
536 //       "type": "string",
537 //       "description": "The (optional) origin of this source: possible values
538 //                       'internal module', 'inlined content from source map',
539 //                       etc."
540 //     },
541 //     "sources": {
542 //       "type": "array",
543 //       "items": {
544 //         "$ref": "#/definitions/Source"
545 //       },
546 //       "description": "An optional list of sources that are related to this
547 //                       source. These may be the source that generated this
548 //                       source."
549 //     },
550 //     "adapterData": {
551 //       "type":["array","boolean","integer","null","number","object","string"],
552 //       "description": "Optional data that a debug adapter might want to loop
553 //                       through the client. The client should leave the data
554 //                       intact and persist it across sessions. The client
555 //                       should not interpret the data."
556 //     },
557 //     "checksums": {
558 //       "type": "array",
559 //       "items": {
560 //         "$ref": "#/definitions/Checksum"
561 //       },
562 //       "description": "The checksums associated with this file."
563 //     }
564 //   }
565 // }
566 llvm::json::Value CreateSource(lldb::SBLineEntry &line_entry) {
567   llvm::json::Object object;
568   lldb::SBFileSpec file = line_entry.GetFileSpec();
569   if (file.IsValid()) {
570     const char *name = file.GetFilename();
571     if (name)
572       EmplaceSafeString(object, "name", name);
573     char path[PATH_MAX] = "";
574     file.GetPath(path, sizeof(path));
575     if (path[0]) {
576       EmplaceSafeString(object, "path", std::string(path));
577     }
578   }
579   return llvm::json::Value(std::move(object));
580 }
581 
582 llvm::json::Value CreateSource(llvm::StringRef source_path) {
583   llvm::json::Object source;
584   llvm::StringRef name = llvm::sys::path::filename(source_path);
585   EmplaceSafeString(source, "name", name);
586   EmplaceSafeString(source, "path", source_path);
587   return llvm::json::Value(std::move(source));
588 }
589 
590 llvm::json::Value CreateSource(lldb::SBFrame &frame, int64_t &disasm_line) {
591   disasm_line = 0;
592   auto line_entry = frame.GetLineEntry();
593   if (line_entry.GetFileSpec().IsValid())
594     return CreateSource(line_entry);
595 
596   llvm::json::Object object;
597   const auto pc = frame.GetPC();
598 
599   lldb::SBInstructionList insts;
600   lldb::SBFunction function = frame.GetFunction();
601   lldb::addr_t low_pc = LLDB_INVALID_ADDRESS;
602   if (function.IsValid()) {
603     low_pc = function.GetStartAddress().GetLoadAddress(g_vsc.target);
604     auto addr_srcref = g_vsc.addr_to_source_ref.find(low_pc);
605     if (addr_srcref != g_vsc.addr_to_source_ref.end()) {
606       // We have this disassembly cached already, return the existing
607       // sourceReference
608       object.try_emplace("sourceReference", addr_srcref->second);
609       disasm_line = g_vsc.GetLineForPC(addr_srcref->second, pc);
610     } else {
611       insts = function.GetInstructions(g_vsc.target);
612     }
613   } else {
614     lldb::SBSymbol symbol = frame.GetSymbol();
615     if (symbol.IsValid()) {
616       low_pc = symbol.GetStartAddress().GetLoadAddress(g_vsc.target);
617       auto addr_srcref = g_vsc.addr_to_source_ref.find(low_pc);
618       if (addr_srcref != g_vsc.addr_to_source_ref.end()) {
619         // We have this disassembly cached already, return the existing
620         // sourceReference
621         object.try_emplace("sourceReference", addr_srcref->second);
622         disasm_line = g_vsc.GetLineForPC(addr_srcref->second, pc);
623       } else {
624         insts = symbol.GetInstructions(g_vsc.target);
625       }
626     }
627   }
628   const auto num_insts = insts.GetSize();
629   if (low_pc != LLDB_INVALID_ADDRESS && num_insts > 0) {
630     EmplaceSafeString(object, "name", frame.GetFunctionName());
631     SourceReference source;
632     llvm::raw_string_ostream src_strm(source.content);
633     std::string line;
634     for (size_t i = 0; i < num_insts; ++i) {
635       lldb::SBInstruction inst = insts.GetInstructionAtIndex(i);
636       const auto inst_addr = inst.GetAddress().GetLoadAddress(g_vsc.target);
637       const char *m = inst.GetMnemonic(g_vsc.target);
638       const char *o = inst.GetOperands(g_vsc.target);
639       const char *c = inst.GetComment(g_vsc.target);
640       if (pc == inst_addr)
641         disasm_line = i + 1;
642       const auto inst_offset = inst_addr - low_pc;
643       int spaces = 0;
644       if (inst_offset < 10)
645         spaces = 3;
646       else if (inst_offset < 100)
647         spaces = 2;
648       else if (inst_offset < 1000)
649         spaces = 1;
650       line.clear();
651       llvm::raw_string_ostream line_strm(line);
652       line_strm << llvm::formatv("{0:X+}: <{1}> {2} {3,12} {4}", inst_addr,
653                                  inst_offset, llvm::fmt_repeat(' ', spaces), m,
654                                  o);
655 
656       // If there is a comment append it starting at column 60 or after one
657       // space past the last char
658       const uint32_t comment_row = std::max(line_strm.str().size(), (size_t)60);
659       if (c && c[0]) {
660         if (line.size() < comment_row)
661           line_strm.indent(comment_row - line_strm.str().size());
662         line_strm << " # " << c;
663       }
664       src_strm << line_strm.str() << "\n";
665       source.addr_to_line[inst_addr] = i + 1;
666     }
667     // Flush the source stream
668     src_strm.str();
669     auto sourceReference = VSCode::GetNextSourceReference();
670     g_vsc.source_map[sourceReference] = std::move(source);
671     g_vsc.addr_to_source_ref[low_pc] = sourceReference;
672     object.try_emplace("sourceReference", sourceReference);
673   }
674   return llvm::json::Value(std::move(object));
675 }
676 
677 // "StackFrame": {
678 //   "type": "object",
679 //   "description": "A Stackframe contains the source location.",
680 //   "properties": {
681 //     "id": {
682 //       "type": "integer",
683 //       "description": "An identifier for the stack frame. It must be unique
684 //                       across all threads. This id can be used to retrieve
685 //                       the scopes of the frame with the 'scopesRequest' or
686 //                       to restart the execution of a stackframe."
687 //     },
688 //     "name": {
689 //       "type": "string",
690 //       "description": "The name of the stack frame, typically a method name."
691 //     },
692 //     "source": {
693 //       "$ref": "#/definitions/Source",
694 //       "description": "The optional source of the frame."
695 //     },
696 //     "line": {
697 //       "type": "integer",
698 //       "description": "The line within the file of the frame. If source is
699 //                       null or doesn't exist, line is 0 and must be ignored."
700 //     },
701 //     "column": {
702 //       "type": "integer",
703 //       "description": "The column within the line. If source is null or
704 //                       doesn't exist, column is 0 and must be ignored."
705 //     },
706 //     "endLine": {
707 //       "type": "integer",
708 //       "description": "An optional end line of the range covered by the
709 //                       stack frame."
710 //     },
711 //     "endColumn": {
712 //       "type": "integer",
713 //       "description": "An optional end column of the range covered by the
714 //                       stack frame."
715 //     },
716 //     "moduleId": {
717 //       "type": ["integer", "string"],
718 //       "description": "The module associated with this frame, if any."
719 //     },
720 //     "presentationHint": {
721 //       "type": "string",
722 //       "enum": [ "normal", "label", "subtle" ],
723 //       "description": "An optional hint for how to present this frame in
724 //                       the UI. A value of 'label' can be used to indicate
725 //                       that the frame is an artificial frame that is used
726 //                       as a visual label or separator. A value of 'subtle'
727 //                       can be used to change the appearance of a frame in
728 //                       a 'subtle' way."
729 //     }
730 //   },
731 //   "required": [ "id", "name", "line", "column" ]
732 // }
733 llvm::json::Value CreateStackFrame(lldb::SBFrame &frame) {
734   llvm::json::Object object;
735   int64_t frame_id = MakeVSCodeFrameID(frame);
736   object.try_emplace("id", frame_id);
737   EmplaceSafeString(object, "name", frame.GetFunctionName());
738   int64_t disasm_line = 0;
739   object.try_emplace("source", CreateSource(frame, disasm_line));
740 
741   auto line_entry = frame.GetLineEntry();
742   if (disasm_line > 0) {
743     object.try_emplace("line", disasm_line);
744   } else {
745     auto line = line_entry.GetLine();
746     if (line == UINT32_MAX)
747       line = 0;
748     object.try_emplace("line", line);
749   }
750   object.try_emplace("column", line_entry.GetColumn());
751   return llvm::json::Value(std::move(object));
752 }
753 
754 // "Thread": {
755 //   "type": "object",
756 //   "description": "A Thread",
757 //   "properties": {
758 //     "id": {
759 //       "type": "integer",
760 //       "description": "Unique identifier for the thread."
761 //     },
762 //     "name": {
763 //       "type": "string",
764 //       "description": "A name of the thread."
765 //     }
766 //   },
767 //   "required": [ "id", "name" ]
768 // }
769 llvm::json::Value CreateThread(lldb::SBThread &thread) {
770   llvm::json::Object object;
771   object.try_emplace("id", (int64_t)thread.GetThreadID());
772   char thread_str[64];
773   snprintf(thread_str, sizeof(thread_str), "Thread #%u", thread.GetIndexID());
774   const char *name = thread.GetName();
775   if (name) {
776     std::string thread_with_name(thread_str);
777     thread_with_name += ' ';
778     thread_with_name += name;
779     EmplaceSafeString(object, "name", thread_with_name);
780   } else {
781     EmplaceSafeString(object, "name", std::string(thread_str));
782   }
783   return llvm::json::Value(std::move(object));
784 }
785 
786 // "StoppedEvent": {
787 //   "allOf": [ { "$ref": "#/definitions/Event" }, {
788 //     "type": "object",
789 //     "description": "Event message for 'stopped' event type. The event
790 //                     indicates that the execution of the debuggee has stopped
791 //                     due to some condition. This can be caused by a break
792 //                     point previously set, a stepping action has completed,
793 //                     by executing a debugger statement etc.",
794 //     "properties": {
795 //       "event": {
796 //         "type": "string",
797 //         "enum": [ "stopped" ]
798 //       },
799 //       "body": {
800 //         "type": "object",
801 //         "properties": {
802 //           "reason": {
803 //             "type": "string",
804 //             "description": "The reason for the event. For backward
805 //                             compatibility this string is shown in the UI if
806 //                             the 'description' attribute is missing (but it
807 //                             must not be translated).",
808 //             "_enum": [ "step", "breakpoint", "exception", "pause", "entry" ]
809 //           },
810 //           "description": {
811 //             "type": "string",
812 //             "description": "The full reason for the event, e.g. 'Paused
813 //                             on exception'. This string is shown in the UI
814 //                             as is."
815 //           },
816 //           "threadId": {
817 //             "type": "integer",
818 //             "description": "The thread which was stopped."
819 //           },
820 //           "text": {
821 //             "type": "string",
822 //             "description": "Additional information. E.g. if reason is
823 //                             'exception', text contains the exception name.
824 //                             This string is shown in the UI."
825 //           },
826 //           "allThreadsStopped": {
827 //             "type": "boolean",
828 //             "description": "If allThreadsStopped is true, a debug adapter
829 //                             can announce that all threads have stopped.
830 //                             The client should use this information to
831 //                             enable that all threads can be expanded to
832 //                             access their stacktraces. If the attribute
833 //                             is missing or false, only the thread with the
834 //                             given threadId can be expanded."
835 //           }
836 //         },
837 //         "required": [ "reason" ]
838 //       }
839 //     },
840 //     "required": [ "event", "body" ]
841 //   }]
842 // }
843 llvm::json::Value CreateThreadStopped(lldb::SBThread &thread,
844                                       uint32_t stop_id) {
845   llvm::json::Object event(CreateEventObject("stopped"));
846   llvm::json::Object body;
847   switch (thread.GetStopReason()) {
848   case lldb::eStopReasonTrace:
849   case lldb::eStopReasonPlanComplete:
850     body.try_emplace("reason", "step");
851     break;
852   case lldb::eStopReasonBreakpoint: {
853     ExceptionBreakpoint *exc_bp = g_vsc.GetExceptionBPFromStopReason(thread);
854     if (exc_bp) {
855       body.try_emplace("reason", "exception");
856       EmplaceSafeString(body, "description", exc_bp->label);
857     } else {
858       body.try_emplace("reason", "breakpoint");
859       char desc_str[64];
860       uint64_t bp_id = thread.GetStopReasonDataAtIndex(0);
861       uint64_t bp_loc_id = thread.GetStopReasonDataAtIndex(1);
862       snprintf(desc_str, sizeof(desc_str), "breakpoint %" PRIu64 ".%" PRIu64,
863                bp_id, bp_loc_id);
864       EmplaceSafeString(body, "description", desc_str);
865     }
866   } break;
867   case lldb::eStopReasonWatchpoint:
868   case lldb::eStopReasonInstrumentation:
869     body.try_emplace("reason", "breakpoint");
870     break;
871   case lldb::eStopReasonProcessorTrace:
872     body.try_emplace("reason", "processor trace");
873     break;
874   case lldb::eStopReasonSignal:
875   case lldb::eStopReasonException:
876     body.try_emplace("reason", "exception");
877     break;
878   case lldb::eStopReasonExec:
879     body.try_emplace("reason", "entry");
880     break;
881   case lldb::eStopReasonFork:
882     body.try_emplace("reason", "fork");
883     break;
884   case lldb::eStopReasonVFork:
885     body.try_emplace("reason", "vfork");
886     break;
887   case lldb::eStopReasonVForkDone:
888     body.try_emplace("reason", "vforkdone");
889     break;
890   case lldb::eStopReasonThreadExiting:
891   case lldb::eStopReasonInvalid:
892   case lldb::eStopReasonNone:
893     break;
894   }
895   if (stop_id == 0)
896     body.try_emplace("reason", "entry");
897   const lldb::tid_t tid = thread.GetThreadID();
898   body.try_emplace("threadId", (int64_t)tid);
899   // If no description has been set, then set it to the default thread stopped
900   // description. If we have breakpoints that get hit and shouldn't be reported
901   // as breakpoints, then they will set the description above.
902   if (ObjectContainsKey(body, "description")) {
903     char description[1024];
904     if (thread.GetStopDescription(description, sizeof(description))) {
905       EmplaceSafeString(body, "description", std::string(description));
906     }
907   }
908   if (tid == g_vsc.focus_tid) {
909     body.try_emplace("threadCausedFocus", true);
910   }
911   body.try_emplace("preserveFocusHint", tid != g_vsc.focus_tid);
912   body.try_emplace("allThreadsStopped", true);
913   event.try_emplace("body", std::move(body));
914   return llvm::json::Value(std::move(event));
915 }
916 
917 const char *GetNonNullVariableName(lldb::SBValue v) {
918   const char *name = v.GetName();
919   return name ? name : "<null>";
920 }
921 
922 std::string CreateUniqueVariableNameForDisplay(lldb::SBValue v,
923                                                bool is_name_duplicated) {
924   lldb::SBStream name_builder;
925   name_builder.Print(GetNonNullVariableName(v));
926   if (is_name_duplicated) {
927     lldb::SBDeclaration declaration = v.GetDeclaration();
928     const char *file_name = declaration.GetFileSpec().GetFilename();
929     const uint32_t line = declaration.GetLine();
930 
931     if (file_name != nullptr && line > 0)
932       name_builder.Printf(" @ %s:%u", file_name, line);
933     else if (const char *location = v.GetLocation())
934       name_builder.Printf(" @ %s", location);
935   }
936   return name_builder.GetData();
937 }
938 
939 // "Variable": {
940 //   "type": "object",
941 //   "description": "A Variable is a name/value pair. Optionally a variable
942 //                   can have a 'type' that is shown if space permits or when
943 //                   hovering over the variable's name. An optional 'kind' is
944 //                   used to render additional properties of the variable,
945 //                   e.g. different icons can be used to indicate that a
946 //                   variable is public or private. If the value is
947 //                   structured (has children), a handle is provided to
948 //                   retrieve the children with the VariablesRequest. If
949 //                   the number of named or indexed children is large, the
950 //                   numbers should be returned via the optional
951 //                   'namedVariables' and 'indexedVariables' attributes. The
952 //                   client can use this optional information to present the
953 //                   children in a paged UI and fetch them in chunks.",
954 //   "properties": {
955 //     "name": {
956 //       "type": "string",
957 //       "description": "The variable's name."
958 //     },
959 //     "value": {
960 //       "type": "string",
961 //       "description": "The variable's value. This can be a multi-line text,
962 //                       e.g. for a function the body of a function."
963 //     },
964 //     "type": {
965 //       "type": "string",
966 //       "description": "The type of the variable's value. Typically shown in
967 //                       the UI when hovering over the value."
968 //     },
969 //     "presentationHint": {
970 //       "$ref": "#/definitions/VariablePresentationHint",
971 //       "description": "Properties of a variable that can be used to determine
972 //                       how to render the variable in the UI."
973 //     },
974 //     "evaluateName": {
975 //       "type": "string",
976 //       "description": "Optional evaluatable name of this variable which can
977 //                       be passed to the 'EvaluateRequest' to fetch the
978 //                       variable's value."
979 //     },
980 //     "variablesReference": {
981 //       "type": "integer",
982 //       "description": "If variablesReference is > 0, the variable is
983 //                       structured and its children can be retrieved by
984 //                       passing variablesReference to the VariablesRequest."
985 //     },
986 //     "namedVariables": {
987 //       "type": "integer",
988 //       "description": "The number of named child variables. The client can
989 //                       use this optional information to present the children
990 //                       in a paged UI and fetch them in chunks."
991 //     },
992 //     "indexedVariables": {
993 //       "type": "integer",
994 //       "description": "The number of indexed child variables. The client
995 //                       can use this optional information to present the
996 //                       children in a paged UI and fetch them in chunks."
997 //     }
998 //   },
999 //   "required": [ "name", "value", "variablesReference" ]
1000 // }
1001 llvm::json::Value CreateVariable(lldb::SBValue v, int64_t variablesReference,
1002                                  int64_t varID, bool format_hex,
1003                                  bool is_name_duplicated) {
1004   llvm::json::Object object;
1005   EmplaceSafeString(object, "name",
1006                     CreateUniqueVariableNameForDisplay(v, is_name_duplicated));
1007 
1008   if (format_hex)
1009     v.SetFormat(lldb::eFormatHex);
1010   SetValueForKey(v, object, "value");
1011   auto type_cstr = v.GetType().GetDisplayTypeName();
1012   EmplaceSafeString(object, "type", type_cstr ? type_cstr : NO_TYPENAME);
1013   if (varID != INT64_MAX)
1014     object.try_emplace("id", varID);
1015   if (v.MightHaveChildren())
1016     object.try_emplace("variablesReference", variablesReference);
1017   else
1018     object.try_emplace("variablesReference", (int64_t)0);
1019   lldb::SBStream evaluateStream;
1020   v.GetExpressionPath(evaluateStream);
1021   const char *evaluateName = evaluateStream.GetData();
1022   if (evaluateName && evaluateName[0])
1023     EmplaceSafeString(object, "evaluateName", std::string(evaluateName));
1024   return llvm::json::Value(std::move(object));
1025 }
1026 
1027 llvm::json::Value CreateCompileUnit(lldb::SBCompileUnit unit) {
1028   llvm::json::Object object;
1029   char unit_path_arr[PATH_MAX];
1030   unit.GetFileSpec().GetPath(unit_path_arr, sizeof(unit_path_arr));
1031   std::string unit_path(unit_path_arr);
1032   object.try_emplace("compileUnitPath", unit_path);
1033   return llvm::json::Value(std::move(object));
1034 }
1035 
1036 /// See
1037 /// https://microsoft.github.io/debug-adapter-protocol/specification#Reverse_Requests_RunInTerminal
1038 llvm::json::Object
1039 CreateRunInTerminalReverseRequest(const llvm::json::Object &launch_request,
1040                                   llvm::StringRef debug_adaptor_path,
1041                                   llvm::StringRef comm_file) {
1042   llvm::json::Object reverse_request;
1043   reverse_request.try_emplace("type", "request");
1044   reverse_request.try_emplace("command", "runInTerminal");
1045 
1046   llvm::json::Object run_in_terminal_args;
1047   // This indicates the IDE to open an embedded terminal, instead of opening the
1048   // terminal in a new window.
1049   run_in_terminal_args.try_emplace("kind", "integrated");
1050 
1051   auto launch_request_arguments = launch_request.getObject("arguments");
1052   // The program path must be the first entry in the "args" field
1053   std::vector<std::string> args = {
1054       debug_adaptor_path.str(), "--comm-file", comm_file.str(),
1055       "--launch-target", GetString(launch_request_arguments, "program").str()};
1056   std::vector<std::string> target_args =
1057       GetStrings(launch_request_arguments, "args");
1058   args.insert(args.end(), target_args.begin(), target_args.end());
1059   run_in_terminal_args.try_emplace("args", args);
1060 
1061   const auto cwd = GetString(launch_request_arguments, "cwd");
1062   if (!cwd.empty())
1063     run_in_terminal_args.try_emplace("cwd", cwd);
1064 
1065   // We need to convert the input list of environments variables into a
1066   // dictionary
1067   std::vector<std::string> envs = GetStrings(launch_request_arguments, "env");
1068   llvm::json::Object environment;
1069   for (const std::string &env : envs) {
1070     size_t index = env.find('=');
1071     environment.try_emplace(env.substr(0, index), env.substr(index + 1));
1072   }
1073   run_in_terminal_args.try_emplace("env",
1074                                    llvm::json::Value(std::move(environment)));
1075 
1076   reverse_request.try_emplace(
1077       "arguments", llvm::json::Value(std::move(run_in_terminal_args)));
1078   return reverse_request;
1079 }
1080 
1081 std::string JSONToString(const llvm::json::Value &json) {
1082   std::string data;
1083   llvm::raw_string_ostream os(data);
1084   os << json;
1085   os.flush();
1086   return data;
1087 }
1088 
1089 } // namespace lldb_vscode
1090