LLDB  mainline
CommandInterpreter.cpp
Go to the documentation of this file.
1 //===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <memory>
10 #include <stdlib.h>
11 #include <string>
12 #include <vector>
13 
14 #include "CommandObjectScript.h"
16 
43 
44 #include "lldb/Core/Debugger.h"
46 #include "lldb/Core/StreamFile.h"
47 #include "lldb/Utility/Log.h"
48 #include "lldb/Utility/State.h"
49 #include "lldb/Utility/Stream.h"
50 #include "lldb/Utility/Timer.h"
51 
52 #ifndef LLDB_DISABLE_LIBEDIT
53 #include "lldb/Host/Editline.h"
54 #endif
55 #include "lldb/Host/Host.h"
56 #include "lldb/Host/HostInfo.h"
57 
64 #include "lldb/Utility/Args.h"
65 
66 #include "lldb/Target/Process.h"
67 #include "lldb/Target/TargetList.h"
68 #include "lldb/Target/Thread.h"
69 
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/SmallString.h"
72 #include "llvm/Support/Path.h"
73 #include "llvm/Support/PrettyStackTrace.h"
74 
75 using namespace lldb;
76 using namespace lldb_private;
77 
78 static const char *k_white_space = " \t\v";
79 
80 static constexpr bool NoGlobalSetting = true;
81 static constexpr uintptr_t DefaultValueTrue = true;
82 static constexpr uintptr_t DefaultValueFalse = false;
83 static constexpr const char *NoCStrDefault = nullptr;
84 
85 static constexpr PropertyDefinition g_properties[] = {
86  {"expand-regex-aliases", OptionValue::eTypeBoolean, NoGlobalSetting,
88  "If true, regular expression alias commands will show the "
89  "expanded command that will be executed. This can be used to "
90  "debug new regular expression alias commands."},
91  {"prompt-on-quit", OptionValue::eTypeBoolean, NoGlobalSetting,
93  "If true, LLDB will prompt you before quitting if there are any live "
94  "processes being debugged. If false, LLDB will quit without asking in any "
95  "case."},
96  {"stop-command-source-on-error", OptionValue::eTypeBoolean, NoGlobalSetting,
98  "If true, LLDB will stop running a 'command source' "
99  "script upon encountering an error."},
100  {"space-repl-prompts", OptionValue::eTypeBoolean, NoGlobalSetting,
102  "If true, blank lines will be printed between between REPL submissions."},
103  {"echo-commands", OptionValue::eTypeBoolean, NoGlobalSetting,
105  "If true, commands will be echoed before they are evaluated."},
106  {"echo-comment-commands", OptionValue::eTypeBoolean, NoGlobalSetting,
108  "If true, commands will be echoed even if they are pure comment lines."}};
109 
110 enum {
117 };
118 
119 ConstString &CommandInterpreter::GetStaticBroadcasterClass() {
120  static ConstString class_name("lldb.commandInterpreter");
121  return class_name;
122 }
123 
124 CommandInterpreter::CommandInterpreter(Debugger &debugger,
125  bool synchronous_execution)
126  : Broadcaster(debugger.GetBroadcasterManager(),
127  CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
128  Properties(OptionValuePropertiesSP(
129  new OptionValueProperties(ConstString("interpreter")))),
131  m_debugger(debugger), m_synchronous_execution(synchronous_execution),
132  m_skip_lldbinit_files(false), m_skip_app_init_files(false),
133  m_command_io_handler_sp(), m_comment_char('#'),
134  m_batch_command_mode(false), m_truncation_warning(eNoTruncation),
135  m_command_source_depth(0), m_num_errors(0), m_quit_requested(false),
136  m_stopped_for_crash(false) {
137  SetEventName(eBroadcastBitThreadShouldExit, "thread-should-exit");
138  SetEventName(eBroadcastBitResetPrompt, "reset-prompt");
141  m_collection_sp->Initialize(g_properties);
142 }
143 
146  return m_collection_sp->GetPropertyAtIndexAsBoolean(
147  nullptr, idx, g_properties[idx].default_uint_value != 0);
148 }
149 
151  const uint32_t idx = ePropertyPromptOnQuit;
152  return m_collection_sp->GetPropertyAtIndexAsBoolean(
153  nullptr, idx, g_properties[idx].default_uint_value != 0);
154 }
155 
157  const uint32_t idx = ePropertyPromptOnQuit;
158  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
159 }
160 
162  const uint32_t idx = eEchoCommands;
163  return m_collection_sp->GetPropertyAtIndexAsBoolean(
164  nullptr, idx, g_properties[idx].default_uint_value != 0);
165 }
166 
168  const uint32_t idx = eEchoCommands;
169  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
170 }
171 
173  const uint32_t idx = eEchoCommentCommands;
174  return m_collection_sp->GetPropertyAtIndexAsBoolean(
175  nullptr, idx, g_properties[idx].default_uint_value != 0);
176 }
177 
179  const uint32_t idx = eEchoCommentCommands;
180  m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
181 }
182 
184  m_allow_exit_code = allow;
185  if (!allow)
186  m_quit_exit_code.reset();
187 }
188 
190  if (!m_allow_exit_code)
191  return false;
192  m_quit_exit_code = exit_code;
193  return true;
194 }
195 
196 int CommandInterpreter::GetQuitExitCode(bool &exited) const {
197  exited = m_quit_exit_code.hasValue();
198  if (exited)
199  return *m_quit_exit_code;
200  return 0;
201 }
202 
203 void CommandInterpreter::ResolveCommand(const char *command_line,
204  CommandReturnObject &result) {
205  std::string command = command_line;
206  if (ResolveCommandImpl(command, result) != nullptr) {
207  result.AppendMessageWithFormat("%s", command.c_str());
209  }
210 }
211 
214  return m_collection_sp->GetPropertyAtIndexAsBoolean(
215  nullptr, idx, g_properties[idx].default_uint_value != 0);
216 }
217 
219  const uint32_t idx = eSpaceReplPrompts;
220  return m_collection_sp->GetPropertyAtIndexAsBoolean(
221  nullptr, idx, g_properties[idx].default_uint_value != 0);
222 }
223 
225  static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
226  Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
227 
228  CommandReturnObject result;
229 
231 
232  // An alias arguments vector to reuse - reset it before use...
233  OptionArgVectorSP alias_arguments_vector_sp(new OptionArgVector);
234 
235  // Set up some initial aliases.
236  CommandObjectSP cmd_obj_sp = GetCommandSPExact("quit", false);
237  if (cmd_obj_sp) {
238  AddAlias("q", cmd_obj_sp);
239  AddAlias("exit", cmd_obj_sp);
240  }
241 
242  cmd_obj_sp = GetCommandSPExact("_regexp-attach", false);
243  if (cmd_obj_sp)
244  AddAlias("attach", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
245 
246  cmd_obj_sp = GetCommandSPExact("process detach", false);
247  if (cmd_obj_sp) {
248  AddAlias("detach", cmd_obj_sp);
249  }
250 
251  cmd_obj_sp = GetCommandSPExact("process continue", false);
252  if (cmd_obj_sp) {
253  AddAlias("c", cmd_obj_sp);
254  AddAlias("continue", cmd_obj_sp);
255  }
256 
257  cmd_obj_sp = GetCommandSPExact("_regexp-break", false);
258  if (cmd_obj_sp)
259  AddAlias("b", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
260 
261  cmd_obj_sp = GetCommandSPExact("_regexp-tbreak", false);
262  if (cmd_obj_sp)
263  AddAlias("tbreak", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
264 
265  cmd_obj_sp = GetCommandSPExact("thread step-inst", false);
266  if (cmd_obj_sp) {
267  AddAlias("stepi", cmd_obj_sp);
268  AddAlias("si", cmd_obj_sp);
269  }
270 
271  cmd_obj_sp = GetCommandSPExact("thread step-inst-over", false);
272  if (cmd_obj_sp) {
273  AddAlias("nexti", cmd_obj_sp);
274  AddAlias("ni", cmd_obj_sp);
275  }
276 
277  cmd_obj_sp = GetCommandSPExact("thread step-in", false);
278  if (cmd_obj_sp) {
279  AddAlias("s", cmd_obj_sp);
280  AddAlias("step", cmd_obj_sp);
281  CommandAlias *sif_alias = AddAlias(
282  "sif", cmd_obj_sp, "--end-linenumber block --step-in-target %1");
283  if (sif_alias) {
284  sif_alias->SetHelp("Step through the current block, stopping if you step "
285  "directly into a function whose name matches the "
286  "TargetFunctionName.");
287  sif_alias->SetSyntax("sif <TargetFunctionName>");
288  }
289  }
290 
291  cmd_obj_sp = GetCommandSPExact("thread step-over", false);
292  if (cmd_obj_sp) {
293  AddAlias("n", cmd_obj_sp);
294  AddAlias("next", cmd_obj_sp);
295  }
296 
297  cmd_obj_sp = GetCommandSPExact("thread step-out", false);
298  if (cmd_obj_sp) {
299  AddAlias("finish", cmd_obj_sp);
300  }
301 
302  cmd_obj_sp = GetCommandSPExact("frame select", false);
303  if (cmd_obj_sp) {
304  AddAlias("f", cmd_obj_sp);
305  }
306 
307  cmd_obj_sp = GetCommandSPExact("thread select", false);
308  if (cmd_obj_sp) {
309  AddAlias("t", cmd_obj_sp);
310  }
311 
312  cmd_obj_sp = GetCommandSPExact("_regexp-jump", false);
313  if (cmd_obj_sp) {
314  AddAlias("j", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
315  AddAlias("jump", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
316  }
317 
318  cmd_obj_sp = GetCommandSPExact("_regexp-list", false);
319  if (cmd_obj_sp) {
320  AddAlias("l", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
321  AddAlias("list", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
322  }
323 
324  cmd_obj_sp = GetCommandSPExact("_regexp-env", false);
325  if (cmd_obj_sp)
326  AddAlias("env", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
327 
328  cmd_obj_sp = GetCommandSPExact("memory read", false);
329  if (cmd_obj_sp)
330  AddAlias("x", cmd_obj_sp);
331 
332  cmd_obj_sp = GetCommandSPExact("_regexp-up", false);
333  if (cmd_obj_sp)
334  AddAlias("up", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
335 
336  cmd_obj_sp = GetCommandSPExact("_regexp-down", false);
337  if (cmd_obj_sp)
338  AddAlias("down", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
339 
340  cmd_obj_sp = GetCommandSPExact("_regexp-display", false);
341  if (cmd_obj_sp)
342  AddAlias("display", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
343 
344  cmd_obj_sp = GetCommandSPExact("disassemble", false);
345  if (cmd_obj_sp)
346  AddAlias("dis", cmd_obj_sp);
347 
348  cmd_obj_sp = GetCommandSPExact("disassemble", false);
349  if (cmd_obj_sp)
350  AddAlias("di", cmd_obj_sp);
351 
352  cmd_obj_sp = GetCommandSPExact("_regexp-undisplay", false);
353  if (cmd_obj_sp)
354  AddAlias("undisplay", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
355 
356  cmd_obj_sp = GetCommandSPExact("_regexp-bt", false);
357  if (cmd_obj_sp)
358  AddAlias("bt", cmd_obj_sp)->SetSyntax(cmd_obj_sp->GetSyntax());
359 
360  cmd_obj_sp = GetCommandSPExact("target create", false);
361  if (cmd_obj_sp)
362  AddAlias("file", cmd_obj_sp);
363 
364  cmd_obj_sp = GetCommandSPExact("target modules", false);
365  if (cmd_obj_sp)
366  AddAlias("image", cmd_obj_sp);
367 
368  alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
369 
370  cmd_obj_sp = GetCommandSPExact("expression", false);
371  if (cmd_obj_sp) {
372  AddAlias("p", cmd_obj_sp, "--")->SetHelpLong("");
373  AddAlias("print", cmd_obj_sp, "--")->SetHelpLong("");
374  AddAlias("call", cmd_obj_sp, "--")->SetHelpLong("");
375  if (auto po = AddAlias("po", cmd_obj_sp, "-O --")) {
376  po->SetHelp("Evaluate an expression on the current thread. Displays any "
377  "returned value with formatting "
378  "controlled by the type's author.");
379  po->SetHelpLong("");
380  }
381  AddAlias("parray", cmd_obj_sp, "--element-count %1 --")->SetHelpLong("");
382  AddAlias("poarray", cmd_obj_sp,
383  "--object-description --element-count %1 --")
384  ->SetHelpLong("");
385  }
386 
387  cmd_obj_sp = GetCommandSPExact("process kill", false);
388  if (cmd_obj_sp) {
389  AddAlias("kill", cmd_obj_sp);
390  }
391 
392  cmd_obj_sp = GetCommandSPExact("process launch", false);
393  if (cmd_obj_sp) {
394  alias_arguments_vector_sp = std::make_shared<OptionArgVector>();
395 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
396  AddAlias("r", cmd_obj_sp, "--");
397  AddAlias("run", cmd_obj_sp, "--");
398 #else
399 #if defined(__APPLE__)
400  std::string shell_option;
401  shell_option.append("--shell-expand-args");
402  shell_option.append(" true");
403  shell_option.append(" --");
404  AddAlias("r", cmd_obj_sp, "--shell-expand-args true --");
405  AddAlias("run", cmd_obj_sp, "--shell-expand-args true --");
406 #else
407  StreamString defaultshell;
408  defaultshell.Printf("--shell=%s --",
409  HostInfo::GetDefaultShell().GetPath().c_str());
410  AddAlias("r", cmd_obj_sp, defaultshell.GetString());
411  AddAlias("run", cmd_obj_sp, defaultshell.GetString());
412 #endif
413 #endif
414  }
415 
416  cmd_obj_sp = GetCommandSPExact("target symbols add", false);
417  if (cmd_obj_sp) {
418  AddAlias("add-dsym", cmd_obj_sp);
419  }
420 
421  cmd_obj_sp = GetCommandSPExact("breakpoint set", false);
422  if (cmd_obj_sp) {
423  AddAlias("rbreak", cmd_obj_sp, "--func-regex %1");
424  }
425 
426  cmd_obj_sp = GetCommandSPExact("frame variable", false);
427  if (cmd_obj_sp) {
428  AddAlias("v", cmd_obj_sp);
429  AddAlias("var", cmd_obj_sp);
430  AddAlias("vo", cmd_obj_sp, "--object-description");
431  }
432 
433  cmd_obj_sp = GetCommandSPExact("register", false);
434  if (cmd_obj_sp) {
435  AddAlias("re", cmd_obj_sp);
436  }
437 }
438 
440  m_command_io_handler_sp.reset();
441 }
442 
444  // This function has not yet been implemented.
445 
446  // Look for any embedded script command
447  // If found,
448  // get interpreter object from the command dictionary,
449  // call execute_one_command on it,
450  // get the results as a string,
451  // substitute that string for current stuff.
452 
453  return arg;
454 }
455 
457  static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
458  Timer scoped_timer(func_cat, LLVM_PRETTY_FUNCTION);
459 
460  lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
461 
462  m_command_dict["apropos"] = CommandObjectSP(new CommandObjectApropos(*this));
463  m_command_dict["breakpoint"] =
464  CommandObjectSP(new CommandObjectMultiwordBreakpoint(*this));
465  m_command_dict["bugreport"] =
466  CommandObjectSP(new CommandObjectMultiwordBugreport(*this));
467  m_command_dict["command"] =
468  CommandObjectSP(new CommandObjectMultiwordCommands(*this));
469  m_command_dict["disassemble"] =
470  CommandObjectSP(new CommandObjectDisassemble(*this));
471  m_command_dict["expression"] =
472  CommandObjectSP(new CommandObjectExpression(*this));
473  m_command_dict["frame"] =
474  CommandObjectSP(new CommandObjectMultiwordFrame(*this));
475  m_command_dict["gui"] = CommandObjectSP(new CommandObjectGUI(*this));
476  m_command_dict["help"] = CommandObjectSP(new CommandObjectHelp(*this));
477  m_command_dict["log"] = CommandObjectSP(new CommandObjectLog(*this));
478  m_command_dict["memory"] = CommandObjectSP(new CommandObjectMemory(*this));
479  m_command_dict["platform"] =
480  CommandObjectSP(new CommandObjectPlatform(*this));
481  m_command_dict["plugin"] = CommandObjectSP(new CommandObjectPlugin(*this));
482  m_command_dict["process"] =
483  CommandObjectSP(new CommandObjectMultiwordProcess(*this));
484  m_command_dict["quit"] = CommandObjectSP(new CommandObjectQuit(*this));
485  m_command_dict["register"] =
486  CommandObjectSP(new CommandObjectRegister(*this));
487  m_command_dict["reproducer"] =
488  CommandObjectSP(new CommandObjectReproducer(*this));
489  m_command_dict["script"] =
490  CommandObjectSP(new CommandObjectScript(*this, script_language));
491  m_command_dict["settings"] =
492  CommandObjectSP(new CommandObjectMultiwordSettings(*this));
493  m_command_dict["source"] =
494  CommandObjectSP(new CommandObjectMultiwordSource(*this));
495  m_command_dict["statistics"] = CommandObjectSP(new CommandObjectStats(*this));
496  m_command_dict["target"] =
497  CommandObjectSP(new CommandObjectMultiwordTarget(*this));
498  m_command_dict["thread"] =
499  CommandObjectSP(new CommandObjectMultiwordThread(*this));
500  m_command_dict["type"] = CommandObjectSP(new CommandObjectType(*this));
501  m_command_dict["version"] = CommandObjectSP(new CommandObjectVersion(*this));
502  m_command_dict["watchpoint"] =
503  CommandObjectSP(new CommandObjectMultiwordWatchpoint(*this));
504  m_command_dict["language"] =
505  CommandObjectSP(new CommandObjectLanguage(*this));
506 
507  const char *break_regexes[][2] = {
508  {"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$",
509  "breakpoint set --file '%1' --line %2"},
510  {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
511  {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
512  {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
513  {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$",
514  "breakpoint set --name '%1'"},
515  {"^(-.*)$", "breakpoint set %1"},
516  {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$",
517  "breakpoint set --name '%2' --shlib '%1'"},
518  {"^\\&(.*[^[:space:]])[[:space:]]*$",
519  "breakpoint set --name '%1' --skip-prologue=0"},
520  {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$",
521  "breakpoint set --name '%1'"}};
522 
523  size_t num_regexes = llvm::array_lengthof(break_regexes);
524 
525  std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_up(
527  *this, "_regexp-break",
528  "Set a breakpoint using one of several shorthand formats.",
529  "\n"
530  "_regexp-break <filename>:<linenum>\n"
531  " main.c:12 // Break at line 12 of "
532  "main.c\n\n"
533  "_regexp-break <linenum>\n"
534  " 12 // Break at line 12 of current "
535  "file\n\n"
536  "_regexp-break 0x<address>\n"
537  " 0x1234000 // Break at address "
538  "0x1234000\n\n"
539  "_regexp-break <name>\n"
540  " main // Break in 'main' after the "
541  "prologue\n\n"
542  "_regexp-break &<name>\n"
543  " &main // Break at first instruction "
544  "in 'main'\n\n"
545  "_regexp-break <module>`<name>\n"
546  " libc.so`malloc // Break in 'malloc' from "
547  "'libc.so'\n\n"
548  "_regexp-break /<source-regex>/\n"
549  " /break here/ // Break on source lines in "
550  "current file\n"
551  " // containing text 'break "
552  "here'.\n",
553  2,
556  false));
557 
558  if (break_regex_cmd_up) {
559  bool success = true;
560  for (size_t i = 0; i < num_regexes; i++) {
561  success = break_regex_cmd_up->AddRegexCommand(break_regexes[i][0],
562  break_regexes[i][1]);
563  if (!success)
564  break;
565  }
566  success =
567  break_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full");
568 
569  if (success) {
570  CommandObjectSP break_regex_cmd_sp(break_regex_cmd_up.release());
571  m_command_dict[break_regex_cmd_sp->GetCommandName()] = break_regex_cmd_sp;
572  }
573  }
574 
575  std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_up(
577  *this, "_regexp-tbreak",
578  "Set a one-shot breakpoint using one of several shorthand formats.",
579  "\n"
580  "_regexp-break <filename>:<linenum>\n"
581  " main.c:12 // Break at line 12 of "
582  "main.c\n\n"
583  "_regexp-break <linenum>\n"
584  " 12 // Break at line 12 of current "
585  "file\n\n"
586  "_regexp-break 0x<address>\n"
587  " 0x1234000 // Break at address "
588  "0x1234000\n\n"
589  "_regexp-break <name>\n"
590  " main // Break in 'main' after the "
591  "prologue\n\n"
592  "_regexp-break &<name>\n"
593  " &main // Break at first instruction "
594  "in 'main'\n\n"
595  "_regexp-break <module>`<name>\n"
596  " libc.so`malloc // Break in 'malloc' from "
597  "'libc.so'\n\n"
598  "_regexp-break /<source-regex>/\n"
599  " /break here/ // Break on source lines in "
600  "current file\n"
601  " // containing text 'break "
602  "here'.\n",
603  2,
606  false));
607 
608  if (tbreak_regex_cmd_up) {
609  bool success = true;
610  for (size_t i = 0; i < num_regexes; i++) {
611  // If you add a resultant command string longer than 1024 characters be
612  // sure to increase the size of this buffer.
613  char buffer[1024];
614  int num_printed =
615  snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o 1");
616  lldbassert(num_printed < 1024);
617  UNUSED_IF_ASSERT_DISABLED(num_printed);
618  success =
619  tbreak_regex_cmd_up->AddRegexCommand(break_regexes[i][0], buffer);
620  if (!success)
621  break;
622  }
623  success =
624  tbreak_regex_cmd_up->AddRegexCommand("^$", "breakpoint list --full");
625 
626  if (success) {
627  CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_up.release());
628  m_command_dict[tbreak_regex_cmd_sp->GetCommandName()] =
629  tbreak_regex_cmd_sp;
630  }
631  }
632 
633  std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_up(
635  *this, "_regexp-attach", "Attach to process by ID or name.",
636  "_regexp-attach <pid> | <process-name>", 2, 0, false));
637  if (attach_regex_cmd_up) {
638  if (attach_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
639  "process attach --pid %1") &&
640  attach_regex_cmd_up->AddRegexCommand(
641  "^(-.*|.* -.*)$", "process attach %1") && // Any options that are
642  // specified get passed to
643  // 'process attach'
644  attach_regex_cmd_up->AddRegexCommand("^(.+)$",
645  "process attach --name '%1'") &&
646  attach_regex_cmd_up->AddRegexCommand("^$", "process attach")) {
647  CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_up.release());
648  m_command_dict[attach_regex_cmd_sp->GetCommandName()] =
649  attach_regex_cmd_sp;
650  }
651  }
652 
653  std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_up(
654  new CommandObjectRegexCommand(*this, "_regexp-down",
655  "Select a newer stack frame. Defaults to "
656  "moving one frame, a numeric argument can "
657  "specify an arbitrary number.",
658  "_regexp-down [<count>]", 2, 0, false));
659  if (down_regex_cmd_up) {
660  if (down_regex_cmd_up->AddRegexCommand("^$", "frame select -r -1") &&
661  down_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
662  "frame select -r -%1")) {
663  CommandObjectSP down_regex_cmd_sp(down_regex_cmd_up.release());
664  m_command_dict[down_regex_cmd_sp->GetCommandName()] = down_regex_cmd_sp;
665  }
666  }
667 
668  std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_up(
670  *this, "_regexp-up",
671  "Select an older stack frame. Defaults to moving one "
672  "frame, a numeric argument can specify an arbitrary number.",
673  "_regexp-up [<count>]", 2, 0, false));
674  if (up_regex_cmd_up) {
675  if (up_regex_cmd_up->AddRegexCommand("^$", "frame select -r 1") &&
676  up_regex_cmd_up->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) {
677  CommandObjectSP up_regex_cmd_sp(up_regex_cmd_up.release());
678  m_command_dict[up_regex_cmd_sp->GetCommandName()] = up_regex_cmd_sp;
679  }
680  }
681 
682  std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_up(
684  *this, "_regexp-display",
685  "Evaluate an expression at every stop (see 'help target stop-hook'.)",
686  "_regexp-display expression", 2, 0, false));
687  if (display_regex_cmd_up) {
688  if (display_regex_cmd_up->AddRegexCommand(
689  "^(.+)$", "target stop-hook add -o \"expr -- %1\"")) {
690  CommandObjectSP display_regex_cmd_sp(display_regex_cmd_up.release());
691  m_command_dict[display_regex_cmd_sp->GetCommandName()] =
692  display_regex_cmd_sp;
693  }
694  }
695 
696  std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_up(
697  new CommandObjectRegexCommand(*this, "_regexp-undisplay",
698  "Stop displaying expression at every "
699  "stop (specified by stop-hook index.)",
700  "_regexp-undisplay stop-hook-number", 2, 0,
701  false));
702  if (undisplay_regex_cmd_up) {
703  if (undisplay_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
704  "target stop-hook delete %1")) {
705  CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_up.release());
706  m_command_dict[undisplay_regex_cmd_sp->GetCommandName()] =
707  undisplay_regex_cmd_sp;
708  }
709  }
710 
711  std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_up(
713  *this, "gdb-remote",
714  "Connect to a process via remote GDB server. "
715  "If no host is specifed, localhost is assumed.",
716  "gdb-remote [<hostname>:]<portnum>", 2, 0, false));
717  if (connect_gdb_remote_cmd_up) {
718  if (connect_gdb_remote_cmd_up->AddRegexCommand(
719  "^([^:]+|\\[[0-9a-fA-F:]+.*\\]):([0-9]+)$",
720  "process connect --plugin gdb-remote connect://%1:%2") &&
721  connect_gdb_remote_cmd_up->AddRegexCommand(
722  "^([[:digit:]]+)$",
723  "process connect --plugin gdb-remote connect://localhost:%1")) {
724  CommandObjectSP command_sp(connect_gdb_remote_cmd_up.release());
725  m_command_dict[command_sp->GetCommandName()] = command_sp;
726  }
727  }
728 
729  std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_up(
731  *this, "kdp-remote",
732  "Connect to a process via remote KDP server. "
733  "If no UDP port is specified, port 41139 is "
734  "assumed.",
735  "kdp-remote <hostname>[:<portnum>]", 2, 0, false));
736  if (connect_kdp_remote_cmd_up) {
737  if (connect_kdp_remote_cmd_up->AddRegexCommand(
738  "^([^:]+:[[:digit:]]+)$",
739  "process connect --plugin kdp-remote udp://%1") &&
740  connect_kdp_remote_cmd_up->AddRegexCommand(
741  "^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) {
742  CommandObjectSP command_sp(connect_kdp_remote_cmd_up.release());
743  m_command_dict[command_sp->GetCommandName()] = command_sp;
744  }
745  }
746 
747  std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_up(
749  *this, "_regexp-bt",
750  "Show the current thread's call stack. Any numeric argument "
751  "displays at most that many "
752  "frames. The argument 'all' displays all threads. Use 'settings"
753  " set frame-format' to customize the printing of individual frames "
754  "and 'settings set thread-format' to customize the thread header.",
755  "bt [<digit> | all]", 2, 0, false));
756  if (bt_regex_cmd_up) {
757  // accept but don't document "bt -c <number>" -- before bt was a regex
758  // command if you wanted to backtrace three frames you would do "bt -c 3"
759  // but the intention is to have this emulate the gdb "bt" command and so
760  // now "bt 3" is the preferred form, in line with gdb.
761  if (bt_regex_cmd_up->AddRegexCommand("^([[:digit:]]+)$",
762  "thread backtrace -c %1") &&
763  bt_regex_cmd_up->AddRegexCommand("^-c ([[:digit:]]+)$",
764  "thread backtrace -c %1") &&
765  bt_regex_cmd_up->AddRegexCommand("^all$", "thread backtrace all") &&
766  bt_regex_cmd_up->AddRegexCommand("^$", "thread backtrace")) {
767  CommandObjectSP command_sp(bt_regex_cmd_up.release());
768  m_command_dict[command_sp->GetCommandName()] = command_sp;
769  }
770  }
771 
772  std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_up(
774  *this, "_regexp-list",
775  "List relevant source code using one of several shorthand formats.",
776  "\n"
777  "_regexp-list <file>:<line> // List around specific file/line\n"
778  "_regexp-list <line> // List current file around specified "
779  "line\n"
780  "_regexp-list <function-name> // List specified function\n"
781  "_regexp-list 0x<address> // List around specified address\n"
782  "_regexp-list -[<count>] // List previous <count> lines\n"
783  "_regexp-list // List subsequent lines",
785  if (list_regex_cmd_up) {
786  if (list_regex_cmd_up->AddRegexCommand("^([0-9]+)[[:space:]]*$",
787  "source list --line %1") &&
788  list_regex_cmd_up->AddRegexCommand(
789  "^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]"
790  "]*$",
791  "source list --file '%1' --line %2") &&
792  list_regex_cmd_up->AddRegexCommand(
793  "^\\*?(0x[[:xdigit:]]+)[[:space:]]*$",
794  "source list --address %1") &&
795  list_regex_cmd_up->AddRegexCommand("^-[[:space:]]*$",
796  "source list --reverse") &&
797  list_regex_cmd_up->AddRegexCommand(
798  "^-([[:digit:]]+)[[:space:]]*$",
799  "source list --reverse --count %1") &&
800  list_regex_cmd_up->AddRegexCommand("^(.+)$",
801  "source list --name \"%1\"") &&
802  list_regex_cmd_up->AddRegexCommand("^$", "source list")) {
803  CommandObjectSP list_regex_cmd_sp(list_regex_cmd_up.release());
804  m_command_dict[list_regex_cmd_sp->GetCommandName()] = list_regex_cmd_sp;
805  }
806  }
807 
808  std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_up(
810  *this, "_regexp-env",
811  "Shorthand for viewing and setting environment variables.",
812  "\n"
813  "_regexp-env // Show enrivonment\n"
814  "_regexp-env <name>=<value> // Set an environment variable",
815  2, 0, false));
816  if (env_regex_cmd_up) {
817  if (env_regex_cmd_up->AddRegexCommand("^$",
818  "settings show target.env-vars") &&
819  env_regex_cmd_up->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$",
820  "settings set target.env-vars %1")) {
821  CommandObjectSP env_regex_cmd_sp(env_regex_cmd_up.release());
822  m_command_dict[env_regex_cmd_sp->GetCommandName()] = env_regex_cmd_sp;
823  }
824  }
825 
826  std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_up(
828  *this, "_regexp-jump", "Set the program counter to a new address.",
829  "\n"
830  "_regexp-jump <line>\n"
831  "_regexp-jump +<line-offset> | -<line-offset>\n"
832  "_regexp-jump <file>:<line>\n"
833  "_regexp-jump *<addr>\n",
834  2, 0, false));
835  if (jump_regex_cmd_up) {
836  if (jump_regex_cmd_up->AddRegexCommand("^\\*(.*)$",
837  "thread jump --addr %1") &&
838  jump_regex_cmd_up->AddRegexCommand("^([0-9]+)$",
839  "thread jump --line %1") &&
840  jump_regex_cmd_up->AddRegexCommand("^([^:]+):([0-9]+)$",
841  "thread jump --file %1 --line %2") &&
842  jump_regex_cmd_up->AddRegexCommand("^([+\\-][0-9]+)$",
843  "thread jump --by %1")) {
844  CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_up.release());
845  m_command_dict[jump_regex_cmd_sp->GetCommandName()] = jump_regex_cmd_sp;
846  }
847  }
848 }
849 
851  const char *cmd_str, bool include_aliases, StringList &matches,
852  StringList &descriptions) {
853  AddNamesMatchingPartialString(m_command_dict, cmd_str, matches,
854  &descriptions);
855 
856  if (include_aliases) {
857  AddNamesMatchingPartialString(m_alias_dict, cmd_str, matches,
858  &descriptions);
859  }
860 
861  return matches.GetSize();
862 }
863 
864 CommandObjectSP
865 CommandInterpreter::GetCommandSP(llvm::StringRef cmd_str, bool include_aliases,
866  bool exact, StringList *matches,
867  StringList *descriptions) const {
868  CommandObjectSP command_sp;
869 
870  std::string cmd = cmd_str;
871 
872  if (HasCommands()) {
873  auto pos = m_command_dict.find(cmd);
874  if (pos != m_command_dict.end())
875  command_sp = pos->second;
876  }
877 
878  if (include_aliases && HasAliases()) {
879  auto alias_pos = m_alias_dict.find(cmd);
880  if (alias_pos != m_alias_dict.end())
881  command_sp = alias_pos->second;
882  }
883 
884  if (HasUserCommands()) {
885  auto pos = m_user_dict.find(cmd);
886  if (pos != m_user_dict.end())
887  command_sp = pos->second;
888  }
889 
890  if (!exact && !command_sp) {
891  // We will only get into here if we didn't find any exact matches.
892 
893  CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
894 
895  StringList local_matches;
896  if (matches == nullptr)
897  matches = &local_matches;
898 
899  unsigned int num_cmd_matches = 0;
900  unsigned int num_alias_matches = 0;
901  unsigned int num_user_matches = 0;
902 
903  // Look through the command dictionaries one by one, and if we get only one
904  // match from any of them in toto, then return that, otherwise return an
905  // empty CommandObjectSP and the list of matches.
906 
907  if (HasCommands()) {
908  num_cmd_matches = AddNamesMatchingPartialString(m_command_dict, cmd_str,
909  *matches, descriptions);
910  }
911 
912  if (num_cmd_matches == 1) {
913  cmd.assign(matches->GetStringAtIndex(0));
914  auto pos = m_command_dict.find(cmd);
915  if (pos != m_command_dict.end())
916  real_match_sp = pos->second;
917  }
918 
919  if (include_aliases && HasAliases()) {
920  num_alias_matches = AddNamesMatchingPartialString(m_alias_dict, cmd_str,
921  *matches, descriptions);
922  }
923 
924  if (num_alias_matches == 1) {
925  cmd.assign(matches->GetStringAtIndex(num_cmd_matches));
926  auto alias_pos = m_alias_dict.find(cmd);
927  if (alias_pos != m_alias_dict.end())
928  alias_match_sp = alias_pos->second;
929  }
930 
931  if (HasUserCommands()) {
932  num_user_matches = AddNamesMatchingPartialString(m_user_dict, cmd_str,
933  *matches, descriptions);
934  }
935 
936  if (num_user_matches == 1) {
937  cmd.assign(
938  matches->GetStringAtIndex(num_cmd_matches + num_alias_matches));
939 
940  auto pos = m_user_dict.find(cmd);
941  if (pos != m_user_dict.end())
942  user_match_sp = pos->second;
943  }
944 
945  // If we got exactly one match, return that, otherwise return the match
946  // list.
947 
948  if (num_user_matches + num_cmd_matches + num_alias_matches == 1) {
949  if (num_cmd_matches)
950  return real_match_sp;
951  else if (num_alias_matches)
952  return alias_match_sp;
953  else
954  return user_match_sp;
955  }
956  } else if (matches && command_sp) {
957  matches->AppendString(cmd_str);
958  if (descriptions)
959  descriptions->AppendString(command_sp->GetHelp());
960  }
961 
962  return command_sp;
963 }
964 
965 bool CommandInterpreter::AddCommand(llvm::StringRef name,
966  const lldb::CommandObjectSP &cmd_sp,
967  bool can_replace) {
968  if (cmd_sp.get())
969  lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
970  "tried to add a CommandObject from a different interpreter");
971 
972  if (name.empty())
973  return false;
974 
975  std::string name_sstr(name);
976  auto name_iter = m_command_dict.find(name_sstr);
977  if (name_iter != m_command_dict.end()) {
978  if (!can_replace || !name_iter->second->IsRemovable())
979  return false;
980  name_iter->second = cmd_sp;
981  } else {
982  m_command_dict[name_sstr] = cmd_sp;
983  }
984  return true;
985 }
986 
987 bool CommandInterpreter::AddUserCommand(llvm::StringRef name,
988  const lldb::CommandObjectSP &cmd_sp,
989  bool can_replace) {
990  if (cmd_sp.get())
991  lldbassert((this == &cmd_sp->GetCommandInterpreter()) &&
992  "tried to add a CommandObject from a different interpreter");
993 
994  if (!name.empty()) {
995  // do not allow replacement of internal commands
996  if (CommandExists(name)) {
997  if (!can_replace)
998  return false;
999  if (!m_command_dict[name]->IsRemovable())
1000  return false;
1001  }
1002 
1003  if (UserCommandExists(name)) {
1004  if (!can_replace)
1005  return false;
1006  if (!m_user_dict[name]->IsRemovable())
1007  return false;
1008  }
1009 
1010  m_user_dict[name] = cmd_sp;
1011  return true;
1012  }
1013  return false;
1014 }
1015 
1016 CommandObjectSP CommandInterpreter::GetCommandSPExact(llvm::StringRef cmd_str,
1017  bool include_aliases) const {
1018  Args cmd_words(cmd_str); // Break up the command string into words, in case
1019  // it's a multi-word command.
1020  CommandObjectSP ret_val; // Possibly empty return value.
1021 
1022  if (cmd_str.empty())
1023  return ret_val;
1024 
1025  if (cmd_words.GetArgumentCount() == 1)
1026  return GetCommandSP(cmd_str, include_aliases, true, nullptr);
1027  else {
1028  // We have a multi-word command (seemingly), so we need to do more work.
1029  // First, get the cmd_obj_sp for the first word in the command.
1030  CommandObjectSP cmd_obj_sp = GetCommandSP(llvm::StringRef(cmd_words.GetArgumentAtIndex(0)),
1031  include_aliases, true, nullptr);
1032  if (cmd_obj_sp.get() != nullptr) {
1033  // Loop through the rest of the words in the command (everything passed
1034  // in was supposed to be part of a command name), and find the
1035  // appropriate sub-command SP for each command word....
1036  size_t end = cmd_words.GetArgumentCount();
1037  for (size_t j = 1; j < end; ++j) {
1038  if (cmd_obj_sp->IsMultiwordObject()) {
1039  cmd_obj_sp =
1040  cmd_obj_sp->GetSubcommandSP(cmd_words.GetArgumentAtIndex(j));
1041  if (cmd_obj_sp.get() == nullptr)
1042  // The sub-command name was invalid. Fail and return the empty
1043  // 'ret_val'.
1044  return ret_val;
1045  } else
1046  // We have more words in the command name, but we don't have a
1047  // multiword object. Fail and return empty 'ret_val'.
1048  return ret_val;
1049  }
1050  // We successfully looped through all the command words and got valid
1051  // command objects for them. Assign the last object retrieved to
1052  // 'ret_val'.
1053  ret_val = cmd_obj_sp;
1054  }
1055  }
1056  return ret_val;
1057 }
1058 
1059 CommandObject *
1061  StringList *matches,
1062  StringList *descriptions) const {
1063  CommandObject *command_obj =
1064  GetCommandSP(cmd_str, false, true, matches, descriptions).get();
1065 
1066  // If we didn't find an exact match to the command string in the commands,
1067  // look in the aliases.
1068 
1069  if (command_obj)
1070  return command_obj;
1071 
1072  command_obj = GetCommandSP(cmd_str, true, true, matches, descriptions).get();
1073 
1074  if (command_obj)
1075  return command_obj;
1076 
1077  // If there wasn't an exact match then look for an inexact one in just the
1078  // commands
1079  command_obj = GetCommandSP(cmd_str, false, false, nullptr).get();
1080 
1081  // Finally, if there wasn't an inexact match among the commands, look for an
1082  // inexact match in both the commands and aliases.
1083 
1084  if (command_obj) {
1085  if (matches)
1086  matches->AppendString(command_obj->GetCommandName());
1087  if (descriptions)
1088  descriptions->AppendString(command_obj->GetHelp());
1089  return command_obj;
1090  }
1091 
1092  return GetCommandSP(cmd_str, true, false, matches, descriptions).get();
1093 }
1094 
1095 bool CommandInterpreter::CommandExists(llvm::StringRef cmd) const {
1096  return m_command_dict.find(cmd) != m_command_dict.end();
1097 }
1098 
1099 bool CommandInterpreter::GetAliasFullName(llvm::StringRef cmd,
1100  std::string &full_name) const {
1101  bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1102  if (exact_match) {
1103  full_name.assign(cmd);
1104  return exact_match;
1105  } else {
1106  StringList matches;
1107  size_t num_alias_matches;
1108  num_alias_matches =
1109  AddNamesMatchingPartialString(m_alias_dict, cmd, matches);
1110  if (num_alias_matches == 1) {
1111  // Make sure this isn't shadowing a command in the regular command space:
1112  StringList regular_matches;
1113  const bool include_aliases = false;
1114  const bool exact = false;
1115  CommandObjectSP cmd_obj_sp(
1116  GetCommandSP(cmd, include_aliases, exact, &regular_matches));
1117  if (cmd_obj_sp || regular_matches.GetSize() > 0)
1118  return false;
1119  else {
1120  full_name.assign(matches.GetStringAtIndex(0));
1121  return true;
1122  }
1123  } else
1124  return false;
1125  }
1126 }
1127 
1128 bool CommandInterpreter::AliasExists(llvm::StringRef cmd) const {
1129  return m_alias_dict.find(cmd) != m_alias_dict.end();
1130 }
1131 
1132 bool CommandInterpreter::UserCommandExists(llvm::StringRef cmd) const {
1133  return m_user_dict.find(cmd) != m_user_dict.end();
1134 }
1135 
1136 CommandAlias *
1137 CommandInterpreter::AddAlias(llvm::StringRef alias_name,
1138  lldb::CommandObjectSP &command_obj_sp,
1139  llvm::StringRef args_string) {
1140  if (command_obj_sp.get())
1141  lldbassert((this == &command_obj_sp->GetCommandInterpreter()) &&
1142  "tried to add a CommandObject from a different interpreter");
1143 
1144  std::unique_ptr<CommandAlias> command_alias_up(
1145  new CommandAlias(*this, command_obj_sp, args_string, alias_name));
1146 
1147  if (command_alias_up && command_alias_up->IsValid()) {
1148  m_alias_dict[alias_name] = CommandObjectSP(command_alias_up.get());
1149  return command_alias_up.release();
1150  }
1151 
1152  return nullptr;
1153 }
1154 
1155 bool CommandInterpreter::RemoveAlias(llvm::StringRef alias_name) {
1156  auto pos = m_alias_dict.find(alias_name);
1157  if (pos != m_alias_dict.end()) {
1158  m_alias_dict.erase(pos);
1159  return true;
1160  }
1161  return false;
1162 }
1163 
1164 bool CommandInterpreter::RemoveCommand(llvm::StringRef cmd) {
1165  auto pos = m_command_dict.find(cmd);
1166  if (pos != m_command_dict.end()) {
1167  if (pos->second->IsRemovable()) {
1168  // Only regular expression objects or python commands are removable
1169  m_command_dict.erase(pos);
1170  return true;
1171  }
1172  }
1173  return false;
1174 }
1175 bool CommandInterpreter::RemoveUser(llvm::StringRef alias_name) {
1176  CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1177  if (pos != m_user_dict.end()) {
1178  m_user_dict.erase(pos);
1179  return true;
1180  }
1181  return false;
1182 }
1183 
1185  uint32_t cmd_types) {
1186  llvm::StringRef help_prologue(GetDebugger().GetIOHandlerHelpPrologue());
1187  if (!help_prologue.empty()) {
1188  OutputFormattedHelpText(result.GetOutputStream(), llvm::StringRef(),
1189  help_prologue);
1190  }
1191 
1192  CommandObject::CommandMap::const_iterator pos;
1193  size_t max_len = FindLongestCommandWord(m_command_dict);
1194 
1195  if ((cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin) {
1196  result.AppendMessage("Debugger commands:");
1197  result.AppendMessage("");
1198 
1199  for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) {
1200  if (!(cmd_types & eCommandTypesHidden) &&
1201  (pos->first.compare(0, 1, "_") == 0))
1202  continue;
1203 
1204  OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1205  pos->second->GetHelp(), max_len);
1206  }
1207  result.AppendMessage("");
1208  }
1209 
1210  if (!m_alias_dict.empty() &&
1211  ((cmd_types & eCommandTypesAliases) == eCommandTypesAliases)) {
1212  result.AppendMessageWithFormat(
1213  "Current command abbreviations "
1214  "(type '%shelp command alias' for more info):\n",
1215  GetCommandPrefix());
1216  result.AppendMessage("");
1217  max_len = FindLongestCommandWord(m_alias_dict);
1218 
1219  for (auto alias_pos = m_alias_dict.begin(); alias_pos != m_alias_dict.end();
1220  ++alias_pos) {
1221  OutputFormattedHelpText(result.GetOutputStream(), alias_pos->first, "--",
1222  alias_pos->second->GetHelp(), max_len);
1223  }
1224  result.AppendMessage("");
1225  }
1226 
1227  if (!m_user_dict.empty() &&
1228  ((cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef)) {
1229  result.AppendMessage("Current user-defined commands:");
1230  result.AppendMessage("");
1231  max_len = FindLongestCommandWord(m_user_dict);
1232  for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) {
1233  OutputFormattedHelpText(result.GetOutputStream(), pos->first, "--",
1234  pos->second->GetHelp(), max_len);
1235  }
1236  result.AppendMessage("");
1237  }
1238 
1239  result.AppendMessageWithFormat(
1240  "For more information on any command, type '%shelp <command-name>'.\n",
1241  GetCommandPrefix());
1242 }
1243 
1245  llvm::StringRef &command_string) {
1246  // This function finds the final, lowest-level, alias-resolved command object
1247  // whose 'Execute' function will eventually be invoked by the given command
1248  // line.
1249 
1250  CommandObject *cmd_obj = nullptr;
1251  size_t start = command_string.find_first_not_of(k_white_space);
1252  size_t end = 0;
1253  bool done = false;
1254  while (!done) {
1255  if (start != std::string::npos) {
1256  // Get the next word from command_string.
1257  end = command_string.find_first_of(k_white_space, start);
1258  if (end == std::string::npos)
1259  end = command_string.size();
1260  std::string cmd_word = command_string.substr(start, end - start);
1261 
1262  if (cmd_obj == nullptr)
1263  // Since cmd_obj is NULL we are on our first time through this loop.
1264  // Check to see if cmd_word is a valid command or alias.
1265  cmd_obj = GetCommandObject(cmd_word);
1266  else if (cmd_obj->IsMultiwordObject()) {
1267  // Our current object is a multi-word object; see if the cmd_word is a
1268  // valid sub-command for our object.
1269  CommandObject *sub_cmd_obj =
1270  cmd_obj->GetSubcommandObject(cmd_word.c_str());
1271  if (sub_cmd_obj)
1272  cmd_obj = sub_cmd_obj;
1273  else // cmd_word was not a valid sub-command word, so we are done
1274  done = true;
1275  } else
1276  // We have a cmd_obj and it is not a multi-word object, so we are done.
1277  done = true;
1278 
1279  // If we didn't find a valid command object, or our command object is not
1280  // a multi-word object, or we are at the end of the command_string, then
1281  // we are done. Otherwise, find the start of the next word.
1282 
1283  if (!cmd_obj || !cmd_obj->IsMultiwordObject() ||
1284  end >= command_string.size())
1285  done = true;
1286  else
1287  start = command_string.find_first_not_of(k_white_space, end);
1288  } else
1289  // Unable to find any more words.
1290  done = true;
1291  }
1292 
1293  command_string = command_string.substr(end);
1294  return cmd_obj;
1295 }
1296 
1297 static const char *k_valid_command_chars =
1298  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
1299 static void StripLeadingSpaces(std::string &s) {
1300  if (!s.empty()) {
1301  size_t pos = s.find_first_not_of(k_white_space);
1302  if (pos == std::string::npos)
1303  s.clear();
1304  else if (pos == 0)
1305  return;
1306  s.erase(0, pos);
1307  }
1308 }
1309 
1310 static size_t FindArgumentTerminator(const std::string &s) {
1311  const size_t s_len = s.size();
1312  size_t offset = 0;
1313  while (offset < s_len) {
1314  size_t pos = s.find("--", offset);
1315  if (pos == std::string::npos)
1316  break;
1317  if (pos > 0) {
1318  if (isspace(s[pos - 1])) {
1319  // Check if the string ends "\s--" (where \s is a space character) or
1320  // if we have "\s--\s".
1321  if ((pos + 2 >= s_len) || isspace(s[pos + 2])) {
1322  return pos;
1323  }
1324  }
1325  }
1326  offset = pos + 2;
1327  }
1328  return std::string::npos;
1329 }
1330 
1331 static bool ExtractCommand(std::string &command_string, std::string &command,
1332  std::string &suffix, char &quote_char) {
1333  command.clear();
1334  suffix.clear();
1335  StripLeadingSpaces(command_string);
1336 
1337  bool result = false;
1338  quote_char = '\0';
1339 
1340  if (!command_string.empty()) {
1341  const char first_char = command_string[0];
1342  if (first_char == '\'' || first_char == '"') {
1343  quote_char = first_char;
1344  const size_t end_quote_pos = command_string.find(quote_char, 1);
1345  if (end_quote_pos == std::string::npos) {
1346  command.swap(command_string);
1347  command_string.erase();
1348  } else {
1349  command.assign(command_string, 1, end_quote_pos - 1);
1350  if (end_quote_pos + 1 < command_string.size())
1351  command_string.erase(0, command_string.find_first_not_of(
1352  k_white_space, end_quote_pos + 1));
1353  else
1354  command_string.erase();
1355  }
1356  } else {
1357  const size_t first_space_pos =
1358  command_string.find_first_of(k_white_space);
1359  if (first_space_pos == std::string::npos) {
1360  command.swap(command_string);
1361  command_string.erase();
1362  } else {
1363  command.assign(command_string, 0, first_space_pos);
1364  command_string.erase(0, command_string.find_first_not_of(
1365  k_white_space, first_space_pos));
1366  }
1367  }
1368  result = true;
1369  }
1370 
1371  if (!command.empty()) {
1372  // actual commands can't start with '-' or '_'
1373  if (command[0] != '-' && command[0] != '_') {
1374  size_t pos = command.find_first_not_of(k_valid_command_chars);
1375  if (pos > 0 && pos != std::string::npos) {
1376  suffix.assign(command.begin() + pos, command.end());
1377  command.erase(pos);
1378  }
1379  }
1380  }
1381 
1382  return result;
1383 }
1384 
1386  llvm::StringRef alias_name, std::string &raw_input_string,
1387  std::string &alias_result, CommandReturnObject &result) {
1388  CommandObject *alias_cmd_obj = nullptr;
1389  Args cmd_args(raw_input_string);
1390  alias_cmd_obj = GetCommandObject(alias_name);
1391  StreamString result_str;
1392 
1393  if (!alias_cmd_obj || !alias_cmd_obj->IsAlias()) {
1394  alias_result.clear();
1395  return alias_cmd_obj;
1396  }
1397  std::pair<CommandObjectSP, OptionArgVectorSP> desugared =
1398  ((CommandAlias *)alias_cmd_obj)->Desugar();
1399  OptionArgVectorSP option_arg_vector_sp = desugared.second;
1400  alias_cmd_obj = desugared.first.get();
1401  std::string alias_name_str = alias_name;
1402  if ((cmd_args.GetArgumentCount() == 0) ||
1403  (alias_name_str != cmd_args.GetArgumentAtIndex(0)))
1404  cmd_args.Unshift(alias_name_str);
1405 
1406  result_str.Printf("%s", alias_cmd_obj->GetCommandName().str().c_str());
1407 
1408  if (!option_arg_vector_sp.get()) {
1409  alias_result = result_str.GetString();
1410  return alias_cmd_obj;
1411  }
1412  OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1413 
1414  int value_type;
1415  std::string option;
1416  std::string value;
1417  for (const auto &entry : *option_arg_vector) {
1418  std::tie(option, value_type, value) = entry;
1419  if (option == "<argument>") {
1420  result_str.Printf(" %s", value.c_str());
1421  continue;
1422  }
1423 
1424  result_str.Printf(" %s", option.c_str());
1425  if (value_type == OptionParser::eNoArgument)
1426  continue;
1427 
1428  if (value_type != OptionParser::eOptionalArgument)
1429  result_str.Printf(" ");
1430  int index = GetOptionArgumentPosition(value.c_str());
1431  if (index == 0)
1432  result_str.Printf("%s", value.c_str());
1433  else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
1434 
1435  result.AppendErrorWithFormat("Not enough arguments provided; you "
1436  "need at least %d arguments to use "
1437  "this alias.\n",
1438  index);
1440  return nullptr;
1441  } else {
1442  size_t strpos = raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
1443  if (strpos != std::string::npos)
1444  raw_input_string = raw_input_string.erase(
1445  strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
1446  result_str.Printf("%s", cmd_args.GetArgumentAtIndex(index));
1447  }
1448  }
1449 
1450  alias_result = result_str.GetString();
1451  return alias_cmd_obj;
1452 }
1453 
1454 Status CommandInterpreter::PreprocessCommand(std::string &command) {
1455  // The command preprocessor needs to do things to the command line before any
1456  // parsing of arguments or anything else is done. The only current stuff that
1457  // gets preprocessed is anything enclosed in backtick ('`') characters is
1458  // evaluated as an expression and the result of the expression must be a
1459  // scalar that can be substituted into the command. An example would be:
1460  // (lldb) memory read `$rsp + 20`
1461  Status error; // Status for any expressions that might not evaluate
1462  size_t start_backtick;
1463  size_t pos = 0;
1464  while ((start_backtick = command.find('`', pos)) != std::string::npos) {
1465  // Stop if an error was encountered during the previous iteration.
1466  if (error.Fail())
1467  break;
1468 
1469  if (start_backtick > 0 && command[start_backtick - 1] == '\\') {
1470  // The backtick was preceded by a '\' character, remove the slash and
1471  // don't treat the backtick as the start of an expression.
1472  command.erase(start_backtick - 1, 1);
1473  // No need to add one to start_backtick since we just deleted a char.
1474  pos = start_backtick;
1475  continue;
1476  }
1477 
1478  const size_t expr_content_start = start_backtick + 1;
1479  const size_t end_backtick = command.find('`', expr_content_start);
1480 
1481  if (end_backtick == std::string::npos) {
1482  // Stop if there's no end backtick.
1483  break;
1484  }
1485 
1486  if (end_backtick == expr_content_start) {
1487  // Skip over empty expression. (two backticks in a row)
1488  command.erase(start_backtick, 2);
1489  continue;
1490  }
1491 
1492  std::string expr_str(command, expr_content_start,
1493  end_backtick - expr_content_start);
1494 
1496  Target *target = exe_ctx.GetTargetPtr();
1497 
1498  // Get a dummy target to allow for calculator mode while processing
1499  // backticks. This also helps break the infinite loop caused when target is
1500  // null.
1501  if (!target)
1502  target = m_debugger.GetDummyTarget();
1503 
1504  if (!target)
1505  continue;
1506 
1507  ValueObjectSP expr_result_valobj_sp;
1508 
1509  EvaluateExpressionOptions options;
1510  options.SetCoerceToId(false);
1511  options.SetUnwindOnError(true);
1512  options.SetIgnoreBreakpoints(true);
1513  options.SetKeepInMemory(false);
1514  options.SetTryAllThreads(true);
1515  options.SetTimeout(llvm::None);
1516 
1517  ExpressionResults expr_result =
1518  target->EvaluateExpression(expr_str.c_str(), exe_ctx.GetFramePtr(),
1519  expr_result_valobj_sp, options);
1520 
1521  if (expr_result == eExpressionCompleted) {
1522  Scalar scalar;
1523  if (expr_result_valobj_sp)
1524  expr_result_valobj_sp =
1525  expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(
1526  expr_result_valobj_sp->GetDynamicValueType(), true);
1527  if (expr_result_valobj_sp->ResolveValue(scalar)) {
1528  command.erase(start_backtick, end_backtick - start_backtick + 1);
1529  StreamString value_strm;
1530  const bool show_type = false;
1531  scalar.GetValue(&value_strm, show_type);
1532  size_t value_string_size = value_strm.GetSize();
1533  if (value_string_size) {
1534  command.insert(start_backtick, value_strm.GetString());
1535  pos = start_backtick + value_string_size;
1536  continue;
1537  } else {
1538  error.SetErrorStringWithFormat("expression value didn't result "
1539  "in a scalar value for the "
1540  "expression '%s'",
1541  expr_str.c_str());
1542  break;
1543  }
1544  } else {
1545  error.SetErrorStringWithFormat("expression value didn't result "
1546  "in a scalar value for the "
1547  "expression '%s'",
1548  expr_str.c_str());
1549  break;
1550  }
1551 
1552  continue;
1553  }
1554 
1555  if (expr_result_valobj_sp)
1556  error = expr_result_valobj_sp->GetError();
1557 
1558  if (error.Success()) {
1559  switch (expr_result) {
1560  case eExpressionSetupError:
1562  "expression setup error for the expression '%s'", expr_str.c_str());
1563  break;
1564  case eExpressionParseError:
1566  "expression parse error for the expression '%s'", expr_str.c_str());
1567  break;
1570  "expression error fetching result for the expression '%s'",
1571  expr_str.c_str());
1572  break;
1573  case eExpressionCompleted:
1574  break;
1575  case eExpressionDiscarded:
1577  "expression discarded for the expression '%s'", expr_str.c_str());
1578  break;
1581  "expression interrupted for the expression '%s'", expr_str.c_str());
1582  break;
1585  "expression hit breakpoint for the expression '%s'",
1586  expr_str.c_str());
1587  break;
1588  case eExpressionTimedOut:
1590  "expression timed out for the expression '%s'", expr_str.c_str());
1591  break;
1593  error.SetErrorStringWithFormat("expression stop at entry point "
1594  "for debugging for the "
1595  "expression '%s'",
1596  expr_str.c_str());
1597  break;
1598  }
1599  }
1600  }
1601  return error;
1602 }
1603 
1604 bool CommandInterpreter::HandleCommand(const char *command_line,
1605  LazyBool lazy_add_to_history,
1606  CommandReturnObject &result,
1607  ExecutionContext *override_context,
1608  bool repeat_on_empty_command,
1609  bool no_context_switching)
1610 
1611 {
1612 
1613  std::string command_string(command_line);
1614  std::string original_command_string(command_line);
1615 
1617  llvm::PrettyStackTraceFormat stack_trace("HandleCommand(command = \"%s\")",
1618  command_line);
1619 
1620  if (log)
1621  log->Printf("Processing command: %s", command_line);
1622 
1623  static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1624  Timer scoped_timer(func_cat, "Handling command: %s.", command_line);
1625 
1626  if (!no_context_switching)
1627  UpdateExecutionContext(override_context);
1628 
1629  if (WasInterrupted()) {
1630  result.AppendError("interrupted");
1632  return false;
1633  }
1634 
1635  bool add_to_history;
1636  if (lazy_add_to_history == eLazyBoolCalculate)
1637  add_to_history = (m_command_source_depth == 0);
1638  else
1639  add_to_history = (lazy_add_to_history == eLazyBoolYes);
1640 
1641  bool empty_command = false;
1642  bool comment_command = false;
1643  if (command_string.empty())
1644  empty_command = true;
1645  else {
1646  const char *k_space_characters = "\t\n\v\f\r ";
1647 
1648  size_t non_space = command_string.find_first_not_of(k_space_characters);
1649  // Check for empty line or comment line (lines whose first non-space
1650  // character is the comment character for this interpreter)
1651  if (non_space == std::string::npos)
1652  empty_command = true;
1653  else if (command_string[non_space] == m_comment_char)
1654  comment_command = true;
1655  else if (command_string[non_space] == CommandHistory::g_repeat_char) {
1656  llvm::StringRef search_str(command_string);
1657  search_str = search_str.drop_front(non_space);
1658  if (auto hist_str = m_command_history.FindString(search_str)) {
1659  add_to_history = false;
1660  command_string = *hist_str;
1661  original_command_string = *hist_str;
1662  } else {
1663  result.AppendErrorWithFormat("Could not find entry: %s in history",
1664  command_string.c_str());
1666  return false;
1667  }
1668  }
1669  }
1670 
1671  if (empty_command) {
1672  if (repeat_on_empty_command) {
1673  if (m_command_history.IsEmpty()) {
1674  result.AppendError("empty command");
1676  return false;
1677  } else {
1678  command_line = m_repeat_command.c_str();
1679  command_string = command_line;
1680  original_command_string = command_line;
1681  if (m_repeat_command.empty()) {
1682  result.AppendErrorWithFormat("No auto repeat.\n");
1684  return false;
1685  }
1686  }
1687  add_to_history = false;
1688  } else {
1690  return true;
1691  }
1692  } else if (comment_command) {
1694  return true;
1695  }
1696 
1697  Status error(PreprocessCommand(command_string));
1698 
1699  if (error.Fail()) {
1700  result.AppendError(error.AsCString());
1702  return false;
1703  }
1704 
1705  // Phase 1.
1706 
1707  // Before we do ANY kind of argument processing, we need to figure out what
1708  // the real/final command object is for the specified command. This gets
1709  // complicated by the fact that the user could have specified an alias, and,
1710  // in translating the alias, there may also be command options and/or even
1711  // data (including raw text strings) that need to be found and inserted into
1712  // the command line as part of the translation. So this first step is plain
1713  // look-up and replacement, resulting in:
1714  // 1. the command object whose Execute method will actually be called
1715  // 2. a revised command string, with all substitutions and replacements
1716  // taken care of
1717  // From 1 above, we can determine whether the Execute function wants raw
1718  // input or not.
1719 
1720  CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
1721 
1722  // Although the user may have abbreviated the command, the command_string now
1723  // has the command expanded to the full name. For example, if the input was
1724  // "br s -n main", command_string is now "breakpoint set -n main".
1725  if (log) {
1726  llvm::StringRef command_name = cmd_obj ? cmd_obj->GetCommandName() : "<not found>";
1727  log->Printf("HandleCommand, cmd_obj : '%s'", command_name.str().c_str());
1728  log->Printf("HandleCommand, (revised) command_string: '%s'",
1729  command_string.c_str());
1730  const bool wants_raw_input =
1731  (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1732  log->Printf("HandleCommand, wants_raw_input:'%s'",
1733  wants_raw_input ? "True" : "False");
1734  }
1735 
1736  // Phase 2.
1737  // Take care of things like setting up the history command & calling the
1738  // appropriate Execute method on the CommandObject, with the appropriate
1739  // arguments.
1740 
1741  if (cmd_obj != nullptr) {
1742  if (add_to_history) {
1743  Args command_args(command_string);
1744  const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1745  if (repeat_command != nullptr)
1746  m_repeat_command.assign(repeat_command);
1747  else
1748  m_repeat_command.assign(original_command_string);
1749 
1750  m_command_history.AppendString(original_command_string);
1751  }
1752 
1753  std::string remainder;
1754  const std::size_t actual_cmd_name_len = cmd_obj->GetCommandName().size();
1755  if (actual_cmd_name_len < command_string.length())
1756  remainder = command_string.substr(actual_cmd_name_len);
1757 
1758  // Remove any initial spaces
1759  size_t pos = remainder.find_first_not_of(k_white_space);
1760  if (pos != 0 && pos != std::string::npos)
1761  remainder.erase(0, pos);
1762 
1763  if (log)
1764  log->Printf(
1765  "HandleCommand, command line after removing command name(s): '%s'",
1766  remainder.c_str());
1767 
1768  cmd_obj->Execute(remainder.c_str(), result);
1769  }
1770 
1771  if (log)
1772  log->Printf("HandleCommand, command %s",
1773  (result.Succeeded() ? "succeeded" : "did not succeed"));
1774 
1775  return result.Succeeded();
1776 }
1777 
1779  int num_command_matches = 0;
1780  bool look_for_subcommand = false;
1781 
1782  // For any of the command completions a unique match will be a complete word.
1783  request.SetWordComplete(true);
1784 
1785  if (request.GetCursorIndex() == -1) {
1786  // We got nothing on the command line, so return the list of commands
1787  bool include_aliases = true;
1788  StringList new_matches, descriptions;
1789  num_command_matches = GetCommandNamesMatchingPartialString(
1790  "", include_aliases, new_matches, descriptions);
1791  request.AddCompletions(new_matches, descriptions);
1792  } else if (request.GetCursorIndex() == 0) {
1793  // The cursor is in the first argument, so just do a lookup in the
1794  // dictionary.
1795  StringList new_matches, new_descriptions;
1796  CommandObject *cmd_obj =
1798  &new_matches, &new_descriptions);
1799 
1800  if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() &&
1801  new_matches.GetStringAtIndex(0) != nullptr &&
1802  strcmp(request.GetParsedLine().GetArgumentAtIndex(0),
1803  new_matches.GetStringAtIndex(0)) == 0) {
1804  if (request.GetParsedLine().GetArgumentCount() == 1) {
1805  request.SetWordComplete(true);
1806  } else {
1807  look_for_subcommand = true;
1808  num_command_matches = 0;
1809  new_matches.DeleteStringAtIndex(0);
1810  new_descriptions.DeleteStringAtIndex(0);
1811  request.GetParsedLine().AppendArgument(llvm::StringRef());
1812  request.SetCursorIndex(request.GetCursorIndex() + 1);
1813  request.SetCursorCharPosition(0);
1814  }
1815  }
1816  request.AddCompletions(new_matches, new_descriptions);
1817  num_command_matches = request.GetNumberOfMatches();
1818  }
1819 
1820  if (request.GetCursorIndex() > 0 || look_for_subcommand) {
1821  // We are completing further on into a commands arguments, so find the
1822  // command and tell it to complete the command. First see if there is a
1823  // matching initial command:
1824  CommandObject *command_object =
1826  if (command_object == nullptr) {
1827  return 0;
1828  } else {
1829  request.GetParsedLine().Shift();
1830  request.SetCursorIndex(request.GetCursorIndex() - 1);
1831  num_command_matches = command_object->HandleCompletion(request);
1832  }
1833  }
1834 
1835  return num_command_matches;
1836 }
1837 
1839  const char *current_line, const char *cursor, const char *last_char,
1840  int match_start_point, int max_return_elements, StringList &matches,
1841  StringList &descriptions) {
1842 
1843  llvm::StringRef command_line(current_line, last_char - current_line);
1844  CompletionResult result;
1845  CompletionRequest request(command_line, cursor - current_line,
1846  match_start_point, max_return_elements, result);
1847  // Don't complete comments, and if the line we are completing is just the
1848  // history repeat character, substitute the appropriate history line.
1849  const char *first_arg = request.GetParsedLine().GetArgumentAtIndex(0);
1850  if (first_arg) {
1851  if (first_arg[0] == m_comment_char)
1852  return 0;
1853  else if (first_arg[0] == CommandHistory::g_repeat_char) {
1854  if (auto hist_str = m_command_history.FindString(first_arg)) {
1855  matches.InsertStringAtIndex(0, *hist_str);
1856  descriptions.InsertStringAtIndex(0, "Previous command history event");
1857  return -2;
1858  } else
1859  return 0;
1860  }
1861  }
1862 
1863  // Only max_return_elements == -1 is supported at present:
1864  lldbassert(max_return_elements == -1);
1865 
1866  int num_command_matches = HandleCompletionMatches(request);
1867  result.GetMatches(matches);
1868  result.GetDescriptions(descriptions);
1869 
1870  if (num_command_matches <= 0)
1871  return num_command_matches;
1872 
1873  if (request.GetParsedLine().GetArgumentCount() == 0) {
1874  // If we got an empty string, insert nothing.
1875  matches.InsertStringAtIndex(0, "");
1876  descriptions.InsertStringAtIndex(0, "");
1877  } else {
1878  // Now figure out if there is a common substring, and if so put that in
1879  // element 0, otherwise put an empty string in element 0.
1880  std::string command_partial_str = request.GetCursorArgumentPrefix().str();
1881 
1882  std::string common_prefix;
1883  matches.LongestCommonPrefix(common_prefix);
1884  const size_t partial_name_len = command_partial_str.size();
1885  common_prefix.erase(0, partial_name_len);
1886 
1887  // If we matched a unique single command, add a space... Only do this if
1888  // the completer told us this was a complete word, however...
1889  if (num_command_matches == 1 && request.GetWordComplete()) {
1890  char quote_char = request.GetParsedLine()[request.GetCursorIndex()].quote;
1891  common_prefix =
1892  Args::EscapeLLDBCommandArgument(common_prefix, quote_char);
1893  if (quote_char != '\0')
1894  common_prefix.push_back(quote_char);
1895  common_prefix.push_back(' ');
1896  }
1897  matches.InsertStringAtIndex(0, common_prefix.c_str());
1898  descriptions.InsertStringAtIndex(0, "");
1899  }
1900  return num_command_matches;
1901 }
1902 
1904 
1905 void CommandInterpreter::UpdatePrompt(llvm::StringRef new_prompt) {
1906  EventSP prompt_change_event_sp(
1907  new Event(eBroadcastBitResetPrompt, new EventDataBytes(new_prompt)));
1908  ;
1909  BroadcastEvent(prompt_change_event_sp);
1910  if (m_command_io_handler_sp)
1911  m_command_io_handler_sp->SetPrompt(new_prompt);
1912 }
1913 
1914 bool CommandInterpreter::Confirm(llvm::StringRef message, bool default_answer) {
1915  // Check AutoConfirm first:
1916  if (m_debugger.GetAutoConfirm())
1917  return default_answer;
1918 
1919  IOHandlerConfirm *confirm =
1920  new IOHandlerConfirm(m_debugger, message, default_answer);
1921  IOHandlerSP io_handler_sp(confirm);
1922  m_debugger.RunIOHandler(io_handler_sp);
1923  return confirm->GetResponse();
1924 }
1925 
1926 const CommandAlias *
1927 CommandInterpreter::GetAlias(llvm::StringRef alias_name) const {
1928  OptionArgVectorSP ret_val;
1929 
1930  auto pos = m_alias_dict.find(alias_name);
1931  if (pos != m_alias_dict.end())
1932  return (CommandAlias *)pos->second.get();
1933 
1934  return nullptr;
1935 }
1936 
1937 bool CommandInterpreter::HasCommands() const { return (!m_command_dict.empty()); }
1938 
1939 bool CommandInterpreter::HasAliases() const { return (!m_alias_dict.empty()); }
1940 
1941 bool CommandInterpreter::HasUserCommands() const { return (!m_user_dict.empty()); }
1942 
1944 
1946  const char *alias_name,
1947  Args &cmd_args,
1948  std::string &raw_input_string,
1949  CommandReturnObject &result) {
1950  OptionArgVectorSP option_arg_vector_sp =
1951  GetAlias(alias_name)->GetOptionArguments();
1952 
1953  bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
1954 
1955  // Make sure that the alias name is the 0th element in cmd_args
1956  std::string alias_name_str = alias_name;
1957  if (alias_name_str != cmd_args.GetArgumentAtIndex(0))
1958  cmd_args.Unshift(alias_name_str);
1959 
1960  Args new_args(alias_cmd_obj->GetCommandName());
1961  if (new_args.GetArgumentCount() == 2)
1962  new_args.Shift();
1963 
1964  if (option_arg_vector_sp.get()) {
1965  if (wants_raw_input) {
1966  // We have a command that both has command options and takes raw input.
1967  // Make *sure* it has a " -- " in the right place in the
1968  // raw_input_string.
1969  size_t pos = raw_input_string.find(" -- ");
1970  if (pos == std::string::npos) {
1971  // None found; assume it goes at the beginning of the raw input string
1972  raw_input_string.insert(0, " -- ");
1973  }
1974  }
1975 
1976  OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1977  const size_t old_size = cmd_args.GetArgumentCount();
1978  std::vector<bool> used(old_size + 1, false);
1979 
1980  used[0] = true;
1981 
1982  int value_type;
1983  std::string option;
1984  std::string value;
1985  for (const auto &option_entry : *option_arg_vector) {
1986  std::tie(option, value_type, value) = option_entry;
1987  if (option == "<argument>") {
1988  if (!wants_raw_input || (value != "--")) {
1989  // Since we inserted this above, make sure we don't insert it twice
1990  new_args.AppendArgument(value);
1991  }
1992  continue;
1993  }
1994 
1995  if (value_type != OptionParser::eOptionalArgument)
1996  new_args.AppendArgument(option);
1997 
1998  if (value == "<no-argument>")
1999  continue;
2000 
2001  int index = GetOptionArgumentPosition(value.c_str());
2002  if (index == 0) {
2003  // value was NOT a positional argument; must be a real value
2004  if (value_type != OptionParser::eOptionalArgument)
2005  new_args.AppendArgument(value);
2006  else {
2007  char buffer[255];
2008  ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2009  value.c_str());
2010  new_args.AppendArgument(llvm::StringRef(buffer));
2011  }
2012 
2013  } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) {
2014  result.AppendErrorWithFormat("Not enough arguments provided; you "
2015  "need at least %d arguments to use "
2016  "this alias.\n",
2017  index);
2019  return;
2020  } else {
2021  // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2022  size_t strpos =
2023  raw_input_string.find(cmd_args.GetArgumentAtIndex(index));
2024  if (strpos != std::string::npos) {
2025  raw_input_string = raw_input_string.erase(
2026  strpos, strlen(cmd_args.GetArgumentAtIndex(index)));
2027  }
2028 
2029  if (value_type != OptionParser::eOptionalArgument)
2030  new_args.AppendArgument(cmd_args.GetArgumentAtIndex(index));
2031  else {
2032  char buffer[255];
2033  ::snprintf(buffer, sizeof(buffer), "%s%s", option.c_str(),
2034  cmd_args.GetArgumentAtIndex(index));
2035  new_args.AppendArgument(buffer);
2036  }
2037  used[index] = true;
2038  }
2039  }
2040 
2041  for (auto entry : llvm::enumerate(cmd_args.entries())) {
2042  if (!used[entry.index()] && !wants_raw_input)
2043  new_args.AppendArgument(entry.value().ref);
2044  }
2045 
2046  cmd_args.Clear();
2047  cmd_args.SetArguments(new_args.GetArgumentCount(),
2048  new_args.GetConstArgumentVector());
2049  } else {
2051  // This alias was not created with any options; nothing further needs to be
2052  // done, unless it is a command that wants raw input, in which case we need
2053  // to clear the rest of the data from cmd_args, since its in the raw input
2054  // string.
2055  if (wants_raw_input) {
2056  cmd_args.Clear();
2057  cmd_args.SetArguments(new_args.GetArgumentCount(),
2058  new_args.GetConstArgumentVector());
2059  }
2060  return;
2061  }
2062 
2064  return;
2065 }
2066 
2068  int position = 0; // Any string that isn't an argument position, i.e. '%'
2069  // followed by an integer, gets a position
2070  // of zero.
2071 
2072  const char *cptr = in_string;
2073 
2074  // Does it start with '%'
2075  if (cptr[0] == '%') {
2076  ++cptr;
2077 
2078  // Is the rest of it entirely digits?
2079  if (isdigit(cptr[0])) {
2080  const char *start = cptr;
2081  while (isdigit(cptr[0]))
2082  ++cptr;
2083 
2084  // We've gotten to the end of the digits; are we at the end of the
2085  // string?
2086  if (cptr[0] == '\0')
2087  position = atoi(start);
2088  }
2089  }
2090 
2091  return position;
2092 }
2093 
2095  CommandReturnObject &result) {
2096  FileSpec init_file;
2097  if (in_cwd) {
2098  lldb::TargetPropertiesSP properties = Target::GetGlobalProperties();
2099  if (properties) {
2100  // In the current working directory we don't load any program specific
2101  // .lldbinit files, we only look for a ".lldbinit" file.
2102  if (m_skip_lldbinit_files)
2103  return;
2104 
2105  LoadCWDlldbinitFile should_load = properties->GetLoadCWDlldbinitFile();
2106  if (should_load == eLoadCWDlldbinitWarn) {
2107  FileSpec dot_lldb(".lldbinit");
2108  FileSystem::Instance().Resolve(dot_lldb);
2109  llvm::SmallString<64> home_dir_path;
2110  llvm::sys::path::home_directory(home_dir_path);
2111  FileSpec homedir_dot_lldb(home_dir_path.c_str());
2112  homedir_dot_lldb.AppendPathComponent(".lldbinit");
2113  FileSystem::Instance().Resolve(homedir_dot_lldb);
2114  if (FileSystem::Instance().Exists(dot_lldb) &&
2115  dot_lldb.GetDirectory() != homedir_dot_lldb.GetDirectory()) {
2116  result.AppendErrorWithFormat(
2117  "There is a .lldbinit file in the current directory which is not "
2118  "being read.\n"
2119  "To silence this warning without sourcing in the local "
2120  ".lldbinit,\n"
2121  "add the following to the lldbinit file in your home directory:\n"
2122  " settings set target.load-cwd-lldbinit false\n"
2123  "To allow lldb to source .lldbinit files in the current working "
2124  "directory,\n"
2125  "set the value of this variable to true. Only do so if you "
2126  "understand and\n"
2127  "accept the security risk.");
2129  return;
2130  }
2131  } else if (should_load == eLoadCWDlldbinitTrue) {
2132  init_file.SetFile("./.lldbinit", FileSpec::Style::native);
2133  FileSystem::Instance().Resolve(init_file);
2134  }
2135  }
2136  } else {
2137  // If we aren't looking in the current working directory we are looking in
2138  // the home directory. We will first see if there is an application
2139  // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a "-"
2140  // and the name of the program. If this file doesn't exist, we fall back to
2141  // just the "~/.lldbinit" file. We also obey any requests to not load the
2142  // init files.
2143  llvm::SmallString<64> home_dir_path;
2144  llvm::sys::path::home_directory(home_dir_path);
2145  FileSpec profilePath(home_dir_path.c_str());
2146  profilePath.AppendPathComponent(".lldbinit");
2147  std::string init_file_path = profilePath.GetPath();
2148 
2149  if (!m_skip_app_init_files) {
2150  FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
2151  const char *program_name = program_file_spec.GetFilename().AsCString();
2152 
2153  if (program_name) {
2154  char program_init_file_name[PATH_MAX];
2155  ::snprintf(program_init_file_name, sizeof(program_init_file_name),
2156  "%s-%s", init_file_path.c_str(), program_name);
2157  init_file.SetFile(program_init_file_name, FileSpec::Style::native);
2158  FileSystem::Instance().Resolve(init_file);
2159  if (!FileSystem::Instance().Exists(init_file))
2160  init_file.Clear();
2161  }
2162  }
2163 
2164  if (!init_file && !m_skip_lldbinit_files)
2165  init_file.SetFile(init_file_path, FileSpec::Style::native);
2166  }
2167 
2168  // If the file exists, tell HandleCommand to 'source' it; this will do the
2169  // actual broadcasting of the commands back to any appropriate listener (see
2170  // CommandObjectSource::Execute for more details).
2171 
2172  if (FileSystem::Instance().Exists(init_file)) {
2173  const bool saved_batch = SetBatchCommandMode(true);
2175  options.SetSilent(true);
2176  options.SetStopOnError(false);
2177  options.SetStopOnContinue(true);
2178 
2179  HandleCommandsFromFile(init_file,
2180  nullptr, // Execution context
2181  options, result);
2182  SetBatchCommandMode(saved_batch);
2183  } else {
2184  // nothing to be done if the file doesn't exist
2186  }
2187 }
2188 
2190  const char *prefix = GetDebugger().GetIOHandlerCommandPrefix();
2191  return prefix == NULL ? "" : prefix;
2192 }
2193 
2194 PlatformSP CommandInterpreter::GetPlatform(bool prefer_target_platform) {
2195  PlatformSP platform_sp;
2196  if (prefer_target_platform) {
2198  Target *target = exe_ctx.GetTargetPtr();
2199  if (target)
2200  platform_sp = target->GetPlatform();
2201  }
2202 
2203  if (!platform_sp)
2204  platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2205  return platform_sp;
2206 }
2207 
2209  ExecutionContext *override_context,
2211  CommandReturnObject &result) {
2212  size_t num_lines = commands.GetSize();
2213 
2214  // If we are going to continue past a "continue" then we need to run the
2215  // commands synchronously. Make sure you reset this value anywhere you return
2216  // from the function.
2217 
2218  bool old_async_execution = m_debugger.GetAsyncExecution();
2219 
2220  // If we've been given an execution context, set it at the start, but don't
2221  // keep resetting it or we will cause series of commands that change the
2222  // context, then do an operation that relies on that context to fail.
2223 
2224  if (override_context != nullptr)
2225  UpdateExecutionContext(override_context);
2226 
2227  if (!options.GetStopOnContinue()) {
2228  m_debugger.SetAsyncExecution(false);
2229  }
2230 
2231  for (size_t idx = 0; idx < num_lines && !WasInterrupted(); idx++) {
2232  const char *cmd = commands.GetStringAtIndex(idx);
2233  if (cmd[0] == '\0')
2234  continue;
2235 
2236  if (options.GetEchoCommands()) {
2237  // TODO: Add Stream support.
2238  result.AppendMessageWithFormat("%s %s\n",
2239  m_debugger.GetPrompt().str().c_str(), cmd);
2240  }
2241 
2242  CommandReturnObject tmp_result;
2243  // If override_context is not NULL, pass no_context_switching = true for
2244  // HandleCommand() since we updated our context already.
2245 
2246  // We might call into a regex or alias command, in which case the
2247  // add_to_history will get lost. This m_command_source_depth dingus is the
2248  // way we turn off adding to the history in that case, so set it up here.
2249  if (!options.GetAddToHistory())
2250  m_command_source_depth++;
2251  bool success =
2252  HandleCommand(cmd, options.m_add_to_history, tmp_result,
2253  nullptr, /* override_context */
2254  true, /* repeat_on_empty_command */
2255  override_context != nullptr /* no_context_switching */);
2256  if (!options.GetAddToHistory())
2257  m_command_source_depth--;
2258 
2259  if (options.GetPrintResults()) {
2260  if (tmp_result.Succeeded())
2261  result.AppendMessage(tmp_result.GetOutputData());
2262  }
2263 
2264  if (!success || !tmp_result.Succeeded()) {
2265  llvm::StringRef error_msg = tmp_result.GetErrorData();
2266  if (error_msg.empty())
2267  error_msg = "<unknown error>.\n";
2268  if (options.GetStopOnError()) {
2269  result.AppendErrorWithFormat(
2270  "Aborting reading of commands after command #%" PRIu64
2271  ": '%s' failed with %s",
2272  (uint64_t)idx, cmd, error_msg.str().c_str());
2274  m_debugger.SetAsyncExecution(old_async_execution);
2275  return;
2276  } else if (options.GetPrintResults()) {
2277  result.AppendMessageWithFormat(
2278  "Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd,
2279  error_msg.str().c_str());
2280  }
2281  }
2282 
2283  if (result.GetImmediateOutputStream())
2284  result.GetImmediateOutputStream()->Flush();
2285 
2286  if (result.GetImmediateErrorStream())
2287  result.GetImmediateErrorStream()->Flush();
2288 
2289  // N.B. Can't depend on DidChangeProcessState, because the state coming
2290  // into the command execution could be running (for instance in Breakpoint
2291  // Commands. So we check the return value to see if it is has running in
2292  // it.
2293  if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2294  (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2295  if (options.GetStopOnContinue()) {
2296  // If we caused the target to proceed, and we're going to stop in that
2297  // case, set the status in our real result before returning. This is
2298  // an error if the continue was not the last command in the set of
2299  // commands to be run.
2300  if (idx != num_lines - 1)
2301  result.AppendErrorWithFormat(
2302  "Aborting reading of commands after command #%" PRIu64
2303  ": '%s' continued the target.\n",
2304  (uint64_t)idx + 1, cmd);
2305  else
2306  result.AppendMessageWithFormat("Command #%" PRIu64
2307  " '%s' continued the target.\n",
2308  (uint64_t)idx + 1, cmd);
2309 
2310  result.SetStatus(tmp_result.GetStatus());
2311  m_debugger.SetAsyncExecution(old_async_execution);
2312 
2313  return;
2314  }
2315  }
2316 
2317  // Also check for "stop on crash here:
2318  bool should_stop = false;
2319  if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) {
2320  TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2321  if (target_sp) {
2322  ProcessSP process_sp(target_sp->GetProcessSP());
2323  if (process_sp) {
2324  for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2325  StopReason reason = thread_sp->GetStopReason();
2326  if (reason == eStopReasonSignal || reason == eStopReasonException ||
2327  reason == eStopReasonInstrumentation) {
2328  should_stop = true;
2329  break;
2330  }
2331  }
2332  }
2333  }
2334  if (should_stop) {
2335  if (idx != num_lines - 1)
2336  result.AppendErrorWithFormat(
2337  "Aborting reading of commands after command #%" PRIu64
2338  ": '%s' stopped with a signal or exception.\n",
2339  (uint64_t)idx + 1, cmd);
2340  else
2341  result.AppendMessageWithFormat(
2342  "Command #%" PRIu64 " '%s' stopped with a signal or exception.\n",
2343  (uint64_t)idx + 1, cmd);
2344 
2345  result.SetStatus(tmp_result.GetStatus());
2346  m_debugger.SetAsyncExecution(old_async_execution);
2347 
2348  return;
2349  }
2350  }
2351  }
2352 
2354  m_debugger.SetAsyncExecution(old_async_execution);
2355 
2356  return;
2357 }
2358 
2359 // Make flags that we can pass into the IOHandler so our delegates can do the
2360 // right thing
2361 enum {
2368 };
2369 
2371  FileSpec &cmd_file, ExecutionContext *context,
2373  if (!FileSystem::Instance().Exists(cmd_file)) {
2374  result.AppendErrorWithFormat(
2375  "Error reading commands from file %s - file not found.\n",
2376  cmd_file.GetFilename().AsCString("<Unknown>"));
2378  return;
2379  }
2380 
2381  StreamFileSP input_file_sp(new StreamFile());
2382  std::string cmd_file_path = cmd_file.GetPath();
2383  Status error = FileSystem::Instance().Open(input_file_sp->GetFile(), cmd_file,
2385 
2386  if (error.Fail()) {
2387  result.AppendErrorWithFormat(
2388  "error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(),
2389  error.AsCString());
2391  return;
2392  }
2393 
2394  Debugger &debugger = GetDebugger();
2395 
2396  uint32_t flags = 0;
2397 
2398  if (options.m_stop_on_continue == eLazyBoolCalculate) {
2399  if (m_command_source_flags.empty()) {
2400  // Stop on continue by default
2402  } else if (m_command_source_flags.back() &
2405  }
2406  } else if (options.m_stop_on_continue == eLazyBoolYes) {
2408  }
2409 
2410  if (options.m_stop_on_error == eLazyBoolCalculate) {
2411  if (m_command_source_flags.empty()) {
2414  } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) {
2416  }
2417  } else if (options.m_stop_on_error == eLazyBoolYes) {
2419  }
2420 
2421  // stop-on-crash can only be set, if it is present in all levels of
2422  // pushed flag sets.
2423  if (options.GetStopOnCrash()) {
2424  if (m_command_source_flags.empty()) {
2426  } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) {
2428  }
2429  }
2430 
2431  if (options.m_echo_commands == eLazyBoolCalculate) {
2432  if (m_command_source_flags.empty()) {
2433  // Echo command by default
2435  } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) {
2437  }
2438  } else if (options.m_echo_commands == eLazyBoolYes) {
2440  }
2441 
2442  // We will only ever ask for this flag, if we echo commands in general.
2444  if (m_command_source_flags.empty()) {
2445  // Echo comments by default
2447  } else if (m_command_source_flags.back() &
2450  }
2451  } else if (options.m_echo_comment_commands == eLazyBoolYes) {
2453  }
2454 
2455  if (options.m_print_results == eLazyBoolCalculate) {
2456  if (m_command_source_flags.empty()) {
2457  // Print output by default
2459  } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) {
2461  }
2462  } else if (options.m_print_results == eLazyBoolYes) {
2464  }
2465 
2466  if (flags & eHandleCommandFlagPrintResult) {
2467  debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n",
2468  cmd_file_path.c_str());
2469  }
2470 
2471  // Used for inheriting the right settings when "command source" might
2472  // have nested "command source" commands
2473  lldb::StreamFileSP empty_stream_sp;
2474  m_command_source_flags.push_back(flags);
2475  IOHandlerSP io_handler_sp(new IOHandlerEditline(
2476  debugger, IOHandler::Type::CommandInterpreter, input_file_sp,
2477  empty_stream_sp, // Pass in an empty stream so we inherit the top
2478  // input reader output stream
2479  empty_stream_sp, // Pass in an empty stream so we inherit the top
2480  // input reader error stream
2481  flags,
2482  nullptr, // Pass in NULL for "editline_name" so no history is saved,
2483  // or written
2484  debugger.GetPrompt(), llvm::StringRef(),
2485  false, // Not multi-line
2486  debugger.GetUseColor(), 0, *this, nullptr));
2487  const bool old_async_execution = debugger.GetAsyncExecution();
2488 
2489  // Set synchronous execution if we are not stopping on continue
2490  if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2491  debugger.SetAsyncExecution(false);
2492 
2493  m_command_source_depth++;
2494 
2495  debugger.RunIOHandler(io_handler_sp);
2496  if (!m_command_source_flags.empty())
2497  m_command_source_flags.pop_back();
2498  m_command_source_depth--;
2500  debugger.SetAsyncExecution(old_async_execution);
2501 }
2502 
2503 bool CommandInterpreter::GetSynchronous() { return m_synchronous_execution; }
2504 
2506  m_synchronous_execution = value;
2507 }
2508 
2510  llvm::StringRef prefix,
2511  llvm::StringRef help_text) {
2512  const uint32_t max_columns = m_debugger.GetTerminalWidth();
2513 
2514  size_t line_width_max = max_columns - prefix.size();
2515  if (line_width_max < 16)
2516  line_width_max = help_text.size() + prefix.size();
2517 
2518  strm.IndentMore(prefix.size());
2519  bool prefixed_yet = false;
2520  while (!help_text.empty()) {
2521  // Prefix the first line, indent subsequent lines to line up
2522  if (!prefixed_yet) {
2523  strm << prefix;
2524  prefixed_yet = true;
2525  } else
2526  strm.Indent();
2527 
2528  // Never print more than the maximum on one line.
2529  llvm::StringRef this_line = help_text.substr(0, line_width_max);
2530 
2531  // Always break on an explicit newline.
2532  std::size_t first_newline = this_line.find_first_of("\n");
2533 
2534  // Don't break on space/tab unless the text is too long to fit on one line.
2535  std::size_t last_space = llvm::StringRef::npos;
2536  if (this_line.size() != help_text.size())
2537  last_space = this_line.find_last_of(" \t");
2538 
2539  // Break at whichever condition triggered first.
2540  this_line = this_line.substr(0, std::min(first_newline, last_space));
2541  strm.PutCString(this_line);
2542  strm.EOL();
2543 
2544  // Remove whitespace / newlines after breaking.
2545  help_text = help_text.drop_front(this_line.size()).ltrim();
2546  }
2547  strm.IndentLess(prefix.size());
2548 }
2549 
2551  llvm::StringRef word_text,
2552  llvm::StringRef separator,
2553  llvm::StringRef help_text,
2554  size_t max_word_len) {
2555  StreamString prefix_stream;
2556  prefix_stream.Printf(" %-*s %*s ", (int)max_word_len, word_text.data(),
2557  (int)separator.size(), separator.data());
2558  OutputFormattedHelpText(strm, prefix_stream.GetString(), help_text);
2559 }
2560 
2561 void CommandInterpreter::OutputHelpText(Stream &strm, llvm::StringRef word_text,
2562  llvm::StringRef separator,
2563  llvm::StringRef help_text,
2564  uint32_t max_word_len) {
2565  int indent_size = max_word_len + separator.size() + 2;
2566 
2567  strm.IndentMore(indent_size);
2568 
2569  StreamString text_strm;
2570  text_strm.Printf("%-*s ", (int)max_word_len, word_text.data());
2571  text_strm << separator << " " << help_text;
2572 
2573  const uint32_t max_columns = m_debugger.GetTerminalWidth();
2574 
2575  llvm::StringRef text = text_strm.GetString();
2576 
2577  uint32_t chars_left = max_columns;
2578 
2579  auto nextWordLength = [](llvm::StringRef S) {
2580  size_t pos = S.find(' ');
2581  return pos == llvm::StringRef::npos ? S.size() : pos;
2582  };
2583 
2584  while (!text.empty()) {
2585  if (text.front() == '\n' ||
2586  (text.front() == ' ' && nextWordLength(text.ltrim(' ')) > chars_left)) {
2587  strm.EOL();
2588  strm.Indent();
2589  chars_left = max_columns - indent_size;
2590  if (text.front() == '\n')
2591  text = text.drop_front();
2592  else
2593  text = text.ltrim(' ');
2594  } else {
2595  strm.PutChar(text.front());
2596  --chars_left;
2597  text = text.drop_front();
2598  }
2599  }
2600 
2601  strm.EOL();
2602  strm.IndentLess(indent_size);
2603 }
2604 
2606  llvm::StringRef search_word, StringList &commands_found,
2607  StringList &commands_help, CommandObject::CommandMap &command_map) {
2608  CommandObject::CommandMap::const_iterator pos;
2609 
2610  for (pos = command_map.begin(); pos != command_map.end(); ++pos) {
2611  llvm::StringRef command_name = pos->first;
2612  CommandObject *cmd_obj = pos->second.get();
2613 
2614  const bool search_short_help = true;
2615  const bool search_long_help = false;
2616  const bool search_syntax = false;
2617  const bool search_options = false;
2618  if (command_name.contains_lower(search_word) ||
2619  cmd_obj->HelpTextContainsWord(search_word, search_short_help,
2620  search_long_help, search_syntax,
2621  search_options)) {
2622  commands_found.AppendString(cmd_obj->GetCommandName());
2623  commands_help.AppendString(cmd_obj->GetHelp());
2624  }
2625 
2626  if (cmd_obj->IsMultiwordObject()) {
2627  CommandObjectMultiword *cmd_multiword = cmd_obj->GetAsMultiwordCommand();
2628  FindCommandsForApropos(search_word, commands_found, commands_help,
2629  cmd_multiword->GetSubcommandDictionary());
2630  }
2631  }
2632 }
2633 
2634 void CommandInterpreter::FindCommandsForApropos(llvm::StringRef search_word,
2635  StringList &commands_found,
2636  StringList &commands_help,
2637  bool search_builtin_commands,
2638  bool search_user_commands,
2639  bool search_alias_commands) {
2640  CommandObject::CommandMap::const_iterator pos;
2641 
2642  if (search_builtin_commands)
2643  FindCommandsForApropos(search_word, commands_found, commands_help,
2644  m_command_dict);
2645 
2646  if (search_user_commands)
2647  FindCommandsForApropos(search_word, commands_found, commands_help,
2648  m_user_dict);
2649 
2650  if (search_alias_commands)
2651  FindCommandsForApropos(search_word, commands_found, commands_help,
2652  m_alias_dict);
2653 }
2654 
2656  ExecutionContext *override_context) {
2657  if (override_context != nullptr) {
2658  m_exe_ctx_ref = *override_context;
2659  } else {
2660  const bool adopt_selected = true;
2661  m_exe_ctx_ref.SetTargetPtr(m_debugger.GetSelectedTarget().get(),
2662  adopt_selected);
2663  }
2664 }
2665 
2667  // The process has stuff waiting for stderr; get it and write it out to the
2668  // appropriate place.
2669  char stdio_buffer[1024];
2670  size_t len;
2671  size_t total_bytes = 0;
2672  Status error;
2673  TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2674  if (target_sp) {
2675  ProcessSP process_sp(target_sp->GetProcessSP());
2676  if (process_sp) {
2677  while ((len = process_sp->GetSTDOUT(stdio_buffer, sizeof(stdio_buffer),
2678  error)) > 0) {
2679  size_t bytes_written = len;
2680  m_debugger.GetOutputFile()->Write(stdio_buffer, bytes_written);
2681  total_bytes += len;
2682  }
2683  while ((len = process_sp->GetSTDERR(stdio_buffer, sizeof(stdio_buffer),
2684  error)) > 0) {
2685  size_t bytes_written = len;
2686  m_debugger.GetErrorFile()->Write(stdio_buffer, bytes_written);
2687  total_bytes += len;
2688  }
2689  }
2690  }
2691  return total_bytes;
2692 }
2693 
2694 void CommandInterpreter::StartHandlingCommand() {
2695  auto idle_state = CommandHandlingState::eIdle;
2696  if (m_command_state.compare_exchange_strong(
2697  idle_state, CommandHandlingState::eInProgress))
2698  lldbassert(m_iohandler_nesting_level == 0);
2699  else
2700  lldbassert(m_iohandler_nesting_level > 0);
2701  ++m_iohandler_nesting_level;
2702 }
2703 
2704 void CommandInterpreter::FinishHandlingCommand() {
2705  lldbassert(m_iohandler_nesting_level > 0);
2706  if (--m_iohandler_nesting_level == 0) {
2707  auto prev_state = m_command_state.exchange(CommandHandlingState::eIdle);
2708  lldbassert(prev_state != CommandHandlingState::eIdle);
2709  }
2710 }
2711 
2712 bool CommandInterpreter::InterruptCommand() {
2713  auto in_progress = CommandHandlingState::eInProgress;
2714  return m_command_state.compare_exchange_strong(
2715  in_progress, CommandHandlingState::eInterrupted);
2716 }
2717 
2719  bool was_interrupted =
2720  (m_command_state == CommandHandlingState::eInterrupted);
2721  lldbassert(!was_interrupted || m_iohandler_nesting_level > 0);
2722  return was_interrupted;
2723 }
2724 
2725 void CommandInterpreter::PrintCommandOutput(Stream &stream,
2726  llvm::StringRef str) {
2727  // Split the output into lines and poll for interrupt requests
2728  const char *data = str.data();
2729  size_t size = str.size();
2730  while (size > 0 && !WasInterrupted()) {
2731  size_t chunk_size = 0;
2732  for (; chunk_size < size; ++chunk_size) {
2733  lldbassert(data[chunk_size] != '\0');
2734  if (data[chunk_size] == '\n') {
2735  ++chunk_size;
2736  break;
2737  }
2738  }
2739  chunk_size = stream.Write(data, chunk_size);
2740  lldbassert(size >= chunk_size);
2741  data += chunk_size;
2742  size -= chunk_size;
2743  }
2744  if (size > 0) {
2745  stream.Printf("\n... Interrupted.\n");
2746  }
2747 }
2748 
2749 bool CommandInterpreter::EchoCommandNonInteractive(
2750  llvm::StringRef line, const Flags &io_handler_flags) const {
2751  if (!io_handler_flags.Test(eHandleCommandFlagEchoCommand))
2752  return false;
2753 
2754  llvm::StringRef command = line.trim();
2755  if (command.empty())
2756  return true;
2757 
2758  if (command.front() == m_comment_char)
2759  return io_handler_flags.Test(eHandleCommandFlagEchoCommentCommand);
2760 
2761  return true;
2762 }
2763 
2765  std::string &line) {
2766  // If we were interrupted, bail out...
2767  if (WasInterrupted())
2768  return;
2769 
2770  const bool is_interactive = io_handler.GetIsInteractive();
2771  if (!is_interactive) {
2772  // When we are not interactive, don't execute blank lines. This will happen
2773  // sourcing a commands file. We don't want blank lines to repeat the
2774  // previous command and cause any errors to occur (like redefining an
2775  // alias, get an error and stop parsing the commands file).
2776  if (line.empty())
2777  return;
2778 
2779  // When using a non-interactive file handle (like when sourcing commands
2780  // from a file) we need to echo the command out so we don't just see the
2781  // command output and no command...
2782  if (EchoCommandNonInteractive(line, io_handler.GetFlags()))
2783  io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(),
2784  line.c_str());
2785  }
2786 
2787  StartHandlingCommand();
2788 
2790  HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2791 
2792  // Now emit the command output text from the command we just executed
2793  if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) {
2794  // Display any STDOUT/STDERR _prior_ to emitting the command result text
2795  GetProcessOutput();
2796 
2797  if (!result.GetImmediateOutputStream()) {
2798  llvm::StringRef output = result.GetOutputData();
2799  PrintCommandOutput(*io_handler.GetOutputStreamFile(), output);
2800  }
2801 
2802  // Now emit the command error text from the command we just executed
2803  if (!result.GetImmediateErrorStream()) {
2804  llvm::StringRef error = result.GetErrorData();
2805  PrintCommandOutput(*io_handler.GetErrorStreamFile(), error);
2806  }
2807  }
2808 
2809  FinishHandlingCommand();
2810 
2811  switch (result.GetStatus()) {
2812  case eReturnStatusInvalid:
2815  case eReturnStatusStarted:
2816  break;
2817 
2821  io_handler.SetIsDone(true);
2822  break;
2823 
2824  case eReturnStatusFailed:
2825  m_num_errors++;
2826  if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
2827  io_handler.SetIsDone(true);
2828  break;
2829 
2830  case eReturnStatusQuit:
2831  m_quit_requested = true;
2832  io_handler.SetIsDone(true);
2833  break;
2834  }
2835 
2836  // Finally, if we're going to stop on crash, check that here:
2837  if (!m_quit_requested && result.GetDidChangeProcessState() &&
2839  bool should_stop = false;
2840  TargetSP target_sp(m_debugger.GetTargetList().GetSelectedTarget());
2841  if (target_sp) {
2842  ProcessSP process_sp(target_sp->GetProcessSP());
2843  if (process_sp) {
2844  for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) {
2845  StopReason reason = thread_sp->GetStopReason();
2846  if ((reason == eStopReasonSignal || reason == eStopReasonException ||
2847  reason == eStopReasonInstrumentation) &&
2848  !result.GetAbnormalStopWasExpected()) {
2849  should_stop = true;
2850  break;
2851  }
2852  }
2853  }
2854  }
2855  if (should_stop) {
2856  io_handler.SetIsDone(true);
2857  m_stopped_for_crash = true;
2858  }
2859  }
2860 }
2861 
2864  Process *process = exe_ctx.GetProcessPtr();
2865 
2866  if (InterruptCommand())
2867  return true;
2868 
2869  if (process) {
2870  StateType state = process->GetState();
2871  if (StateIsRunningState(state)) {
2872  process->Halt();
2873  return true; // Don't do any updating when we are running
2874  }
2875  }
2876 
2877  ScriptInterpreter *script_interpreter =
2878  m_debugger.GetScriptInterpreter(false);
2879  if (script_interpreter) {
2880  if (script_interpreter->Interrupt())
2881  return true;
2882  }
2883  return false;
2884 }
2885 
2887  const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2888  void *baton) {
2889  Debugger &debugger = GetDebugger();
2890  IOHandlerSP io_handler_sp(
2892  "lldb", // Name of input reader for history
2893  llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2894  llvm::StringRef(), // Continuation prompt
2895  true, // Get multiple lines
2896  debugger.GetUseColor(),
2897  0, // Don't show line numbers
2898  delegate, // IOHandlerDelegate
2899  nullptr)); // FileShadowCollector
2900 
2901  if (io_handler_sp) {
2902  io_handler_sp->SetUserData(baton);
2903  if (asynchronously)
2904  debugger.PushIOHandler(io_handler_sp);
2905  else
2906  debugger.RunIOHandler(io_handler_sp);
2907  }
2908 }
2909 
2911  const char *prompt, IOHandlerDelegate &delegate, bool asynchronously,
2912  void *baton) {
2913  Debugger &debugger = GetDebugger();
2914  IOHandlerSP io_handler_sp(
2916  "lldb-python", // Name of input reader for history
2917  llvm::StringRef::withNullAsEmpty(prompt), // Prompt
2918  llvm::StringRef(), // Continuation prompt
2919  true, // Get multiple lines
2920  debugger.GetUseColor(),
2921  0, // Don't show line numbers
2922  delegate, // IOHandlerDelegate
2923  nullptr)); // FileShadowCollector
2924 
2925  if (io_handler_sp) {
2926  io_handler_sp->SetUserData(baton);
2927  if (asynchronously)
2928  debugger.PushIOHandler(io_handler_sp);
2929  else
2930  debugger.RunIOHandler(io_handler_sp);
2931  }
2932 }
2933 
2935  return m_debugger.IsTopIOHandler(m_command_io_handler_sp);
2936 }
2937 
2938 lldb::IOHandlerSP
2940  CommandInterpreterRunOptions *options) {
2941  // Always re-create the IOHandlerEditline in case the input changed. The old
2942  // instance might have had a non-interactive input and now it does or vice
2943  // versa.
2944  if (force_create || !m_command_io_handler_sp) {
2945  // Always re-create the IOHandlerEditline in case the input changed. The
2946  // old instance might have had a non-interactive input and now it does or
2947  // vice versa.
2948  uint32_t flags = 0;
2949 
2950  if (options) {
2951  if (options->m_stop_on_continue == eLazyBoolYes)
2953  if (options->m_stop_on_error == eLazyBoolYes)
2955  if (options->m_stop_on_crash == eLazyBoolYes)
2957  if (options->m_echo_commands != eLazyBoolNo)
2959  if (options->m_echo_comment_commands != eLazyBoolNo)
2961  if (options->m_print_results != eLazyBoolNo)
2963  } else {
2965  }
2966 
2967  m_command_io_handler_sp = std::make_shared<IOHandlerEditline>(
2969  m_debugger.GetInputFile(), m_debugger.GetOutputFile(),
2970  m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(),
2971  llvm::StringRef(), // Continuation prompt
2972  false, // Don't enable multiple line input, just single line commands
2973  m_debugger.GetUseColor(),
2974  0, // Don't show line numbers
2975  *this, // IOHandlerDelegate
2977  }
2978  return m_command_io_handler_sp;
2979 }
2980 
2982  bool auto_handle_events, bool spawn_thread,
2983  CommandInterpreterRunOptions &options) {
2984  // Always re-create the command interpreter when we run it in case any file
2985  // handles have changed.
2986  bool force_create = true;
2987  m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
2988  m_stopped_for_crash = false;
2989 
2990  if (auto_handle_events)
2991  m_debugger.StartEventHandlerThread();
2992 
2993  if (spawn_thread) {
2994  m_debugger.StartIOHandlerThread();
2995  } else {
2996  m_debugger.ExecuteIOHandlers();
2997 
2998  if (auto_handle_events)
2999  m_debugger.StopEventHandlerThread();
3000  }
3001 }
3002 
3003 CommandObject *
3004 CommandInterpreter::ResolveCommandImpl(std::string &command_line,
3005  CommandReturnObject &result) {
3006  std::string scratch_command(command_line); // working copy so we don't modify
3007  // command_line unless we succeed
3008  CommandObject *cmd_obj = nullptr;
3009  StreamString revised_command_line;
3010  bool wants_raw_input = false;
3011  size_t actual_cmd_name_len = 0;
3012  std::string next_word;
3013  StringList matches;
3014  bool done = false;
3015  while (!done) {
3016  char quote_char = '\0';
3017  std::string suffix;
3018  ExtractCommand(scratch_command, next_word, suffix, quote_char);
3019  if (cmd_obj == nullptr) {
3020  std::string full_name;
3021  bool is_alias = GetAliasFullName(next_word, full_name);
3022  cmd_obj = GetCommandObject(next_word, &matches);
3023  bool is_real_command =
3024  (!is_alias) || (cmd_obj != nullptr && !cmd_obj->IsAlias());
3025  if (!is_real_command) {
3026  matches.Clear();
3027  std::string alias_result;
3028  cmd_obj =
3029  BuildAliasResult(full_name, scratch_command, alias_result, result);
3030  revised_command_line.Printf("%s", alias_result.c_str());
3031  if (cmd_obj) {
3032  wants_raw_input = cmd_obj->WantsRawCommandString();
3033  actual_cmd_name_len = cmd_obj->GetCommandName().size();
3034  }
3035  } else {
3036  if (cmd_obj) {
3037  llvm::StringRef cmd_name = cmd_obj->GetCommandName();
3038  actual_cmd_name_len += cmd_name.size();
3039  revised_command_line.Printf("%s", cmd_name.str().c_str());
3040  wants_raw_input = cmd_obj->WantsRawCommandString();
3041  } else {
3042  revised_command_line.Printf("%s", next_word.c_str());
3043  }
3044  }
3045  } else {
3046  if (cmd_obj->IsMultiwordObject()) {
3047  CommandObject *sub_cmd_obj =
3048  cmd_obj->GetSubcommandObject(next_word.c_str());
3049  if (sub_cmd_obj) {
3050  // The subcommand's name includes the parent command's name, so
3051  // restart rather than append to the revised_command_line.
3052  llvm::StringRef sub_cmd_name = sub_cmd_obj->GetCommandName();
3053  actual_cmd_name_len = sub_cmd_name.size() + 1;
3054  revised_command_line.Clear();
3055  revised_command_line.Printf("%s", sub_cmd_name.str().c_str());
3056  cmd_obj = sub_cmd_obj;
3057  wants_raw_input = cmd_obj->WantsRawCommandString();
3058  } else {
3059  if (quote_char)
3060  revised_command_line.Printf(" %c%s%s%c", quote_char,
3061  next_word.c_str(), suffix.c_str(),
3062  quote_char);
3063  else
3064  revised_command_line.Printf(" %s%s", next_word.c_str(),
3065  suffix.c_str());
3066  done = true;
3067  }
3068  } else {
3069  if (quote_char)
3070  revised_command_line.Printf(" %c%s%s%c", quote_char,
3071  next_word.c_str(), suffix.c_str(),
3072  quote_char);
3073  else
3074  revised_command_line.Printf(" %s%s", next_word.c_str(),
3075  suffix.c_str());
3076  done = true;
3077  }
3078  }
3079 
3080  if (cmd_obj == nullptr) {
3081  const size_t num_matches = matches.GetSize();
3082  if (matches.GetSize() > 1) {
3083  StreamString error_msg;
3084  error_msg.Printf("Ambiguous command '%s'. Possible matches:\n",
3085  next_word.c_str());
3086 
3087  for (uint32_t i = 0; i < num_matches; ++i) {
3088  error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3089  }
3090  result.AppendRawError(error_msg.GetString());
3091  } else {
3092  // We didn't have only one match, otherwise we wouldn't get here.
3093  lldbassert(num_matches == 0);
3094  result.AppendErrorWithFormat("'%s' is not a valid command.\n",
3095  next_word.c_str());
3096  }
3098  return nullptr;
3099  }
3100 
3101  if (cmd_obj->IsMultiwordObject()) {
3102  if (!suffix.empty()) {
3103  result.AppendErrorWithFormat(
3104  "command '%s' did not recognize '%s%s%s' as valid (subcommand "
3105  "might be invalid).\n",
3106  cmd_obj->GetCommandName().str().c_str(),
3107  next_word.empty() ? "" : next_word.c_str(),
3108  next_word.empty() ? " -- " : " ", suffix.c_str());
3110  return nullptr;
3111  }
3112  } else {
3113  // If we found a normal command, we are done
3114  done = true;
3115  if (!suffix.empty()) {
3116  switch (suffix[0]) {
3117  case '/':
3118  // GDB format suffixes
3119  {
3120  Options *command_options = cmd_obj->GetOptions();
3121  if (command_options &&
3122  command_options->SupportsLongOption("gdb-format")) {
3123  std::string gdb_format_option("--gdb-format=");
3124  gdb_format_option += (suffix.c_str() + 1);
3125 
3126  std::string cmd = revised_command_line.GetString();
3127  size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3128  if (arg_terminator_idx != std::string::npos) {
3129  // Insert the gdb format option before the "--" that terminates
3130  // options
3131  gdb_format_option.append(1, ' ');
3132  cmd.insert(arg_terminator_idx, gdb_format_option);
3133  revised_command_line.Clear();
3134  revised_command_line.PutCString(cmd);
3135  } else
3136  revised_command_line.Printf(" %s", gdb_format_option.c_str());
3137 
3138  if (wants_raw_input &&
3139  FindArgumentTerminator(cmd) == std::string::npos)
3140  revised_command_line.PutCString(" --");
3141  } else {
3142  result.AppendErrorWithFormat(
3143  "the '%s' command doesn't support the --gdb-format option\n",
3144  cmd_obj->GetCommandName().str().c_str());
3146  return nullptr;
3147  }
3148  }
3149  break;
3150 
3151  default:
3152  result.AppendErrorWithFormat(
3153  "unknown command shorthand suffix: '%s'\n", suffix.c_str());
3155  return nullptr;
3156  }
3157  }
3158  }
3159  if (scratch_command.empty())
3160  done = true;
3161  }
3162 
3163  if (!scratch_command.empty())
3164  revised_command_line.Printf(" %s", scratch_command.c_str());
3165 
3166  if (cmd_obj != NULL)
3167  command_line = revised_command_line.GetString();
3168 
3169  return cmd_obj;
3170 }
static const char g_repeat_char
int GetQuitExitCode(bool &exited) const
Returns the exit code that the user has specified when running the &#39;quit&#39; command.
void SetIgnoreBreakpoints(bool ignore=false)
Definition: Target.h:289
A class to manage flag bits.
Definition: Debugger.h:82
ConstString & GetFilename()
Filename string get accessor.
Definition: FileSpec.cpp:369
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:61
A command line argument class.
Definition: Args.h:32
#define UNUSED_IF_ASSERT_DISABLED(x)
Definition: lldb-defines.h:134
void SetEventName(uint32_t event_mask, const char *name)
Set the name for an event bit.
Definition: Broadcaster.h:361
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
void Shift()
Shifts the first argument C string value of the array off the argument array.
Definition: Args.cpp:284
lldb::PlatformSP GetSelectedPlatform()
Select the active platform.
Definition: Platform.h:958
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:224
lldb::StreamFileSP GetErrorFile()
Definition: Debugger.h:133
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
Status Halt(bool clear_thread_plans=false, bool use_run_lock=true)
Halts a running process.
Definition: Process.cpp:3127
#define lldbassert(x)
Definition: LLDBAssert.h:15
llvm::ArrayRef< ArgEntry > entries() const
Definition: Args.h:123
void GetHelp(CommandReturnObject &result, uint32_t types=eCommandTypesAllThem)
lldb::OptionValuePropertiesSP m_collection_sp
static const char * k_valid_command_chars
void OutputHelpText(Stream &stream, llvm::StringRef command_word, llvm::StringRef separator, llvm::StringRef help_text, uint32_t max_word_len)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
bool AddCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
Target * GetDummyTarget()
Definition: Debugger.cpp:1693
static constexpr uintptr_t DefaultValueFalse
static constexpr uintptr_t DefaultValueTrue
const char * GetIOHandlerCommandPrefix()
Definition: Debugger.cpp:1020
void BuildAliasCommandArgs(CommandObject *alias_cmd_obj, const char *alias_name, Args &cmd_args, std::string &raw_input_string, CommandReturnObject &result)
void SetAsyncExecution(bool async)
Definition: Debugger.cpp:875
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.cpp:254
repro::DataRecorder * GetInputRecorder()
Definition: Debugger.cpp:879
static constexpr const char * NoCStrDefault
void SetUnwindOnError(bool unwind=false)
Definition: Target.h:285
void SetTargetPtr(Target *target, bool adopt_selected)
A file utility class.
Definition: FileSpec.h:55
virtual const char * GetRepeatCommand(Args &current_command_args, uint32_t index)
Get the command that appropriate for a "repeat" of the current command.
lldb::StateType GetState()
Get accessor for the current process state.
Definition: Process.cpp:1347
lldb::StreamFileSP GetOutputFile()
Definition: Debugger.h:131
int GetOptionArgumentPosition(const char *in_string)
void LongestCommonPrefix(std::string &common_prefix)
Definition: StringList.cpp:103
A timer class that simplifies common timing metrics.
Definition: Timer.h:23
lldb::ExpressionResults EvaluateExpression(llvm::StringRef expression, ExecutionContextScope *exe_scope, lldb::ValueObjectSP &result_valobj_sp, const EvaluateExpressionOptions &options=EvaluateExpressionOptions(), std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Definition: Target.cpp:2375
void AddCompletions(const StringList &completions)
Adds multiple possible completion strings.
An event broadcasting class.
Definition: Broadcaster.h:250
std::size_t GetNumberOfMatches() const
lldb::PlatformSP GetPlatform(bool prefer_target_platform)
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
void Clear()
Clears the object state.
Definition: FileSpec.cpp:285
void AppendRawError(llvm::StringRef in_string)
void SetArguments(size_t argc, const char **argv)
Sets the argument vector value, optionally copying all arguments into an internal buffer...
Definition: Args.cpp:363
int HandleCompletion(const char *current_line, const char *cursor, const char *last_char, int match_start_point, int max_return_elements, StringList &matches, StringList &descriptions)
lldb::StreamFileSP & GetErrorStreamFile()
Definition: IOHandler.cpp:128
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition: Stream.h:100
CommandObject * BuildAliasResult(llvm::StringRef alias_name, std::string &raw_input_string, std::string &alias_result, CommandReturnObject &result)
static FileSystem & Instance()
A delegate class for use with IOHandler subclasses.
Definition: IOHandler.h:188
void SetSyntax(llvm::StringRef str)
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
bool RemoveCommand(llvm::StringRef cmd)
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx. ...
Definition: Args.cpp:256
void Unshift(llvm::StringRef arg_str, char quote_char='\0')
Inserts a class owned copy of arg_cstr at the beginning of the argument vector.
Definition: Args.cpp:292
void GetValue(Stream *s, bool show_type) const
Definition: Scalar.cpp:240
void BroadcastEvent(lldb::EventSP &event_sp)
Broadcast an event which has no associated data.
Definition: Broadcaster.h:283
virtual int HandleCompletion(CompletionRequest &request)
This default version handles calling option argument completions and then calls HandleArgumentComplet...
CommandObject * GetCommandObject(llvm::StringRef cmd, StringList *matches=nullptr, StringList *descriptions=nullptr) const
void FindCommandsForApropos(llvm::StringRef word, StringList &commands_found, StringList &commands_help, bool search_builtin_commands, bool search_user_commands, bool search_alias_commands)
bool AddUserCommand(llvm::StringRef name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
"lldb/Utility/ArgCompletionRequest.h"
bool IsTopIOHandler(const lldb::IOHandlerSP &reader_sp)
Definition: Debugger.cpp:1002
bool StateIsRunningState(lldb::StateType state)
Check if a state represents a state where the process or thread is running.
Definition: State.cpp:68
void SetKeepInMemory(bool keep=true)
Definition: Target.h:295
int GetCommandNamesMatchingPartialString(const char *cmd_cstr, bool include_aliases, StringList &matches, StringList &descriptions)
static size_t FindArgumentTerminator(const std::string &s)
bool Confirm(llvm::StringRef message, bool default_answer)
llvm::StringRef GetCursorArgumentPrefix() const
void GetLLDBCommandsFromIOHandler(const char *prompt, IOHandlerDelegate &delegate, bool asynchronously, void *baton)
Target * GetTargetPtr() const
Returns a pointer to the target object.
void SetTimeout(const Timeout< std::micro > &timeout)
Definition: Target.h:306
virtual CommandObjectMultiword * GetAsMultiwordCommand()
void HandleCommandsFromFile(FileSpec &file, ExecutionContext *context, CommandInterpreterRunOptions &options, CommandReturnObject &result)
Execute a list of commands from a file.
bool Test(ValueType bit) const
Test a single flag bit.
Definition: Flags.h:107
bool GetIsInteractive()
Check if the input is being supplied interactively by a user.
Definition: IOHandler.cpp:130
void AppendPathComponent(llvm::StringRef component)
Definition: FileSpec.cpp:463
std::vector< std::tuple< std::string, int, std::string > > OptionArgVector
Definition: Options.h:25
virtual bool Execute(const char *args_string, CommandReturnObject &result)=0
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
const char * GetStringAtIndex(size_t idx) const
Definition: StringList.cpp:82
size_t EOL()
Output and End of Line character to the stream.
Definition: Stream.cpp:127
uint32_t GetTerminalWidth() const
Definition: Debugger.cpp:442
CommandAlias * AddAlias(llvm::StringRef alias_name, lldb::CommandObjectSP &command_obj_sp, llvm::StringRef args_string=llvm::StringRef())
lldb::ScriptLanguage GetScriptLanguage() const
Definition: Debugger.cpp:430
const char * ProcessEmbeddedScriptCommands(const char *arg)
static std::string EscapeLLDBCommandArgument(const std::string &arg, char quote_char)
Definition: Args.cpp:632
virtual bool IsMultiwordObject()
virtual bool WantsRawCommandString()=0
void AppendMessageWithFormat(const char *format,...) __attribute__((format(printf
int HandleCompletionMatches(CompletionRequest &request)
void UpdateExecutionContext(ExecutionContext *override_context)
void AppendMessage(llvm::StringRef in_string)
llvm::StringRef GetString() const
lldb::IOHandlerSP GetIOHandler(bool force_create=false, CommandInterpreterRunOptions *options=nullptr)
void IOHandlerInputComplete(IOHandler &io_handler, std::string &line) override
Called when a line or lines have been retrieved.
A plug-in interface definition class for debugging a process.
Definition: Process.h:353
Process * GetProcessPtr() const
Returns a pointer to the process object.
void PushIOHandler(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
Definition: Debugger.cpp:1095
void IndentLess(int amount=2)
Decrement the current indentation level.
Definition: Stream.cpp:221
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:106
virtual const char * GetPrompt()
Definition: IOHandler.h:96
bool Success() const
Test for success condition.
Definition: Status.cpp:287
TargetList & GetTargetList()
Get accessor for the target list.
Definition: Debugger.h:180
OptionArgVectorSP GetOptionArguments() const
Definition: CommandAlias.h:64
void OutputFormattedHelpText(Stream &strm, llvm::StringRef prefix, llvm::StringRef help_text)
virtual Options * GetOptions()
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
#define LIBLLDB_LOG_COMMANDS
Definition: Logging.h:32
static constexpr bool NoGlobalSetting
void DeleteStringAtIndex(size_t id)
Definition: StringList.cpp:144
void GetMatches(StringList &matches) const
Adds all collected completion matches to the given list.
size_t GetSize() const
Definition: StringList.cpp:70
CommandObject::CommandMap & GetSubcommandDictionary()
void InsertStringAtIndex(size_t idx, const std::string &str)
Definition: StringList.cpp:130
void AllowExitCodeOnQuit(bool allow)
Specify if the command interpreter should allow that the user can specify a custom exit code when cal...
void HandleCommands(const StringList &commands, ExecutionContext *context, CommandInterpreterRunOptions &options, CommandReturnObject &result)
Execute a list of commands in sequence.
size_t PutChar(char ch)
Definition: Stream.cpp:103
A command line option parsing protocol class.
Definition: Options.h:62
A class to manage flags.
Definition: Flags.h:22
void SetCoerceToId(bool coerce=true)
Definition: Target.h:281
ConstString & GetDirectory()
Directory string get accessor.
Definition: FileSpec.cpp:363
void AppendString(llvm::StringRef str, bool reject_if_dupe=true)
void GetDescriptions(StringList &descriptions) const
Adds all collected completion descriptions to the given list.
bool GetUseColor() const
Definition: Debugger.cpp:464
ScriptInterpreter * GetScriptInterpreter(bool can_create=true)
Definition: Debugger.cpp:1289
int AddNamesMatchingPartialString(const std::map< std::string, ValueType > &in_map, llvm::StringRef cmd_str, StringList &matches, StringList *descriptions=nullptr)
Definition: CommandObject.h:35
void void AppendError(llvm::StringRef in_string)
void RunIOHandler(const lldb::IOHandlerSP &reader_sp)
Definition: Debugger.cpp:1028
lldb::CommandObjectSP GetCommandSP(llvm::StringRef cmd, bool include_aliases=true, bool exact=true, StringList *matches=nullptr, StringList *descriptions=nullptr) const
lldb::PlatformSP GetPlatform()
Definition: Target.h:1214
bool AliasExists(llvm::StringRef cmd) const
A uniqued constant string class.
Definition: ConstString.h:38
void SetStopOnContinue(bool stop_on_continue)
llvm::Optional< llvm::StringRef > FindString(llvm::StringRef input_str) const
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
LoadCWDlldbinitFile
Definition: Target.h:53
bool UserCommandExists(llvm::StringRef cmd) const
Definition: SBAddress.h:15
void AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
Definition: Args.cpp:321
void SetTryAllThreads(bool try_others=true)
Definition: Target.h:318
std::map< std::string, lldb::CommandObjectSP > CommandMap
static const char * k_white_space
static constexpr PropertyDefinition g_properties[]
size_t Indent(const char *s=nullptr)
Indent the current line in the stream.
Definition: Stream.cpp:131
virtual void SetIsDone(bool b)
Definition: IOHandler.h:86
bool HandleCommand(const char *command_line, LazyBool add_to_history, CommandReturnObject &result, ExecutionContext *override_context=nullptr, bool repeat_on_empty_command=true, bool no_context_switching=false)
#define PATH_MAX
lldb::CommandObjectSP GetCommandSPExact(llvm::StringRef cmd, bool include_aliases) const
bool RemoveUser(llvm::StringRef alias_name)
static void StripLeadingSpaces(std::string &s)
bool CommandExists(llvm::StringRef cmd) const
bool HelpTextContainsWord(llvm::StringRef search_word, bool search_short_help=true, bool search_long_help=true, bool search_syntax=true, bool search_options=true)
const Args & GetParsedLine() const
size_t FindLongestCommandWord(std::map< std::string, ValueType > &dict)
Definition: CommandObject.h:55
std::shared_ptr< OptionArgVector > OptionArgVectorSP
Definition: Options.h:28
lldb::TargetSP GetSelectedTarget()
Definition: TargetList.cpp:615
lldb::StreamFileSP & GetOutputStreamFile()
Definition: IOHandler.cpp:126
int SetErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Set the current error string to a formatted error string.
Definition: Status.cpp:255
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition: FileSpec.cpp:198
void ResolveCommand(const char *command_line, CommandReturnObject &result)
bool GetAliasFullName(llvm::StringRef cmd, std::string &full_name) const
void RunCommandInterpreter(bool auto_handle_events, bool spawn_thread, CommandInterpreterRunOptions &options)
void IndentMore(int amount=2)
Increment the current indentation level.
Definition: Stream.cpp:218
virtual CommandObject * GetSubcommandObject(llvm::StringRef sub_cmd, StringList *matches=nullptr)
llvm::StringRef GetPrompt() const
Definition: Debugger.cpp:398
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition: Status.cpp:130
bool SupportsLongOption(const char *long_option)
Definition: Options.cpp:326
lldb::TargetSP GetSelectedTarget()
Definition: Debugger.h:167
void AppendString(const std::string &s)
Definition: StringList.cpp:43
bool RemoveAlias(llvm::StringRef alias_name)
ValueType GetError() const
Access the error value.
Definition: Status.cpp:174
void SetHelp(llvm::StringRef str) override
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:376
bool GetAutoConfirm() const
Definition: Debugger.cpp:371
static bool ExtractCommand(std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
CommandObject * GetCommandObjectForCommand(llvm::StringRef &command_line)
bool IOHandlerInterrupt(IOHandler &io_handler) override
void Printf(const char *format,...) __attribute__((format(printf
Definition: Log.cpp:113
LLVM_NODISCARD bool SetQuitExitCode(int exit_code)
Sets the exit code for the quit command.
virtual llvm::StringRef GetHelp()
llvm::StringRef GetCommandName() const
static const lldb::TargetPropertiesSP & GetGlobalProperties()
Definition: Target.cpp:2690
PlatformList & GetPlatformList()
Definition: Debugger.h:182
void SetStatus(lldb::ReturnStatus status)
void SourceInitFile(bool in_cwd, CommandReturnObject &result)
void SetHelpLong(llvm::StringRef str) override
const CommandAlias * GetAlias(llvm::StringRef alias_name) const
int Open(const char *path, int flags, int mode)
Wraps ::open in a platform-independent way.
void UpdatePrompt(llvm::StringRef prompt)
An error handling class.
Definition: Status.h:44
void GetPythonCommandsFromIOHandler(const char *prompt, IOHandlerDelegate &delegate, bool asynchronously, void *baton)