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