blob: 88696571c93c46ad92200d40add741b777c89c87 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include <string>
Caroline Ticebd5c63e2010-10-12 21:57:09 +000011#include <vector>
Chris Lattner24943d22010-06-08 16:52:24 +000012
13#include <getopt.h>
14#include <stdlib.h>
15
Greg Clayton5c28dd12011-06-23 17:59:56 +000016#include "CommandObjectScript.h"
Peter Collingbourne921fac02011-06-23 20:37:26 +000017#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000018
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectApropos.h"
20#include "../Commands/CommandObjectArgs.h"
21#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
25#include "../Commands/CommandObjectHelp.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectLog.h"
27#include "../Commands/CommandObjectMemory.h"
Greg Claytonb1888f22011-03-19 01:12:21 +000028#include "../Commands/CommandObjectPlatform.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000029#include "../Commands/CommandObjectProcess.h"
30#include "../Commands/CommandObjectQuit.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectRegister.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000034#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSyntax.h"
36#include "../Commands/CommandObjectTarget.h"
37#include "../Commands/CommandObjectThread.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000038#include "../Commands/CommandObjectType.h"
Johnny Chen902e0182010-12-23 20:21:44 +000039#include "../Commands/CommandObjectVersion.h"
Johnny Chen01acfa72011-09-22 18:04:58 +000040#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
Jim Ingham84cdc152010-06-15 19:49:27 +000042#include "lldb/Interpreter/Args.h"
Caroline Tice5ddbe212011-05-06 21:37:15 +000043#include "lldb/Interpreter/Options.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000045#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046#include "lldb/Core/Stream.h"
47#include "lldb/Core/Timer.h"
Greg Claytoncd548032011-02-01 01:31:41 +000048#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049#include "lldb/Target/Process.h"
50#include "lldb/Target/Thread.h"
51#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000052#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000053
54#include "lldb/Interpreter/CommandReturnObject.h"
55#include "lldb/Interpreter/CommandInterpreter.h"
Caroline Tice0aa2e552011-01-14 00:29:16 +000056#include "lldb/Interpreter/ScriptInterpreterNone.h"
57#include "lldb/Interpreter/ScriptInterpreterPython.h"
Chris Lattner24943d22010-06-08 16:52:24 +000058
59using namespace lldb;
60using namespace lldb_private;
61
62CommandInterpreter::CommandInterpreter
63(
Greg Clayton63094e02010-06-23 01:19:29 +000064 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000065 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000066 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000067) :
Greg Clayton49ce6822010-10-31 03:01:06 +000068 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000069 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000070 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000071 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000072 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000073 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +000074 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +000075 m_repeat_char ('!'),
Enrico Granata293a7b32011-08-15 19:24:02 +000076 m_batch_command_mode (false),
77 m_truncation_warning(eNoTruncation)
Chris Lattner24943d22010-06-08 16:52:24 +000078{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000079 const char *dbg_name = debugger.GetInstanceName().AsCString();
80 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
81 StreamString var_name;
82 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000083 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000084 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000085 m_debugger.GetInstanceName().AsCString());
86 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
87 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
88 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000089}
90
91void
92CommandInterpreter::Initialize ()
93{
94 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
95
96 CommandReturnObject result;
97
98 LoadCommandDictionary ();
99
Chris Lattner24943d22010-06-08 16:52:24 +0000100 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000101 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
102 if (cmd_obj_sp)
103 {
104 AddAlias ("q", cmd_obj_sp);
105 AddAlias ("exit", cmd_obj_sp);
106 }
107
108 cmd_obj_sp = GetCommandSPExact ("process continue", false);
109 if (cmd_obj_sp)
110 {
111 AddAlias ("c", cmd_obj_sp);
112 AddAlias ("continue", cmd_obj_sp);
113 }
114
115 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
116 if (cmd_obj_sp)
117 AddAlias ("b", cmd_obj_sp);
118
119 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
120 if (cmd_obj_sp)
121 AddAlias ("bt", cmd_obj_sp);
122
123 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
124 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000125 {
126 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000127 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000128 }
129
130 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
131 if (cmd_obj_sp)
132 {
133 AddAlias ("nexti", cmd_obj_sp);
134 AddAlias ("ni", cmd_obj_sp);
135 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000136
137 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
138 if (cmd_obj_sp)
139 {
140 AddAlias ("s", cmd_obj_sp);
141 AddAlias ("step", cmd_obj_sp);
142 }
143
144 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
145 if (cmd_obj_sp)
146 {
147 AddAlias ("n", cmd_obj_sp);
148 AddAlias ("next", cmd_obj_sp);
149 }
150
151 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
152 if (cmd_obj_sp)
153 {
154 AddAlias ("f", cmd_obj_sp);
155 AddAlias ("finish", cmd_obj_sp);
156 }
157
158 cmd_obj_sp = GetCommandSPExact ("source list", false);
159 if (cmd_obj_sp)
160 {
161 AddAlias ("l", cmd_obj_sp);
162 AddAlias ("list", cmd_obj_sp);
163 }
164
165 cmd_obj_sp = GetCommandSPExact ("memory read", false);
166 if (cmd_obj_sp)
167 AddAlias ("x", cmd_obj_sp);
168
169 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
170 if (cmd_obj_sp)
171 AddAlias ("up", cmd_obj_sp);
172
173 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
174 if (cmd_obj_sp)
175 AddAlias ("down", cmd_obj_sp);
176
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000177 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000178 if (cmd_obj_sp)
179 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000180
181 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
182 if (cmd_obj_sp)
183 AddAlias ("dis", cmd_obj_sp);
184
185 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
186 if (cmd_obj_sp)
187 AddAlias ("di", cmd_obj_sp);
188
189
Jason Molenda730cae02011-10-22 01:30:52 +0000190
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000191 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000192 if (cmd_obj_sp)
193 AddAlias ("undisplay", cmd_obj_sp);
194
Caroline Tice5ddbe212011-05-06 21:37:15 +0000195 cmd_obj_sp = GetCommandSPExact ("target create", false);
196 if (cmd_obj_sp)
197 AddAlias ("file", cmd_obj_sp);
198
199 cmd_obj_sp = GetCommandSPExact ("target modules", false);
200 if (cmd_obj_sp)
201 AddAlias ("image", cmd_obj_sp);
202
203
204 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000205
Caroline Tice5ddbe212011-05-06 21:37:15 +0000206 cmd_obj_sp = GetCommandSPExact ("expression", false);
207 if (cmd_obj_sp)
208 {
209 AddAlias ("expr", cmd_obj_sp);
210
211 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
212 AddAlias ("p", cmd_obj_sp);
213 AddAlias ("print", cmd_obj_sp);
214 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
215 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
216
217 alias_arguments_vector_sp.reset (new OptionArgVector);
218 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
219 AddAlias ("po", cmd_obj_sp);
220 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
221 }
222
223 cmd_obj_sp = GetCommandSPExact ("process launch", false);
224 if (cmd_obj_sp)
225 {
226 alias_arguments_vector_sp.reset (new OptionArgVector);
227 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
228 AddAlias ("r", cmd_obj_sp);
229 AddAlias ("run", cmd_obj_sp);
230 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
231 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
232 }
Chris Lattner24943d22010-06-08 16:52:24 +0000233}
234
Chris Lattner24943d22010-06-08 16:52:24 +0000235const char *
236CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
237{
238 // This function has not yet been implemented.
239
240 // Look for any embedded script command
241 // If found,
242 // get interpreter object from the command dictionary,
243 // call execute_one_command on it,
244 // get the results as a string,
245 // substitute that string for current stuff.
246
247 return arg;
248}
249
250
251void
252CommandInterpreter::LoadCommandDictionary ()
253{
254 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
255
256 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
257 //
258 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
259 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
260 // the cross-referencing stuff) are created!!!
261 //
262 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
263
264
265 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
266 // are created. This is so that when another command is created that needs to go into a crossref object,
267 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
268 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
269
Chris Lattner24943d22010-06-08 16:52:24 +0000270 // Non-CommandObjectCrossref commands can now be created.
271
Caroline Tice5bc8c972010-09-20 20:44:43 +0000272 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000273
Greg Clayton238c0a12010-09-18 01:14:36 +0000274 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000275 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000276 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000277 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000278 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
279 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000280// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000281 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000282 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000283 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000284 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
285 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000286 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000287 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000288 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000289 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000290 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000291 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000292 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000293 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
294 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000295 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000296 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000297 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000298
299 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000300 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000301 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000302 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000303 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000304 if (break_regex_cmd_ap.get())
305 {
306 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
307 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
308 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000309 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000310 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000311 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000312 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
313 {
314 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
315 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
316 }
317 }
Jim Inghame56493f2011-03-22 02:29:32 +0000318
319 std::auto_ptr<CommandObjectRegexCommand>
320 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000321 "_regexp-down",
322 "Go down \"n\" frames in the stack (1 frame by default).",
323 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000324 if (down_regex_cmd_ap.get())
325 {
326 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
327 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
328 {
329 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
330 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
331 }
332 }
333
334 std::auto_ptr<CommandObjectRegexCommand>
335 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000336 "_regexp-up",
337 "Go up \"n\" frames in the stack (1 frame by default).",
338 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000339 if (up_regex_cmd_ap.get())
340 {
341 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
342 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
343 {
344 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
345 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
346 }
347 }
Jason Molenda730cae02011-10-22 01:30:52 +0000348
349 std::auto_ptr<CommandObjectRegexCommand>
350 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000351 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000352 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000353 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000354 if (display_regex_cmd_ap.get())
355 {
356 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
357 {
358 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
359 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
360 }
361 }
362
363 std::auto_ptr<CommandObjectRegexCommand>
364 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000365 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000366 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000367 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000368 if (undisplay_regex_cmd_ap.get())
369 {
370 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
371 {
372 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
373 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
374 }
375 }
376
Chris Lattner24943d22010-06-08 16:52:24 +0000377}
378
379int
380CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
381 StringList &matches)
382{
383 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
384
385 if (include_aliases)
386 {
387 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
388 }
389
390 return matches.GetSize();
391}
392
393CommandObjectSP
394CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
395{
396 CommandObject::CommandMap::iterator pos;
397 CommandObjectSP ret_val;
398
399 std::string cmd(cmd_cstr);
400
401 if (HasCommands())
402 {
403 pos = m_command_dict.find(cmd);
404 if (pos != m_command_dict.end())
405 ret_val = pos->second;
406 }
407
408 if (include_aliases && HasAliases())
409 {
410 pos = m_alias_dict.find(cmd);
411 if (pos != m_alias_dict.end())
412 ret_val = pos->second;
413 }
414
415 if (HasUserCommands())
416 {
417 pos = m_user_dict.find(cmd);
418 if (pos != m_user_dict.end())
419 ret_val = pos->second;
420 }
421
422 if (!exact && ret_val == NULL)
423 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000424 // We will only get into here if we didn't find any exact matches.
425
426 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
427
Chris Lattner24943d22010-06-08 16:52:24 +0000428 StringList local_matches;
429 if (matches == NULL)
430 matches = &local_matches;
431
Jim Inghamd40f8a62010-07-06 22:46:59 +0000432 unsigned int num_cmd_matches = 0;
433 unsigned int num_alias_matches = 0;
434 unsigned int num_user_matches = 0;
435
436 // Look through the command dictionaries one by one, and if we get only one match from any of
437 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
438
Chris Lattner24943d22010-06-08 16:52:24 +0000439 if (HasCommands())
440 {
441 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
442 }
443
444 if (num_cmd_matches == 1)
445 {
446 cmd.assign(matches->GetStringAtIndex(0));
447 pos = m_command_dict.find(cmd);
448 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000449 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000450 }
451
Jim Ingham9a574172010-06-24 20:28:42 +0000452 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000453 {
454 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
455
456 }
457
Jim Inghamd40f8a62010-07-06 22:46:59 +0000458 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000459 {
460 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
461 pos = m_alias_dict.find(cmd);
462 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000463 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000464 }
465
Jim Ingham9a574172010-06-24 20:28:42 +0000466 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000467 {
468 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
469 }
470
Jim Inghamd40f8a62010-07-06 22:46:59 +0000471 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000472 {
473 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
474
475 pos = m_user_dict.find (cmd);
476 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000477 user_match_sp = pos->second;
478 }
479
480 // If we got exactly one match, return that, otherwise return the match list.
481
482 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
483 {
484 if (num_cmd_matches)
485 return real_match_sp;
486 else if (num_alias_matches)
487 return alias_match_sp;
488 else
489 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000490 }
491 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000492 else if (matches && ret_val != NULL)
493 {
494 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000495 }
496
497
498 return ret_val;
499}
500
Greg Claytond12aeab2011-04-20 16:37:46 +0000501bool
502CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
503{
504 if (name && name[0])
505 {
506 std::string name_sstr(name);
507 if (!can_replace)
508 {
509 if (m_command_dict.find (name_sstr) != m_command_dict.end())
510 return false;
511 }
512 m_command_dict[name_sstr] = cmd_sp;
513 return true;
514 }
515 return false;
516}
517
Enrico Granata6b1596d2011-08-16 23:24:13 +0000518bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000519CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000520 const lldb::CommandObjectSP &cmd_sp,
521 bool can_replace)
522{
Enrico Granata6010ace2011-11-07 22:57:04 +0000523 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000524 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000525
526 const char* name_cstr = name.c_str();
527
528 // do not allow replacement of internal commands
529 if (CommandExists(name_cstr))
530 return false;
531
532 if (can_replace == false && UserCommandExists(name_cstr))
533 return false;
534
535 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000536 return true;
537 }
538 return false;
539}
Greg Claytond12aeab2011-04-20 16:37:46 +0000540
Jim Inghamd40f8a62010-07-06 22:46:59 +0000541CommandObjectSP
542CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000543{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000544 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
545 CommandObjectSP ret_val; // Possibly empty return value.
546
547 if (cmd_cstr == NULL)
548 return ret_val;
549
550 if (cmd_words.GetArgumentCount() == 1)
551 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
552 else
553 {
554 // We have a multi-word command (seemingly), so we need to do more work.
555 // First, get the cmd_obj_sp for the first word in the command.
556 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
557 if (cmd_obj_sp.get() != NULL)
558 {
559 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
560 // command name), and find the appropriate sub-command SP for each command word....
561 size_t end = cmd_words.GetArgumentCount();
562 for (size_t j= 1; j < end; ++j)
563 {
564 if (cmd_obj_sp->IsMultiwordObject())
565 {
566 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
567 (cmd_words.GetArgumentAtIndex (j));
568 if (cmd_obj_sp.get() == NULL)
569 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
570 return ret_val;
571 }
572 else
573 // We have more words in the command name, but we don't have a multiword object. Fail and return
574 // empty 'ret_val'.
575 return ret_val;
576 }
577 // We successfully looped through all the command words and got valid command objects for them. Assign the
578 // last object retrieved to 'ret_val'.
579 ret_val = cmd_obj_sp;
580 }
581 }
582 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000583}
584
585CommandObject *
586CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
587{
588 return GetCommandSPExact (cmd_cstr, include_aliases).get();
589}
590
591CommandObject *
592CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
593{
594 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
595
596 // If we didn't find an exact match to the command string in the commands, look in
597 // the aliases.
598
599 if (command_obj == NULL)
600 {
601 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
602 }
603
604 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
605 // in both the commands and the aliases.
606
607 if (command_obj == NULL)
608 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
609
610 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000611}
612
613bool
614CommandInterpreter::CommandExists (const char *cmd)
615{
616 return m_command_dict.find(cmd) != m_command_dict.end();
617}
618
619bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000620CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
621 const char *options_args,
622 OptionArgVectorSP &option_arg_vector_sp)
623{
624 bool success = true;
625 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
626
627 if (!options_args || (strlen (options_args) < 1))
628 return true;
629
630 std::string options_string (options_args);
631 Args args (options_args);
632 CommandReturnObject result;
633 // Check to see if the command being aliased can take any command options.
634 Options *options = cmd_obj_sp->GetOptions ();
635 if (options)
636 {
637 // See if any options were specified as part of the alias; if so, handle them appropriately.
638 options->NotifyOptionParsingStarting ();
639 args.Unshift ("dummy_arg");
640 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
641 args.Shift ();
642 if (result.Succeeded())
643 options->VerifyPartialOptions (result);
644 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
645 {
646 result.AppendError ("Unable to create requested alias.\n");
647 return false;
648 }
649 }
650
Greg Clayton7268b4c2011-10-28 21:38:01 +0000651 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000652 {
653 if (cmd_obj_sp->WantsRawCommandString ())
654 option_arg_vector->push_back (OptionArgPair ("<argument>",
655 OptionArgValue (-1,
656 options_string)));
657 else
658 {
659 int argc = args.GetArgumentCount();
660 for (size_t i = 0; i < argc; ++i)
661 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
662 option_arg_vector->push_back
663 (OptionArgPair ("<argument>",
664 OptionArgValue (-1,
665 std::string (args.GetArgumentAtIndex (i)))));
666 }
667 }
668
669 return success;
670}
671
672bool
Chris Lattner24943d22010-06-08 16:52:24 +0000673CommandInterpreter::AliasExists (const char *cmd)
674{
675 return m_alias_dict.find(cmd) != m_alias_dict.end();
676}
677
678bool
679CommandInterpreter::UserCommandExists (const char *cmd)
680{
681 return m_user_dict.find(cmd) != m_user_dict.end();
682}
683
684void
685CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
686{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000687 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000688 m_alias_dict[alias_name] = command_obj_sp;
689}
690
691bool
692CommandInterpreter::RemoveAlias (const char *alias_name)
693{
694 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
695 if (pos != m_alias_dict.end())
696 {
697 m_alias_dict.erase(pos);
698 return true;
699 }
700 return false;
701}
702bool
703CommandInterpreter::RemoveUser (const char *alias_name)
704{
705 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
706 if (pos != m_user_dict.end())
707 {
708 m_user_dict.erase(pos);
709 return true;
710 }
711 return false;
712}
713
Chris Lattner24943d22010-06-08 16:52:24 +0000714void
715CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
716{
717 help_string.Printf ("'%s", command_name);
718 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
719
720 if (option_arg_vector_sp != NULL)
721 {
722 OptionArgVector *options = option_arg_vector_sp.get();
723 for (int i = 0; i < options->size(); ++i)
724 {
725 OptionArgPair cur_option = (*options)[i];
726 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000727 OptionArgValue value_pair = cur_option.second;
728 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000729 if (opt.compare("<argument>") == 0)
730 {
731 help_string.Printf (" %s", value.c_str());
732 }
733 else
734 {
735 help_string.Printf (" %s", opt.c_str());
736 if ((value.compare ("<no-argument>") != 0)
737 && (value.compare ("<need-argument") != 0))
738 {
739 help_string.Printf (" %s", value.c_str());
740 }
741 }
742 }
743 }
744
745 help_string.Printf ("'");
746}
747
Greg Clayton65124ea2010-08-26 22:05:43 +0000748size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000749CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
750{
751 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000752 CommandObject::CommandMap::const_iterator end = dict.end();
753 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000754
Greg Clayton65124ea2010-08-26 22:05:43 +0000755 for (pos = dict.begin(); pos != end; ++pos)
756 {
757 size_t len = pos->first.size();
758 if (max_len < len)
759 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000760 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000761 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000762}
763
764void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000765CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000766 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000767{
768 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000769 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000770
771 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000772 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000773
774 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
775 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000776
Enrico Granata6b1596d2011-08-16 23:24:13 +0000777 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
778 {
779 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
780 max_len);
781 }
782 result.AppendMessage("");
783
784 }
785
Greg Clayton7268b4c2011-10-28 21:38:01 +0000786 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000787 {
Jim Inghame3663e82010-10-22 18:47:16 +0000788 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000789 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000790 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000791 max_len = FindLongestCommandWord (m_alias_dict);
792
Chris Lattner24943d22010-06-08 16:52:24 +0000793 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
794 {
795 StreamString sstr;
796 StreamString translation_and_help;
797 std::string entry_name = pos->first;
798 std::string second_entry = pos->second.get()->GetCommandName();
799 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
800
801 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
802 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
803 translation_and_help.GetData(), max_len);
804 }
805 result.AppendMessage("");
806 }
807
Greg Clayton7268b4c2011-10-28 21:38:01 +0000808 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000809 {
810 result.AppendMessage ("The following is a list of your current user-defined commands:");
811 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000812 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000813 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
814 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000815 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
816 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000817 }
818 result.AppendMessage("");
819 }
820
821 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
822}
823
Caroline Ticee0da7a52010-12-09 22:52:49 +0000824CommandObject *
825CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000826{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000827 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
828 // eventually be invoked by the given command line.
829
830 CommandObject *cmd_obj = NULL;
831 std::string white_space (" \t\v");
832 size_t start = command_string.find_first_not_of (white_space);
833 size_t end = 0;
834 bool done = false;
835 while (!done)
836 {
837 if (start != std::string::npos)
838 {
839 // Get the next word from command_string.
840 end = command_string.find_first_of (white_space, start);
841 if (end == std::string::npos)
842 end = command_string.size();
843 std::string cmd_word = command_string.substr (start, end - start);
844
845 if (cmd_obj == NULL)
846 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
847 // command or alias.
848 cmd_obj = GetCommandObject (cmd_word.c_str());
849 else if (cmd_obj->IsMultiwordObject ())
850 {
851 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
852 CommandObject *sub_cmd_obj =
853 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
854 if (sub_cmd_obj)
855 cmd_obj = sub_cmd_obj;
856 else // cmd_word was not a valid sub-command word, so we are donee
857 done = true;
858 }
859 else
860 // We have a cmd_obj and it is not a multi-word object, so we are done.
861 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000862
Caroline Ticee0da7a52010-12-09 22:52:49 +0000863 // If we didn't find a valid command object, or our command object is not a multi-word object, or
864 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
865 // next word.
866
867 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
868 done = true;
869 else
870 start = command_string.find_first_not_of (white_space, end);
871 }
872 else
873 // Unable to find any more words.
874 done = true;
875 }
876
877 if (end == command_string.size())
878 command_string.clear();
879 else
880 command_string = command_string.substr(end);
881
882 return cmd_obj;
883}
884
Greg Clayton9d855c62011-10-25 00:36:27 +0000885static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000886static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000887static void
888StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000889{
Greg Clayton9d855c62011-10-25 00:36:27 +0000890 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000891 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000892 size_t pos = s.find_first_not_of (k_white_space);
893 if (pos == std::string::npos)
894 s.clear();
895 else if (pos == 0)
896 return;
897 s.erase (0, pos);
898 }
899}
900
Greg Clayton3840cd72011-11-09 23:25:03 +0000901static size_t
902FindArgumentTerminator (const std::string &s)
903{
904 printf ("FindArgumentTerminator( s = '%s') => ", s.c_str());
905 const size_t s_len = s.size();
906 size_t offset = 0;
907 while (offset < s_len)
908 {
909 size_t pos = s.find ("--", offset);
910 if (pos == std::string::npos)
911 break;
912 if (pos > 0)
913 {
914 if (isspace(s[pos-1]))
915 {
916 // Check if the string ends "\s--" (where \s is a space character)
917 // or if we have "\s--\s".
918 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
919 {
920 printf ("%zu\n", pos);
921 return pos;
922 }
923 }
924 }
925 offset = pos + 2;
926 }
927 printf ("-1\n");
928 return std::string::npos;
929}
930
Greg Clayton9d855c62011-10-25 00:36:27 +0000931static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000932ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000933{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000934 command.clear();
935 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000936 StripLeadingSpaces (command_string);
937
938 bool result = false;
939 quote_char = '\0';
940
941 if (!command_string.empty())
942 {
943 const char first_char = command_string[0];
944 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000945 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000946 quote_char = first_char;
947 const size_t end_quote_pos = command_string.find (quote_char, 1);
948 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000949 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000950 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000951 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000952 }
953 else
954 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000955 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +0000956 if (end_quote_pos + 1 < command_string.size())
957 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
958 else
959 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000960 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000961 }
962 else
963 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000964 const size_t first_space_pos = command_string.find_first_of (k_white_space);
965 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000966 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000967 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000968 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +0000969 }
970 else
971 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000972 command.assign (command_string, 0, first_space_pos);
973 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +0000974 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000975 }
Greg Clayton9d855c62011-10-25 00:36:27 +0000976 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000977 }
Greg Clayton7268b4c2011-10-28 21:38:01 +0000978
979
980 if (!command.empty())
981 {
982 // actual commands can't start with '-' or '_'
983 if (command[0] != '-' && command[0] != '_')
984 {
985 size_t pos = command.find_first_not_of(k_valid_command_chars);
986 if (pos > 0 && pos != std::string::npos)
987 {
988 suffix.assign (command.begin() + pos, command.end());
989 command.erase (pos);
990 }
991 }
992 }
Greg Clayton9d855c62011-10-25 00:36:27 +0000993
994 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000995}
996
Greg Clayton7268b4c2011-10-28 21:38:01 +0000997CommandObject *
998CommandInterpreter::BuildAliasResult (const char *alias_name,
999 std::string &raw_input_string,
1000 std::string &alias_result,
1001 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001002{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001003 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001004 Args cmd_args (raw_input_string.c_str());
1005 alias_cmd_obj = GetCommandObject (alias_name);
1006 StreamString result_str;
1007
1008 if (alias_cmd_obj)
1009 {
1010 std::string alias_name_str = alias_name;
1011 if ((cmd_args.GetArgumentCount() == 0)
1012 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1013 cmd_args.Unshift (alias_name);
1014
1015 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1016 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1017
1018 if (option_arg_vector_sp.get())
1019 {
1020 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1021
1022 for (int i = 0; i < option_arg_vector->size(); ++i)
1023 {
1024 OptionArgPair option_pair = (*option_arg_vector)[i];
1025 OptionArgValue value_pair = option_pair.second;
1026 int value_type = value_pair.first;
1027 std::string option = option_pair.first;
1028 std::string value = value_pair.second;
1029 if (option.compare ("<argument>") == 0)
1030 result_str.Printf (" %s", value.c_str());
1031 else
1032 {
1033 result_str.Printf (" %s", option.c_str());
1034 if (value_type != optional_argument)
1035 result_str.Printf (" ");
1036 if (value.compare ("<no_argument>") != 0)
1037 {
1038 int index = GetOptionArgumentPosition (value.c_str());
1039 if (index == 0)
1040 result_str.Printf ("%s", value.c_str());
1041 else if (index >= cmd_args.GetArgumentCount())
1042 {
1043
1044 result.AppendErrorWithFormat
1045 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1046 index);
1047 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001048 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001049 }
1050 else
1051 {
1052 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1053 if (strpos != std::string::npos)
1054 raw_input_string = raw_input_string.erase (strpos,
1055 strlen (cmd_args.GetArgumentAtIndex (index)));
1056 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1057 }
1058 }
1059 }
1060 }
1061 }
1062
1063 alias_result = result_str.GetData();
1064 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001065 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001066}
1067
Greg Claytonf5c0c722011-10-14 07:41:33 +00001068Error
1069CommandInterpreter::PreprocessCommand (std::string &command)
1070{
1071 // The command preprocessor needs to do things to the command
1072 // line before any parsing of arguments or anything else is done.
1073 // The only current stuff that gets proprocessed is anyting enclosed
1074 // in backtick ('`') characters is evaluated as an expression and
1075 // the result of the expression must be a scalar that can be substituted
1076 // into the command. An example would be:
1077 // (lldb) memory read `$rsp + 20`
1078 Error error; // Error for any expressions that might not evaluate
1079 size_t start_backtick;
1080 size_t pos = 0;
1081 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1082 {
1083 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1084 {
1085 // The backtick was preceeded by a '\' character, remove the slash
1086 // and don't treat the backtick as the start of an expression
1087 command.erase(start_backtick-1, 1);
1088 // No need to add one to start_backtick since we just deleted a char
1089 pos = start_backtick;
1090 }
1091 else
1092 {
1093 const size_t expr_content_start = start_backtick + 1;
1094 const size_t end_backtick = command.find ('`', expr_content_start);
1095 if (end_backtick == std::string::npos)
1096 return error;
1097 else if (end_backtick == expr_content_start)
1098 {
1099 // Empty expression (two backticks in a row)
1100 command.erase (start_backtick, 2);
1101 }
1102 else
1103 {
1104 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1105
1106 Target *target = m_exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001107 // Get a dummy target to allow for calculator mode while processing backticks.
1108 // This also helps break the infinite loop caused when target is null.
1109 if (!target)
1110 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001111 if (target)
1112 {
1113 const bool unwind_on_error = true;
1114 const bool keep_in_memory = false;
1115 ValueObjectSP expr_result_valobj_sp;
1116 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1117 m_exe_ctx.GetFramePtr(),
1118 eExecutionPolicyOnlyWhenNeeded,
1119 unwind_on_error, keep_in_memory,
1120 eNoDynamicValues,
1121 expr_result_valobj_sp);
1122 if (expr_result == eExecutionCompleted)
1123 {
1124 Scalar scalar;
1125 if (expr_result_valobj_sp->ResolveValue (scalar))
1126 {
1127 command.erase (start_backtick, end_backtick - start_backtick + 1);
1128 StreamString value_strm;
1129 const bool show_type = false;
1130 scalar.GetValue (&value_strm, show_type);
1131 size_t value_string_size = value_strm.GetSize();
1132 if (value_string_size)
1133 {
1134 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1135 pos = start_backtick + value_string_size;
1136 continue;
1137 }
1138 else
1139 {
1140 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1141 }
1142 }
1143 else
1144 {
1145 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1146 }
1147 }
1148 else
1149 {
1150 if (expr_result_valobj_sp)
1151 error = expr_result_valobj_sp->GetError();
1152 if (error.Success())
1153 {
1154
1155 switch (expr_result)
1156 {
1157 case eExecutionSetupError:
1158 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1159 break;
1160 case eExecutionCompleted:
1161 break;
1162 case eExecutionDiscarded:
1163 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1164 break;
1165 case eExecutionInterrupted:
1166 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1167 break;
1168 case eExecutionTimedOut:
1169 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1170 break;
1171 }
1172 }
1173 }
1174 }
1175 }
1176 if (error.Fail())
1177 break;
1178 }
1179 }
1180 return error;
1181}
1182
1183
Caroline Ticee0da7a52010-12-09 22:52:49 +00001184bool
1185CommandInterpreter::HandleCommand (const char *command_line,
1186 bool add_to_history,
1187 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001188 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001189 bool repeat_on_empty_command,
1190 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001191
Caroline Ticee0da7a52010-12-09 22:52:49 +00001192{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001193
Caroline Ticee0da7a52010-12-09 22:52:49 +00001194 bool done = false;
1195 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001196 bool wants_raw_input = false;
1197 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001198 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001199
1200 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001201 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1202
1203 // Make a scoped cleanup object that will clear the crash description string
1204 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001205 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001206
Caroline Ticee0da7a52010-12-09 22:52:49 +00001207 if (log)
1208 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001209
Jim Inghamabab14b2010-11-04 23:08:45 +00001210 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1211
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001212 if (!no_context_switching)
1213 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +00001214
Jim Ingham949d5ac2011-02-18 00:54:25 +00001215 bool empty_command = false;
1216 bool comment_command = false;
1217 if (command_string.empty())
1218 empty_command = true;
1219 else
Chris Lattner24943d22010-06-08 16:52:24 +00001220 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001221 const char *k_space_characters = "\t\n\v\f\r ";
1222
1223 size_t non_space = command_string.find_first_not_of (k_space_characters);
1224 // Check for empty line or comment line (lines whose first
1225 // non-space character is the comment character for this interpreter)
1226 if (non_space == std::string::npos)
1227 empty_command = true;
1228 else if (command_string[non_space] == m_comment_char)
1229 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001230 else if (command_string[non_space] == m_repeat_char)
1231 {
1232 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1233 if (history_string == NULL)
1234 {
1235 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1236 result.SetStatus(eReturnStatusFailed);
1237 return false;
1238 }
1239 add_to_history = false;
1240 command_string = history_string;
1241 original_command_string = history_string;
1242 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001243 }
1244
1245 if (empty_command)
1246 {
1247 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001248 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001249 if (m_command_history.empty())
1250 {
1251 result.AppendError ("empty command");
1252 result.SetStatus(eReturnStatusFailed);
1253 return false;
1254 }
1255 else
1256 {
1257 command_line = m_repeat_command.c_str();
1258 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001259 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001260 if (m_repeat_command.empty())
1261 {
1262 result.AppendErrorWithFormat("No auto repeat.\n");
1263 result.SetStatus (eReturnStatusFailed);
1264 return false;
1265 }
1266 }
1267 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001268 }
1269 else
1270 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001271 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1272 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001273 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001274 }
1275 else if (comment_command)
1276 {
1277 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1278 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001279 }
Caroline Tice649116c2011-05-11 16:07:06 +00001280
Greg Claytonf5c0c722011-10-14 07:41:33 +00001281
1282 Error error (PreprocessCommand (command_string));
1283
1284 if (error.Fail())
1285 {
1286 result.AppendError (error.AsCString());
1287 result.SetStatus(eReturnStatusFailed);
1288 return false;
1289 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001290 // Phase 1.
1291
1292 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1293 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1294 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1295 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1296 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
Greg Clayton5d187e52011-01-08 20:28:42 +00001297 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001298 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001299
Caroline Ticee0da7a52010-12-09 22:52:49 +00001300 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001301 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001302 std::string next_word;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001303 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001304 {
Caroline Tice649116c2011-05-11 16:07:06 +00001305 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001306 std::string suffix;
1307 ExtractCommand (command_string, next_word, suffix, quote_char);
1308 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001309 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001310 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001311 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001312 std::string alias_result;
1313 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1314 revised_command_line.Printf ("%s", alias_result.c_str());
1315 if (cmd_obj)
1316 {
1317 wants_raw_input = cmd_obj->WantsRawCommandString ();
1318 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1319 }
Chris Lattner24943d22010-06-08 16:52:24 +00001320 }
1321 else
1322 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001323 cmd_obj = GetCommandObject (next_word.c_str());
1324 if (cmd_obj)
1325 {
1326 actual_cmd_name_len += next_word.length();
1327 revised_command_line.Printf ("%s", next_word.c_str());
1328 wants_raw_input = cmd_obj->WantsRawCommandString ();
1329 }
Caroline Tice649116c2011-05-11 16:07:06 +00001330 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001331 {
1332 revised_command_line.Printf ("%s", next_word.c_str());
1333 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001334 }
1335 }
1336 else
1337 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001338 if (cmd_obj->IsMultiwordObject ())
1339 {
1340 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1341 if (sub_cmd_obj)
1342 {
1343 actual_cmd_name_len += next_word.length() + 1;
1344 revised_command_line.Printf (" %s", next_word.c_str());
1345 cmd_obj = sub_cmd_obj;
1346 wants_raw_input = cmd_obj->WantsRawCommandString ();
1347 }
1348 else
1349 {
1350 if (quote_char)
1351 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1352 else
1353 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1354 done = true;
1355 }
1356 }
Caroline Tice649116c2011-05-11 16:07:06 +00001357 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001358 {
1359 if (quote_char)
1360 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1361 else
1362 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1363 done = true;
1364 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001365 }
1366
1367 if (cmd_obj == NULL)
1368 {
1369 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1370 result.SetStatus (eReturnStatusFailed);
1371 return false;
1372 }
1373
Greg Clayton7268b4c2011-10-28 21:38:01 +00001374 if (cmd_obj->IsMultiwordObject ())
1375 {
1376 if (!suffix.empty())
1377 {
1378
1379 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1380 next_word.c_str(),
1381 suffix.c_str());
1382 result.SetStatus (eReturnStatusFailed);
1383 return false;
1384 }
1385 }
1386 else
1387 {
1388 // If we found a normal command, we are done
1389 done = true;
1390 if (!suffix.empty())
1391 {
1392 switch (suffix[0])
1393 {
1394 case '/':
1395 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001396 {
1397 Options *command_options = cmd_obj->GetOptions();
1398 if (command_options && command_options->SupportsLongOption("gdb-format"))
1399 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001400 std::string gdb_format_option ("--gdb-format=");
1401 gdb_format_option += (suffix.c_str() + 1);
1402
1403 bool inserted = false;
1404 std::string &cmd = revised_command_line.GetString();
1405 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1406 if (arg_terminator_idx != std::string::npos)
1407 {
1408 // Insert the gdb format option before the "--" that terminates options
1409 gdb_format_option.append(1,' ');
1410 cmd.insert(arg_terminator_idx, gdb_format_option);
1411 inserted = true;
1412 }
1413
1414 if (!inserted)
1415 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1416
1417 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1418 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001419 }
1420 else
1421 {
1422 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1423 cmd_obj->GetCommandName());
1424 result.SetStatus (eReturnStatusFailed);
1425 return false;
1426 }
1427 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001428 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001429
1430 default:
1431 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1432 suffix.c_str());
1433 result.SetStatus (eReturnStatusFailed);
1434 return false;
1435
Greg Clayton7268b4c2011-10-28 21:38:01 +00001436 }
1437 }
1438 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001439 if (command_string.length() == 0)
1440 done = true;
1441
Chris Lattner24943d22010-06-08 16:52:24 +00001442 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001443
Greg Clayton7268b4c2011-10-28 21:38:01 +00001444 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001445 revised_command_line.Printf (" %s", command_string.c_str());
1446
1447 // End of Phase 1.
1448 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1449 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1450 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1451 // wants_raw_input specifies whether the Execute method expects raw input or not.
1452
1453
1454 if (log)
1455 {
1456 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1457 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1458 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1459 }
1460
1461 // Phase 2.
1462 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1463 // CommandObject, with the appropriate arguments.
1464
1465 if (cmd_obj != NULL)
1466 {
1467 if (add_to_history)
1468 {
1469 Args command_args (revised_command_line.GetData());
1470 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1471 if (repeat_command != NULL)
1472 m_repeat_command.assign(repeat_command);
1473 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001474 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001475
Jim Ingham6247dbe2011-07-12 03:12:18 +00001476 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001477 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001478 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001479 }
1480
1481 command_string = revised_command_line.GetData();
1482 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001483 std::string remainder;
1484 if (actual_cmd_name_len < command_string.length())
1485 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1486 // than cmd_obj->GetCommandName(), because name completion
1487 // allows users to enter short versions of the names,
1488 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001489
1490 // Remove any initial spaces
1491 std::string white_space (" \t\v");
1492 size_t pos = remainder.find_first_not_of (white_space);
1493 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001494 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001495
1496 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001497 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001498
1499
1500 if (wants_raw_input)
1501 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1502 else
1503 {
1504 Args cmd_args (remainder.c_str());
1505 cmd_obj->ExecuteWithOptions (cmd_args, result);
1506 }
1507 }
1508 else
1509 {
1510 // We didn't find the first command object, so complete the first argument.
1511 Args command_args (revised_command_line.GetData());
1512 StringList matches;
1513 int num_matches;
1514 int cursor_index = 0;
1515 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1516 bool word_complete;
1517 num_matches = HandleCompletionMatches (command_args,
1518 cursor_index,
1519 cursor_char_position,
1520 0,
1521 -1,
1522 word_complete,
1523 matches);
1524
1525 if (num_matches > 0)
1526 {
1527 std::string error_msg;
1528 error_msg.assign ("ambiguous command '");
1529 error_msg.append(command_args.GetArgumentAtIndex(0));
1530 error_msg.append ("'.");
1531
1532 error_msg.append (" Possible completions:");
1533 for (int i = 0; i < num_matches; i++)
1534 {
1535 error_msg.append ("\n\t");
1536 error_msg.append (matches.GetStringAtIndex (i));
1537 }
1538 error_msg.append ("\n");
1539 result.AppendRawError (error_msg.c_str(), error_msg.size());
1540 }
1541 else
1542 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1543
1544 result.SetStatus (eReturnStatusFailed);
1545 }
1546
Jason Molenda24c991c2011-08-25 00:20:04 +00001547 if (log)
1548 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1549
Chris Lattner24943d22010-06-08 16:52:24 +00001550 return result.Succeeded();
1551}
1552
1553int
1554CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1555 int &cursor_index,
1556 int &cursor_char_position,
1557 int match_start_point,
1558 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001559 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001560 StringList &matches)
1561{
1562 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001563 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001564
1565 // For any of the command completions a unique match will be a complete word.
1566 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001567
1568 if (cursor_index == -1)
1569 {
1570 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001571 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001572 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1573 }
1574 else if (cursor_index == 0)
1575 {
1576 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001577 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001578 num_command_matches = matches.GetSize();
1579
1580 if (num_command_matches == 1
1581 && cmd_obj && cmd_obj->IsMultiwordObject()
1582 && matches.GetStringAtIndex(0) != NULL
1583 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1584 {
1585 look_for_subcommand = true;
1586 num_command_matches = 0;
1587 matches.DeleteStringAtIndex(0);
1588 parsed_line.AppendArgument ("");
1589 cursor_index++;
1590 cursor_char_position = 0;
1591 }
1592 }
1593
1594 if (cursor_index > 0 || look_for_subcommand)
1595 {
1596 // We are completing further on into a commands arguments, so find the command and tell it
1597 // to complete the command.
1598 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001599 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001600 if (command_object == NULL)
1601 {
1602 return 0;
1603 }
1604 else
1605 {
1606 parsed_line.Shift();
1607 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001608 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001609 cursor_index,
1610 cursor_char_position,
1611 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001612 max_return_elements,
1613 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001614 matches);
1615 }
1616 }
1617
1618 return num_command_matches;
1619
1620}
1621
1622int
1623CommandInterpreter::HandleCompletion (const char *current_line,
1624 const char *cursor,
1625 const char *last_char,
1626 int match_start_point,
1627 int max_return_elements,
1628 StringList &matches)
1629{
1630 // We parse the argument up to the cursor, so the last argument in parsed_line is
1631 // the one containing the cursor, and the cursor is after the last character.
1632
1633 Args parsed_line(current_line, last_char - current_line);
1634 Args partial_parsed_line(current_line, cursor - current_line);
1635
Jim Ingham6247dbe2011-07-12 03:12:18 +00001636 // Don't complete comments, and if the line we are completing is just the history repeat character,
1637 // substitute the appropriate history line.
1638 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1639 if (first_arg)
1640 {
1641 if (first_arg[0] == m_comment_char)
1642 return 0;
1643 else if (first_arg[0] == m_repeat_char)
1644 {
1645 const char *history_string = FindHistoryString (first_arg);
1646 if (history_string != NULL)
1647 {
1648 matches.Clear();
1649 matches.InsertStringAtIndex(0, history_string);
1650 return -2;
1651 }
1652 else
1653 return 0;
1654
1655 }
1656 }
1657
1658
Chris Lattner24943d22010-06-08 16:52:24 +00001659 int num_args = partial_parsed_line.GetArgumentCount();
1660 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1661 int cursor_char_position;
1662
1663 if (cursor_index == -1)
1664 cursor_char_position = 0;
1665 else
1666 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001667
1668 if (cursor > current_line && cursor[-1] == ' ')
1669 {
1670 // We are just after a space. If we are in an argument, then we will continue
1671 // parsing, but if we are between arguments, then we have to complete whatever the next
1672 // element would be.
1673 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1674 // protected by a quote) then the space will also be in the parsed argument...
1675
1676 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1677 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1678 {
1679 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1680 cursor_index++;
1681 cursor_char_position = 0;
1682 }
1683 }
Chris Lattner24943d22010-06-08 16:52:24 +00001684
1685 int num_command_matches;
1686
1687 matches.Clear();
1688
1689 // Only max_return_elements == -1 is supported at present:
1690 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001691 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001692 num_command_matches = HandleCompletionMatches (parsed_line,
1693 cursor_index,
1694 cursor_char_position,
1695 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001696 max_return_elements,
1697 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001698 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001699
1700 if (num_command_matches <= 0)
1701 return num_command_matches;
1702
1703 if (num_args == 0)
1704 {
1705 // If we got an empty string, insert nothing.
1706 matches.InsertStringAtIndex(0, "");
1707 }
1708 else
1709 {
1710 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1711 // put an empty string in element 0.
1712 std::string command_partial_str;
1713 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001714 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1715 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001716
1717 std::string common_prefix;
1718 matches.LongestCommonPrefix (common_prefix);
1719 int partial_name_len = command_partial_str.size();
1720
1721 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001722 // Only do this if the completer told us this was a complete word, however...
1723 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001724 {
1725 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1726 if (quote_char != '\0')
1727 common_prefix.push_back(quote_char);
1728
1729 common_prefix.push_back(' ');
1730 }
1731 common_prefix.erase (0, partial_name_len);
1732 matches.InsertStringAtIndex(0, common_prefix.c_str());
1733 }
1734 return num_command_matches;
1735}
1736
Chris Lattner24943d22010-06-08 16:52:24 +00001737
1738CommandInterpreter::~CommandInterpreter ()
1739{
1740}
1741
1742const char *
1743CommandInterpreter::GetPrompt ()
1744{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001745 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001746}
1747
1748void
1749CommandInterpreter::SetPrompt (const char *new_prompt)
1750{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001751 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001752}
1753
Jim Ingham5e16ef52010-10-04 19:49:29 +00001754size_t
Greg Clayton58928562011-02-09 01:08:52 +00001755CommandInterpreter::GetConfirmationInputReaderCallback
1756(
1757 void *baton,
1758 InputReader &reader,
1759 lldb::InputReaderAction action,
1760 const char *bytes,
1761 size_t bytes_len
1762)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001763{
Greg Clayton58928562011-02-09 01:08:52 +00001764 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001765 bool *response_ptr = (bool *) baton;
1766
1767 switch (action)
1768 {
1769 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001770 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001771 {
1772 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001773 {
Greg Clayton58928562011-02-09 01:08:52 +00001774 out_file.Printf ("%s", reader.GetPrompt());
1775 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001776 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001777 }
1778 break;
1779
1780 case eInputReaderDeactivate:
1781 break;
1782
1783 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001784 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001785 {
Greg Clayton58928562011-02-09 01:08:52 +00001786 out_file.Printf ("%s", reader.GetPrompt());
1787 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001788 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001789 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001790
1791 case eInputReaderAsynchronousOutputWritten:
1792 break;
1793
Jim Ingham5e16ef52010-10-04 19:49:29 +00001794 case eInputReaderGotToken:
1795 if (bytes_len == 0)
1796 {
1797 reader.SetIsDone(true);
1798 }
1799 else if (bytes[0] == 'y')
1800 {
1801 *response_ptr = true;
1802 reader.SetIsDone(true);
1803 }
1804 else if (bytes[0] == 'n')
1805 {
1806 *response_ptr = false;
1807 reader.SetIsDone(true);
1808 }
1809 else
1810 {
Greg Clayton58928562011-02-09 01:08:52 +00001811 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001812 {
Greg Clayton58928562011-02-09 01:08:52 +00001813 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1814 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001815 }
1816 }
1817 break;
1818
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001819 case eInputReaderInterrupt:
1820 case eInputReaderEndOfFile:
1821 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1822 reader.SetIsDone (true);
1823 break;
1824
Jim Ingham5e16ef52010-10-04 19:49:29 +00001825 case eInputReaderDone:
1826 break;
1827 }
1828
1829 return bytes_len;
1830
1831}
1832
1833bool
1834CommandInterpreter::Confirm (const char *message, bool default_answer)
1835{
Jim Ingham93057472010-10-04 22:44:14 +00001836 // Check AutoConfirm first:
1837 if (m_debugger.GetAutoConfirm())
1838 return default_answer;
1839
Jim Ingham5e16ef52010-10-04 19:49:29 +00001840 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1841 bool response = default_answer;
1842 if (reader_sp)
1843 {
1844 std::string prompt(message);
1845 prompt.append(": [");
1846 if (default_answer)
1847 prompt.append ("Y/n] ");
1848 else
1849 prompt.append ("y/N] ");
1850
1851 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1852 &response, // baton
1853 eInputReaderGranularityLine, // token size, to pass to callback function
1854 NULL, // end token
1855 prompt.c_str(), // prompt
1856 true)); // echo input
1857 if (err.Success())
1858 {
1859 GetDebugger().PushInputReader (reader_sp);
1860 }
1861 reader_sp->WaitOnReaderIsDone();
1862 }
1863 return response;
1864}
1865
1866
Chris Lattner24943d22010-06-08 16:52:24 +00001867void
1868CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1869{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001870 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001871
1872 if (cmd_obj_sp != NULL)
1873 {
1874 CommandObject *cmd_obj = cmd_obj_sp.get();
1875 if (cmd_obj->IsCrossRefObject ())
1876 cmd_obj->AddObject (object_type);
1877 }
1878}
1879
Chris Lattner24943d22010-06-08 16:52:24 +00001880OptionArgVectorSP
1881CommandInterpreter::GetAliasOptions (const char *alias_name)
1882{
1883 OptionArgMap::iterator pos;
1884 OptionArgVectorSP ret_val;
1885
1886 std::string alias (alias_name);
1887
1888 if (HasAliasOptions())
1889 {
1890 pos = m_alias_options.find (alias);
1891 if (pos != m_alias_options.end())
1892 ret_val = pos->second;
1893 }
1894
1895 return ret_val;
1896}
1897
1898void
1899CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1900{
1901 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1902 if (pos != m_alias_options.end())
1903 {
1904 m_alias_options.erase (pos);
1905 }
1906}
1907
1908void
1909CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1910{
1911 m_alias_options[alias_name] = option_arg_vector_sp;
1912}
1913
1914bool
1915CommandInterpreter::HasCommands ()
1916{
1917 return (!m_command_dict.empty());
1918}
1919
1920bool
1921CommandInterpreter::HasAliases ()
1922{
1923 return (!m_alias_dict.empty());
1924}
1925
1926bool
1927CommandInterpreter::HasUserCommands ()
1928{
1929 return (!m_user_dict.empty());
1930}
1931
1932bool
1933CommandInterpreter::HasAliasOptions ()
1934{
1935 return (!m_alias_options.empty());
1936}
1937
Chris Lattner24943d22010-06-08 16:52:24 +00001938void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001939CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1940 const char *alias_name,
1941 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001942 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001943 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001944{
1945 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001946
1947 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001948
Caroline Tice44c841d2010-12-07 19:58:26 +00001949 // Make sure that the alias name is the 0th element in cmd_args
1950 std::string alias_name_str = alias_name;
1951 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1952 cmd_args.Unshift (alias_name);
1953
1954 Args new_args (alias_cmd_obj->GetCommandName());
1955 if (new_args.GetArgumentCount() == 2)
1956 new_args.Shift();
1957
Chris Lattner24943d22010-06-08 16:52:24 +00001958 if (option_arg_vector_sp.get())
1959 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001960 if (wants_raw_input)
1961 {
1962 // We have a command that both has command options and takes raw input. Make *sure* it has a
1963 // " -- " in the right place in the raw_input_string.
1964 size_t pos = raw_input_string.find(" -- ");
1965 if (pos == std::string::npos)
1966 {
1967 // None found; assume it goes at the beginning of the raw input string
1968 raw_input_string.insert (0, " -- ");
1969 }
1970 }
Chris Lattner24943d22010-06-08 16:52:24 +00001971
1972 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1973 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001974 std::vector<bool> used (old_size + 1, false);
1975
1976 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001977
1978 for (int i = 0; i < option_arg_vector->size(); ++i)
1979 {
1980 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001981 OptionArgValue value_pair = option_pair.second;
1982 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001983 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001984 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001985 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001986 {
1987 if (!wants_raw_input
1988 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1989 new_args.AppendArgument (value.c_str());
1990 }
Chris Lattner24943d22010-06-08 16:52:24 +00001991 else
1992 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001993 if (value_type != optional_argument)
1994 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001995 if (value.compare ("<no-argument>") != 0)
1996 {
1997 int index = GetOptionArgumentPosition (value.c_str());
1998 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001999 {
Chris Lattner24943d22010-06-08 16:52:24 +00002000 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002001 if (value_type != optional_argument)
2002 new_args.AppendArgument (value.c_str());
2003 else
2004 {
2005 char buffer[255];
2006 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2007 new_args.AppendArgument (buffer);
2008 }
2009
2010 }
Chris Lattner24943d22010-06-08 16:52:24 +00002011 else if (index >= cmd_args.GetArgumentCount())
2012 {
2013 result.AppendErrorWithFormat
2014 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2015 index);
2016 result.SetStatus (eReturnStatusFailed);
2017 return;
2018 }
2019 else
2020 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002021 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2022 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2023 if (strpos != std::string::npos)
2024 {
2025 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2026 }
2027
2028 if (value_type != optional_argument)
2029 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2030 else
2031 {
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 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002037 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002038 }
2039 }
2040 }
2041 }
2042
2043 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2044 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002045 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002046 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2047 }
2048
2049 cmd_args.Clear();
2050 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2051 }
2052 else
2053 {
2054 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002055 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2056 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2057 // input string.
2058 if (wants_raw_input)
2059 {
2060 cmd_args.Clear();
2061 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2062 }
Chris Lattner24943d22010-06-08 16:52:24 +00002063 return;
2064 }
2065
2066 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2067 return;
2068}
2069
2070
2071int
2072CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2073{
2074 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2075 // of zero.
2076
2077 char *cptr = (char *) in_string;
2078
2079 // Does it start with '%'
2080 if (cptr[0] == '%')
2081 {
2082 ++cptr;
2083
2084 // Is the rest of it entirely digits?
2085 if (isdigit (cptr[0]))
2086 {
2087 const char *start = cptr;
2088 while (isdigit (cptr[0]))
2089 ++cptr;
2090
2091 // We've gotten to the end of the digits; are we at the end of the string?
2092 if (cptr[0] == '\0')
2093 position = atoi (start);
2094 }
2095 }
2096
2097 return position;
2098}
2099
2100void
2101CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2102{
Jim Ingham574c3d62011-08-12 23:34:31 +00002103 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002104 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002105 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002106 // In the current working directory we don't load any program specific
2107 // .lldbinit files, we only look for a "./.lldbinit" file.
2108 if (m_skip_lldbinit_files)
2109 return;
2110
2111 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002112 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002113 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002114 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002115 // If we aren't looking in the current working directory we are looking
2116 // in the home directory. We will first see if there is an application
2117 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2118 // "-" and the name of the program. If this file doesn't exist, we fall
2119 // back to just the "~/.lldbinit" file. We also obey any requests to not
2120 // load the init files.
2121 const char *init_file_path = "~/.lldbinit";
2122
2123 if (m_skip_app_init_files == false)
2124 {
2125 FileSpec program_file_spec (Host::GetProgramFileSpec());
2126 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002127
Greg Claytond6edcb52011-09-11 00:01:44 +00002128 if (program_name)
2129 {
2130 char program_init_file_name[PATH_MAX];
2131 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2132 init_file.SetFile (program_init_file_name, true);
2133 if (!init_file.Exists())
2134 init_file.Clear();
2135 }
2136 }
2137
2138 if (!init_file && !m_skip_lldbinit_files)
2139 init_file.SetFile (init_file_path, true);
2140 }
2141
Chris Lattner24943d22010-06-08 16:52:24 +00002142 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2143 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2144
2145 if (init_file.Exists())
2146 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002147 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2148 bool stop_on_continue = true;
2149 bool stop_on_error = false;
2150 bool echo_commands = false;
2151 bool print_results = false;
2152
2153 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002154 }
2155 else
2156 {
2157 // nothing to be done if the file doesn't exist
2158 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2159 }
2160}
2161
Greg Claytonb72d0f02011-04-12 05:54:46 +00002162PlatformSP
2163CommandInterpreter::GetPlatform (bool prefer_target_platform)
2164{
2165 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002166 if (prefer_target_platform)
2167 {
2168 Target *target = m_exe_ctx.GetTargetPtr();
2169 if (target)
2170 platform_sp = target->GetPlatform();
2171 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002172
2173 if (!platform_sp)
2174 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2175 return platform_sp;
2176}
2177
Jim Ingham949d5ac2011-02-18 00:54:25 +00002178void
Jim Inghama4fede32011-03-11 01:51:49 +00002179CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002180 ExecutionContext *override_context,
2181 bool stop_on_continue,
2182 bool stop_on_error,
2183 bool echo_commands,
2184 bool print_results,
2185 CommandReturnObject &result)
2186{
2187 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002188
2189 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2190 // Make sure you reset this value anywhere you return from the function.
2191
2192 bool old_async_execution = m_debugger.GetAsyncExecution();
2193
2194 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2195 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2196
2197 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002198 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002199
2200 if (!stop_on_continue)
2201 {
2202 m_debugger.SetAsyncExecution (false);
2203 }
2204
2205 for (int idx = 0; idx < num_lines; idx++)
2206 {
2207 const char *cmd = commands.GetStringAtIndex(idx);
2208 if (cmd[0] == '\0')
2209 continue;
2210
Jim Ingham949d5ac2011-02-18 00:54:25 +00002211 if (echo_commands)
2212 {
2213 result.AppendMessageWithFormat ("%s %s\n",
2214 GetPrompt(),
2215 cmd);
2216 }
2217
Greg Claytonaa378b12011-02-20 02:15:07 +00002218 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002219 // If override_context is not NULL, pass no_context_switching = true for
2220 // HandleCommand() since we updated our context already.
2221 bool success = HandleCommand(cmd, false, tmp_result,
2222 NULL, /* override_context */
2223 true, /* repeat_on_empty_command */
2224 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002225
2226 if (print_results)
2227 {
2228 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002229 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002230 }
2231
2232 if (!success || !tmp_result.Succeeded())
2233 {
2234 if (stop_on_error)
2235 {
2236 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
2237 idx, cmd);
2238 result.SetStatus (eReturnStatusFailed);
2239 m_debugger.SetAsyncExecution (old_async_execution);
2240 return;
2241 }
2242 else if (print_results)
2243 {
2244 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
2245 idx + 1,
2246 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002247 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002248 }
2249 }
2250
Caroline Tice4a348082011-05-02 20:41:46 +00002251 if (result.GetImmediateOutputStream())
2252 result.GetImmediateOutputStream()->Flush();
2253
2254 if (result.GetImmediateErrorStream())
2255 result.GetImmediateErrorStream()->Flush();
2256
Jim Ingham949d5ac2011-02-18 00:54:25 +00002257 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2258 // could be running (for instance in Breakpoint Commands.
2259 // So we check the return value to see if it is has running in it.
2260 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2261 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2262 {
2263 if (stop_on_continue)
2264 {
2265 // If we caused the target to proceed, and we're going to stop in that case, set the
2266 // status in our real result before returning. This is an error if the continue was not the
2267 // last command in the set of commands to be run.
2268 if (idx != num_lines - 1)
2269 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2270 idx + 1, cmd);
2271 else
2272 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2273
2274 result.SetStatus(tmp_result.GetStatus());
2275 m_debugger.SetAsyncExecution (old_async_execution);
2276
2277 return;
2278 }
2279 }
2280
2281 }
2282
2283 result.SetStatus (eReturnStatusSuccessFinishResult);
2284 m_debugger.SetAsyncExecution (old_async_execution);
2285
2286 return;
2287}
2288
2289void
2290CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2291 ExecutionContext *context,
2292 bool stop_on_continue,
2293 bool stop_on_error,
2294 bool echo_command,
2295 bool print_result,
2296 CommandReturnObject &result)
2297{
2298 if (cmd_file.Exists())
2299 {
2300 bool success;
2301 StringList commands;
2302 success = commands.ReadFileLines(cmd_file);
2303 if (!success)
2304 {
2305 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2306 result.SetStatus (eReturnStatusFailed);
2307 return;
2308 }
2309 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
2310 }
2311 else
2312 {
2313 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2314 cmd_file.GetFilename().AsCString());
2315 result.SetStatus (eReturnStatusFailed);
2316 return;
2317 }
2318}
2319
Chris Lattner24943d22010-06-08 16:52:24 +00002320ScriptInterpreter *
2321CommandInterpreter::GetScriptInterpreter ()
2322{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002323 if (m_script_interpreter_ap.get() != NULL)
2324 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002325
Caroline Tice0aa2e552011-01-14 00:29:16 +00002326 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2327 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002328 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002329 case eScriptLanguagePython:
2330#ifndef LLDB_DISABLE_PYTHON
2331 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2332 break;
2333#else
2334 // Fall through to the None case when python is disabled
2335#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002336 case eScriptLanguageNone:
2337 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2338 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002339 default:
2340 break;
2341 };
2342
2343 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002344}
2345
2346
2347
2348bool
2349CommandInterpreter::GetSynchronous ()
2350{
2351 return m_synchronous_execution;
2352}
2353
2354void
2355CommandInterpreter::SetSynchronous (bool value)
2356{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002357 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002358}
2359
2360void
2361CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2362 const char *word_text,
2363 const char *separator,
2364 const char *help_text,
2365 uint32_t max_word_len)
2366{
Greg Clayton238c0a12010-09-18 01:14:36 +00002367 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2368
Chris Lattner24943d22010-06-08 16:52:24 +00002369 int indent_size = max_word_len + strlen (separator) + 2;
2370
2371 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002372
2373 StreamString text_strm;
2374 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2375
2376 size_t len = text_strm.GetSize();
2377 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002378 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002379 {
2380 text_strm.EOL();
2381 len = text_strm.GetSize();
2382 }
Chris Lattner24943d22010-06-08 16:52:24 +00002383
2384 if (len < max_columns)
2385 {
2386 // Output it as a single line.
2387 strm.Printf ("%s", text);
2388 }
2389 else
2390 {
2391 // We need to break it up into multiple lines.
2392 bool first_line = true;
2393 int text_width;
2394 int start = 0;
2395 int end = start;
2396 int final_end = strlen (text);
2397 int sub_len;
2398
2399 while (end < final_end)
2400 {
2401 if (first_line)
2402 text_width = max_columns - 1;
2403 else
2404 text_width = max_columns - indent_size - 1;
2405
2406 // Don't start the 'text' on a space, since we're already outputting the indentation.
2407 if (!first_line)
2408 {
2409 while ((start < final_end) && (text[start] == ' '))
2410 start++;
2411 }
2412
2413 end = start + text_width;
2414 if (end > final_end)
2415 end = final_end;
2416 else
2417 {
2418 // If we're not at the end of the text, make sure we break the line on white space.
2419 while (end > start
2420 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2421 end--;
2422 }
2423
2424 sub_len = end - start;
2425 if (start != 0)
2426 strm.EOL();
2427 if (!first_line)
2428 strm.Indent();
2429 else
2430 first_line = false;
2431 assert (start <= final_end);
2432 assert (start + sub_len <= final_end);
2433 if (sub_len > 0)
2434 strm.Write (text + start, sub_len);
2435 start = end + 1;
2436 }
2437 }
2438 strm.EOL();
2439 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002440}
2441
2442void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002443CommandInterpreter::OutputHelpText (Stream &strm,
2444 const char *word_text,
2445 const char *separator,
2446 const char *help_text,
2447 uint32_t max_word_len)
2448{
2449 int indent_size = max_word_len + strlen (separator) + 2;
2450
2451 strm.IndentMore (indent_size);
2452
2453 StreamString text_strm;
2454 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2455
2456 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2457 bool first_line = true;
2458
2459 size_t len = text_strm.GetSize();
2460 const char *text = text_strm.GetData();
2461
2462 uint32_t chars_left = max_columns;
2463
2464 for (uint32_t i = 0; i < len; i++)
2465 {
2466 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2467 {
2468 first_line = false;
2469 chars_left = max_columns - indent_size;
2470 strm.EOL();
2471 strm.Indent();
2472 }
2473 else
2474 {
2475 strm.PutChar(text[i]);
2476 chars_left--;
2477 }
2478
2479 }
2480
2481 strm.EOL();
2482 strm.IndentLess(indent_size);
2483}
2484
2485void
Chris Lattner24943d22010-06-08 16:52:24 +00002486CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2487 StringList &commands_found, StringList &commands_help)
2488{
2489 CommandObject::CommandMap::const_iterator pos;
2490 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2491 CommandObject *sub_cmd_obj;
2492
2493 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2494 {
2495 const char * command_name = pos->first.c_str();
2496 sub_cmd_obj = pos->second.get();
2497 StreamString complete_command_name;
2498
2499 complete_command_name.Printf ("%s %s", prefix, command_name);
2500
Greg Clayton238c0a12010-09-18 01:14:36 +00002501 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002502 {
2503 commands_found.AppendString (complete_command_name.GetData());
2504 commands_help.AppendString (sub_cmd_obj->GetHelp());
2505 }
2506
2507 if (sub_cmd_obj->IsMultiwordObject())
2508 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2509 commands_help);
2510 }
2511
2512}
2513
2514void
2515CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2516 StringList &commands_help)
2517{
2518 CommandObject::CommandMap::const_iterator pos;
2519
2520 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2521 {
2522 const char *command_name = pos->first.c_str();
2523 CommandObject *cmd_obj = pos->second.get();
2524
Greg Clayton238c0a12010-09-18 01:14:36 +00002525 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002526 {
2527 commands_found.AppendString (command_name);
2528 commands_help.AppendString (cmd_obj->GetHelp());
2529 }
2530
2531 if (cmd_obj->IsMultiwordObject())
2532 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2533
2534 }
2535}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002536
2537
2538void
2539CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2540{
2541 m_exe_ctx.Clear();
2542
2543 if (override_context != NULL)
2544 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002545 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002546 }
2547 else
2548 {
2549 TargetSP target_sp (m_debugger.GetSelectedTarget());
2550 if (target_sp)
2551 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002552 m_exe_ctx.SetTargetSP (target_sp);
2553 ProcessSP process_sp (target_sp->GetProcessSP());
2554 m_exe_ctx.SetProcessSP (process_sp);
2555 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002556 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002557 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread().get());
2558 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002559 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002560 m_exe_ctx.SetThreadSP (thread_sp);
2561 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2562 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002563 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002564 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002565 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002566 if (frame_sp)
2567 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002568 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002569 if (frame_sp)
2570 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002571 }
2572 }
2573 }
2574 }
2575}
2576
Jim Ingham6247dbe2011-07-12 03:12:18 +00002577void
2578CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2579{
2580 DumpHistory (stream, 0, count - 1);
2581}
2582
2583void
2584CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2585{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002586 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2587 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002588 {
2589 if (!m_command_history[i].empty())
2590 {
2591 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002592 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002593 }
2594 }
2595}
2596
2597const char *
2598CommandInterpreter::FindHistoryString (const char *input_str) const
2599{
2600 if (input_str[0] != m_repeat_char)
2601 return NULL;
2602 if (input_str[1] == '-')
2603 {
2604 bool success;
2605 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2606 if (!success)
2607 return NULL;
2608 if (idx > m_command_history.size())
2609 return NULL;
2610 idx = m_command_history.size() - idx;
2611 return m_command_history[idx].c_str();
2612
2613 }
2614 else if (input_str[1] == m_repeat_char)
2615 {
2616 if (m_command_history.empty())
2617 return NULL;
2618 else
2619 return m_command_history.back().c_str();
2620 }
2621 else
2622 {
2623 bool success;
2624 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2625 if (!success)
2626 return NULL;
2627 if (idx >= m_command_history.size())
2628 return NULL;
2629 return m_command_history[idx].c_str();
2630 }
2631}