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