Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Core/Debugger.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- Debugger.cpp ------------------------------------------------------===//
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 "lldb/Core/Debugger.h"
10
11
#include "lldb/Breakpoint/Breakpoint.h"
12
#include "lldb/Core/FormatEntity.h"
13
#include "lldb/Core/Mangled.h"
14
#include "lldb/Core/ModuleList.h"
15
#include "lldb/Core/PluginManager.h"
16
#include "lldb/Core/StreamAsynchronousIO.h"
17
#include "lldb/Core/StreamFile.h"
18
#include "lldb/DataFormatters/DataVisualization.h"
19
#include "lldb/Expression/REPL.h"
20
#include "lldb/Host/File.h"
21
#include "lldb/Host/FileSystem.h"
22
#include "lldb/Host/HostInfo.h"
23
#include "lldb/Host/Terminal.h"
24
#include "lldb/Host/ThreadLauncher.h"
25
#include "lldb/Interpreter/CommandInterpreter.h"
26
#include "lldb/Interpreter/CommandReturnObject.h"
27
#include "lldb/Interpreter/OptionValue.h"
28
#include "lldb/Interpreter/OptionValueLanguage.h"
29
#include "lldb/Interpreter/OptionValueProperties.h"
30
#include "lldb/Interpreter/OptionValueSInt64.h"
31
#include "lldb/Interpreter/OptionValueString.h"
32
#include "lldb/Interpreter/Property.h"
33
#include "lldb/Interpreter/ScriptInterpreter.h"
34
#include "lldb/Symbol/Function.h"
35
#include "lldb/Symbol/Symbol.h"
36
#include "lldb/Symbol/SymbolContext.h"
37
#include "lldb/Target/Language.h"
38
#include "lldb/Target/Process.h"
39
#include "lldb/Target/StructuredDataPlugin.h"
40
#include "lldb/Target/Target.h"
41
#include "lldb/Target/TargetList.h"
42
#include "lldb/Target/Thread.h"
43
#include "lldb/Target/ThreadList.h"
44
#include "lldb/Utility/AnsiTerminal.h"
45
#include "lldb/Utility/Event.h"
46
#include "lldb/Utility/Listener.h"
47
#include "lldb/Utility/Log.h"
48
#include "lldb/Utility/Reproducer.h"
49
#include "lldb/Utility/ReproducerProvider.h"
50
#include "lldb/Utility/State.h"
51
#include "lldb/Utility/Stream.h"
52
#include "lldb/Utility/StreamCallback.h"
53
#include "lldb/Utility/StreamString.h"
54
55
#if defined(_WIN32)
56
#include "lldb/Host/windows/PosixApi.h"
57
#include "lldb/Host/windows/windows.h"
58
#endif
59
60
#include "llvm/ADT/None.h"
61
#include "llvm/ADT/STLExtras.h"
62
#include "llvm/ADT/StringRef.h"
63
#include "llvm/ADT/iterator.h"
64
#include "llvm/Support/DynamicLibrary.h"
65
#include "llvm/Support/FileSystem.h"
66
#include "llvm/Support/Process.h"
67
#include "llvm/Support/Threading.h"
68
#include "llvm/Support/raw_ostream.h"
69
70
#include <cstdio>
71
#include <cstdlib>
72
#include <cstring>
73
#include <list>
74
#include <memory>
75
#include <mutex>
76
#include <set>
77
#include <string>
78
#include <system_error>
79
80
// Includes for pipe()
81
#if defined(_WIN32)
82
#include <fcntl.h>
83
#include <io.h>
84
#else
85
#include <unistd.h>
86
#endif
87
88
namespace lldb_private {
89
class Address;
90
}
91
92
using namespace lldb;
93
using namespace lldb_private;
94
95
static lldb::user_id_t g_unique_id = 1;
96
static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024;
97
98
#pragma mark Static Functions
99
100
typedef std::vector<DebuggerSP> DebuggerList;
101
static std::recursive_mutex *g_debugger_list_mutex_ptr =
102
    nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
103
static DebuggerList *g_debugger_list_ptr =
104
    nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain
105
106
static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = {
107
    {
108
        Debugger::eStopDisassemblyTypeNever,
109
        "never",
110
        "Never show disassembly when displaying a stop context.",
111
    },
112
    {
113
        Debugger::eStopDisassemblyTypeNoDebugInfo,
114
        "no-debuginfo",
115
        "Show disassembly when there is no debug information.",
116
    },
117
    {
118
        Debugger::eStopDisassemblyTypeNoSource,
119
        "no-source",
120
        "Show disassembly when there is no source information, or the source "
121
        "file "
122
        "is missing when displaying a stop context.",
123
    },
124
    {
125
        Debugger::eStopDisassemblyTypeAlways,
126
        "always",
127
        "Always show disassembly when displaying a stop context.",
128
    },
129
};
130
131
static constexpr OptionEnumValueElement g_language_enumerators[] = {
132
    {
133
        eScriptLanguageNone,
134
        "none",
135
        "Disable scripting languages.",
136
    },
137
    {
138
        eScriptLanguagePython,
139
        "python",
140
        "Select python as the default scripting language.",
141
    },
142
    {
143
        eScriptLanguageDefault,
144
        "default",
145
        "Select the lldb default as the default scripting language.",
146
    },
147
};
148
149
static constexpr OptionEnumValueElement s_stop_show_column_values[] = {
150
    {
151
        eStopShowColumnAnsiOrCaret,
152
        "ansi-or-caret",
153
        "Highlight the stop column with ANSI terminal codes when color/ANSI "
154
        "mode is enabled; otherwise, fall back to using a text-only caret (^) "
155
        "as if \"caret-only\" mode was selected.",
156
    },
157
    {
158
        eStopShowColumnAnsi,
159
        "ansi",
160
        "Highlight the stop column with ANSI terminal codes when running LLDB "
161
        "with color/ANSI enabled.",
162
    },
163
    {
164
        eStopShowColumnCaret,
165
        "caret",
166
        "Highlight the stop column with a caret character (^) underneath the "
167
        "stop column. This method introduces a new line in source listings "
168
        "that display thread stop locations.",
169
    },
170
    {
171
        eStopShowColumnNone,
172
        "none",
173
        "Do not highlight the stop column.",
174
    },
175
};
176
177
#define LLDB_PROPERTIES_debugger
178
#include "CoreProperties.inc"
179
180
enum {
181
#define LLDB_PROPERTIES_debugger
182
#include "CorePropertiesEnum.inc"
183
};
184
185
LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr;
186
187
Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx,
188
                                  VarSetOperationType op,
189
                                  llvm::StringRef property_path,
190
31.2k
                                  llvm::StringRef value) {
191
31.2k
  bool is_load_script =
192
31.2k
      (property_path == "target.load-script-from-symbol-file");
193
  // These properties might change how we visualize data.
194
31.2k
  bool invalidate_data_vis = (property_path == "escape-non-printables");
195
31.2k
  invalidate_data_vis |=
196
31.2k
      (property_path == "target.max-zero-padding-in-float-format");
197
31.2k
  if (invalidate_data_vis) {
198
13
    DataVisualization::ForceUpdate();
199
13
  }
200
201
31.2k
  TargetSP target_sp;
202
31.2k
  LoadScriptFromSymFile load_script_old_value;
203
31.2k
  if (is_load_script && 
exe_ctx->GetTargetSP()4
) {
204
0
    target_sp = exe_ctx->GetTargetSP();
205
0
    load_script_old_value =
206
0
        target_sp->TargetProperties::GetLoadScriptFromSymbolFile();
207
0
  }
208
31.2k
  Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value));
209
31.2k
  if (error.Success()) {
210
    // FIXME it would be nice to have "on-change" callbacks for properties
211
31.2k
    if (property_path == g_debugger_properties[ePropertyPrompt].name) {
212
4
      llvm::StringRef new_prompt = GetPrompt();
213
4
      std::string str = lldb_private::ansi::FormatAnsiTerminalCodes(
214
4
          new_prompt, GetUseColor());
215
4
      if (str.length())
216
4
        new_prompt = str;
217
4
      GetCommandInterpreter().UpdatePrompt(new_prompt);
218
4
      auto bytes = std::make_unique<EventDataBytes>(new_prompt);
219
4
      auto prompt_change_event_sp = std::make_shared<Event>(
220
4
          CommandInterpreter::eBroadcastBitResetPrompt, bytes.release());
221
4
      GetCommandInterpreter().BroadcastEvent(prompt_change_event_sp);
222
31.1k
    } else if (property_path == g_debugger_properties[ePropertyUseColor].name) {
223
      // use-color changed. Ping the prompt so it can reset the ansi terminal
224
      // codes.
225
3.40k
      SetPrompt(GetPrompt());
226
27.7k
    } else if (property_path == g_debugger_properties[ePropertyUseSourceCache].name) {
227
      // use-source-cache changed. Wipe out the cache contents if it was disabled.
228
3
      if (!GetUseSourceCache()) {
229
1
        m_source_file_cache.Clear();
230
1
      }
231
27.7k
    } else if (is_load_script && 
target_sp4
&&
232
27.7k
               
load_script_old_value == eLoadScriptFromSymFileWarn0
) {
233
0
      if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() ==
234
0
          eLoadScriptFromSymFileTrue) {
235
0
        std::list<Status> errors;
236
0
        StreamString feedback_stream;
237
0
        if (!target_sp->LoadScriptingResources(errors, &feedback_stream)) {
238
0
          Stream &s = GetErrorStream();
239
0
          for (auto error : errors) {
240
0
            s.Printf("%s\n", error.AsCString());
241
0
          }
242
0
          if (feedback_stream.GetSize())
243
0
            s.PutCString(feedback_stream.GetString());
244
0
        }
245
0
      }
246
0
    }
247
31.2k
  }
248
31.2k
  return error;
249
31.2k
}
250
251
32
bool Debugger::GetAutoConfirm() const {
252
32
  const uint32_t idx = ePropertyAutoConfirm;
253
32
  return m_collection_sp->GetPropertyAtIndexAsBoolean(
254
32
      nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
255
32
}
256
257
997k
const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const {
258
997k
  const uint32_t idx = ePropertyDisassemblyFormat;
259
997k
  return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
260
997k
}
261
262
6.03k
const FormatEntity::Entry *Debugger::GetFrameFormat() const {
263
6.03k
  const uint32_t idx = ePropertyFrameFormat;
264
6.03k
  return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
265
6.03k
}
266
267
0
const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const {
268
0
  const uint32_t idx = ePropertyFrameFormatUnique;
269
0
  return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
270
0
}
271
272
49
uint32_t Debugger::GetStopDisassemblyMaxSize() const {
273
49
  const uint32_t idx = ePropertyStopDisassemblyMaxSize;
274
49
  return m_collection_sp->GetPropertyAtIndexAsUInt64(
275
49
      nullptr, idx, g_debugger_properties[idx].default_uint_value);
276
49
}
277
278
167
bool Debugger::GetNotifyVoid() const {
279
167
  const uint32_t idx = ePropertyNotiftVoid;
280
167
  return m_collection_sp->GetPropertyAtIndexAsBoolean(
281
167
      nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
282
167
}
283
284
19.6k
llvm::StringRef Debugger::GetPrompt() const {
285
19.6k
  const uint32_t idx = ePropertyPrompt;
286
19.6k
  return m_collection_sp->GetPropertyAtIndexAsString(
287
19.6k
      nullptr, idx, g_debugger_properties[idx].default_cstr_value);
288
19.6k
}
289
290
9.37k
void Debugger::SetPrompt(llvm::StringRef p) {
291
9.37k
  const uint32_t idx = ePropertyPrompt;
292
9.37k
  m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
293
9.37k
  llvm::StringRef new_prompt = GetPrompt();
294
9.37k
  std::string str =
295
9.37k
      lldb_private::ansi::FormatAnsiTerminalCodes(new_prompt, GetUseColor());
296
9.37k
  if (str.length())
297
9.37k
    new_prompt = str;
298
9.37k
  GetCommandInterpreter().UpdatePrompt(new_prompt);
299
9.37k
}
300
301
0
llvm::StringRef Debugger::GetReproducerPath() const {
302
0
  auto &r = repro::Reproducer::Instance();
303
0
  return r.GetReproducerPath().GetCString();
304
0
}
305
306
1.06k
const FormatEntity::Entry *Debugger::GetThreadFormat() const {
307
1.06k
  const uint32_t idx = ePropertyThreadFormat;
308
1.06k
  return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
309
1.06k
}
310
311
2.51k
const FormatEntity::Entry *Debugger::GetThreadStopFormat() const {
312
2.51k
  const uint32_t idx = ePropertyThreadStopFormat;
313
2.51k
  return m_collection_sp->GetPropertyAtIndexAsFormatEntity(nullptr, idx);
314
2.51k
}
315
316
564k
lldb::ScriptLanguage Debugger::GetScriptLanguage() const {
317
564k
  const uint32_t idx = ePropertyScriptLanguage;
318
564k
  return (lldb::ScriptLanguage)m_collection_sp->GetPropertyAtIndexAsEnumeration(
319
564k
      nullptr, idx, g_debugger_properties[idx].default_uint_value);
320
564k
}
321
322
18
bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) {
323
18
  const uint32_t idx = ePropertyScriptLanguage;
324
18
  return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx,
325
18
                                                          script_lang);
326
18
}
327
328
1
lldb::LanguageType Debugger::GetREPLLanguage() const {
329
1
  const uint32_t idx = ePropertyREPLLanguage;
330
1
  OptionValueLanguage *value =
331
1
      m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(nullptr, idx);
332
1
  if (value)
333
1
    return value->GetCurrentValue();
334
0
  return LanguageType();
335
1
}
336
337
2
bool Debugger::SetREPLLanguage(lldb::LanguageType repl_lang) {
338
2
  const uint32_t idx = ePropertyREPLLanguage;
339
2
  return m_collection_sp->SetPropertyAtIndexAsLanguage(nullptr, idx, repl_lang);
340
2
}
341
342
1.39k
uint32_t Debugger::GetTerminalWidth() const {
343
1.39k
  const uint32_t idx = ePropertyTerminalWidth;
344
1.39k
  return m_collection_sp->GetPropertyAtIndexAsSInt64(
345
1.39k
      nullptr, idx, g_debugger_properties[idx].default_uint_value);
346
1.39k
}
347
348
9
bool Debugger::SetTerminalWidth(uint32_t term_width) {
349
9
  if (auto handler_sp = m_io_handler_stack.Top())
350
0
    handler_sp->TerminalSizeChanged();
351
352
9
  const uint32_t idx = ePropertyTerminalWidth;
353
9
  return m_collection_sp->SetPropertyAtIndexAsSInt64(nullptr, idx, term_width);
354
9
}
355
356
3.63k
bool Debugger::GetUseExternalEditor() const {
357
3.63k
  const uint32_t idx = ePropertyUseExternalEditor;
358
3.63k
  return m_collection_sp->GetPropertyAtIndexAsBoolean(
359
3.63k
      nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
360
3.63k
}
361
362
348
bool Debugger::SetUseExternalEditor(bool b) {
363
348
  const uint32_t idx = ePropertyUseExternalEditor;
364
348
  return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
365
348
}
366
367
2.07M
bool Debugger::GetUseColor() const {
368
2.07M
  const uint32_t idx = ePropertyUseColor;
369
2.07M
  return m_collection_sp->GetPropertyAtIndexAsBoolean(
370
2.07M
      nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
371
2.07M
}
372
373
5.96k
bool Debugger::SetUseColor(bool b) {
374
5.96k
  const uint32_t idx = ePropertyUseColor;
375
5.96k
  bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
376
5.96k
  SetPrompt(GetPrompt());
377
5.96k
  return ret;
378
5.96k
}
379
380
6
bool Debugger::GetUseAutosuggestion() const {
381
6
  const uint32_t idx = ePropertyShowAutosuggestion;
382
6
  return m_collection_sp->GetPropertyAtIndexAsBoolean(
383
6
      nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
384
6
}
385
386
20.3k
bool Debugger::GetUseSourceCache() const {
387
20.3k
  const uint32_t idx = ePropertyUseSourceCache;
388
20.3k
  return m_collection_sp->GetPropertyAtIndexAsBoolean(
389
20.3k
      nullptr, idx, g_debugger_properties[idx].default_uint_value != 0);
390
20.3k
}
391
392
0
bool Debugger::SetUseSourceCache(bool b) {
393
0
  const uint32_t idx = ePropertyUseSourceCache;
394
0
  bool ret = m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
395
0
  if (!ret) {
396
0
    m_source_file_cache.Clear();
397
0
  }
398
0
  return ret;
399
0
}
400
31
bool Debugger::GetHighlightSource() const {
401
31
  const uint32_t idx = ePropertyHighlightSource;
402
31
  return m_collection_sp->GetPropertyAtIndexAsBoolean(
403
31
      nullptr, idx, g_debugger_properties[idx].default_uint_value);
404
31
}
405
406
1.99k
StopShowColumn Debugger::GetStopShowColumn() const {
407
1.99k
  const uint32_t idx = ePropertyStopShowColumn;
408
1.99k
  return (lldb::StopShowColumn)m_collection_sp->GetPropertyAtIndexAsEnumeration(
409
1.99k
      nullptr, idx, g_debugger_properties[idx].default_uint_value);
410
1.99k
}
411
412
31
llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const {
413
31
  const uint32_t idx = ePropertyStopShowColumnAnsiPrefix;
414
31
  return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
415
31
}
416
417
31
llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const {
418
31
  const uint32_t idx = ePropertyStopShowColumnAnsiSuffix;
419
31
  return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
420
31
}
421
422
31
llvm::StringRef Debugger::GetStopShowLineMarkerAnsiPrefix() const {
423
31
  const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix;
424
31
  return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
425
31
}
426
427
31
llvm::StringRef Debugger::GetStopShowLineMarkerAnsiSuffix() const {
428
31
  const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix;
429
31
  return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, "");
430
31
}
431
432
4.19k
uint32_t Debugger::GetStopSourceLineCount(bool before) const {
433
4.19k
  const uint32_t idx =
434
4.19k
      before ? 
ePropertyStopLineCountBefore2.09k
:
ePropertyStopLineCountAfter2.09k
;
435
4.19k
  return m_collection_sp->GetPropertyAtIndexAsSInt64(
436
4.19k
      nullptr, idx, g_debugger_properties[idx].default_uint_value);
437
4.19k
}
438
439
2.09k
Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const {
440
2.09k
  const uint32_t idx = ePropertyStopDisassemblyDisplay;
441
2.09k
  return (Debugger::StopDisassemblyType)
442
2.09k
      m_collection_sp->GetPropertyAtIndexAsEnumeration(
443
2.09k
          nullptr, idx, g_debugger_properties[idx].default_uint_value);
444
2.09k
}
445
446
129
uint32_t Debugger::GetDisassemblyLineCount() const {
447
129
  const uint32_t idx = ePropertyStopDisassemblyCount;
448
129
  return m_collection_sp->GetPropertyAtIndexAsSInt64(
449
129
      nullptr, idx, g_debugger_properties[idx].default_uint_value);
450
129
}
451
452
49.4k
bool Debugger::GetAutoOneLineSummaries() const {
453
49.4k
  const uint32_t idx = ePropertyAutoOneLineSummaries;
454
49.4k
  return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
455
49.4k
}
456
457
4.90k
bool Debugger::GetEscapeNonPrintables() const {
458
4.90k
  const uint32_t idx = ePropertyEscapeNonPrintables;
459
4.90k
  return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
460
4.90k
}
461
462
0
bool Debugger::GetAutoIndent() const {
463
0
  const uint32_t idx = ePropertyAutoIndent;
464
0
  return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
465
0
}
466
467
0
bool Debugger::SetAutoIndent(bool b) {
468
0
  const uint32_t idx = ePropertyAutoIndent;
469
0
  return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
470
0
}
471
472
0
bool Debugger::GetPrintDecls() const {
473
0
  const uint32_t idx = ePropertyPrintDecls;
474
0
  return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
475
0
}
476
477
0
bool Debugger::SetPrintDecls(bool b) {
478
0
  const uint32_t idx = ePropertyPrintDecls;
479
0
  return m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
480
0
}
481
482
0
uint32_t Debugger::GetTabSize() const {
483
0
  const uint32_t idx = ePropertyTabSize;
484
0
  return m_collection_sp->GetPropertyAtIndexAsUInt64(
485
0
      nullptr, idx, g_debugger_properties[idx].default_uint_value);
486
0
}
487
488
0
bool Debugger::SetTabSize(uint32_t tab_size) {
489
0
  const uint32_t idx = ePropertyTabSize;
490
0
  return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, tab_size);
491
0
}
492
493
#pragma mark Debugger
494
495
// const DebuggerPropertiesSP &
496
// Debugger::GetSettings() const
497
//{
498
//    return m_properties_sp;
499
//}
500
//
501
502
3.44k
void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) {
503
3.44k
  assert(g_debugger_list_ptr == nullptr &&
504
3.44k
         "Debugger::Initialize called more than once!");
505
0
  g_debugger_list_mutex_ptr = new std::recursive_mutex();
506
3.44k
  g_debugger_list_ptr = new DebuggerList();
507
3.44k
  g_load_plugin_callback = load_plugin_callback;
508
3.44k
}
509
510
3.43k
void Debugger::Terminate() {
511
3.43k
  assert(g_debugger_list_ptr &&
512
3.43k
         "Debugger::Terminate called without a matching Debugger::Initialize!");
513
514
3.43k
  if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
515
    // Clear our global list of debugger objects
516
3.43k
    {
517
3.43k
      std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
518
3.43k
      for (const auto &debugger : *g_debugger_list_ptr)
519
164
        debugger->Clear();
520
3.43k
      g_debugger_list_ptr->clear();
521
3.43k
    }
522
3.43k
  }
523
3.43k
}
524
525
3.44k
void Debugger::SettingsInitialize() { Target::SettingsInitialize(); }
526
527
3.43k
void Debugger::SettingsTerminate() { Target::SettingsTerminate(); }
528
529
2
bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) {
530
2
  if (g_load_plugin_callback) {
531
2
    llvm::sys::DynamicLibrary dynlib =
532
2
        g_load_plugin_callback(shared_from_this(), spec, error);
533
2
    if (dynlib.isValid()) {
534
1
      m_loaded_plugins.push_back(dynlib);
535
1
      return true;
536
1
    }
537
2
  } else {
538
    // The g_load_plugin_callback is registered in SBDebugger::Initialize() and
539
    // if the public API layer isn't available (code is linking against all of
540
    // the internal LLDB static libraries), then we can't load plugins
541
0
    error.SetErrorString("Public API layer is not available");
542
0
  }
543
1
  return false;
544
2
}
545
546
static FileSystem::EnumerateDirectoryResult
547
LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft,
548
0
                   llvm::StringRef path) {
549
0
  Status error;
550
551
0
  static ConstString g_dylibext(".dylib");
552
0
  static ConstString g_solibext(".so");
553
554
0
  if (!baton)
555
0
    return FileSystem::eEnumerateDirectoryResultQuit;
556
557
0
  Debugger *debugger = (Debugger *)baton;
558
559
0
  namespace fs = llvm::sys::fs;
560
  // If we have a regular file, a symbolic link or unknown file type, try and
561
  // process the file. We must handle unknown as sometimes the directory
562
  // enumeration might be enumerating a file system that doesn't have correct
563
  // file type information.
564
0
  if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file ||
565
0
      ft == fs::file_type::type_unknown) {
566
0
    FileSpec plugin_file_spec(path);
567
0
    FileSystem::Instance().Resolve(plugin_file_spec);
568
569
0
    if (plugin_file_spec.GetFileNameExtension() != g_dylibext &&
570
0
        plugin_file_spec.GetFileNameExtension() != g_solibext) {
571
0
      return FileSystem::eEnumerateDirectoryResultNext;
572
0
    }
573
574
0
    Status plugin_load_error;
575
0
    debugger->LoadPlugin(plugin_file_spec, plugin_load_error);
576
577
0
    return FileSystem::eEnumerateDirectoryResultNext;
578
0
  } else if (ft == fs::file_type::directory_file ||
579
0
             ft == fs::file_type::symlink_file ||
580
0
             ft == fs::file_type::type_unknown) {
581
    // Try and recurse into anything that a directory or symbolic link. We must
582
    // also do this for unknown as sometimes the directory enumeration might be
583
    // enumerating a file system that doesn't have correct file type
584
    // information.
585
0
    return FileSystem::eEnumerateDirectoryResultEnter;
586
0
  }
587
588
0
  return FileSystem::eEnumerateDirectoryResultNext;
589
0
}
590
591
5.95k
void Debugger::InstanceInitialize() {
592
5.95k
  const bool find_directories = true;
593
5.95k
  const bool find_files = true;
594
5.95k
  const bool find_other = true;
595
5.95k
  char dir_path[PATH_MAX];
596
5.95k
  if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) {
597
0
    if (FileSystem::Instance().Exists(dir_spec) &&
598
0
        dir_spec.GetPath(dir_path, sizeof(dir_path))) {
599
0
      FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
600
0
                                                find_files, find_other,
601
0
                                                LoadPluginCallback, this);
602
0
    }
603
0
  }
604
605
5.95k
  if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) {
606
5.95k
    if (FileSystem::Instance().Exists(dir_spec) &&
607
5.95k
        
dir_spec.GetPath(dir_path, sizeof(dir_path))0
) {
608
0
      FileSystem::Instance().EnumerateDirectory(dir_path, find_directories,
609
0
                                                find_files, find_other,
610
0
                                                LoadPluginCallback, this);
611
0
    }
612
5.95k
  }
613
614
5.95k
  PluginManager::DebuggerInitialize(*this);
615
5.95k
}
616
617
DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback,
618
5.95k
                                    void *baton) {
619
5.95k
  DebuggerSP debugger_sp(new Debugger(log_callback, baton));
620
5.95k
  if (g_debugger_list_ptr && 
g_debugger_list_mutex_ptr5.94k
) {
621
5.94k
    std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
622
5.94k
    g_debugger_list_ptr->push_back(debugger_sp);
623
5.94k
  }
624
5.95k
  debugger_sp->InstanceInitialize();
625
5.95k
  return debugger_sp;
626
5.95k
}
627
628
5.77k
void Debugger::Destroy(DebuggerSP &debugger_sp) {
629
5.77k
  if (!debugger_sp)
630
2
    return;
631
632
5.77k
  CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter();
633
634
5.77k
  if (cmd_interpreter.GetSaveSessionOnQuit()) {
635
1
    CommandReturnObject result(debugger_sp->GetUseColor());
636
1
    cmd_interpreter.SaveTranscript(result);
637
1
    if (result.Succeeded())
638
1
      debugger_sp->GetOutputStream() << result.GetOutputData() << '\n';
639
0
    else
640
0
      debugger_sp->GetErrorStream() << result.GetErrorData() << '\n';
641
1
  }
642
643
5.77k
  debugger_sp->Clear();
644
645
5.77k
  if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
646
5.77k
    std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
647
5.77k
    DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
648
5.82k
    for (pos = g_debugger_list_ptr->begin(); pos != end; 
++pos50
) {
649
5.82k
      if ((*pos).get() == debugger_sp.get()) {
650
5.77k
        g_debugger_list_ptr->erase(pos);
651
5.77k
        return;
652
5.77k
      }
653
5.82k
    }
654
5.77k
  }
655
5.77k
}
656
657
7
DebuggerSP Debugger::FindDebuggerWithInstanceName(ConstString instance_name) {
658
7
  DebuggerSP debugger_sp;
659
7
  if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
660
7
    std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
661
7
    DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
662
9
    for (pos = g_debugger_list_ptr->begin(); pos != end; 
++pos2
) {
663
7
      if ((*pos)->m_instance_name == instance_name) {
664
5
        debugger_sp = *pos;
665
5
        break;
666
5
      }
667
7
    }
668
7
  }
669
7
  return debugger_sp;
670
7
}
671
672
0
TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) {
673
0
  TargetSP target_sp;
674
0
  if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
675
0
    std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
676
0
    DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
677
0
    for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
678
0
      target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid);
679
0
      if (target_sp)
680
0
        break;
681
0
    }
682
0
  }
683
0
  return target_sp;
684
0
}
685
686
0
TargetSP Debugger::FindTargetWithProcess(Process *process) {
687
0
  TargetSP target_sp;
688
0
  if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
689
0
    std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
690
0
    DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
691
0
    for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) {
692
0
      target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process);
693
0
      if (target_sp)
694
0
        break;
695
0
    }
696
0
  }
697
0
  return target_sp;
698
0
}
699
700
5.95k
ConstString Debugger::GetStaticBroadcasterClass() {
701
5.95k
  static ConstString class_name("lldb.debugger");
702
5.95k
  return class_name;
703
5.95k
}
704
705
Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton)
706
    : UserID(g_unique_id++),
707
      Properties(std::make_shared<OptionValueProperties>()),
708
      m_input_file_sp(std::make_shared<NativeFile>(stdin, false)),
709
      m_output_stream_sp(std::make_shared<StreamFile>(stdout, false)),
710
      m_error_stream_sp(std::make_shared<StreamFile>(stderr, false)),
711
      m_input_recorder(nullptr),
712
      m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()),
713
      m_terminal_state(), m_target_list(*this), m_platform_list(),
714
      m_listener_sp(Listener::MakeListener("lldb.Debugger")),
715
      m_source_manager_up(), m_source_file_cache(),
716
      m_command_interpreter_up(
717
          std::make_unique<CommandInterpreter>(*this, false)),
718
      m_io_handler_stack(), m_instance_name(), m_loaded_plugins(),
719
      m_event_handler_thread(), m_io_handler_thread(),
720
      m_sync_broadcaster(nullptr, "lldb.debugger.sync"),
721
      m_broadcaster(m_broadcaster_manager_sp,
722
                    GetStaticBroadcasterClass().AsCString()),
723
5.95k
      m_forward_listener_sp(), m_clear_once() {
724
5.95k
  m_instance_name.SetString(llvm::formatv("debugger_{0}", GetID()).str());
725
5.95k
  if (log_callback)
726
0
    m_log_callback_stream_sp =
727
0
        std::make_shared<StreamCallback>(log_callback, baton);
728
5.95k
  m_command_interpreter_up->Initialize();
729
  // Always add our default platform to the platform list
730
5.95k
  PlatformSP default_platform_sp(Platform::GetHostPlatform());
731
5.95k
  assert(default_platform_sp);
732
0
  m_platform_list.Append(default_platform_sp, true);
733
734
  // Create the dummy target.
735
5.95k
  {
736
5.95k
    ArchSpec arch(Target::GetDefaultArchitecture());
737
5.95k
    if (!arch.IsValid())
738
5.95k
      arch = HostInfo::GetArchitecture();
739
5.95k
    assert(arch.IsValid() && "No valid default or host archspec");
740
0
    const bool is_dummy_target = true;
741
5.95k
    m_dummy_target_sp.reset(
742
5.95k
        new Target(*this, arch, default_platform_sp, is_dummy_target));
743
5.95k
  }
744
0
  assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?");
745
746
0
  m_collection_sp->Initialize(g_debugger_properties);
747
5.95k
  m_collection_sp->AppendProperty(
748
5.95k
      ConstString("target"),
749
5.95k
      ConstString("Settings specify to debugging targets."), true,
750
5.95k
      Target::GetGlobalProperties().GetValueProperties());
751
5.95k
  m_collection_sp->AppendProperty(
752
5.95k
      ConstString("platform"), ConstString("Platform settings."), true,
753
5.95k
      Platform::GetGlobalPlatformProperties().GetValueProperties());
754
5.95k
  m_collection_sp->AppendProperty(
755
5.95k
      ConstString("symbols"), ConstString("Symbol lookup and cache settings."),
756
5.95k
      true, ModuleList::GetGlobalModuleListProperties().GetValueProperties());
757
5.95k
  if (m_command_interpreter_up) {
758
5.95k
    m_collection_sp->AppendProperty(
759
5.95k
        ConstString("interpreter"),
760
5.95k
        ConstString("Settings specify to the debugger's command interpreter."),
761
5.95k
        true, m_command_interpreter_up->GetValueProperties());
762
5.95k
  }
763
5.95k
  OptionValueSInt64 *term_width =
764
5.95k
      m_collection_sp->GetPropertyAtIndexAsOptionValueSInt64(
765
5.95k
          nullptr, ePropertyTerminalWidth);
766
5.95k
  term_width->SetMinimumValue(10);
767
5.95k
  term_width->SetMaximumValue(1024);
768
769
  // Turn off use-color if this is a dumb terminal.
770
5.95k
  const char *term = getenv("TERM");
771
5.95k
  if (term && 
!strcmp(term, "dumb")5.93k
)
772
0
    SetUseColor(false);
773
  // Turn off use-color if we don't write to a terminal with color support.
774
5.95k
  if (!GetOutputFile().GetIsTerminalWithColors())
775
5.94k
    SetUseColor(false);
776
777
#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
778
  // Enabling use of ANSI color codes because LLDB is using them to highlight
779
  // text.
780
  llvm::sys::Process::UseANSIEscapeCodes(true);
781
#endif
782
5.95k
}
783
784
5.94k
Debugger::~Debugger() { Clear(); }
785
786
11.8k
void Debugger::Clear() {
787
  // Make sure we call this function only once. With the C++ global destructor
788
  // chain having a list of debuggers and with code that can be running on
789
  // other threads, we need to ensure this doesn't happen multiple times.
790
  //
791
  // The following functions call Debugger::Clear():
792
  //     Debugger::~Debugger();
793
  //     static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp);
794
  //     static void Debugger::Terminate();
795
11.8k
  llvm::call_once(m_clear_once, [this]() {
796
5.94k
    ClearIOHandlers();
797
5.94k
    StopIOHandlerThread();
798
5.94k
    StopEventHandlerThread();
799
5.94k
    m_listener_sp->Clear();
800
5.94k
    for (TargetSP target_sp : m_target_list.Targets()) {
801
290
      if (target_sp) {
802
290
        if (ProcessSP process_sp = target_sp->GetProcessSP())
803
163
          process_sp->Finalize();
804
290
        target_sp->Destroy();
805
290
      }
806
290
    }
807
5.94k
    m_broadcaster_manager_sp->Clear();
808
809
    // Close the input file _before_ we close the input read communications
810
    // class as it does NOT own the input file, our m_input_file does.
811
5.94k
    m_terminal_state.Clear();
812
5.94k
    GetInputFile().Close();
813
814
5.94k
    m_command_interpreter_up->Clear();
815
5.94k
  });
816
11.8k
}
817
818
0
bool Debugger::GetCloseInputOnEOF() const {
819
  //    return m_input_comm.GetCloseOnEOF();
820
0
  return false;
821
0
}
822
823
2.34k
void Debugger::SetCloseInputOnEOF(bool b) {
824
  //    m_input_comm.SetCloseOnEOF(b);
825
2.34k
}
826
827
6.27k
bool Debugger::GetAsyncExecution() {
828
6.27k
  return !m_command_interpreter_up->GetSynchronous();
829
6.27k
}
830
831
11.9k
void Debugger::SetAsyncExecution(bool async_execution) {
832
11.9k
  m_command_interpreter_up->SetSynchronous(!async_execution);
833
11.9k
}
834
835
455
repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; }
836
837
349
static inline int OpenPipe(int fds[2], std::size_t size) {
838
#ifdef _WIN32
839
  return _pipe(fds, size, O_BINARY);
840
#else
841
349
  (void)size;
842
349
  return pipe(fds);
843
349
#endif
844
349
}
845
846
349
Status Debugger::SetInputString(const char *data) {
847
349
  Status result;
848
349
  enum PIPES { READ, WRITE }; // Indexes for the read and write fds
849
349
  int fds[2] = {-1, -1};
850
851
349
  if (data == nullptr) {
852
0
    result.SetErrorString("String data is null");
853
0
    return result;
854
0
  }
855
856
349
  size_t size = strlen(data);
857
349
  if (size == 0) {
858
0
    result.SetErrorString("String data is empty");
859
0
    return result;
860
0
  }
861
862
349
  if (OpenPipe(fds, size) != 0) {
863
0
    result.SetErrorString(
864
0
        "can't create pipe file descriptors for LLDB commands");
865
0
    return result;
866
0
  }
867
868
349
  write(fds[WRITE], data, size);
869
  // Close the write end of the pipe, so that the command interpreter will exit
870
  // when it consumes all the data.
871
349
  llvm::sys::Process::SafelyCloseFileDescriptor(fds[WRITE]);
872
873
  // Open the read file descriptor as a FILE * that we can return as an input
874
  // handle.
875
349
  FILE *commands_file = fdopen(fds[READ], "rb");
876
349
  if (commands_file == nullptr) {
877
0
    result.SetErrorStringWithFormat("fdopen(%i, \"rb\") failed (errno = %i) "
878
0
                                    "when trying to open LLDB commands pipe",
879
0
                                    fds[READ], errno);
880
0
    llvm::sys::Process::SafelyCloseFileDescriptor(fds[READ]);
881
0
    return result;
882
0
  }
883
884
349
  return SetInputFile(
885
349
      (FileSP)std::make_shared<NativeFile>(commands_file, true));
886
349
}
887
888
809
Status Debugger::SetInputFile(FileSP file_sp) {
889
809
  Status error;
890
809
  repro::DataRecorder *recorder = nullptr;
891
809
  if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator())
892
38
    recorder = g->GetOrCreate<repro::CommandProvider>().GetNewRecorder();
893
894
809
  static std::unique_ptr<repro::MultiLoader<repro::CommandProvider>> loader =
895
809
      repro::MultiLoader<repro::CommandProvider>::Create(
896
809
          repro::Reproducer::Instance().GetLoader());
897
809
  if (loader) {
898
0
    llvm::Optional<std::string> nextfile = loader->GetNextFile();
899
0
    FILE *fh = nextfile ? FileSystem::Instance().Fopen(nextfile->c_str(), "r")
900
0
                        : nullptr;
901
    // FIXME Jonas Devlieghere: shouldn't this error be propagated out to the
902
    // reproducer somehow if fh is NULL?
903
0
    if (fh) {
904
0
      file_sp = std::make_shared<NativeFile>(fh, true);
905
0
    }
906
0
  }
907
908
809
  if (!file_sp || !file_sp->IsValid()) {
909
0
    error.SetErrorString("invalid file");
910
0
    return error;
911
0
  }
912
913
809
  SetInputFile(file_sp, recorder);
914
809
  return error;
915
809
}
916
917
809
void Debugger::SetInputFile(FileSP file_sp, repro::DataRecorder *recorder) {
918
809
  assert(file_sp && file_sp->IsValid());
919
0
  m_input_recorder = recorder;
920
809
  m_input_file_sp = std::move(file_sp);
921
  // Save away the terminal state if that is relevant, so that we can restore
922
  // it in RestoreInputState.
923
809
  SaveInputTerminalState();
924
809
}
925
926
422
void Debugger::SetOutputFile(FileSP file_sp) {
927
422
  assert(file_sp && file_sp->IsValid());
928
0
  m_output_stream_sp = std::make_shared<StreamFile>(file_sp);
929
422
}
930
931
411
void Debugger::SetErrorFile(FileSP file_sp) {
932
411
  assert(file_sp && file_sp->IsValid());
933
0
  m_error_stream_sp = std::make_shared<StreamFile>(file_sp);
934
411
}
935
936
809
void Debugger::SaveInputTerminalState() {
937
809
  int fd = GetInputFile().GetDescriptor();
938
809
  if (fd != File::kInvalidDescriptor)
939
807
    m_terminal_state.Save(fd, true);
940
809
}
941
942
0
void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); }
943
944
378k
ExecutionContext Debugger::GetSelectedExecutionContext() {
945
378k
  bool adopt_selected = true;
946
378k
  ExecutionContextRef exe_ctx_ref(GetSelectedTarget().get(), adopt_selected);
947
378k
  return ExecutionContext(exe_ctx_ref);
948
378k
}
949
950
0
void Debugger::DispatchInputInterrupt() {
951
0
  std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
952
0
  IOHandlerSP reader_sp(m_io_handler_stack.Top());
953
0
  if (reader_sp)
954
0
    reader_sp->Interrupt();
955
0
}
956
957
0
void Debugger::DispatchInputEndOfFile() {
958
0
  std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
959
0
  IOHandlerSP reader_sp(m_io_handler_stack.Top());
960
0
  if (reader_sp)
961
0
    reader_sp->GotEOF();
962
0
}
963
964
6.40k
void Debugger::ClearIOHandlers() {
965
  // The bottom input reader should be the main debugger input reader.  We do
966
  // not want to close that one here.
967
6.40k
  std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
968
6.40k
  while (m_io_handler_stack.GetSize() > 1) {
969
0
    IOHandlerSP reader_sp(m_io_handler_stack.Top());
970
0
    if (reader_sp)
971
0
      PopIOHandler(reader_sp);
972
0
  }
973
6.40k
}
974
975
455
void Debugger::RunIOHandlers() {
976
455
  IOHandlerSP reader_sp = m_io_handler_stack.Top();
977
930
  while (true) {
978
930
    if (!reader_sp)
979
455
      break;
980
981
475
    reader_sp->Run();
982
475
    {
983
475
      std::lock_guard<std::recursive_mutex> guard(
984
475
          m_io_handler_synchronous_mutex);
985
986
      // Remove all input readers that are done from the top of the stack
987
937
      while (true) {
988
937
        IOHandlerSP top_reader_sp = m_io_handler_stack.Top();
989
937
        if (top_reader_sp && 
top_reader_sp->GetIsDone()482
)
990
462
          PopIOHandler(top_reader_sp);
991
475
        else
992
475
          break;
993
937
      }
994
475
      reader_sp = m_io_handler_stack.Top();
995
475
    }
996
475
  }
997
455
  ClearIOHandlers();
998
455
}
999
1000
497
void Debugger::RunIOHandlerSync(const IOHandlerSP &reader_sp) {
1001
497
  std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex);
1002
1003
497
  PushIOHandler(reader_sp);
1004
497
  IOHandlerSP top_reader_sp = reader_sp;
1005
1006
505
  while (top_reader_sp) {
1007
505
    if (!top_reader_sp)
1008
0
      break;
1009
1010
505
    top_reader_sp->Run();
1011
1012
    // Don't unwind past the starting point.
1013
505
    if (top_reader_sp.get() == reader_sp.get()) {
1014
501
      if (PopIOHandler(reader_sp))
1015
497
        break;
1016
501
    }
1017
1018
    // If we pushed new IO handlers, pop them if they're done or restart the
1019
    // loop to run them if they're not.
1020
12
    
while (8
true) {
1021
12
      top_reader_sp = m_io_handler_stack.Top();
1022
12
      if (top_reader_sp && top_reader_sp->GetIsDone()) {
1023
4
        PopIOHandler(top_reader_sp);
1024
        // Don't unwind past the starting point.
1025
4
        if (top_reader_sp.get() == reader_sp.get())
1026
0
          return;
1027
8
      } else {
1028
8
        break;
1029
8
      }
1030
12
    }
1031
8
  }
1032
497
}
1033
1034
0
bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) {
1035
0
  return m_io_handler_stack.IsTop(reader_sp);
1036
0
}
1037
1038
bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type,
1039
0
                                      IOHandler::Type second_top_type) {
1040
0
  return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type);
1041
0
}
1042
1043
273
void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) {
1044
273
  lldb_private::StreamFile &stream =
1045
273
      is_stdout ? 
GetOutputStream()245
:
GetErrorStream()28
;
1046
273
  m_io_handler_stack.PrintAsync(&stream, s, len);
1047
273
}
1048
1049
0
ConstString Debugger::GetTopIOHandlerControlSequence(char ch) {
1050
0
  return m_io_handler_stack.GetTopIOHandlerControlSequence(ch);
1051
0
}
1052
1053
23
const char *Debugger::GetIOHandlerCommandPrefix() {
1054
23
  return m_io_handler_stack.GetTopIOHandlerCommandPrefix();
1055
23
}
1056
1057
12
const char *Debugger::GetIOHandlerHelpPrologue() {
1058
12
  return m_io_handler_stack.GetTopIOHandlerHelpPrologue();
1059
12
}
1060
1061
21.6k
bool Debugger::RemoveIOHandler(const IOHandlerSP &reader_sp) {
1062
21.6k
  return PopIOHandler(reader_sp);
1063
21.6k
}
1064
1065
void Debugger::RunIOHandlerAsync(const IOHandlerSP &reader_sp,
1066
10.1k
                                 bool cancel_top_handler) {
1067
10.1k
  PushIOHandler(reader_sp, cancel_top_handler);
1068
10.1k
}
1069
1070
void Debugger::AdoptTopIOHandlerFilesIfInvalid(FileSP &in, StreamFileSP &out,
1071
7.51k
                                               StreamFileSP &err) {
1072
  // Before an IOHandler runs, it must have in/out/err streams. This function
1073
  // is called when one ore more of the streams are nullptr. We use the top
1074
  // input reader's in/out/err streams, or fall back to the debugger file
1075
  // handles, or we fall back onto stdin/stdout/stderr as a last resort.
1076
1077
7.51k
  std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1078
7.51k
  IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1079
  // If no STDIN has been set, then set it appropriately
1080
7.51k
  if (!in || 
!in->IsValid()485
) {
1081
7.03k
    if (top_reader_sp)
1082
724
      in = top_reader_sp->GetInputFileSP();
1083
6.30k
    else
1084
6.30k
      in = GetInputFileSP();
1085
    // If there is nothing, use stdin
1086
7.03k
    if (!in)
1087
0
      in = std::make_shared<NativeFile>(stdin, false);
1088
7.03k
  }
1089
  // If no STDOUT has been set, then set it appropriately
1090
7.51k
  if (!out || 
!out->GetFile().IsValid()0
) {
1091
7.51k
    if (top_reader_sp)
1092
1.20k
      out = top_reader_sp->GetOutputStreamFileSP();
1093
6.31k
    else
1094
6.31k
      out = GetOutputStreamSP();
1095
    // If there is nothing, use stdout
1096
7.51k
    if (!out)
1097
0
      out = std::make_shared<StreamFile>(stdout, false);
1098
7.51k
  }
1099
  // If no STDERR has been set, then set it appropriately
1100
7.51k
  if (!err || 
!err->GetFile().IsValid()0
) {
1101
7.51k
    if (top_reader_sp)
1102
1.20k
      err = top_reader_sp->GetErrorStreamFileSP();
1103
6.31k
    else
1104
6.31k
      err = GetErrorStreamSP();
1105
    // If there is nothing, use stderr
1106
7.51k
    if (!err)
1107
0
      err = std::make_shared<StreamFile>(stderr, false);
1108
7.51k
  }
1109
7.51k
}
1110
1111
void Debugger::PushIOHandler(const IOHandlerSP &reader_sp,
1112
10.6k
                             bool cancel_top_handler) {
1113
10.6k
  if (!reader_sp)
1114
0
    return;
1115
1116
10.6k
  std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1117
1118
  // Get the current top input reader...
1119
10.6k
  IOHandlerSP top_reader_sp(m_io_handler_stack.Top());
1120
1121
  // Don't push the same IO handler twice...
1122
10.6k
  if (reader_sp == top_reader_sp)
1123
83
    return;
1124
1125
  // Push our new input reader
1126
10.6k
  m_io_handler_stack.Push(reader_sp);
1127
10.6k
  reader_sp->Activate();
1128
1129
  // Interrupt the top input reader to it will exit its Run() function and let
1130
  // this new input reader take over
1131
10.6k
  if (top_reader_sp) {
1132
601
    top_reader_sp->Deactivate();
1133
601
    if (cancel_top_handler)
1134
589
      top_reader_sp->Cancel();
1135
601
  }
1136
10.6k
}
1137
1138
22.6k
bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) {
1139
22.6k
  if (!pop_reader_sp)
1140
0
    return false;
1141
1142
22.6k
  std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex());
1143
1144
  // The reader on the stop of the stack is done, so let the next read on the
1145
  // stack refresh its prompt and if there is one...
1146
22.6k
  if (m_io_handler_stack.IsEmpty())
1147
11.8k
    return false;
1148
1149
10.8k
  IOHandlerSP reader_sp(m_io_handler_stack.Top());
1150
1151
10.8k
  if (pop_reader_sp != reader_sp)
1152
205
    return false;
1153
1154
10.6k
  reader_sp->Deactivate();
1155
10.6k
  reader_sp->Cancel();
1156
10.6k
  m_io_handler_stack.Pop();
1157
1158
10.6k
  reader_sp = m_io_handler_stack.Top();
1159
10.6k
  if (reader_sp)
1160
601
    reader_sp->Activate();
1161
1162
10.6k
  return true;
1163
10.8k
}
1164
1165
2.42k
StreamSP Debugger::GetAsyncOutputStream() {
1166
2.42k
  return std::make_shared<StreamAsynchronousIO>(*this, true);
1167
2.42k
}
1168
1169
1.26k
StreamSP Debugger::GetAsyncErrorStream() {
1170
1.26k
  return std::make_shared<StreamAsynchronousIO>(*this, false);
1171
1.26k
}
1172
1173
163
size_t Debugger::GetNumDebuggers() {
1174
163
  if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1175
163
    std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1176
163
    return g_debugger_list_ptr->size();
1177
163
  }
1178
0
  return 0;
1179
163
}
1180
1181
88
lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) {
1182
88
  DebuggerSP debugger_sp;
1183
1184
88
  if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1185
88
    std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1186
88
    if (index < g_debugger_list_ptr->size())
1187
88
      debugger_sp = g_debugger_list_ptr->at(index);
1188
88
  }
1189
1190
88
  return debugger_sp;
1191
88
}
1192
1193
9.29k
DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) {
1194
9.29k
  DebuggerSP debugger_sp;
1195
1196
9.29k
  if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) {
1197
9.29k
    std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1198
9.29k
    DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1199
9.33k
    for (pos = g_debugger_list_ptr->begin(); pos != end; 
++pos32
) {
1200
9.33k
      if ((*pos)->GetID() == id) {
1201
9.29k
        debugger_sp = *pos;
1202
9.29k
        break;
1203
9.29k
      }
1204
9.33k
    }
1205
9.29k
  }
1206
9.29k
  return debugger_sp;
1207
9.29k
}
1208
1209
bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format,
1210
                                         const SymbolContext *sc,
1211
                                         const SymbolContext *prev_sc,
1212
                                         const ExecutionContext *exe_ctx,
1213
1.94M
                                         const Address *addr, Stream &s) {
1214
1.94M
  FormatEntity::Entry format_entry;
1215
1216
1.94M
  if (format == nullptr) {
1217
968k
    if (exe_ctx != nullptr && exe_ctx->HasTargetScope())
1218
968k
      format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat();
1219
968k
    if (format == nullptr) {
1220
0
      FormatEntity::Parse("${addr}: ", format_entry);
1221
0
      format = &format_entry;
1222
0
    }
1223
968k
  }
1224
1.94M
  bool function_changed = false;
1225
1.94M
  bool initial_function = false;
1226
1.94M
  if (prev_sc && 
(968k
prev_sc->function968k
||
prev_sc->symbol968k
)) {
1227
940k
    if (sc && (sc->function || 
sc->symbol939k
)) {
1228
940k
      if (prev_sc->symbol && sc->symbol) {
1229
940k
        if (!sc->symbol->Compare(prev_sc->symbol->GetName(),
1230
940k
                                 prev_sc->symbol->GetType())) {
1231
7
          function_changed = true;
1232
7
        }
1233
940k
      } else 
if (0
prev_sc->function0
&&
sc->function0
) {
1234
0
        if (prev_sc->function->GetMangled() != sc->function->GetMangled()) {
1235
0
          function_changed = true;
1236
0
        }
1237
0
      }
1238
940k
    }
1239
940k
  }
1240
  // The first context on a list of instructions will have a prev_sc that has
1241
  // no Function or Symbol -- if SymbolContext had an IsValid() method, it
1242
  // would return false.  But we do get a prev_sc pointer.
1243
1.94M
  if ((sc && 
(1.93M
sc->function1.93M
||
sc->symbol1.93M
)) &&
prev_sc1.93M
&&
1244
1.94M
      
(968k
prev_sc->function == nullptr968k
&&
prev_sc->symbol == nullptr967k
)) {
1245
28.3k
    initial_function = true;
1246
28.3k
  }
1247
1.94M
  return FormatEntity::Format(*format, s, sc, exe_ctx, addr, nullptr,
1248
1.94M
                              function_changed, initial_function);
1249
1.94M
}
1250
1251
void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback,
1252
1
                                  void *baton) {
1253
  // For simplicity's sake, I am not going to deal with how to close down any
1254
  // open logging streams, I just redirect everything from here on out to the
1255
  // callback.
1256
1
  m_log_callback_stream_sp =
1257
1
      std::make_shared<StreamCallback>(log_callback, baton);
1258
1
}
1259
1260
0
ConstString Debugger::ProgressEventData::GetFlavorString() {
1261
0
  static ConstString g_flavor("Debugger::ProgressEventData");
1262
0
  return g_flavor;
1263
0
}
1264
1265
0
ConstString Debugger::ProgressEventData::GetFlavor() const {
1266
0
  return Debugger::ProgressEventData::GetFlavorString();
1267
0
}
1268
1269
0
void Debugger::ProgressEventData::Dump(Stream *s) const {
1270
0
  s->Printf(" id = %" PRIu64 ", message = \"%s\"", m_id, m_message.c_str());
1271
0
  if (m_completed == 0 || m_completed == m_total)
1272
0
    s->Printf(", type = %s", m_completed == 0 ? "start" : "end");
1273
0
  else
1274
0
    s->PutCString(", type = update");
1275
  // If m_total is UINT64_MAX, there is no progress to report, just "start"
1276
  // and "end". If it isn't we will show the completed and total amounts.
1277
0
  if (m_total != UINT64_MAX)
1278
0
    s->Printf(", progress = %" PRIu64 " of %" PRIu64, m_completed, m_total);
1279
0
}
1280
1281
const Debugger::ProgressEventData *
1282
0
Debugger::ProgressEventData::GetEventDataFromEvent(const Event *event_ptr) {
1283
0
  if (event_ptr)
1284
0
    if (const EventData *event_data = event_ptr->GetData())
1285
0
      if (event_data->GetFlavor() == ProgressEventData::GetFlavorString())
1286
0
        return static_cast<const ProgressEventData *>(event_ptr->GetData());
1287
0
  return nullptr;
1288
0
}
1289
1290
static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id,
1291
                                  const std::string &message,
1292
                                  uint64_t completed, uint64_t total,
1293
349k
                                  bool is_debugger_specific) {
1294
  // Only deliver progress events if we have any progress listeners.
1295
349k
  const uint32_t event_type = Debugger::eBroadcastBitProgress;
1296
349k
  if (!debugger.GetBroadcaster().EventTypeHasListeners(event_type))
1297
349k
    return;
1298
0
  EventSP event_sp(new Event(event_type, new Debugger::ProgressEventData(
1299
0
                                             progress_id, message, completed,
1300
0
                                             total, is_debugger_specific)));
1301
0
  debugger.GetBroadcaster().BroadcastEvent(event_sp);
1302
0
}
1303
1304
void Debugger::ReportProgress(uint64_t progress_id, const std::string &message,
1305
                              uint64_t completed, uint64_t total,
1306
342k
                              llvm::Optional<lldb::user_id_t> debugger_id) {
1307
  // Check if this progress is for a specific debugger.
1308
342k
  if (debugger_id.hasValue()) {
1309
    // It is debugger specific, grab it and deliver the event if the debugger
1310
    // still exists.
1311
0
    DebuggerSP debugger_sp = FindDebuggerWithID(*debugger_id);
1312
0
    if (debugger_sp)
1313
0
      PrivateReportProgress(*debugger_sp, progress_id, message, completed,
1314
0
                            total, /*is_debugger_specific*/ true);
1315
0
    return;
1316
0
  }
1317
  // The progress event is not debugger specific, iterate over all debuggers
1318
  // and deliver a progress event to each one.
1319
342k
  if (g_debugger_list_ptr && 
g_debugger_list_mutex_ptr342k
) {
1320
342k
    std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr);
1321
342k
    DebuggerList::iterator pos, end = g_debugger_list_ptr->end();
1322
692k
    for (pos = g_debugger_list_ptr->begin(); pos != end; 
++pos349k
)
1323
349k
      PrivateReportProgress(*(*pos), progress_id, message, completed, total,
1324
349k
                            /*is_debugger_specific*/ false);
1325
342k
  }
1326
342k
}
1327
1328
bool Debugger::EnableLog(llvm::StringRef channel,
1329
                         llvm::ArrayRef<const char *> categories,
1330
                         llvm::StringRef log_file, uint32_t log_options,
1331
67
                         llvm::raw_ostream &error_stream) {
1332
67
  const bool should_close = true;
1333
67
  const bool unbuffered = true;
1334
1335
67
  std::shared_ptr<llvm::raw_ostream> log_stream_sp;
1336
67
  if (m_log_callback_stream_sp) {
1337
1
    log_stream_sp = m_log_callback_stream_sp;
1338
    // For now when using the callback mode you always get thread & timestamp.
1339
1
    log_options |=
1340
1
        LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME;
1341
66
  } else if (log_file.empty()) {
1342
24
    log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1343
24
        GetOutputFile().GetDescriptor(), !should_close, unbuffered);
1344
42
  } else {
1345
42
    auto pos = m_log_streams.find(log_file);
1346
42
    if (pos != m_log_streams.end())
1347
9
      log_stream_sp = pos->second.lock();
1348
42
    if (!log_stream_sp) {
1349
42
      File::OpenOptions flags =
1350
42
          File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate;
1351
42
      if (log_options & LLDB_LOG_OPTION_APPEND)
1352
1
        flags |= File::eOpenOptionAppend;
1353
41
      else
1354
41
        flags |= File::eOpenOptionTruncate;
1355
42
      llvm::Expected<FileUP> file = FileSystem::Instance().Open(
1356
42
          FileSpec(log_file), flags, lldb::eFilePermissionsFileDefault, false);
1357
42
      if (!file) {
1358
1
        error_stream << "Unable to open log file '" << log_file
1359
1
                     << "': " << llvm::toString(file.takeError()) << "\n";
1360
1
        return false;
1361
1
      }
1362
1363
41
      log_stream_sp = std::make_shared<llvm::raw_fd_ostream>(
1364
41
          (*file)->GetDescriptor(), should_close, unbuffered);
1365
41
      m_log_streams[log_file] = log_stream_sp;
1366
41
    }
1367
42
  }
1368
66
  assert(log_stream_sp);
1369
1370
66
  if (log_options == 0)
1371
60
    log_options =
1372
60
        LLDB_LOG_OPTION_PREPEND_THREAD_NAME | LLDB_LOG_OPTION_THREADSAFE;
1373
1374
66
  return Log::EnableLogChannel(log_stream_sp, log_options, channel, categories,
1375
66
                               error_stream);
1376
67
}
1377
1378
ScriptInterpreter *
1379
Debugger::GetScriptInterpreter(bool can_create,
1380
7.67k
                               llvm::Optional<lldb::ScriptLanguage> language) {
1381
7.67k
  std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex);
1382
7.67k
  lldb::ScriptLanguage script_language =
1383
7.67k
      language ? 
*language286
:
GetScriptLanguage()7.39k
;
1384
1385
7.67k
  if (!m_script_interpreters[script_language]) {
1386
1.44k
    if (!can_create)
1387
0
      return nullptr;
1388
1.44k
    m_script_interpreters[script_language] =
1389
1.44k
        PluginManager::GetScriptInterpreterForLanguage(script_language, *this);
1390
1.44k
  }
1391
1392
7.67k
  return m_script_interpreters[script_language].get();
1393
7.67k
}
1394
1395
18
SourceManager &Debugger::GetSourceManager() {
1396
18
  if (!m_source_manager_up)
1397
7
    m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
1398
18
  return *m_source_manager_up;
1399
18
}
1400
1401
// This function handles events that were broadcast by the process.
1402
133
void Debugger::HandleBreakpointEvent(const EventSP &event_sp) {
1403
133
  using namespace lldb;
1404
133
  const uint32_t event_type =
1405
133
      Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent(
1406
133
          event_sp);
1407
1408
  //    if (event_type & eBreakpointEventTypeAdded
1409
  //        || event_type & eBreakpointEventTypeRemoved
1410
  //        || event_type & eBreakpointEventTypeEnabled
1411
  //        || event_type & eBreakpointEventTypeDisabled
1412
  //        || event_type & eBreakpointEventTypeCommandChanged
1413
  //        || event_type & eBreakpointEventTypeConditionChanged
1414
  //        || event_type & eBreakpointEventTypeIgnoreChanged
1415
  //        || event_type & eBreakpointEventTypeLocationsResolved)
1416
  //    {
1417
  //        // Don't do anything about these events, since the breakpoint
1418
  //        commands already echo these actions.
1419
  //    }
1420
  //
1421
133
  if (event_type & eBreakpointEventTypeLocationsAdded) {
1422
3
    uint32_t num_new_locations =
1423
3
        Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent(
1424
3
            event_sp);
1425
3
    if (num_new_locations > 0) {
1426
3
      BreakpointSP breakpoint =
1427
3
          Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp);
1428
3
      StreamSP output_sp(GetAsyncOutputStream());
1429
3
      if (output_sp) {
1430
3
        output_sp->Printf("%d location%s added to breakpoint %d\n",
1431
3
                          num_new_locations, num_new_locations == 1 ? "" : 
"s"0
,
1432
3
                          breakpoint->GetID());
1433
3
        output_sp->Flush();
1434
3
      }
1435
3
    }
1436
3
  }
1437
  //    else if (event_type & eBreakpointEventTypeLocationsRemoved)
1438
  //    {
1439
  //        // These locations just get disabled, not sure it is worth spamming
1440
  //        folks about this on the command line.
1441
  //    }
1442
  //    else if (event_type & eBreakpointEventTypeLocationsResolved)
1443
  //    {
1444
  //        // This might be an interesting thing to note, but I'm going to
1445
  //        leave it quiet for now, it just looked noisy.
1446
  //    }
1447
133
}
1448
1449
void Debugger::FlushProcessOutput(Process &process, bool flush_stdout,
1450
1.21k
                                  bool flush_stderr) {
1451
1.21k
  const auto &flush = [&](Stream &stream,
1452
2.36k
                          size_t (Process::*get)(char *, size_t, Status &)) {
1453
2.36k
    Status error;
1454
2.36k
    size_t len;
1455
2.36k
    char buffer[1024];
1456
2.41k
    while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0)
1457
48
      stream.Write(buffer, len);
1458
2.36k
    stream.Flush();
1459
2.36k
  };
1460
1461
1.21k
  std::lock_guard<std::mutex> guard(m_output_flush_mutex);
1462
1.21k
  if (flush_stdout)
1463
1.21k
    flush(*GetAsyncOutputStream(), &Process::GetSTDOUT);
1464
1.21k
  if (flush_stderr)
1465
1.14k
    flush(*GetAsyncErrorStream(), &Process::GetSTDERR);
1466
1.21k
}
1467
1468
// This function handles events that were broadcast by the process.
1469
85
void Debugger::HandleProcessEvent(const EventSP &event_sp) {
1470
85
  using namespace lldb;
1471
85
  const uint32_t event_type = event_sp->GetType();
1472
85
  ProcessSP process_sp =
1473
85
      (event_type == Process::eBroadcastBitStructuredData)
1474
85
          ? 
EventDataStructuredData::GetProcessFromEvent(event_sp.get())0
1475
85
          : Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
1476
1477
85
  StreamSP output_stream_sp = GetAsyncOutputStream();
1478
85
  StreamSP error_stream_sp = GetAsyncErrorStream();
1479
85
  const bool gui_enabled = IsForwardingEvents();
1480
1481
85
  if (!gui_enabled) {
1482
85
    bool pop_process_io_handler = false;
1483
85
    assert(process_sp);
1484
1485
0
    bool state_is_stopped = false;
1486
85
    const bool got_state_changed =
1487
85
        (event_type & Process::eBroadcastBitStateChanged) != 0;
1488
85
    const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0;
1489
85
    const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0;
1490
85
    const bool got_structured_data =
1491
85
        (event_type & Process::eBroadcastBitStructuredData) != 0;
1492
1493
85
    if (got_state_changed) {
1494
10
      StateType event_state =
1495
10
          Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1496
10
      state_is_stopped = StateIsStoppedState(event_state, false);
1497
10
    }
1498
1499
    // Display running state changes first before any STDIO
1500
85
    if (got_state_changed && 
!state_is_stopped10
) {
1501
5
      Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1502
5
                                              pop_process_io_handler);
1503
5
    }
1504
1505
    // Now display STDOUT and STDERR
1506
85
    FlushProcessOutput(*process_sp, got_stdout || 
got_state_changed10
,
1507
85
                       got_stderr || got_state_changed);
1508
1509
    // Give structured data events an opportunity to display.
1510
85
    if (got_structured_data) {
1511
0
      StructuredDataPluginSP plugin_sp =
1512
0
          EventDataStructuredData::GetPluginFromEvent(event_sp.get());
1513
0
      if (plugin_sp) {
1514
0
        auto structured_data_sp =
1515
0
            EventDataStructuredData::GetObjectFromEvent(event_sp.get());
1516
0
        if (output_stream_sp) {
1517
0
          StreamString content_stream;
1518
0
          Status error =
1519
0
              plugin_sp->GetDescription(structured_data_sp, content_stream);
1520
0
          if (error.Success()) {
1521
0
            if (!content_stream.GetString().empty()) {
1522
              // Add newline.
1523
0
              content_stream.PutChar('\n');
1524
0
              content_stream.Flush();
1525
1526
              // Print it.
1527
0
              output_stream_sp->PutCString(content_stream.GetString());
1528
0
            }
1529
0
          } else {
1530
0
            error_stream_sp->Format("Failed to print structured "
1531
0
                                    "data with plugin {0}: {1}",
1532
0
                                    plugin_sp->GetPluginName(), error);
1533
0
          }
1534
0
        }
1535
0
      }
1536
0
    }
1537
1538
    // Now display any stopped state changes after any STDIO
1539
85
    if (got_state_changed && 
state_is_stopped10
) {
1540
5
      Process::HandleProcessStateChangedEvent(event_sp, output_stream_sp.get(),
1541
5
                                              pop_process_io_handler);
1542
5
    }
1543
1544
85
    output_stream_sp->Flush();
1545
85
    error_stream_sp->Flush();
1546
1547
85
    if (pop_process_io_handler)
1548
5
      process_sp->PopProcessIOHandler();
1549
85
  }
1550
85
}
1551
1552
15
void Debugger::HandleThreadEvent(const EventSP &event_sp) {
1553
  // At present the only thread event we handle is the Frame Changed event, and
1554
  // all we do for that is just reprint the thread status for that thread.
1555
15
  using namespace lldb;
1556
15
  const uint32_t event_type = event_sp->GetType();
1557
15
  const bool stop_format = true;
1558
15
  if (event_type == Thread::eBroadcastBitStackChanged ||
1559
15
      event_type == Thread::eBroadcastBitThreadSelected) {
1560
15
    ThreadSP thread_sp(
1561
15
        Thread::ThreadEventData::GetThreadFromEvent(event_sp.get()));
1562
15
    if (thread_sp) {
1563
15
      thread_sp->GetStatus(*GetAsyncOutputStream(), 0, 1, 1, stop_format);
1564
15
    }
1565
15
  }
1566
15
}
1567
1568
9.93k
bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; }
1569
1570
0
void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) {
1571
0
  m_forward_listener_sp = listener_sp;
1572
0
}
1573
1574
0
void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) {
1575
0
  m_forward_listener_sp.reset();
1576
0
}
1577
1578
454
void Debugger::DefaultEventHandler() {
1579
454
  ListenerSP listener_sp(GetListener());
1580
454
  ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass());
1581
454
  ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass());
1582
454
  ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass());
1583
454
  BroadcastEventSpec target_event_spec(broadcaster_class_target,
1584
454
                                       Target::eBroadcastBitBreakpointChanged);
1585
1586
454
  BroadcastEventSpec process_event_spec(
1587
454
      broadcaster_class_process,
1588
454
      Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT |
1589
454
          Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData);
1590
1591
454
  BroadcastEventSpec thread_event_spec(broadcaster_class_thread,
1592
454
                                       Thread::eBroadcastBitStackChanged |
1593
454
                                           Thread::eBroadcastBitThreadSelected);
1594
1595
454
  listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1596
454
                                          target_event_spec);
1597
454
  listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1598
454
                                          process_event_spec);
1599
454
  listener_sp->StartListeningForEventSpec(m_broadcaster_manager_sp,
1600
454
                                          thread_event_spec);
1601
454
  listener_sp->StartListeningForEvents(
1602
454
      m_command_interpreter_up.get(),
1603
454
      CommandInterpreter::eBroadcastBitQuitCommandReceived |
1604
454
          CommandInterpreter::eBroadcastBitAsynchronousOutputData |
1605
454
          CommandInterpreter::eBroadcastBitAsynchronousErrorData);
1606
1607
  // Let the thread that spawned us know that we have started up and that we
1608
  // are now listening to all required events so no events get missed
1609
454
  m_sync_broadcaster.BroadcastEvent(eBroadcastBitEventThreadIsListening);
1610
1611
454
  bool done = false;
1612
1.14k
  while (!done) {
1613
687
    EventSP event_sp;
1614
687
    if (listener_sp->GetEvent(event_sp, llvm::None)) {
1615
687
      if (event_sp) {
1616
687
        Broadcaster *broadcaster = event_sp->GetBroadcaster();
1617
687
        if (broadcaster) {
1618
687
          uint32_t event_type = event_sp->GetType();
1619
687
          ConstString broadcaster_class(broadcaster->GetBroadcasterClass());
1620
687
          if (broadcaster_class == broadcaster_class_process) {
1621
85
            HandleProcessEvent(event_sp);
1622
602
          } else if (broadcaster_class == broadcaster_class_target) {
1623
133
            if (Breakpoint::BreakpointEventData::GetEventDataFromEvent(
1624
133
                    event_sp.get())) {
1625
133
              HandleBreakpointEvent(event_sp);
1626
133
            }
1627
469
          } else if (broadcaster_class == broadcaster_class_thread) {
1628
15
            HandleThreadEvent(event_sp);
1629
454
          } else if (broadcaster == m_command_interpreter_up.get()) {
1630
454
            if (event_type &
1631
454
                CommandInterpreter::eBroadcastBitQuitCommandReceived) {
1632
454
              done = true;
1633
454
            } else 
if (0
event_type &
1634
0
                       CommandInterpreter::eBroadcastBitAsynchronousErrorData) {
1635
0
              const char *data = static_cast<const char *>(
1636
0
                  EventDataBytes::GetBytesFromEvent(event_sp.get()));
1637
0
              if (data && data[0]) {
1638
0
                StreamSP error_sp(GetAsyncErrorStream());
1639
0
                if (error_sp) {
1640
0
                  error_sp->PutCString(data);
1641
0
                  error_sp->Flush();
1642
0
                }
1643
0
              }
1644
0
            } else if (event_type & CommandInterpreter::
1645
0
                                        eBroadcastBitAsynchronousOutputData) {
1646
0
              const char *data = static_cast<const char *>(
1647
0
                  EventDataBytes::GetBytesFromEvent(event_sp.get()));
1648
0
              if (data && data[0]) {
1649
0
                StreamSP output_sp(GetAsyncOutputStream());
1650
0
                if (output_sp) {
1651
0
                  output_sp->PutCString(data);
1652
0
                  output_sp->Flush();
1653
0
                }
1654
0
              }
1655
0
            }
1656
454
          }
1657
687
        }
1658
1659
687
        if (m_forward_listener_sp)
1660
0
          m_forward_listener_sp->AddEvent(event_sp);
1661
687
      }
1662
687
    }
1663
687
  }
1664
454
}
1665
1666
454
lldb::thread_result_t Debugger::EventHandlerThread(lldb::thread_arg_t arg) {
1667
454
  ((Debugger *)arg)->DefaultEventHandler();
1668
454
  return {};
1669
454
}
1670
1671
454
bool Debugger::StartEventHandlerThread() {
1672
454
  if (!m_event_handler_thread.IsJoinable()) {
1673
    // We must synchronize with the DefaultEventHandler() thread to ensure it
1674
    // is up and running and listening to events before we return from this
1675
    // function. We do this by listening to events for the
1676
    // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster
1677
454
    ConstString full_name("lldb.debugger.event-handler");
1678
454
    ListenerSP listener_sp(Listener::MakeListener(full_name.AsCString()));
1679
454
    listener_sp->StartListeningForEvents(&m_sync_broadcaster,
1680
454
                                         eBroadcastBitEventThreadIsListening);
1681
1682
454
    llvm::StringRef thread_name =
1683
454
        full_name.GetLength() < llvm::get_max_thread_name_length()
1684
454
            ? full_name.GetStringRef()
1685
454
            : 
"dbg.evt-handler"0
;
1686
1687
    // Use larger 8MB stack for this thread
1688
454
    llvm::Expected<HostThread> event_handler_thread =
1689
454
        ThreadLauncher::LaunchThread(thread_name, EventHandlerThread, this,
1690
454
                                     g_debugger_event_thread_stack_bytes);
1691
1692
454
    if (event_handler_thread) {
1693
454
      m_event_handler_thread = *event_handler_thread;
1694
454
    } else {
1695
0
      LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1696
0
               "failed to launch host thread: {}",
1697
0
               llvm::toString(event_handler_thread.takeError()));
1698
0
    }
1699
1700
    // Make sure DefaultEventHandler() is running and listening to events
1701
    // before we return from this function. We are only listening for events of
1702
    // type eBroadcastBitEventThreadIsListening so we don't need to check the
1703
    // event, we just need to wait an infinite amount of time for it (nullptr
1704
    // timeout as the first parameter)
1705
454
    lldb::EventSP event_sp;
1706
454
    listener_sp->GetEvent(event_sp, llvm::None);
1707
454
  }
1708
454
  return m_event_handler_thread.IsJoinable();
1709
454
}
1710
1711
6.40k
void Debugger::StopEventHandlerThread() {
1712
6.40k
  if (m_event_handler_thread.IsJoinable()) {
1713
454
    GetCommandInterpreter().BroadcastEvent(
1714
454
        CommandInterpreter::eBroadcastBitQuitCommandReceived);
1715
454
    m_event_handler_thread.Join(nullptr);
1716
454
  }
1717
6.40k
}
1718
1719
2
lldb::thread_result_t Debugger::IOHandlerThread(lldb::thread_arg_t arg) {
1720
2
  Debugger *debugger = (Debugger *)arg;
1721
2
  debugger->RunIOHandlers();
1722
2
  debugger->StopEventHandlerThread();
1723
2
  return {};
1724
2
}
1725
1726
0
bool Debugger::HasIOHandlerThread() { return m_io_handler_thread.IsJoinable(); }
1727
1728
2
bool Debugger::StartIOHandlerThread() {
1729
2
  if (!m_io_handler_thread.IsJoinable()) {
1730
2
    llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread(
1731
2
        "lldb.debugger.io-handler", IOHandlerThread, this,
1732
2
        8 * 1024 * 1024); // Use larger 8MB stack for this thread
1733
2
    if (io_handler_thread) {
1734
2
      m_io_handler_thread = *io_handler_thread;
1735
2
    } else {
1736
0
      LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
1737
0
               "failed to launch host thread: {}",
1738
0
               llvm::toString(io_handler_thread.takeError()));
1739
0
    }
1740
2
  }
1741
2
  return m_io_handler_thread.IsJoinable();
1742
2
}
1743
1744
5.94k
void Debugger::StopIOHandlerThread() {
1745
5.94k
  if (m_io_handler_thread.IsJoinable()) {
1746
2
    GetInputFile().Close();
1747
2
    m_io_handler_thread.Join(nullptr);
1748
2
  }
1749
5.94k
}
1750
1751
0
void Debugger::JoinIOHandlerThread() {
1752
0
  if (HasIOHandlerThread()) {
1753
0
    thread_result_t result;
1754
0
    m_io_handler_thread.Join(&result);
1755
0
    m_io_handler_thread = LLDB_INVALID_HOST_THREAD;
1756
0
  }
1757
0
}
1758
1759
12.4k
Target &Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) {
1760
12.4k
  if (!prefer_dummy) {
1761
12.4k
    if (TargetSP target = m_target_list.GetSelectedTarget())
1762
12.3k
      return *target;
1763
12.4k
  }
1764
141
  return GetDummyTarget();
1765
12.4k
}
1766
1767
3
Status Debugger::RunREPL(LanguageType language, const char *repl_options) {
1768
3
  Status err;
1769
3
  FileSpec repl_executable;
1770
1771
3
  if (language == eLanguageTypeUnknown)
1772
1
    language = GetREPLLanguage();
1773
1774
3
  if (language == eLanguageTypeUnknown) {
1775
1
    LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs();
1776
1777
1
    if (auto single_lang = repl_languages.GetSingularLanguage()) {
1778
0
      language = *single_lang;
1779
1
    } else if (repl_languages.Empty()) {
1780
0
      err.SetErrorString(
1781
0
          "LLDB isn't configured with REPL support for any languages.");
1782
0
      return err;
1783
1
    } else {
1784
1
      err.SetErrorString(
1785
1
          "Multiple possible REPL languages.  Please specify a language.");
1786
1
      return err;
1787
1
    }
1788
1
  }
1789
1790
2
  Target *const target =
1791
2
      nullptr; // passing in an empty target means the REPL must create one
1792
1793
2
  REPLSP repl_sp(REPL::Create(err, language, this, target, repl_options));
1794
1795
2
  if (!err.Success()) {
1796
1
    return err;
1797
1
  }
1798
1799
1
  if (!repl_sp) {
1800
1
    err.SetErrorStringWithFormat("couldn't find a REPL for %s",
1801
1
                                 Language::GetNameForLanguageType(language));
1802
1
    return err;
1803
1
  }
1804
1805
0
  repl_sp->SetCompilerOptions(repl_options);
1806
0
  repl_sp->RunLoop();
1807
1808
0
  return err;
1809
1
}