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