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