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/DebuggerEvents.h" |
13 | #include "lldb/Core/FormatEntity.h" |
14 | #include "lldb/Core/Mangled.h" |
15 | #include "lldb/Core/ModuleList.h" |
16 | #include "lldb/Core/ModuleSpec.h" |
17 | #include "lldb/Core/PluginManager.h" |
18 | #include "lldb/Core/Progress.h" |
19 | #include "lldb/Core/StreamAsynchronousIO.h" |
20 | #include "lldb/DataFormatters/DataVisualization.h" |
21 | #include "lldb/Expression/REPL.h" |
22 | #include "lldb/Host/File.h" |
23 | #include "lldb/Host/FileSystem.h" |
24 | #include "lldb/Host/HostInfo.h" |
25 | #include "lldb/Host/StreamFile.h" |
26 | #include "lldb/Host/Terminal.h" |
27 | #include "lldb/Host/ThreadLauncher.h" |
28 | #include "lldb/Interpreter/CommandInterpreter.h" |
29 | #include "lldb/Interpreter/CommandReturnObject.h" |
30 | #include "lldb/Interpreter/OptionValue.h" |
31 | #include "lldb/Interpreter/OptionValueLanguage.h" |
32 | #include "lldb/Interpreter/OptionValueProperties.h" |
33 | #include "lldb/Interpreter/OptionValueSInt64.h" |
34 | #include "lldb/Interpreter/OptionValueString.h" |
35 | #include "lldb/Interpreter/Property.h" |
36 | #include "lldb/Interpreter/ScriptInterpreter.h" |
37 | #include "lldb/Symbol/Function.h" |
38 | #include "lldb/Symbol/Symbol.h" |
39 | #include "lldb/Symbol/SymbolContext.h" |
40 | #include "lldb/Target/Language.h" |
41 | #include "lldb/Target/Process.h" |
42 | #include "lldb/Target/StructuredDataPlugin.h" |
43 | #include "lldb/Target/Target.h" |
44 | #include "lldb/Target/TargetList.h" |
45 | #include "lldb/Target/Thread.h" |
46 | #include "lldb/Target/ThreadList.h" |
47 | #include "lldb/Utility/AnsiTerminal.h" |
48 | #include "lldb/Utility/Event.h" |
49 | #include "lldb/Utility/LLDBLog.h" |
50 | #include "lldb/Utility/Listener.h" |
51 | #include "lldb/Utility/Log.h" |
52 | #include "lldb/Utility/State.h" |
53 | #include "lldb/Utility/Stream.h" |
54 | #include "lldb/Utility/StreamString.h" |
55 | #include "lldb/lldb-enumerations.h" |
56 | |
57 | #if defined(_WIN32) |
58 | #include "lldb/Host/windows/PosixApi.h" |
59 | #include "lldb/Host/windows/windows.h" |
60 | #endif |
61 | |
62 | #include "llvm/ADT/STLExtras.h" |
63 | #include "llvm/ADT/StringRef.h" |
64 | #include "llvm/ADT/iterator.h" |
65 | #include "llvm/Support/DynamicLibrary.h" |
66 | #include "llvm/Support/FileSystem.h" |
67 | #include "llvm/Support/Process.h" |
68 | #include "llvm/Support/ThreadPool.h" |
69 | #include "llvm/Support/Threading.h" |
70 | #include "llvm/Support/raw_ostream.h" |
71 | |
72 | #include <cstdio> |
73 | #include <cstdlib> |
74 | #include <cstring> |
75 | #include <list> |
76 | #include <memory> |
77 | #include <mutex> |
78 | #include <optional> |
79 | #include <set> |
80 | #include <string> |
81 | #include <system_error> |
82 | |
83 | // Includes for pipe() |
84 | #if defined(_WIN32) |
85 | #include <fcntl.h> |
86 | #include <io.h> |
87 | #else |
88 | #include <unistd.h> |
89 | #endif |
90 | |
91 | namespace lldb_private { |
92 | class Address; |
93 | } |
94 | |
95 | using namespace lldb; |
96 | using namespace lldb_private; |
97 | |
98 | static lldb::user_id_t g_unique_id = 1; |
99 | static size_t g_debugger_event_thread_stack_bytes = 8 * 1024 * 1024; |
100 | |
101 | #pragma mark Static Functions |
102 | |
103 | static std::recursive_mutex *g_debugger_list_mutex_ptr = |
104 | nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain |
105 | static Debugger::DebuggerList *g_debugger_list_ptr = |
106 | nullptr; // NOTE: intentional leak to avoid issues with C++ destructor chain |
107 | static llvm::DefaultThreadPool *g_thread_pool = nullptr; |
108 | |
109 | static constexpr OptionEnumValueElement g_show_disassembly_enum_values[] = { |
110 | { |
111 | .value: Debugger::eStopDisassemblyTypeNever, |
112 | .string_value: "never" , |
113 | .usage: "Never show disassembly when displaying a stop context." , |
114 | }, |
115 | { |
116 | .value: Debugger::eStopDisassemblyTypeNoDebugInfo, |
117 | .string_value: "no-debuginfo" , |
118 | .usage: "Show disassembly when there is no debug information." , |
119 | }, |
120 | { |
121 | .value: Debugger::eStopDisassemblyTypeNoSource, |
122 | .string_value: "no-source" , |
123 | .usage: "Show disassembly when there is no source information, or the source " |
124 | "file " |
125 | "is missing when displaying a stop context." , |
126 | }, |
127 | { |
128 | .value: Debugger::eStopDisassemblyTypeAlways, |
129 | .string_value: "always" , |
130 | .usage: "Always show disassembly when displaying a stop context." , |
131 | }, |
132 | }; |
133 | |
134 | static constexpr OptionEnumValueElement g_language_enumerators[] = { |
135 | { |
136 | .value: eScriptLanguageNone, |
137 | .string_value: "none" , |
138 | .usage: "Disable scripting languages." , |
139 | }, |
140 | { |
141 | .value: eScriptLanguagePython, |
142 | .string_value: "python" , |
143 | .usage: "Select python as the default scripting language." , |
144 | }, |
145 | { |
146 | .value: eScriptLanguageDefault, |
147 | .string_value: "default" , |
148 | .usage: "Select the lldb default as the default scripting language." , |
149 | }, |
150 | }; |
151 | |
152 | static constexpr OptionEnumValueElement g_dwim_print_verbosities[] = { |
153 | {.value: eDWIMPrintVerbosityNone, .string_value: "none" , |
154 | .usage: "Use no verbosity when running dwim-print." }, |
155 | {.value: eDWIMPrintVerbosityExpression, .string_value: "expression" , |
156 | .usage: "Use partial verbosity when running dwim-print - display a message when " |
157 | "`expression` evaluation is used." }, |
158 | {.value: eDWIMPrintVerbosityFull, .string_value: "full" , |
159 | .usage: "Use full verbosity when running dwim-print." }, |
160 | }; |
161 | |
162 | static constexpr OptionEnumValueElement s_stop_show_column_values[] = { |
163 | { |
164 | .value: eStopShowColumnAnsiOrCaret, |
165 | .string_value: "ansi-or-caret" , |
166 | .usage: "Highlight the stop column with ANSI terminal codes when color/ANSI " |
167 | "mode is enabled; otherwise, fall back to using a text-only caret (^) " |
168 | "as if \"caret-only\" mode was selected." , |
169 | }, |
170 | { |
171 | .value: eStopShowColumnAnsi, |
172 | .string_value: "ansi" , |
173 | .usage: "Highlight the stop column with ANSI terminal codes when running LLDB " |
174 | "with color/ANSI enabled." , |
175 | }, |
176 | { |
177 | .value: eStopShowColumnCaret, |
178 | .string_value: "caret" , |
179 | .usage: "Highlight the stop column with a caret character (^) underneath the " |
180 | "stop column. This method introduces a new line in source listings " |
181 | "that display thread stop locations." , |
182 | }, |
183 | { |
184 | .value: eStopShowColumnNone, |
185 | .string_value: "none" , |
186 | .usage: "Do not highlight the stop column." , |
187 | }, |
188 | }; |
189 | |
190 | #define LLDB_PROPERTIES_debugger |
191 | #include "CoreProperties.inc" |
192 | |
193 | enum { |
194 | #define LLDB_PROPERTIES_debugger |
195 | #include "CorePropertiesEnum.inc" |
196 | }; |
197 | |
198 | LoadPluginCallbackType Debugger::g_load_plugin_callback = nullptr; |
199 | |
200 | Status Debugger::SetPropertyValue(const ExecutionContext *exe_ctx, |
201 | VarSetOperationType op, |
202 | llvm::StringRef property_path, |
203 | llvm::StringRef value) { |
204 | bool is_load_script = |
205 | (property_path == "target.load-script-from-symbol-file" ); |
206 | // These properties might change how we visualize data. |
207 | bool invalidate_data_vis = (property_path == "escape-non-printables" ); |
208 | invalidate_data_vis |= |
209 | (property_path == "target.max-zero-padding-in-float-format" ); |
210 | if (invalidate_data_vis) { |
211 | DataVisualization::ForceUpdate(); |
212 | } |
213 | |
214 | TargetSP target_sp; |
215 | LoadScriptFromSymFile load_script_old_value = eLoadScriptFromSymFileFalse; |
216 | if (is_load_script && exe_ctx && exe_ctx->GetTargetSP()) { |
217 | target_sp = exe_ctx->GetTargetSP(); |
218 | load_script_old_value = |
219 | target_sp->TargetProperties::GetLoadScriptFromSymbolFile(); |
220 | } |
221 | Status error(Properties::SetPropertyValue(exe_ctx, op, property_path, value)); |
222 | if (error.Success()) { |
223 | // FIXME it would be nice to have "on-change" callbacks for properties |
224 | if (property_path == g_debugger_properties[ePropertyPrompt].name) { |
225 | llvm::StringRef new_prompt = GetPrompt(); |
226 | std::string str = lldb_private::ansi::FormatAnsiTerminalCodes( |
227 | format: new_prompt, do_color: GetUseColor()); |
228 | if (str.length()) |
229 | new_prompt = str; |
230 | GetCommandInterpreter().UpdatePrompt(prompt: new_prompt); |
231 | auto bytes = std::make_unique<EventDataBytes>(args&: new_prompt); |
232 | auto prompt_change_event_sp = std::make_shared<Event>( |
233 | args: CommandInterpreter::eBroadcastBitResetPrompt, args: bytes.release()); |
234 | GetCommandInterpreter().BroadcastEvent(event_sp&: prompt_change_event_sp); |
235 | } else if (property_path == g_debugger_properties[ePropertyUseColor].name) { |
236 | // use-color changed. Ping the prompt so it can reset the ansi terminal |
237 | // codes. |
238 | SetPrompt(GetPrompt()); |
239 | } else if (property_path == |
240 | g_debugger_properties[ePropertyPromptAnsiPrefix].name || |
241 | property_path == |
242 | g_debugger_properties[ePropertyPromptAnsiSuffix].name) { |
243 | // Prompt colors changed. Ping the prompt so it can reset the ansi |
244 | // terminal codes. |
245 | SetPrompt(GetPrompt()); |
246 | } else if (property_path == |
247 | g_debugger_properties[ePropertyUseSourceCache].name) { |
248 | // use-source-cache changed. Wipe out the cache contents if it was |
249 | // disabled. |
250 | if (!GetUseSourceCache()) { |
251 | m_source_file_cache.Clear(); |
252 | } |
253 | } else if (is_load_script && target_sp && |
254 | load_script_old_value == eLoadScriptFromSymFileWarn) { |
255 | if (target_sp->TargetProperties::GetLoadScriptFromSymbolFile() == |
256 | eLoadScriptFromSymFileTrue) { |
257 | std::list<Status> errors; |
258 | StreamString feedback_stream; |
259 | if (!target_sp->LoadScriptingResources(errors, feedback_stream)) { |
260 | Stream &s = GetErrorStream(); |
261 | for (auto error : errors) { |
262 | s.Printf(format: "%s\n" , error.AsCString()); |
263 | } |
264 | if (feedback_stream.GetSize()) |
265 | s.PutCString(cstr: feedback_stream.GetString()); |
266 | } |
267 | } |
268 | } |
269 | } |
270 | return error; |
271 | } |
272 | |
273 | bool Debugger::GetAutoConfirm() const { |
274 | constexpr uint32_t idx = ePropertyAutoConfirm; |
275 | return GetPropertyAtIndexAs<bool>( |
276 | idx, g_debugger_properties[idx].default_uint_value != 0); |
277 | } |
278 | |
279 | const FormatEntity::Entry *Debugger::GetDisassemblyFormat() const { |
280 | constexpr uint32_t idx = ePropertyDisassemblyFormat; |
281 | return GetPropertyAtIndexAs<const FormatEntity::Entry *>(idx); |
282 | } |
283 | |
284 | const FormatEntity::Entry *Debugger::GetFrameFormat() const { |
285 | constexpr uint32_t idx = ePropertyFrameFormat; |
286 | return GetPropertyAtIndexAs<const FormatEntity::Entry *>(idx); |
287 | } |
288 | |
289 | const FormatEntity::Entry *Debugger::GetFrameFormatUnique() const { |
290 | constexpr uint32_t idx = ePropertyFrameFormatUnique; |
291 | return GetPropertyAtIndexAs<const FormatEntity::Entry *>(idx); |
292 | } |
293 | |
294 | uint64_t Debugger::GetStopDisassemblyMaxSize() const { |
295 | constexpr uint32_t idx = ePropertyStopDisassemblyMaxSize; |
296 | return GetPropertyAtIndexAs<uint64_t>( |
297 | idx, g_debugger_properties[idx].default_uint_value); |
298 | } |
299 | |
300 | bool Debugger::GetNotifyVoid() const { |
301 | constexpr uint32_t idx = ePropertyNotiftVoid; |
302 | return GetPropertyAtIndexAs<uint64_t>( |
303 | idx, g_debugger_properties[idx].default_uint_value != 0); |
304 | } |
305 | |
306 | llvm::StringRef Debugger::GetPrompt() const { |
307 | constexpr uint32_t idx = ePropertyPrompt; |
308 | return GetPropertyAtIndexAs<llvm::StringRef>( |
309 | idx, g_debugger_properties[idx].default_cstr_value); |
310 | } |
311 | |
312 | llvm::StringRef Debugger::GetPromptAnsiPrefix() const { |
313 | const uint32_t idx = ePropertyPromptAnsiPrefix; |
314 | return GetPropertyAtIndexAs<llvm::StringRef>( |
315 | idx, g_debugger_properties[idx].default_cstr_value); |
316 | } |
317 | |
318 | llvm::StringRef Debugger::GetPromptAnsiSuffix() const { |
319 | const uint32_t idx = ePropertyPromptAnsiSuffix; |
320 | return GetPropertyAtIndexAs<llvm::StringRef>( |
321 | idx, g_debugger_properties[idx].default_cstr_value); |
322 | } |
323 | |
324 | void Debugger::SetPrompt(llvm::StringRef p) { |
325 | constexpr uint32_t idx = ePropertyPrompt; |
326 | SetPropertyAtIndex(idx, t: p); |
327 | llvm::StringRef new_prompt = GetPrompt(); |
328 | std::string str = |
329 | lldb_private::ansi::FormatAnsiTerminalCodes(format: new_prompt, do_color: GetUseColor()); |
330 | if (str.length()) |
331 | new_prompt = str; |
332 | GetCommandInterpreter().UpdatePrompt(prompt: new_prompt); |
333 | } |
334 | |
335 | const FormatEntity::Entry *Debugger::GetThreadFormat() const { |
336 | constexpr uint32_t idx = ePropertyThreadFormat; |
337 | return GetPropertyAtIndexAs<const FormatEntity::Entry *>(idx); |
338 | } |
339 | |
340 | const FormatEntity::Entry *Debugger::GetThreadStopFormat() const { |
341 | constexpr uint32_t idx = ePropertyThreadStopFormat; |
342 | return GetPropertyAtIndexAs<const FormatEntity::Entry *>(idx); |
343 | } |
344 | |
345 | lldb::ScriptLanguage Debugger::GetScriptLanguage() const { |
346 | const uint32_t idx = ePropertyScriptLanguage; |
347 | return GetPropertyAtIndexAs<lldb::ScriptLanguage>( |
348 | idx, static_cast<lldb::ScriptLanguage>( |
349 | g_debugger_properties[idx].default_uint_value)); |
350 | } |
351 | |
352 | bool Debugger::SetScriptLanguage(lldb::ScriptLanguage script_lang) { |
353 | const uint32_t idx = ePropertyScriptLanguage; |
354 | return SetPropertyAtIndex(idx, t: script_lang); |
355 | } |
356 | |
357 | lldb::LanguageType Debugger::GetREPLLanguage() const { |
358 | const uint32_t idx = ePropertyREPLLanguage; |
359 | return GetPropertyAtIndexAs<LanguageType>(idx, default_value: {}); |
360 | } |
361 | |
362 | bool Debugger::SetREPLLanguage(lldb::LanguageType repl_lang) { |
363 | const uint32_t idx = ePropertyREPLLanguage; |
364 | return SetPropertyAtIndex(idx, t: repl_lang); |
365 | } |
366 | |
367 | uint64_t Debugger::GetTerminalWidth() const { |
368 | const uint32_t idx = ePropertyTerminalWidth; |
369 | return GetPropertyAtIndexAs<uint64_t>( |
370 | idx, g_debugger_properties[idx].default_uint_value); |
371 | } |
372 | |
373 | bool Debugger::SetTerminalWidth(uint64_t term_width) { |
374 | if (auto handler_sp = m_io_handler_stack.Top()) |
375 | handler_sp->TerminalSizeChanged(); |
376 | |
377 | const uint32_t idx = ePropertyTerminalWidth; |
378 | return SetPropertyAtIndex(idx, t: term_width); |
379 | } |
380 | |
381 | bool Debugger::GetUseExternalEditor() const { |
382 | const uint32_t idx = ePropertyUseExternalEditor; |
383 | return GetPropertyAtIndexAs<bool>( |
384 | idx, g_debugger_properties[idx].default_uint_value != 0); |
385 | } |
386 | |
387 | bool Debugger::SetUseExternalEditor(bool b) { |
388 | const uint32_t idx = ePropertyUseExternalEditor; |
389 | return SetPropertyAtIndex(idx, t: b); |
390 | } |
391 | |
392 | llvm::StringRef Debugger::GetExternalEditor() const { |
393 | const uint32_t idx = ePropertyExternalEditor; |
394 | return GetPropertyAtIndexAs<llvm::StringRef>( |
395 | idx, g_debugger_properties[idx].default_cstr_value); |
396 | } |
397 | |
398 | bool Debugger::SetExternalEditor(llvm::StringRef editor) { |
399 | const uint32_t idx = ePropertyExternalEditor; |
400 | return SetPropertyAtIndex(idx, t: editor); |
401 | } |
402 | |
403 | bool Debugger::GetUseColor() const { |
404 | const uint32_t idx = ePropertyUseColor; |
405 | return GetPropertyAtIndexAs<bool>( |
406 | idx, g_debugger_properties[idx].default_uint_value != 0); |
407 | } |
408 | |
409 | bool Debugger::SetUseColor(bool b) { |
410 | const uint32_t idx = ePropertyUseColor; |
411 | bool ret = SetPropertyAtIndex(idx, t: b); |
412 | SetPrompt(GetPrompt()); |
413 | return ret; |
414 | } |
415 | |
416 | bool Debugger::GetShowProgress() const { |
417 | const uint32_t idx = ePropertyShowProgress; |
418 | return GetPropertyAtIndexAs<bool>( |
419 | idx, g_debugger_properties[idx].default_uint_value != 0); |
420 | } |
421 | |
422 | bool Debugger::SetShowProgress(bool show_progress) { |
423 | const uint32_t idx = ePropertyShowProgress; |
424 | return SetPropertyAtIndex(idx, t: show_progress); |
425 | } |
426 | |
427 | llvm::StringRef Debugger::GetShowProgressAnsiPrefix() const { |
428 | const uint32_t idx = ePropertyShowProgressAnsiPrefix; |
429 | return GetPropertyAtIndexAs<llvm::StringRef>( |
430 | idx, g_debugger_properties[idx].default_cstr_value); |
431 | } |
432 | |
433 | llvm::StringRef Debugger::GetShowProgressAnsiSuffix() const { |
434 | const uint32_t idx = ePropertyShowProgressAnsiSuffix; |
435 | return GetPropertyAtIndexAs<llvm::StringRef>( |
436 | idx, g_debugger_properties[idx].default_cstr_value); |
437 | } |
438 | |
439 | bool Debugger::GetUseAutosuggestion() const { |
440 | const uint32_t idx = ePropertyShowAutosuggestion; |
441 | return GetPropertyAtIndexAs<bool>( |
442 | idx, g_debugger_properties[idx].default_uint_value != 0); |
443 | } |
444 | |
445 | llvm::StringRef Debugger::GetAutosuggestionAnsiPrefix() const { |
446 | const uint32_t idx = ePropertyShowAutosuggestionAnsiPrefix; |
447 | return GetPropertyAtIndexAs<llvm::StringRef>( |
448 | idx, g_debugger_properties[idx].default_cstr_value); |
449 | } |
450 | |
451 | llvm::StringRef Debugger::GetAutosuggestionAnsiSuffix() const { |
452 | const uint32_t idx = ePropertyShowAutosuggestionAnsiSuffix; |
453 | return GetPropertyAtIndexAs<llvm::StringRef>( |
454 | idx, g_debugger_properties[idx].default_cstr_value); |
455 | } |
456 | |
457 | llvm::StringRef Debugger::GetRegexMatchAnsiPrefix() const { |
458 | const uint32_t idx = ePropertyShowRegexMatchAnsiPrefix; |
459 | return GetPropertyAtIndexAs<llvm::StringRef>( |
460 | idx, g_debugger_properties[idx].default_cstr_value); |
461 | } |
462 | |
463 | llvm::StringRef Debugger::GetRegexMatchAnsiSuffix() const { |
464 | const uint32_t idx = ePropertyShowRegexMatchAnsiSuffix; |
465 | return GetPropertyAtIndexAs<llvm::StringRef>( |
466 | idx, g_debugger_properties[idx].default_cstr_value); |
467 | } |
468 | |
469 | bool Debugger::GetShowDontUsePoHint() const { |
470 | const uint32_t idx = ePropertyShowDontUsePoHint; |
471 | return GetPropertyAtIndexAs<bool>( |
472 | idx, g_debugger_properties[idx].default_uint_value != 0); |
473 | } |
474 | |
475 | bool Debugger::GetUseSourceCache() const { |
476 | const uint32_t idx = ePropertyUseSourceCache; |
477 | return GetPropertyAtIndexAs<bool>( |
478 | idx, g_debugger_properties[idx].default_uint_value != 0); |
479 | } |
480 | |
481 | bool Debugger::SetUseSourceCache(bool b) { |
482 | const uint32_t idx = ePropertyUseSourceCache; |
483 | bool ret = SetPropertyAtIndex(idx, t: b); |
484 | if (!ret) { |
485 | m_source_file_cache.Clear(); |
486 | } |
487 | return ret; |
488 | } |
489 | bool Debugger::GetHighlightSource() const { |
490 | const uint32_t idx = ePropertyHighlightSource; |
491 | return GetPropertyAtIndexAs<bool>( |
492 | idx, g_debugger_properties[idx].default_uint_value != 0); |
493 | } |
494 | |
495 | StopShowColumn Debugger::GetStopShowColumn() const { |
496 | const uint32_t idx = ePropertyStopShowColumn; |
497 | return GetPropertyAtIndexAs<lldb::StopShowColumn>( |
498 | idx, static_cast<lldb::StopShowColumn>( |
499 | g_debugger_properties[idx].default_uint_value)); |
500 | } |
501 | |
502 | llvm::StringRef Debugger::GetStopShowColumnAnsiPrefix() const { |
503 | const uint32_t idx = ePropertyStopShowColumnAnsiPrefix; |
504 | return GetPropertyAtIndexAs<llvm::StringRef>( |
505 | idx, g_debugger_properties[idx].default_cstr_value); |
506 | } |
507 | |
508 | llvm::StringRef Debugger::GetStopShowColumnAnsiSuffix() const { |
509 | const uint32_t idx = ePropertyStopShowColumnAnsiSuffix; |
510 | return GetPropertyAtIndexAs<llvm::StringRef>( |
511 | idx, g_debugger_properties[idx].default_cstr_value); |
512 | } |
513 | |
514 | llvm::StringRef Debugger::GetStopShowLineMarkerAnsiPrefix() const { |
515 | const uint32_t idx = ePropertyStopShowLineMarkerAnsiPrefix; |
516 | return GetPropertyAtIndexAs<llvm::StringRef>( |
517 | idx, g_debugger_properties[idx].default_cstr_value); |
518 | } |
519 | |
520 | llvm::StringRef Debugger::GetStopShowLineMarkerAnsiSuffix() const { |
521 | const uint32_t idx = ePropertyStopShowLineMarkerAnsiSuffix; |
522 | return GetPropertyAtIndexAs<llvm::StringRef>( |
523 | idx, g_debugger_properties[idx].default_cstr_value); |
524 | } |
525 | |
526 | uint64_t Debugger::GetStopSourceLineCount(bool before) const { |
527 | const uint32_t idx = |
528 | before ? ePropertyStopLineCountBefore : ePropertyStopLineCountAfter; |
529 | return GetPropertyAtIndexAs<uint64_t>( |
530 | idx, g_debugger_properties[idx].default_uint_value); |
531 | } |
532 | |
533 | Debugger::StopDisassemblyType Debugger::GetStopDisassemblyDisplay() const { |
534 | const uint32_t idx = ePropertyStopDisassemblyDisplay; |
535 | return GetPropertyAtIndexAs<Debugger::StopDisassemblyType>( |
536 | idx, static_cast<Debugger::StopDisassemblyType>( |
537 | g_debugger_properties[idx].default_uint_value)); |
538 | } |
539 | |
540 | uint64_t Debugger::GetDisassemblyLineCount() const { |
541 | const uint32_t idx = ePropertyStopDisassemblyCount; |
542 | return GetPropertyAtIndexAs<uint64_t>( |
543 | idx, g_debugger_properties[idx].default_uint_value); |
544 | } |
545 | |
546 | bool Debugger::GetAutoOneLineSummaries() const { |
547 | const uint32_t idx = ePropertyAutoOneLineSummaries; |
548 | return GetPropertyAtIndexAs<bool>( |
549 | idx, g_debugger_properties[idx].default_uint_value != 0); |
550 | } |
551 | |
552 | bool Debugger::GetEscapeNonPrintables() const { |
553 | const uint32_t idx = ePropertyEscapeNonPrintables; |
554 | return GetPropertyAtIndexAs<bool>( |
555 | idx, g_debugger_properties[idx].default_uint_value != 0); |
556 | } |
557 | |
558 | bool Debugger::GetAutoIndent() const { |
559 | const uint32_t idx = ePropertyAutoIndent; |
560 | return GetPropertyAtIndexAs<bool>( |
561 | idx, g_debugger_properties[idx].default_uint_value != 0); |
562 | } |
563 | |
564 | bool Debugger::SetAutoIndent(bool b) { |
565 | const uint32_t idx = ePropertyAutoIndent; |
566 | return SetPropertyAtIndex(idx, t: b); |
567 | } |
568 | |
569 | bool Debugger::GetPrintDecls() const { |
570 | const uint32_t idx = ePropertyPrintDecls; |
571 | return GetPropertyAtIndexAs<bool>( |
572 | idx, g_debugger_properties[idx].default_uint_value != 0); |
573 | } |
574 | |
575 | bool Debugger::SetPrintDecls(bool b) { |
576 | const uint32_t idx = ePropertyPrintDecls; |
577 | return SetPropertyAtIndex(idx, t: b); |
578 | } |
579 | |
580 | uint64_t Debugger::GetTabSize() const { |
581 | const uint32_t idx = ePropertyTabSize; |
582 | return GetPropertyAtIndexAs<uint64_t>( |
583 | idx, g_debugger_properties[idx].default_uint_value); |
584 | } |
585 | |
586 | bool Debugger::SetTabSize(uint64_t tab_size) { |
587 | const uint32_t idx = ePropertyTabSize; |
588 | return SetPropertyAtIndex(idx, t: tab_size); |
589 | } |
590 | |
591 | lldb::DWIMPrintVerbosity Debugger::GetDWIMPrintVerbosity() const { |
592 | const uint32_t idx = ePropertyDWIMPrintVerbosity; |
593 | return GetPropertyAtIndexAs<lldb::DWIMPrintVerbosity>( |
594 | idx, static_cast<lldb::DWIMPrintVerbosity>( |
595 | g_debugger_properties[idx].default_uint_value)); |
596 | } |
597 | |
598 | #pragma mark Debugger |
599 | |
600 | // const DebuggerPropertiesSP & |
601 | // Debugger::GetSettings() const |
602 | //{ |
603 | // return m_properties_sp; |
604 | //} |
605 | // |
606 | |
607 | void Debugger::Initialize(LoadPluginCallbackType load_plugin_callback) { |
608 | assert(g_debugger_list_ptr == nullptr && |
609 | "Debugger::Initialize called more than once!" ); |
610 | g_debugger_list_mutex_ptr = new std::recursive_mutex(); |
611 | g_debugger_list_ptr = new DebuggerList(); |
612 | g_thread_pool = new llvm::DefaultThreadPool(llvm::optimal_concurrency()); |
613 | g_load_plugin_callback = load_plugin_callback; |
614 | } |
615 | |
616 | void Debugger::Terminate() { |
617 | assert(g_debugger_list_ptr && |
618 | "Debugger::Terminate called without a matching Debugger::Initialize!" ); |
619 | |
620 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
621 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
622 | for (const auto &debugger : *g_debugger_list_ptr) |
623 | debugger->HandleDestroyCallback(); |
624 | } |
625 | |
626 | if (g_thread_pool) { |
627 | // The destructor will wait for all the threads to complete. |
628 | delete g_thread_pool; |
629 | } |
630 | |
631 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
632 | // Clear our global list of debugger objects |
633 | { |
634 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
635 | for (const auto &debugger : *g_debugger_list_ptr) |
636 | debugger->Clear(); |
637 | g_debugger_list_ptr->clear(); |
638 | } |
639 | } |
640 | } |
641 | |
642 | void Debugger::SettingsInitialize() { Target::SettingsInitialize(); } |
643 | |
644 | void Debugger::SettingsTerminate() { Target::SettingsTerminate(); } |
645 | |
646 | bool Debugger::LoadPlugin(const FileSpec &spec, Status &error) { |
647 | if (g_load_plugin_callback) { |
648 | llvm::sys::DynamicLibrary dynlib = |
649 | g_load_plugin_callback(shared_from_this(), spec, error); |
650 | if (dynlib.isValid()) { |
651 | m_loaded_plugins.push_back(x: dynlib); |
652 | return true; |
653 | } |
654 | } else { |
655 | // The g_load_plugin_callback is registered in SBDebugger::Initialize() and |
656 | // if the public API layer isn't available (code is linking against all of |
657 | // the internal LLDB static libraries), then we can't load plugins |
658 | error.SetErrorString("Public API layer is not available" ); |
659 | } |
660 | return false; |
661 | } |
662 | |
663 | static FileSystem::EnumerateDirectoryResult |
664 | LoadPluginCallback(void *baton, llvm::sys::fs::file_type ft, |
665 | llvm::StringRef path) { |
666 | Status error; |
667 | |
668 | static constexpr llvm::StringLiteral g_dylibext(".dylib" ); |
669 | static constexpr llvm::StringLiteral g_solibext(".so" ); |
670 | |
671 | if (!baton) |
672 | return FileSystem::eEnumerateDirectoryResultQuit; |
673 | |
674 | Debugger *debugger = (Debugger *)baton; |
675 | |
676 | namespace fs = llvm::sys::fs; |
677 | // If we have a regular file, a symbolic link or unknown file type, try and |
678 | // process the file. We must handle unknown as sometimes the directory |
679 | // enumeration might be enumerating a file system that doesn't have correct |
680 | // file type information. |
681 | if (ft == fs::file_type::regular_file || ft == fs::file_type::symlink_file || |
682 | ft == fs::file_type::type_unknown) { |
683 | FileSpec plugin_file_spec(path); |
684 | FileSystem::Instance().Resolve(file_spec&: plugin_file_spec); |
685 | |
686 | if (plugin_file_spec.GetFileNameExtension() != g_dylibext && |
687 | plugin_file_spec.GetFileNameExtension() != g_solibext) { |
688 | return FileSystem::eEnumerateDirectoryResultNext; |
689 | } |
690 | |
691 | Status plugin_load_error; |
692 | debugger->LoadPlugin(spec: plugin_file_spec, error&: plugin_load_error); |
693 | |
694 | return FileSystem::eEnumerateDirectoryResultNext; |
695 | } else if (ft == fs::file_type::directory_file || |
696 | ft == fs::file_type::symlink_file || |
697 | ft == fs::file_type::type_unknown) { |
698 | // Try and recurse into anything that a directory or symbolic link. We must |
699 | // also do this for unknown as sometimes the directory enumeration might be |
700 | // enumerating a file system that doesn't have correct file type |
701 | // information. |
702 | return FileSystem::eEnumerateDirectoryResultEnter; |
703 | } |
704 | |
705 | return FileSystem::eEnumerateDirectoryResultNext; |
706 | } |
707 | |
708 | void Debugger::InstanceInitialize() { |
709 | const bool find_directories = true; |
710 | const bool find_files = true; |
711 | const bool find_other = true; |
712 | char dir_path[PATH_MAX]; |
713 | if (FileSpec dir_spec = HostInfo::GetSystemPluginDir()) { |
714 | if (FileSystem::Instance().Exists(file_spec: dir_spec) && |
715 | dir_spec.GetPath(path: dir_path, max_path_length: sizeof(dir_path))) { |
716 | FileSystem::Instance().EnumerateDirectory(path: dir_path, find_directories, |
717 | find_files, find_other, |
718 | callback: LoadPluginCallback, callback_baton: this); |
719 | } |
720 | } |
721 | |
722 | if (FileSpec dir_spec = HostInfo::GetUserPluginDir()) { |
723 | if (FileSystem::Instance().Exists(file_spec: dir_spec) && |
724 | dir_spec.GetPath(path: dir_path, max_path_length: sizeof(dir_path))) { |
725 | FileSystem::Instance().EnumerateDirectory(path: dir_path, find_directories, |
726 | find_files, find_other, |
727 | callback: LoadPluginCallback, callback_baton: this); |
728 | } |
729 | } |
730 | |
731 | PluginManager::DebuggerInitialize(debugger&: *this); |
732 | } |
733 | |
734 | DebuggerSP Debugger::CreateInstance(lldb::LogOutputCallback log_callback, |
735 | void *baton) { |
736 | DebuggerSP debugger_sp(new Debugger(log_callback, baton)); |
737 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
738 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
739 | g_debugger_list_ptr->push_back(x: debugger_sp); |
740 | } |
741 | debugger_sp->InstanceInitialize(); |
742 | return debugger_sp; |
743 | } |
744 | |
745 | void Debugger::HandleDestroyCallback() { |
746 | if (m_destroy_callback) { |
747 | m_destroy_callback(GetID(), m_destroy_callback_baton); |
748 | m_destroy_callback = nullptr; |
749 | } |
750 | } |
751 | |
752 | void Debugger::Destroy(DebuggerSP &debugger_sp) { |
753 | if (!debugger_sp) |
754 | return; |
755 | |
756 | debugger_sp->HandleDestroyCallback(); |
757 | CommandInterpreter &cmd_interpreter = debugger_sp->GetCommandInterpreter(); |
758 | |
759 | if (cmd_interpreter.GetSaveSessionOnQuit()) { |
760 | CommandReturnObject result(debugger_sp->GetUseColor()); |
761 | cmd_interpreter.SaveTranscript(result); |
762 | if (result.Succeeded()) |
763 | (*debugger_sp->GetAsyncOutputStream()) << result.GetOutputData() << '\n'; |
764 | else |
765 | (*debugger_sp->GetAsyncErrorStream()) << result.GetErrorData() << '\n'; |
766 | } |
767 | |
768 | debugger_sp->Clear(); |
769 | |
770 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
771 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
772 | DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); |
773 | for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { |
774 | if ((*pos).get() == debugger_sp.get()) { |
775 | g_debugger_list_ptr->erase(position: pos); |
776 | return; |
777 | } |
778 | } |
779 | } |
780 | } |
781 | |
782 | DebuggerSP |
783 | Debugger::FindDebuggerWithInstanceName(llvm::StringRef instance_name) { |
784 | if (!g_debugger_list_ptr || !g_debugger_list_mutex_ptr) |
785 | return DebuggerSP(); |
786 | |
787 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
788 | for (const DebuggerSP &debugger_sp : *g_debugger_list_ptr) { |
789 | if (!debugger_sp) |
790 | continue; |
791 | |
792 | if (llvm::StringRef(debugger_sp->GetInstanceName()) == instance_name) |
793 | return debugger_sp; |
794 | } |
795 | return DebuggerSP(); |
796 | } |
797 | |
798 | TargetSP Debugger::FindTargetWithProcessID(lldb::pid_t pid) { |
799 | TargetSP target_sp; |
800 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
801 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
802 | DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); |
803 | for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { |
804 | target_sp = (*pos)->GetTargetList().FindTargetWithProcessID(pid); |
805 | if (target_sp) |
806 | break; |
807 | } |
808 | } |
809 | return target_sp; |
810 | } |
811 | |
812 | TargetSP Debugger::FindTargetWithProcess(Process *process) { |
813 | TargetSP target_sp; |
814 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
815 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
816 | DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); |
817 | for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { |
818 | target_sp = (*pos)->GetTargetList().FindTargetWithProcess(process); |
819 | if (target_sp) |
820 | break; |
821 | } |
822 | } |
823 | return target_sp; |
824 | } |
825 | |
826 | ConstString Debugger::GetStaticBroadcasterClass() { |
827 | static ConstString class_name("lldb.debugger" ); |
828 | return class_name; |
829 | } |
830 | |
831 | Debugger::Debugger(lldb::LogOutputCallback log_callback, void *baton) |
832 | : UserID(g_unique_id++), |
833 | Properties(std::make_shared<OptionValueProperties>()), |
834 | m_input_file_sp(std::make_shared<NativeFile>(stdin, args: false)), |
835 | m_output_stream_sp(std::make_shared<StreamFile>(stdout, args: false)), |
836 | m_error_stream_sp(std::make_shared<StreamFile>(stderr, args: false)), |
837 | m_input_recorder(nullptr), |
838 | m_broadcaster_manager_sp(BroadcasterManager::MakeBroadcasterManager()), |
839 | m_terminal_state(), m_target_list(*this), m_platform_list(), |
840 | m_listener_sp(Listener::MakeListener(name: "lldb.Debugger" )), |
841 | m_source_manager_up(), m_source_file_cache(), |
842 | m_command_interpreter_up( |
843 | std::make_unique<CommandInterpreter>(args&: *this, args: false)), |
844 | m_io_handler_stack(), |
845 | m_instance_name(llvm::formatv(Fmt: "debugger_{0}" , Vals: GetID()).str()), |
846 | m_loaded_plugins(), m_event_handler_thread(), m_io_handler_thread(), |
847 | m_sync_broadcaster(nullptr, "lldb.debugger.sync" ), |
848 | m_broadcaster(m_broadcaster_manager_sp, |
849 | GetStaticBroadcasterClass().AsCString()), |
850 | m_forward_listener_sp(), m_clear_once() { |
851 | // Initialize the debugger properties as early as possible as other parts of |
852 | // LLDB will start querying them during construction. |
853 | m_collection_sp->Initialize(g_debugger_properties); |
854 | m_collection_sp->AppendProperty( |
855 | name: "target" , desc: "Settings specify to debugging targets." , is_global: true, |
856 | value_sp: Target::GetGlobalProperties().GetValueProperties()); |
857 | m_collection_sp->AppendProperty( |
858 | name: "platform" , desc: "Platform settings." , is_global: true, |
859 | value_sp: Platform::GetGlobalPlatformProperties().GetValueProperties()); |
860 | m_collection_sp->AppendProperty( |
861 | name: "symbols" , desc: "Symbol lookup and cache settings." , is_global: true, |
862 | value_sp: ModuleList::GetGlobalModuleListProperties().GetValueProperties()); |
863 | m_collection_sp->AppendProperty( |
864 | name: LanguageProperties::GetSettingName(), desc: "Language settings." , is_global: true, |
865 | value_sp: Language::GetGlobalLanguageProperties().GetValueProperties()); |
866 | if (m_command_interpreter_up) { |
867 | m_collection_sp->AppendProperty( |
868 | name: "interpreter" , |
869 | desc: "Settings specify to the debugger's command interpreter." , is_global: true, |
870 | value_sp: m_command_interpreter_up->GetValueProperties()); |
871 | } |
872 | if (log_callback) |
873 | m_callback_handler_sp = |
874 | std::make_shared<CallbackLogHandler>(args&: log_callback, args&: baton); |
875 | m_command_interpreter_up->Initialize(); |
876 | // Always add our default platform to the platform list |
877 | PlatformSP default_platform_sp(Platform::GetHostPlatform()); |
878 | assert(default_platform_sp); |
879 | m_platform_list.Append(platform_sp: default_platform_sp, set_selected: true); |
880 | |
881 | // Create the dummy target. |
882 | { |
883 | ArchSpec arch(Target::GetDefaultArchitecture()); |
884 | if (!arch.IsValid()) |
885 | arch = HostInfo::GetArchitecture(); |
886 | assert(arch.IsValid() && "No valid default or host archspec" ); |
887 | const bool is_dummy_target = true; |
888 | m_dummy_target_sp.reset( |
889 | p: new Target(*this, arch, default_platform_sp, is_dummy_target)); |
890 | } |
891 | assert(m_dummy_target_sp.get() && "Couldn't construct dummy target?" ); |
892 | |
893 | OptionValueUInt64 *term_width = |
894 | m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64( |
895 | ePropertyTerminalWidth); |
896 | term_width->SetMinimumValue(10); |
897 | term_width->SetMaximumValue(1024); |
898 | |
899 | // Turn off use-color if this is a dumb terminal. |
900 | const char *term = getenv(name: "TERM" ); |
901 | if (term && !strcmp(s1: term, s2: "dumb" )) |
902 | SetUseColor(false); |
903 | // Turn off use-color if we don't write to a terminal with color support. |
904 | if (!GetOutputFile().GetIsTerminalWithColors()) |
905 | SetUseColor(false); |
906 | |
907 | if (Diagnostics::Enabled()) { |
908 | m_diagnostics_callback_id = Diagnostics::Instance().AddCallback( |
909 | callback: [this](const FileSpec &dir) -> llvm::Error { |
910 | for (auto &entry : m_stream_handlers) { |
911 | llvm::StringRef log_path = entry.first(); |
912 | llvm::StringRef file_name = llvm::sys::path::filename(path: log_path); |
913 | FileSpec destination = dir.CopyByAppendingPathComponent(component: file_name); |
914 | std::error_code ec = |
915 | llvm::sys::fs::copy_file(From: log_path, To: destination.GetPath()); |
916 | if (ec) |
917 | return llvm::errorCodeToError(EC: ec); |
918 | } |
919 | return llvm::Error::success(); |
920 | }); |
921 | } |
922 | |
923 | #if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING) |
924 | // Enabling use of ANSI color codes because LLDB is using them to highlight |
925 | // text. |
926 | llvm::sys::Process::UseANSIEscapeCodes(true); |
927 | #endif |
928 | } |
929 | |
930 | Debugger::~Debugger() { Clear(); } |
931 | |
932 | void Debugger::Clear() { |
933 | // Make sure we call this function only once. With the C++ global destructor |
934 | // chain having a list of debuggers and with code that can be running on |
935 | // other threads, we need to ensure this doesn't happen multiple times. |
936 | // |
937 | // The following functions call Debugger::Clear(): |
938 | // Debugger::~Debugger(); |
939 | // static void Debugger::Destroy(lldb::DebuggerSP &debugger_sp); |
940 | // static void Debugger::Terminate(); |
941 | llvm::call_once(flag&: m_clear_once, F: [this]() { |
942 | ClearIOHandlers(); |
943 | StopIOHandlerThread(); |
944 | StopEventHandlerThread(); |
945 | m_listener_sp->Clear(); |
946 | for (TargetSP target_sp : m_target_list.Targets()) { |
947 | if (target_sp) { |
948 | if (ProcessSP process_sp = target_sp->GetProcessSP()) |
949 | process_sp->Finalize(destructing: false /* not destructing */); |
950 | target_sp->Destroy(); |
951 | } |
952 | } |
953 | m_broadcaster_manager_sp->Clear(); |
954 | |
955 | // Close the input file _before_ we close the input read communications |
956 | // class as it does NOT own the input file, our m_input_file does. |
957 | m_terminal_state.Clear(); |
958 | GetInputFile().Close(); |
959 | |
960 | m_command_interpreter_up->Clear(); |
961 | |
962 | if (Diagnostics::Enabled()) |
963 | Diagnostics::Instance().RemoveCallback(id: m_diagnostics_callback_id); |
964 | }); |
965 | } |
966 | |
967 | bool Debugger::GetAsyncExecution() { |
968 | return !m_command_interpreter_up->GetSynchronous(); |
969 | } |
970 | |
971 | void Debugger::SetAsyncExecution(bool async_execution) { |
972 | m_command_interpreter_up->SetSynchronous(!async_execution); |
973 | } |
974 | |
975 | repro::DataRecorder *Debugger::GetInputRecorder() { return m_input_recorder; } |
976 | |
977 | static inline int OpenPipe(int fds[2], std::size_t size) { |
978 | #ifdef _WIN32 |
979 | return _pipe(fds, size, O_BINARY); |
980 | #else |
981 | (void)size; |
982 | return pipe(pipedes: fds); |
983 | #endif |
984 | } |
985 | |
986 | Status Debugger::SetInputString(const char *data) { |
987 | Status result; |
988 | enum PIPES { READ, WRITE }; // Indexes for the read and write fds |
989 | int fds[2] = {-1, -1}; |
990 | |
991 | if (data == nullptr) { |
992 | result.SetErrorString("String data is null" ); |
993 | return result; |
994 | } |
995 | |
996 | size_t size = strlen(s: data); |
997 | if (size == 0) { |
998 | result.SetErrorString("String data is empty" ); |
999 | return result; |
1000 | } |
1001 | |
1002 | if (OpenPipe(fds, size) != 0) { |
1003 | result.SetErrorString( |
1004 | "can't create pipe file descriptors for LLDB commands" ); |
1005 | return result; |
1006 | } |
1007 | |
1008 | int r = write(fd: fds[WRITE], buf: data, n: size); |
1009 | (void)r; |
1010 | // Close the write end of the pipe, so that the command interpreter will exit |
1011 | // when it consumes all the data. |
1012 | llvm::sys::Process::SafelyCloseFileDescriptor(FD: fds[WRITE]); |
1013 | |
1014 | // Open the read file descriptor as a FILE * that we can return as an input |
1015 | // handle. |
1016 | FILE *commands_file = fdopen(fd: fds[READ], modes: "rb" ); |
1017 | if (commands_file == nullptr) { |
1018 | result.SetErrorStringWithFormat("fdopen(%i, \"rb\") failed (errno = %i) " |
1019 | "when trying to open LLDB commands pipe" , |
1020 | fds[READ], errno); |
1021 | llvm::sys::Process::SafelyCloseFileDescriptor(FD: fds[READ]); |
1022 | return result; |
1023 | } |
1024 | |
1025 | SetInputFile((FileSP)std::make_shared<NativeFile>(args&: commands_file, args: true)); |
1026 | return result; |
1027 | } |
1028 | |
1029 | void Debugger::SetInputFile(FileSP file_sp) { |
1030 | assert(file_sp && file_sp->IsValid()); |
1031 | m_input_file_sp = std::move(file_sp); |
1032 | // Save away the terminal state if that is relevant, so that we can restore |
1033 | // it in RestoreInputState. |
1034 | SaveInputTerminalState(); |
1035 | } |
1036 | |
1037 | void Debugger::SetOutputFile(FileSP file_sp) { |
1038 | assert(file_sp && file_sp->IsValid()); |
1039 | m_output_stream_sp = std::make_shared<StreamFile>(args&: file_sp); |
1040 | } |
1041 | |
1042 | void Debugger::SetErrorFile(FileSP file_sp) { |
1043 | assert(file_sp && file_sp->IsValid()); |
1044 | m_error_stream_sp = std::make_shared<StreamFile>(args&: file_sp); |
1045 | } |
1046 | |
1047 | void Debugger::SaveInputTerminalState() { |
1048 | int fd = GetInputFile().GetDescriptor(); |
1049 | if (fd != File::kInvalidDescriptor) |
1050 | m_terminal_state.Save(term: fd, save_process_group: true); |
1051 | } |
1052 | |
1053 | void Debugger::RestoreInputTerminalState() { m_terminal_state.Restore(); } |
1054 | |
1055 | ExecutionContext Debugger::GetSelectedExecutionContext() { |
1056 | bool adopt_selected = true; |
1057 | ExecutionContextRef exe_ctx_ref(GetSelectedTarget().get(), adopt_selected); |
1058 | return ExecutionContext(exe_ctx_ref); |
1059 | } |
1060 | |
1061 | void Debugger::DispatchInputInterrupt() { |
1062 | std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); |
1063 | IOHandlerSP reader_sp(m_io_handler_stack.Top()); |
1064 | if (reader_sp) |
1065 | reader_sp->Interrupt(); |
1066 | } |
1067 | |
1068 | void Debugger::DispatchInputEndOfFile() { |
1069 | std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); |
1070 | IOHandlerSP reader_sp(m_io_handler_stack.Top()); |
1071 | if (reader_sp) |
1072 | reader_sp->GotEOF(); |
1073 | } |
1074 | |
1075 | void Debugger::ClearIOHandlers() { |
1076 | // The bottom input reader should be the main debugger input reader. We do |
1077 | // not want to close that one here. |
1078 | std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); |
1079 | while (m_io_handler_stack.GetSize() > 1) { |
1080 | IOHandlerSP reader_sp(m_io_handler_stack.Top()); |
1081 | if (reader_sp) |
1082 | PopIOHandler(reader_sp); |
1083 | } |
1084 | } |
1085 | |
1086 | void Debugger::RunIOHandlers() { |
1087 | IOHandlerSP reader_sp = m_io_handler_stack.Top(); |
1088 | while (true) { |
1089 | if (!reader_sp) |
1090 | break; |
1091 | |
1092 | reader_sp->Run(); |
1093 | { |
1094 | std::lock_guard<std::recursive_mutex> guard( |
1095 | m_io_handler_synchronous_mutex); |
1096 | |
1097 | // Remove all input readers that are done from the top of the stack |
1098 | while (true) { |
1099 | IOHandlerSP top_reader_sp = m_io_handler_stack.Top(); |
1100 | if (top_reader_sp && top_reader_sp->GetIsDone()) |
1101 | PopIOHandler(reader_sp: top_reader_sp); |
1102 | else |
1103 | break; |
1104 | } |
1105 | reader_sp = m_io_handler_stack.Top(); |
1106 | } |
1107 | } |
1108 | ClearIOHandlers(); |
1109 | } |
1110 | |
1111 | void Debugger::RunIOHandlerSync(const IOHandlerSP &reader_sp) { |
1112 | std::lock_guard<std::recursive_mutex> guard(m_io_handler_synchronous_mutex); |
1113 | |
1114 | PushIOHandler(reader_sp); |
1115 | IOHandlerSP top_reader_sp = reader_sp; |
1116 | |
1117 | while (top_reader_sp) { |
1118 | top_reader_sp->Run(); |
1119 | |
1120 | // Don't unwind past the starting point. |
1121 | if (top_reader_sp.get() == reader_sp.get()) { |
1122 | if (PopIOHandler(reader_sp)) |
1123 | break; |
1124 | } |
1125 | |
1126 | // If we pushed new IO handlers, pop them if they're done or restart the |
1127 | // loop to run them if they're not. |
1128 | while (true) { |
1129 | top_reader_sp = m_io_handler_stack.Top(); |
1130 | if (top_reader_sp && top_reader_sp->GetIsDone()) { |
1131 | PopIOHandler(reader_sp: top_reader_sp); |
1132 | // Don't unwind past the starting point. |
1133 | if (top_reader_sp.get() == reader_sp.get()) |
1134 | return; |
1135 | } else { |
1136 | break; |
1137 | } |
1138 | } |
1139 | } |
1140 | } |
1141 | |
1142 | bool Debugger::IsTopIOHandler(const lldb::IOHandlerSP &reader_sp) { |
1143 | return m_io_handler_stack.IsTop(io_handler_sp: reader_sp); |
1144 | } |
1145 | |
1146 | bool Debugger::CheckTopIOHandlerTypes(IOHandler::Type top_type, |
1147 | IOHandler::Type second_top_type) { |
1148 | return m_io_handler_stack.CheckTopIOHandlerTypes(top_type, second_top_type); |
1149 | } |
1150 | |
1151 | void Debugger::PrintAsync(const char *s, size_t len, bool is_stdout) { |
1152 | bool printed = m_io_handler_stack.PrintAsync(s, len, is_stdout); |
1153 | if (!printed) { |
1154 | lldb::StreamFileSP stream = |
1155 | is_stdout ? m_output_stream_sp : m_error_stream_sp; |
1156 | stream->Write(src: s, src_len: len); |
1157 | } |
1158 | } |
1159 | |
1160 | llvm::StringRef Debugger::GetTopIOHandlerControlSequence(char ch) { |
1161 | return m_io_handler_stack.GetTopIOHandlerControlSequence(ch); |
1162 | } |
1163 | |
1164 | const char *Debugger::GetIOHandlerCommandPrefix() { |
1165 | return m_io_handler_stack.GetTopIOHandlerCommandPrefix(); |
1166 | } |
1167 | |
1168 | const char *Debugger::GetIOHandlerHelpPrologue() { |
1169 | return m_io_handler_stack.GetTopIOHandlerHelpPrologue(); |
1170 | } |
1171 | |
1172 | bool Debugger::RemoveIOHandler(const IOHandlerSP &reader_sp) { |
1173 | return PopIOHandler(reader_sp); |
1174 | } |
1175 | |
1176 | void Debugger::RunIOHandlerAsync(const IOHandlerSP &reader_sp, |
1177 | bool cancel_top_handler) { |
1178 | PushIOHandler(reader_sp, cancel_top_handler); |
1179 | } |
1180 | |
1181 | void Debugger::AdoptTopIOHandlerFilesIfInvalid(FileSP &in, StreamFileSP &out, |
1182 | StreamFileSP &err) { |
1183 | // Before an IOHandler runs, it must have in/out/err streams. This function |
1184 | // is called when one ore more of the streams are nullptr. We use the top |
1185 | // input reader's in/out/err streams, or fall back to the debugger file |
1186 | // handles, or we fall back onto stdin/stdout/stderr as a last resort. |
1187 | |
1188 | std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); |
1189 | IOHandlerSP top_reader_sp(m_io_handler_stack.Top()); |
1190 | // If no STDIN has been set, then set it appropriately |
1191 | if (!in || !in->IsValid()) { |
1192 | if (top_reader_sp) |
1193 | in = top_reader_sp->GetInputFileSP(); |
1194 | else |
1195 | in = GetInputFileSP(); |
1196 | // If there is nothing, use stdin |
1197 | if (!in) |
1198 | in = std::make_shared<NativeFile>(stdin, args: false); |
1199 | } |
1200 | // If no STDOUT has been set, then set it appropriately |
1201 | if (!out || !out->GetFile().IsValid()) { |
1202 | if (top_reader_sp) |
1203 | out = top_reader_sp->GetOutputStreamFileSP(); |
1204 | else |
1205 | out = GetOutputStreamSP(); |
1206 | // If there is nothing, use stdout |
1207 | if (!out) |
1208 | out = std::make_shared<StreamFile>(stdout, args: false); |
1209 | } |
1210 | // If no STDERR has been set, then set it appropriately |
1211 | if (!err || !err->GetFile().IsValid()) { |
1212 | if (top_reader_sp) |
1213 | err = top_reader_sp->GetErrorStreamFileSP(); |
1214 | else |
1215 | err = GetErrorStreamSP(); |
1216 | // If there is nothing, use stderr |
1217 | if (!err) |
1218 | err = std::make_shared<StreamFile>(stderr, args: false); |
1219 | } |
1220 | } |
1221 | |
1222 | void Debugger::PushIOHandler(const IOHandlerSP &reader_sp, |
1223 | bool cancel_top_handler) { |
1224 | if (!reader_sp) |
1225 | return; |
1226 | |
1227 | std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); |
1228 | |
1229 | // Get the current top input reader... |
1230 | IOHandlerSP top_reader_sp(m_io_handler_stack.Top()); |
1231 | |
1232 | // Don't push the same IO handler twice... |
1233 | if (reader_sp == top_reader_sp) |
1234 | return; |
1235 | |
1236 | // Push our new input reader |
1237 | m_io_handler_stack.Push(sp: reader_sp); |
1238 | reader_sp->Activate(); |
1239 | |
1240 | // Interrupt the top input reader to it will exit its Run() function and let |
1241 | // this new input reader take over |
1242 | if (top_reader_sp) { |
1243 | top_reader_sp->Deactivate(); |
1244 | if (cancel_top_handler) |
1245 | top_reader_sp->Cancel(); |
1246 | } |
1247 | } |
1248 | |
1249 | bool Debugger::PopIOHandler(const IOHandlerSP &pop_reader_sp) { |
1250 | if (!pop_reader_sp) |
1251 | return false; |
1252 | |
1253 | std::lock_guard<std::recursive_mutex> guard(m_io_handler_stack.GetMutex()); |
1254 | |
1255 | // The reader on the stop of the stack is done, so let the next read on the |
1256 | // stack refresh its prompt and if there is one... |
1257 | if (m_io_handler_stack.IsEmpty()) |
1258 | return false; |
1259 | |
1260 | IOHandlerSP reader_sp(m_io_handler_stack.Top()); |
1261 | |
1262 | if (pop_reader_sp != reader_sp) |
1263 | return false; |
1264 | |
1265 | reader_sp->Deactivate(); |
1266 | reader_sp->Cancel(); |
1267 | m_io_handler_stack.Pop(); |
1268 | |
1269 | reader_sp = m_io_handler_stack.Top(); |
1270 | if (reader_sp) |
1271 | reader_sp->Activate(); |
1272 | |
1273 | return true; |
1274 | } |
1275 | |
1276 | StreamSP Debugger::GetAsyncOutputStream() { |
1277 | return std::make_shared<StreamAsynchronousIO>(args&: *this, args: true, args: GetUseColor()); |
1278 | } |
1279 | |
1280 | StreamSP Debugger::GetAsyncErrorStream() { |
1281 | return std::make_shared<StreamAsynchronousIO>(args&: *this, args: false, args: GetUseColor()); |
1282 | } |
1283 | |
1284 | void Debugger::RequestInterrupt() { |
1285 | std::lock_guard<std::mutex> guard(m_interrupt_mutex); |
1286 | m_interrupt_requested++; |
1287 | } |
1288 | |
1289 | void Debugger::CancelInterruptRequest() { |
1290 | std::lock_guard<std::mutex> guard(m_interrupt_mutex); |
1291 | if (m_interrupt_requested > 0) |
1292 | m_interrupt_requested--; |
1293 | } |
1294 | |
1295 | bool Debugger::InterruptRequested() { |
1296 | // This is the one we should call internally. This will return true either |
1297 | // if there's a debugger interrupt and we aren't on the IOHandler thread, |
1298 | // or if we are on the IOHandler thread and there's a CommandInterpreter |
1299 | // interrupt. |
1300 | if (!IsIOHandlerThreadCurrentThread()) { |
1301 | std::lock_guard<std::mutex> guard(m_interrupt_mutex); |
1302 | return m_interrupt_requested != 0; |
1303 | } |
1304 | return GetCommandInterpreter().WasInterrupted(); |
1305 | } |
1306 | |
1307 | Debugger::InterruptionReport::InterruptionReport( |
1308 | std::string function_name, const llvm::formatv_object_base &payload) |
1309 | : m_function_name(std::move(function_name)), |
1310 | m_interrupt_time(std::chrono::system_clock::now()), |
1311 | m_thread_id(llvm::get_threadid()) { |
1312 | llvm::raw_string_ostream desc(m_description); |
1313 | desc << payload << "\n" ; |
1314 | } |
1315 | |
1316 | void Debugger::ReportInterruption(const InterruptionReport &report) { |
1317 | // For now, just log the description: |
1318 | Log *log = GetLog(mask: LLDBLog::Host); |
1319 | LLDB_LOG(log, "Interruption: {0}" , report.m_description); |
1320 | } |
1321 | |
1322 | Debugger::DebuggerList Debugger::DebuggersRequestingInterruption() { |
1323 | DebuggerList result; |
1324 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
1325 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
1326 | for (auto debugger_sp : *g_debugger_list_ptr) { |
1327 | if (debugger_sp->InterruptRequested()) |
1328 | result.push_back(x: debugger_sp); |
1329 | } |
1330 | } |
1331 | return result; |
1332 | } |
1333 | |
1334 | size_t Debugger::GetNumDebuggers() { |
1335 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
1336 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
1337 | return g_debugger_list_ptr->size(); |
1338 | } |
1339 | return 0; |
1340 | } |
1341 | |
1342 | lldb::DebuggerSP Debugger::GetDebuggerAtIndex(size_t index) { |
1343 | DebuggerSP debugger_sp; |
1344 | |
1345 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
1346 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
1347 | if (index < g_debugger_list_ptr->size()) |
1348 | debugger_sp = g_debugger_list_ptr->at(n: index); |
1349 | } |
1350 | |
1351 | return debugger_sp; |
1352 | } |
1353 | |
1354 | DebuggerSP Debugger::FindDebuggerWithID(lldb::user_id_t id) { |
1355 | DebuggerSP debugger_sp; |
1356 | |
1357 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
1358 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
1359 | DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); |
1360 | for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) { |
1361 | if ((*pos)->GetID() == id) { |
1362 | debugger_sp = *pos; |
1363 | break; |
1364 | } |
1365 | } |
1366 | } |
1367 | return debugger_sp; |
1368 | } |
1369 | |
1370 | bool Debugger::FormatDisassemblerAddress(const FormatEntity::Entry *format, |
1371 | const SymbolContext *sc, |
1372 | const SymbolContext *prev_sc, |
1373 | const ExecutionContext *exe_ctx, |
1374 | const Address *addr, Stream &s) { |
1375 | FormatEntity::Entry format_entry; |
1376 | |
1377 | if (format == nullptr) { |
1378 | if (exe_ctx != nullptr && exe_ctx->HasTargetScope()) |
1379 | format = exe_ctx->GetTargetRef().GetDebugger().GetDisassemblyFormat(); |
1380 | if (format == nullptr) { |
1381 | FormatEntity::Parse(format: "${addr}: " , entry&: format_entry); |
1382 | format = &format_entry; |
1383 | } |
1384 | } |
1385 | bool function_changed = false; |
1386 | bool initial_function = false; |
1387 | if (prev_sc && (prev_sc->function || prev_sc->symbol)) { |
1388 | if (sc && (sc->function || sc->symbol)) { |
1389 | if (prev_sc->symbol && sc->symbol) { |
1390 | if (!sc->symbol->Compare(name: prev_sc->symbol->GetName(), |
1391 | type: prev_sc->symbol->GetType())) { |
1392 | function_changed = true; |
1393 | } |
1394 | } else if (prev_sc->function && sc->function) { |
1395 | if (prev_sc->function->GetMangled() != sc->function->GetMangled()) { |
1396 | function_changed = true; |
1397 | } |
1398 | } |
1399 | } |
1400 | } |
1401 | // The first context on a list of instructions will have a prev_sc that has |
1402 | // no Function or Symbol -- if SymbolContext had an IsValid() method, it |
1403 | // would return false. But we do get a prev_sc pointer. |
1404 | if ((sc && (sc->function || sc->symbol)) && prev_sc && |
1405 | (prev_sc->function == nullptr && prev_sc->symbol == nullptr)) { |
1406 | initial_function = true; |
1407 | } |
1408 | return FormatEntity::Format(entry: *format, s, sc, exe_ctx, addr, valobj: nullptr, |
1409 | function_changed, initial_function); |
1410 | } |
1411 | |
1412 | void Debugger::AssertCallback(llvm::StringRef message, |
1413 | llvm::StringRef backtrace, |
1414 | llvm::StringRef prompt) { |
1415 | Debugger::ReportError( |
1416 | message: llvm::formatv(Fmt: "{0}\n{1}{2}" , Vals&: message, Vals&: backtrace, Vals&: prompt).str()); |
1417 | } |
1418 | |
1419 | void Debugger::SetLoggingCallback(lldb::LogOutputCallback log_callback, |
1420 | void *baton) { |
1421 | // For simplicity's sake, I am not going to deal with how to close down any |
1422 | // open logging streams, I just redirect everything from here on out to the |
1423 | // callback. |
1424 | m_callback_handler_sp = |
1425 | std::make_shared<CallbackLogHandler>(args&: log_callback, args&: baton); |
1426 | } |
1427 | |
1428 | void Debugger::SetDestroyCallback( |
1429 | lldb_private::DebuggerDestroyCallback destroy_callback, void *baton) { |
1430 | m_destroy_callback = destroy_callback; |
1431 | m_destroy_callback_baton = baton; |
1432 | } |
1433 | |
1434 | static void PrivateReportProgress(Debugger &debugger, uint64_t progress_id, |
1435 | std::string title, std::string details, |
1436 | uint64_t completed, uint64_t total, |
1437 | bool is_debugger_specific, |
1438 | uint32_t progress_broadcast_bit) { |
1439 | // Only deliver progress events if we have any progress listeners. |
1440 | if (!debugger.GetBroadcaster().EventTypeHasListeners(event_type: progress_broadcast_bit)) |
1441 | return; |
1442 | |
1443 | EventSP event_sp(new Event( |
1444 | progress_broadcast_bit, |
1445 | new ProgressEventData(progress_id, std::move(title), std::move(details), |
1446 | completed, total, is_debugger_specific))); |
1447 | debugger.GetBroadcaster().BroadcastEvent(event_sp); |
1448 | } |
1449 | |
1450 | void Debugger::ReportProgress(uint64_t progress_id, std::string title, |
1451 | std::string details, uint64_t completed, |
1452 | uint64_t total, |
1453 | std::optional<lldb::user_id_t> debugger_id, |
1454 | uint32_t progress_category_bit) { |
1455 | // Check if this progress is for a specific debugger. |
1456 | if (debugger_id) { |
1457 | // It is debugger specific, grab it and deliver the event if the debugger |
1458 | // still exists. |
1459 | DebuggerSP debugger_sp = FindDebuggerWithID(id: *debugger_id); |
1460 | if (debugger_sp) |
1461 | PrivateReportProgress(debugger&: *debugger_sp, progress_id, title: std::move(title), |
1462 | details: std::move(details), completed, total, |
1463 | /*is_debugger_specific*/ true, |
1464 | progress_broadcast_bit: progress_category_bit); |
1465 | return; |
1466 | } |
1467 | // The progress event is not debugger specific, iterate over all debuggers |
1468 | // and deliver a progress event to each one. |
1469 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
1470 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
1471 | DebuggerList::iterator pos, end = g_debugger_list_ptr->end(); |
1472 | for (pos = g_debugger_list_ptr->begin(); pos != end; ++pos) |
1473 | PrivateReportProgress(debugger&: *(*pos), progress_id, title, details, completed, |
1474 | total, /*is_debugger_specific*/ false, |
1475 | progress_broadcast_bit: progress_category_bit); |
1476 | } |
1477 | } |
1478 | |
1479 | static void PrivateReportDiagnostic(Debugger &debugger, |
1480 | DiagnosticEventData::Type type, |
1481 | std::string message, |
1482 | bool debugger_specific) { |
1483 | uint32_t event_type = 0; |
1484 | switch (type) { |
1485 | case DiagnosticEventData::Type::Info: |
1486 | assert(false && "DiagnosticEventData::Type::Info should not be broadcast" ); |
1487 | return; |
1488 | case DiagnosticEventData::Type::Warning: |
1489 | event_type = Debugger::eBroadcastBitWarning; |
1490 | break; |
1491 | case DiagnosticEventData::Type::Error: |
1492 | event_type = Debugger::eBroadcastBitError; |
1493 | break; |
1494 | } |
1495 | |
1496 | Broadcaster &broadcaster = debugger.GetBroadcaster(); |
1497 | if (!broadcaster.EventTypeHasListeners(event_type)) { |
1498 | // Diagnostics are too important to drop. If nobody is listening, print the |
1499 | // diagnostic directly to the debugger's error stream. |
1500 | DiagnosticEventData event_data(type, std::move(message), debugger_specific); |
1501 | StreamSP stream = debugger.GetAsyncErrorStream(); |
1502 | event_data.Dump(s: stream.get()); |
1503 | return; |
1504 | } |
1505 | EventSP event_sp = std::make_shared<Event>( |
1506 | args&: event_type, |
1507 | args: new DiagnosticEventData(type, std::move(message), debugger_specific)); |
1508 | broadcaster.BroadcastEvent(event_sp); |
1509 | } |
1510 | |
1511 | void Debugger::ReportDiagnosticImpl(DiagnosticEventData::Type type, |
1512 | std::string message, |
1513 | std::optional<lldb::user_id_t> debugger_id, |
1514 | std::once_flag *once) { |
1515 | auto ReportDiagnosticLambda = [&]() { |
1516 | // The diagnostic subsystem is optional but we still want to broadcast |
1517 | // events when it's disabled. |
1518 | if (Diagnostics::Enabled()) |
1519 | Diagnostics::Instance().Report(message); |
1520 | |
1521 | // We don't broadcast info events. |
1522 | if (type == DiagnosticEventData::Type::Info) |
1523 | return; |
1524 | |
1525 | // Check if this diagnostic is for a specific debugger. |
1526 | if (debugger_id) { |
1527 | // It is debugger specific, grab it and deliver the event if the debugger |
1528 | // still exists. |
1529 | DebuggerSP debugger_sp = FindDebuggerWithID(id: *debugger_id); |
1530 | if (debugger_sp) |
1531 | PrivateReportDiagnostic(debugger&: *debugger_sp, type, message: std::move(message), debugger_specific: true); |
1532 | return; |
1533 | } |
1534 | // The diagnostic event is not debugger specific, iterate over all debuggers |
1535 | // and deliver a diagnostic event to each one. |
1536 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
1537 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
1538 | for (const auto &debugger : *g_debugger_list_ptr) |
1539 | PrivateReportDiagnostic(debugger&: *debugger, type, message, debugger_specific: false); |
1540 | } |
1541 | }; |
1542 | |
1543 | if (once) |
1544 | std::call_once(once&: *once, f&: ReportDiagnosticLambda); |
1545 | else |
1546 | ReportDiagnosticLambda(); |
1547 | } |
1548 | |
1549 | void Debugger::ReportWarning(std::string message, |
1550 | std::optional<lldb::user_id_t> debugger_id, |
1551 | std::once_flag *once) { |
1552 | ReportDiagnosticImpl(type: DiagnosticEventData::Type::Warning, message: std::move(message), |
1553 | debugger_id, once); |
1554 | } |
1555 | |
1556 | void Debugger::ReportError(std::string message, |
1557 | std::optional<lldb::user_id_t> debugger_id, |
1558 | std::once_flag *once) { |
1559 | ReportDiagnosticImpl(type: DiagnosticEventData::Type::Error, message: std::move(message), |
1560 | debugger_id, once); |
1561 | } |
1562 | |
1563 | void Debugger::ReportInfo(std::string message, |
1564 | std::optional<lldb::user_id_t> debugger_id, |
1565 | std::once_flag *once) { |
1566 | ReportDiagnosticImpl(type: DiagnosticEventData::Type::Info, message: std::move(message), |
1567 | debugger_id, once); |
1568 | } |
1569 | |
1570 | void Debugger::ReportSymbolChange(const ModuleSpec &module_spec) { |
1571 | if (g_debugger_list_ptr && g_debugger_list_mutex_ptr) { |
1572 | std::lock_guard<std::recursive_mutex> guard(*g_debugger_list_mutex_ptr); |
1573 | for (DebuggerSP debugger_sp : *g_debugger_list_ptr) { |
1574 | EventSP event_sp = std::make_shared<Event>( |
1575 | args: Debugger::eBroadcastSymbolChange, |
1576 | args: new SymbolChangeEventData(debugger_sp, module_spec)); |
1577 | debugger_sp->GetBroadcaster().BroadcastEvent(event_sp); |
1578 | } |
1579 | } |
1580 | } |
1581 | |
1582 | static std::shared_ptr<LogHandler> |
1583 | CreateLogHandler(LogHandlerKind log_handler_kind, int fd, bool should_close, |
1584 | size_t buffer_size) { |
1585 | switch (log_handler_kind) { |
1586 | case eLogHandlerStream: |
1587 | return std::make_shared<StreamLogHandler>(args&: fd, args&: should_close, args&: buffer_size); |
1588 | case eLogHandlerCircular: |
1589 | return std::make_shared<RotatingLogHandler>(args&: buffer_size); |
1590 | case eLogHandlerSystem: |
1591 | return std::make_shared<SystemLogHandler>(); |
1592 | case eLogHandlerCallback: |
1593 | return {}; |
1594 | } |
1595 | return {}; |
1596 | } |
1597 | |
1598 | bool Debugger::EnableLog(llvm::StringRef channel, |
1599 | llvm::ArrayRef<const char *> categories, |
1600 | llvm::StringRef log_file, uint32_t log_options, |
1601 | size_t buffer_size, LogHandlerKind log_handler_kind, |
1602 | llvm::raw_ostream &error_stream) { |
1603 | |
1604 | std::shared_ptr<LogHandler> log_handler_sp; |
1605 | if (m_callback_handler_sp) { |
1606 | log_handler_sp = m_callback_handler_sp; |
1607 | // For now when using the callback mode you always get thread & timestamp. |
1608 | log_options |= |
1609 | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_THREAD_NAME; |
1610 | } else if (log_file.empty()) { |
1611 | log_handler_sp = |
1612 | CreateLogHandler(log_handler_kind, fd: GetOutputFile().GetDescriptor(), |
1613 | /*should_close=*/false, buffer_size); |
1614 | } else { |
1615 | auto pos = m_stream_handlers.find(Key: log_file); |
1616 | if (pos != m_stream_handlers.end()) |
1617 | log_handler_sp = pos->second.lock(); |
1618 | if (!log_handler_sp) { |
1619 | File::OpenOptions flags = |
1620 | File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate; |
1621 | if (log_options & LLDB_LOG_OPTION_APPEND) |
1622 | flags |= File::eOpenOptionAppend; |
1623 | else |
1624 | flags |= File::eOpenOptionTruncate; |
1625 | llvm::Expected<FileUP> file = FileSystem::Instance().Open( |
1626 | file_spec: FileSpec(log_file), options: flags, permissions: lldb::eFilePermissionsFileDefault, should_close_fd: false); |
1627 | if (!file) { |
1628 | error_stream << "Unable to open log file '" << log_file |
1629 | << "': " << llvm::toString(E: file.takeError()) << "\n" ; |
1630 | return false; |
1631 | } |
1632 | |
1633 | log_handler_sp = |
1634 | CreateLogHandler(log_handler_kind, fd: (*file)->GetDescriptor(), |
1635 | /*should_close=*/true, buffer_size); |
1636 | m_stream_handlers[log_file] = log_handler_sp; |
1637 | } |
1638 | } |
1639 | assert(log_handler_sp); |
1640 | |
1641 | if (log_options == 0) |
1642 | log_options = LLDB_LOG_OPTION_PREPEND_THREAD_NAME; |
1643 | |
1644 | return Log::EnableLogChannel(log_handler_sp, log_options, channel, categories, |
1645 | error_stream); |
1646 | } |
1647 | |
1648 | ScriptInterpreter * |
1649 | Debugger::GetScriptInterpreter(bool can_create, |
1650 | std::optional<lldb::ScriptLanguage> language) { |
1651 | std::lock_guard<std::recursive_mutex> locker(m_script_interpreter_mutex); |
1652 | lldb::ScriptLanguage script_language = |
1653 | language ? *language : GetScriptLanguage(); |
1654 | |
1655 | if (!m_script_interpreters[script_language]) { |
1656 | if (!can_create) |
1657 | return nullptr; |
1658 | m_script_interpreters[script_language] = |
1659 | PluginManager::GetScriptInterpreterForLanguage(script_lang: script_language, debugger&: *this); |
1660 | } |
1661 | |
1662 | return m_script_interpreters[script_language].get(); |
1663 | } |
1664 | |
1665 | SourceManager &Debugger::GetSourceManager() { |
1666 | if (!m_source_manager_up) |
1667 | m_source_manager_up = std::make_unique<SourceManager>(args: shared_from_this()); |
1668 | return *m_source_manager_up; |
1669 | } |
1670 | |
1671 | // This function handles events that were broadcast by the process. |
1672 | void Debugger::HandleBreakpointEvent(const EventSP &event_sp) { |
1673 | using namespace lldb; |
1674 | const uint32_t event_type = |
1675 | Breakpoint::BreakpointEventData::GetBreakpointEventTypeFromEvent( |
1676 | event_sp); |
1677 | |
1678 | // if (event_type & eBreakpointEventTypeAdded |
1679 | // || event_type & eBreakpointEventTypeRemoved |
1680 | // || event_type & eBreakpointEventTypeEnabled |
1681 | // || event_type & eBreakpointEventTypeDisabled |
1682 | // || event_type & eBreakpointEventTypeCommandChanged |
1683 | // || event_type & eBreakpointEventTypeConditionChanged |
1684 | // || event_type & eBreakpointEventTypeIgnoreChanged |
1685 | // || event_type & eBreakpointEventTypeLocationsResolved) |
1686 | // { |
1687 | // // Don't do anything about these events, since the breakpoint |
1688 | // commands already echo these actions. |
1689 | // } |
1690 | // |
1691 | if (event_type & eBreakpointEventTypeLocationsAdded) { |
1692 | uint32_t num_new_locations = |
1693 | Breakpoint::BreakpointEventData::GetNumBreakpointLocationsFromEvent( |
1694 | event_sp); |
1695 | if (num_new_locations > 0) { |
1696 | BreakpointSP breakpoint = |
1697 | Breakpoint::BreakpointEventData::GetBreakpointFromEvent(event_sp); |
1698 | StreamSP output_sp(GetAsyncOutputStream()); |
1699 | if (output_sp) { |
1700 | output_sp->Printf(format: "%d location%s added to breakpoint %d\n" , |
1701 | num_new_locations, num_new_locations == 1 ? "" : "s" , |
1702 | breakpoint->GetID()); |
1703 | output_sp->Flush(); |
1704 | } |
1705 | } |
1706 | } |
1707 | // else if (event_type & eBreakpointEventTypeLocationsRemoved) |
1708 | // { |
1709 | // // These locations just get disabled, not sure it is worth spamming |
1710 | // folks about this on the command line. |
1711 | // } |
1712 | // else if (event_type & eBreakpointEventTypeLocationsResolved) |
1713 | // { |
1714 | // // This might be an interesting thing to note, but I'm going to |
1715 | // leave it quiet for now, it just looked noisy. |
1716 | // } |
1717 | } |
1718 | |
1719 | void Debugger::FlushProcessOutput(Process &process, bool flush_stdout, |
1720 | bool flush_stderr) { |
1721 | const auto &flush = [&](Stream &stream, |
1722 | size_t (Process::*get)(char *, size_t, Status &)) { |
1723 | Status error; |
1724 | size_t len; |
1725 | char buffer[1024]; |
1726 | while ((len = (process.*get)(buffer, sizeof(buffer), error)) > 0) |
1727 | stream.Write(src: buffer, src_len: len); |
1728 | stream.Flush(); |
1729 | }; |
1730 | |
1731 | std::lock_guard<std::mutex> guard(m_output_flush_mutex); |
1732 | if (flush_stdout) |
1733 | flush(*GetAsyncOutputStream(), &Process::GetSTDOUT); |
1734 | if (flush_stderr) |
1735 | flush(*GetAsyncErrorStream(), &Process::GetSTDERR); |
1736 | } |
1737 | |
1738 | // This function handles events that were broadcast by the process. |
1739 | void Debugger::HandleProcessEvent(const EventSP &event_sp) { |
1740 | using namespace lldb; |
1741 | const uint32_t event_type = event_sp->GetType(); |
1742 | ProcessSP process_sp = |
1743 | (event_type == Process::eBroadcastBitStructuredData) |
1744 | ? EventDataStructuredData::GetProcessFromEvent(event_ptr: event_sp.get()) |
1745 | : Process::ProcessEventData::GetProcessFromEvent(event_ptr: event_sp.get()); |
1746 | |
1747 | StreamSP output_stream_sp = GetAsyncOutputStream(); |
1748 | StreamSP error_stream_sp = GetAsyncErrorStream(); |
1749 | const bool gui_enabled = IsForwardingEvents(); |
1750 | |
1751 | if (!gui_enabled) { |
1752 | bool pop_process_io_handler = false; |
1753 | assert(process_sp); |
1754 | |
1755 | bool state_is_stopped = false; |
1756 | const bool got_state_changed = |
1757 | (event_type & Process::eBroadcastBitStateChanged) != 0; |
1758 | const bool got_stdout = (event_type & Process::eBroadcastBitSTDOUT) != 0; |
1759 | const bool got_stderr = (event_type & Process::eBroadcastBitSTDERR) != 0; |
1760 | const bool got_structured_data = |
1761 | (event_type & Process::eBroadcastBitStructuredData) != 0; |
1762 | |
1763 | if (got_state_changed) { |
1764 | StateType event_state = |
1765 | Process::ProcessEventData::GetStateFromEvent(event_ptr: event_sp.get()); |
1766 | state_is_stopped = StateIsStoppedState(state: event_state, must_exist: false); |
1767 | } |
1768 | |
1769 | // Display running state changes first before any STDIO |
1770 | if (got_state_changed && !state_is_stopped) { |
1771 | // This is a public stop which we are going to announce to the user, so |
1772 | // we should force the most relevant frame selection here. |
1773 | Process::HandleProcessStateChangedEvent(event_sp, stream: output_stream_sp.get(), |
1774 | select_most_relevant: SelectMostRelevantFrame, |
1775 | pop_process_io_handler); |
1776 | } |
1777 | |
1778 | // Now display STDOUT and STDERR |
1779 | FlushProcessOutput(process&: *process_sp, flush_stdout: got_stdout || got_state_changed, |
1780 | flush_stderr: got_stderr || got_state_changed); |
1781 | |
1782 | // Give structured data events an opportunity to display. |
1783 | if (got_structured_data) { |
1784 | StructuredDataPluginSP plugin_sp = |
1785 | EventDataStructuredData::GetPluginFromEvent(event_ptr: event_sp.get()); |
1786 | if (plugin_sp) { |
1787 | auto structured_data_sp = |
1788 | EventDataStructuredData::GetObjectFromEvent(event_ptr: event_sp.get()); |
1789 | if (output_stream_sp) { |
1790 | StreamString content_stream; |
1791 | Status error = |
1792 | plugin_sp->GetDescription(object_sp: structured_data_sp, stream&: content_stream); |
1793 | if (error.Success()) { |
1794 | if (!content_stream.GetString().empty()) { |
1795 | // Add newline. |
1796 | content_stream.PutChar(ch: '\n'); |
1797 | content_stream.Flush(); |
1798 | |
1799 | // Print it. |
1800 | output_stream_sp->PutCString(cstr: content_stream.GetString()); |
1801 | } |
1802 | } else { |
1803 | error_stream_sp->Format(format: "Failed to print structured " |
1804 | "data with plugin {0}: {1}" , |
1805 | args: plugin_sp->GetPluginName(), args&: error); |
1806 | } |
1807 | } |
1808 | } |
1809 | } |
1810 | |
1811 | // Now display any stopped state changes after any STDIO |
1812 | if (got_state_changed && state_is_stopped) { |
1813 | Process::HandleProcessStateChangedEvent(event_sp, stream: output_stream_sp.get(), |
1814 | select_most_relevant: SelectMostRelevantFrame, |
1815 | pop_process_io_handler); |
1816 | } |
1817 | |
1818 | output_stream_sp->Flush(); |
1819 | error_stream_sp->Flush(); |
1820 | |
1821 | if (pop_process_io_handler) |
1822 | process_sp->PopProcessIOHandler(); |
1823 | } |
1824 | } |
1825 | |
1826 | void Debugger::HandleThreadEvent(const EventSP &event_sp) { |
1827 | // At present the only thread event we handle is the Frame Changed event, and |
1828 | // all we do for that is just reprint the thread status for that thread. |
1829 | using namespace lldb; |
1830 | const uint32_t event_type = event_sp->GetType(); |
1831 | const bool stop_format = true; |
1832 | if (event_type == Thread::eBroadcastBitStackChanged || |
1833 | event_type == Thread::eBroadcastBitThreadSelected) { |
1834 | ThreadSP thread_sp( |
1835 | Thread::ThreadEventData::GetThreadFromEvent(event_ptr: event_sp.get())); |
1836 | if (thread_sp) { |
1837 | thread_sp->GetStatus(strm&: *GetAsyncOutputStream(), start_frame: 0, num_frames: 1, num_frames_with_source: 1, stop_format); |
1838 | } |
1839 | } |
1840 | } |
1841 | |
1842 | bool Debugger::IsForwardingEvents() { return (bool)m_forward_listener_sp; } |
1843 | |
1844 | void Debugger::EnableForwardEvents(const ListenerSP &listener_sp) { |
1845 | m_forward_listener_sp = listener_sp; |
1846 | } |
1847 | |
1848 | void Debugger::CancelForwardEvents(const ListenerSP &listener_sp) { |
1849 | m_forward_listener_sp.reset(); |
1850 | } |
1851 | |
1852 | lldb::thread_result_t Debugger::DefaultEventHandler() { |
1853 | ListenerSP listener_sp(GetListener()); |
1854 | ConstString broadcaster_class_target(Target::GetStaticBroadcasterClass()); |
1855 | ConstString broadcaster_class_process(Process::GetStaticBroadcasterClass()); |
1856 | ConstString broadcaster_class_thread(Thread::GetStaticBroadcasterClass()); |
1857 | BroadcastEventSpec target_event_spec(broadcaster_class_target, |
1858 | Target::eBroadcastBitBreakpointChanged); |
1859 | |
1860 | BroadcastEventSpec process_event_spec( |
1861 | broadcaster_class_process, |
1862 | Process::eBroadcastBitStateChanged | Process::eBroadcastBitSTDOUT | |
1863 | Process::eBroadcastBitSTDERR | Process::eBroadcastBitStructuredData); |
1864 | |
1865 | BroadcastEventSpec thread_event_spec(broadcaster_class_thread, |
1866 | Thread::eBroadcastBitStackChanged | |
1867 | Thread::eBroadcastBitThreadSelected); |
1868 | |
1869 | listener_sp->StartListeningForEventSpec(manager_sp: m_broadcaster_manager_sp, |
1870 | event_spec: target_event_spec); |
1871 | listener_sp->StartListeningForEventSpec(manager_sp: m_broadcaster_manager_sp, |
1872 | event_spec: process_event_spec); |
1873 | listener_sp->StartListeningForEventSpec(manager_sp: m_broadcaster_manager_sp, |
1874 | event_spec: thread_event_spec); |
1875 | listener_sp->StartListeningForEvents( |
1876 | broadcaster: m_command_interpreter_up.get(), |
1877 | event_mask: CommandInterpreter::eBroadcastBitQuitCommandReceived | |
1878 | CommandInterpreter::eBroadcastBitAsynchronousOutputData | |
1879 | CommandInterpreter::eBroadcastBitAsynchronousErrorData); |
1880 | |
1881 | listener_sp->StartListeningForEvents( |
1882 | broadcaster: &m_broadcaster, event_mask: eBroadcastBitProgress | eBroadcastBitWarning | |
1883 | eBroadcastBitError | eBroadcastSymbolChange); |
1884 | |
1885 | // Let the thread that spawned us know that we have started up and that we |
1886 | // are now listening to all required events so no events get missed |
1887 | m_sync_broadcaster.BroadcastEvent(event_type: eBroadcastBitEventThreadIsListening); |
1888 | |
1889 | bool done = false; |
1890 | while (!done) { |
1891 | EventSP event_sp; |
1892 | if (listener_sp->GetEvent(event_sp, timeout: std::nullopt)) { |
1893 | if (event_sp) { |
1894 | Broadcaster *broadcaster = event_sp->GetBroadcaster(); |
1895 | if (broadcaster) { |
1896 | uint32_t event_type = event_sp->GetType(); |
1897 | ConstString broadcaster_class(broadcaster->GetBroadcasterClass()); |
1898 | if (broadcaster_class == broadcaster_class_process) { |
1899 | HandleProcessEvent(event_sp); |
1900 | } else if (broadcaster_class == broadcaster_class_target) { |
1901 | if (Breakpoint::BreakpointEventData::GetEventDataFromEvent( |
1902 | event_sp: event_sp.get())) { |
1903 | HandleBreakpointEvent(event_sp); |
1904 | } |
1905 | } else if (broadcaster_class == broadcaster_class_thread) { |
1906 | HandleThreadEvent(event_sp); |
1907 | } else if (broadcaster == m_command_interpreter_up.get()) { |
1908 | if (event_type & |
1909 | CommandInterpreter::eBroadcastBitQuitCommandReceived) { |
1910 | done = true; |
1911 | } else if (event_type & |
1912 | CommandInterpreter::eBroadcastBitAsynchronousErrorData) { |
1913 | const char *data = static_cast<const char *>( |
1914 | EventDataBytes::GetBytesFromEvent(event_ptr: event_sp.get())); |
1915 | if (data && data[0]) { |
1916 | StreamSP error_sp(GetAsyncErrorStream()); |
1917 | if (error_sp) { |
1918 | error_sp->PutCString(cstr: data); |
1919 | error_sp->Flush(); |
1920 | } |
1921 | } |
1922 | } else if (event_type & CommandInterpreter:: |
1923 | eBroadcastBitAsynchronousOutputData) { |
1924 | const char *data = static_cast<const char *>( |
1925 | EventDataBytes::GetBytesFromEvent(event_ptr: event_sp.get())); |
1926 | if (data && data[0]) { |
1927 | StreamSP output_sp(GetAsyncOutputStream()); |
1928 | if (output_sp) { |
1929 | output_sp->PutCString(cstr: data); |
1930 | output_sp->Flush(); |
1931 | } |
1932 | } |
1933 | } |
1934 | } else if (broadcaster == &m_broadcaster) { |
1935 | if (event_type & Debugger::eBroadcastBitProgress) |
1936 | HandleProgressEvent(event_sp); |
1937 | else if (event_type & Debugger::eBroadcastBitWarning) |
1938 | HandleDiagnosticEvent(event_sp); |
1939 | else if (event_type & Debugger::eBroadcastBitError) |
1940 | HandleDiagnosticEvent(event_sp); |
1941 | } |
1942 | } |
1943 | |
1944 | if (m_forward_listener_sp) |
1945 | m_forward_listener_sp->AddEvent(event&: event_sp); |
1946 | } |
1947 | } |
1948 | } |
1949 | return {}; |
1950 | } |
1951 | |
1952 | bool Debugger::StartEventHandlerThread() { |
1953 | if (!m_event_handler_thread.IsJoinable()) { |
1954 | // We must synchronize with the DefaultEventHandler() thread to ensure it |
1955 | // is up and running and listening to events before we return from this |
1956 | // function. We do this by listening to events for the |
1957 | // eBroadcastBitEventThreadIsListening from the m_sync_broadcaster |
1958 | ConstString full_name("lldb.debugger.event-handler" ); |
1959 | ListenerSP listener_sp(Listener::MakeListener(name: full_name.AsCString())); |
1960 | listener_sp->StartListeningForEvents(broadcaster: &m_sync_broadcaster, |
1961 | event_mask: eBroadcastBitEventThreadIsListening); |
1962 | |
1963 | llvm::StringRef thread_name = |
1964 | full_name.GetLength() < llvm::get_max_thread_name_length() |
1965 | ? full_name.GetStringRef() |
1966 | : "dbg.evt-handler" ; |
1967 | |
1968 | // Use larger 8MB stack for this thread |
1969 | llvm::Expected<HostThread> event_handler_thread = |
1970 | ThreadLauncher::LaunchThread( |
1971 | name: thread_name, thread_function: [this] { return DefaultEventHandler(); }, |
1972 | min_stack_byte_size: g_debugger_event_thread_stack_bytes); |
1973 | |
1974 | if (event_handler_thread) { |
1975 | m_event_handler_thread = *event_handler_thread; |
1976 | } else { |
1977 | LLDB_LOG_ERROR(GetLog(LLDBLog::Host), event_handler_thread.takeError(), |
1978 | "failed to launch host thread: {0}" ); |
1979 | } |
1980 | |
1981 | // Make sure DefaultEventHandler() is running and listening to events |
1982 | // before we return from this function. We are only listening for events of |
1983 | // type eBroadcastBitEventThreadIsListening so we don't need to check the |
1984 | // event, we just need to wait an infinite amount of time for it (nullptr |
1985 | // timeout as the first parameter) |
1986 | lldb::EventSP event_sp; |
1987 | listener_sp->GetEvent(event_sp, timeout: std::nullopt); |
1988 | } |
1989 | return m_event_handler_thread.IsJoinable(); |
1990 | } |
1991 | |
1992 | void Debugger::StopEventHandlerThread() { |
1993 | if (m_event_handler_thread.IsJoinable()) { |
1994 | GetCommandInterpreter().BroadcastEvent( |
1995 | event_type: CommandInterpreter::eBroadcastBitQuitCommandReceived); |
1996 | m_event_handler_thread.Join(result: nullptr); |
1997 | } |
1998 | } |
1999 | |
2000 | lldb::thread_result_t Debugger::IOHandlerThread() { |
2001 | RunIOHandlers(); |
2002 | StopEventHandlerThread(); |
2003 | return {}; |
2004 | } |
2005 | |
2006 | void Debugger::HandleProgressEvent(const lldb::EventSP &event_sp) { |
2007 | auto *data = ProgressEventData::GetEventDataFromEvent(event_ptr: event_sp.get()); |
2008 | if (!data) |
2009 | return; |
2010 | |
2011 | // Do some bookkeeping for the current event, regardless of whether we're |
2012 | // going to show the progress. |
2013 | const uint64_t id = data->GetID(); |
2014 | if (m_current_event_id) { |
2015 | Log *log = GetLog(mask: LLDBLog::Events); |
2016 | if (log && log->GetVerbose()) { |
2017 | StreamString log_stream; |
2018 | log_stream.AsRawOstream() |
2019 | << static_cast<void *>(this) << " Debugger(" << GetID() |
2020 | << ")::HandleProgressEvent( m_current_event_id = " |
2021 | << *m_current_event_id << ", data = { " ; |
2022 | data->Dump(s: &log_stream); |
2023 | log_stream << " } )" ; |
2024 | log->PutString(str: log_stream.GetString()); |
2025 | } |
2026 | if (id != *m_current_event_id) |
2027 | return; |
2028 | if (data->GetCompleted() == data->GetTotal()) |
2029 | m_current_event_id.reset(); |
2030 | } else { |
2031 | m_current_event_id = id; |
2032 | } |
2033 | |
2034 | // Decide whether we actually are going to show the progress. This decision |
2035 | // can change between iterations so check it inside the loop. |
2036 | if (!GetShowProgress()) |
2037 | return; |
2038 | |
2039 | // Determine whether the current output file is an interactive terminal with |
2040 | // color support. We assume that if we support ANSI escape codes we support |
2041 | // vt100 escape codes. |
2042 | File &file = GetOutputFile(); |
2043 | if (!file.GetIsInteractive() || !file.GetIsTerminalWithColors()) |
2044 | return; |
2045 | |
2046 | StreamSP output = GetAsyncOutputStream(); |
2047 | |
2048 | // Print over previous line, if any. |
2049 | output->Printf(format: "\r" ); |
2050 | |
2051 | if (data->GetCompleted() == data->GetTotal()) { |
2052 | // Clear the current line. |
2053 | output->Printf(format: "\x1B[2K" ); |
2054 | output->Flush(); |
2055 | return; |
2056 | } |
2057 | |
2058 | // Trim the progress message if it exceeds the window's width and print it. |
2059 | std::string message = data->GetMessage(); |
2060 | if (data->IsFinite()) |
2061 | message = llvm::formatv(Fmt: "[{0}/{1}] {2}" , Vals: data->GetCompleted(), |
2062 | Vals: data->GetTotal(), Vals&: message) |
2063 | .str(); |
2064 | |
2065 | // Trim the progress message if it exceeds the window's width and print it. |
2066 | const uint32_t term_width = GetTerminalWidth(); |
2067 | const uint32_t ellipsis = 3; |
2068 | if (message.size() + ellipsis >= term_width) |
2069 | message = message.substr(pos: 0, n: term_width - ellipsis); |
2070 | |
2071 | const bool use_color = GetUseColor(); |
2072 | llvm::StringRef ansi_prefix = GetShowProgressAnsiPrefix(); |
2073 | if (!ansi_prefix.empty()) |
2074 | output->Printf( |
2075 | format: "%s" , ansi::FormatAnsiTerminalCodes(format: ansi_prefix, do_color: use_color).c_str()); |
2076 | |
2077 | output->Printf(format: "%s..." , message.c_str()); |
2078 | |
2079 | llvm::StringRef ansi_suffix = GetShowProgressAnsiSuffix(); |
2080 | if (!ansi_suffix.empty()) |
2081 | output->Printf( |
2082 | format: "%s" , ansi::FormatAnsiTerminalCodes(format: ansi_suffix, do_color: use_color).c_str()); |
2083 | |
2084 | // Clear until the end of the line. |
2085 | output->Printf(format: "\x1B[K\r" ); |
2086 | |
2087 | // Flush the output. |
2088 | output->Flush(); |
2089 | } |
2090 | |
2091 | void Debugger::HandleDiagnosticEvent(const lldb::EventSP &event_sp) { |
2092 | auto *data = DiagnosticEventData::GetEventDataFromEvent(event_ptr: event_sp.get()); |
2093 | if (!data) |
2094 | return; |
2095 | |
2096 | StreamSP stream = GetAsyncErrorStream(); |
2097 | data->Dump(s: stream.get()); |
2098 | } |
2099 | |
2100 | bool Debugger::HasIOHandlerThread() const { |
2101 | return m_io_handler_thread.IsJoinable(); |
2102 | } |
2103 | |
2104 | HostThread Debugger::SetIOHandlerThread(HostThread &new_thread) { |
2105 | HostThread old_host = m_io_handler_thread; |
2106 | m_io_handler_thread = new_thread; |
2107 | return old_host; |
2108 | } |
2109 | |
2110 | bool Debugger::StartIOHandlerThread() { |
2111 | if (!m_io_handler_thread.IsJoinable()) { |
2112 | llvm::Expected<HostThread> io_handler_thread = ThreadLauncher::LaunchThread( |
2113 | name: "lldb.debugger.io-handler" , thread_function: [this] { return IOHandlerThread(); }, |
2114 | min_stack_byte_size: 8 * 1024 * 1024); // Use larger 8MB stack for this thread |
2115 | if (io_handler_thread) { |
2116 | m_io_handler_thread = *io_handler_thread; |
2117 | } else { |
2118 | LLDB_LOG_ERROR(GetLog(LLDBLog::Host), io_handler_thread.takeError(), |
2119 | "failed to launch host thread: {0}" ); |
2120 | } |
2121 | } |
2122 | return m_io_handler_thread.IsJoinable(); |
2123 | } |
2124 | |
2125 | void Debugger::StopIOHandlerThread() { |
2126 | if (m_io_handler_thread.IsJoinable()) { |
2127 | GetInputFile().Close(); |
2128 | m_io_handler_thread.Join(result: nullptr); |
2129 | } |
2130 | } |
2131 | |
2132 | void Debugger::JoinIOHandlerThread() { |
2133 | if (HasIOHandlerThread()) { |
2134 | thread_result_t result; |
2135 | m_io_handler_thread.Join(result: &result); |
2136 | m_io_handler_thread = LLDB_INVALID_HOST_THREAD; |
2137 | } |
2138 | } |
2139 | |
2140 | bool Debugger::IsIOHandlerThreadCurrentThread() const { |
2141 | if (!HasIOHandlerThread()) |
2142 | return false; |
2143 | return m_io_handler_thread.EqualsThread(thread: Host::GetCurrentThread()); |
2144 | } |
2145 | |
2146 | Target &Debugger::GetSelectedOrDummyTarget(bool prefer_dummy) { |
2147 | if (!prefer_dummy) { |
2148 | if (TargetSP target = m_target_list.GetSelectedTarget()) |
2149 | return *target; |
2150 | } |
2151 | return GetDummyTarget(); |
2152 | } |
2153 | |
2154 | Status Debugger::RunREPL(LanguageType language, const char *repl_options) { |
2155 | Status err; |
2156 | FileSpec repl_executable; |
2157 | |
2158 | if (language == eLanguageTypeUnknown) |
2159 | language = GetREPLLanguage(); |
2160 | |
2161 | if (language == eLanguageTypeUnknown) { |
2162 | LanguageSet repl_languages = Language::GetLanguagesSupportingREPLs(); |
2163 | |
2164 | if (auto single_lang = repl_languages.GetSingularLanguage()) { |
2165 | language = *single_lang; |
2166 | } else if (repl_languages.Empty()) { |
2167 | err.SetErrorString( |
2168 | "LLDB isn't configured with REPL support for any languages." ); |
2169 | return err; |
2170 | } else { |
2171 | err.SetErrorString( |
2172 | "Multiple possible REPL languages. Please specify a language." ); |
2173 | return err; |
2174 | } |
2175 | } |
2176 | |
2177 | Target *const target = |
2178 | nullptr; // passing in an empty target means the REPL must create one |
2179 | |
2180 | REPLSP repl_sp(REPL::Create(Status&: err, language, debugger: this, target, repl_options)); |
2181 | |
2182 | if (!err.Success()) { |
2183 | return err; |
2184 | } |
2185 | |
2186 | if (!repl_sp) { |
2187 | err.SetErrorStringWithFormat("couldn't find a REPL for %s" , |
2188 | Language::GetNameForLanguageType(language)); |
2189 | return err; |
2190 | } |
2191 | |
2192 | repl_sp->SetCompilerOptions(repl_options); |
2193 | repl_sp->RunLoop(); |
2194 | |
2195 | return err; |
2196 | } |
2197 | |
2198 | llvm::ThreadPoolInterface &Debugger::GetThreadPool() { |
2199 | assert(g_thread_pool && |
2200 | "Debugger::GetThreadPool called before Debugger::Initialize" ); |
2201 | return *g_thread_pool; |
2202 | } |
2203 | |