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