blob: 8c3d2d37d75cb7897011fbaece2ec0eb2f4d9345 [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
Jim Ingham5a15e692012-02-16 06:50:00 +000062ConstString &
63CommandInterpreter::GetStaticBroadcasterClass ()
64{
65 static ConstString class_name ("lldb.commandInterpreter");
66 return class_name;
67}
68
Chris Lattner24943d22010-06-08 16:52:24 +000069CommandInterpreter::CommandInterpreter
70(
Greg Clayton63094e02010-06-23 01:19:29 +000071 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000072 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000073 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000074) :
Jim Ingham5a15e692012-02-16 06:50:00 +000075 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000076 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000077 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000078 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000079 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000080 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +000081 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +000082 m_repeat_char ('!'),
Enrico Granata293a7b32011-08-15 19:24:02 +000083 m_batch_command_mode (false),
84 m_truncation_warning(eNoTruncation)
Chris Lattner24943d22010-06-08 16:52:24 +000085{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000086 const char *dbg_name = debugger.GetInstanceName().AsCString();
87 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
88 StreamString var_name;
89 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000090 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000091 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000092 m_debugger.GetInstanceName().AsCString());
93 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
94 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
95 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham5a15e692012-02-16 06:50:00 +000096
97 CheckInWithManager ();
Chris Lattner24943d22010-06-08 16:52:24 +000098}
99
100void
101CommandInterpreter::Initialize ()
102{
103 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
104
105 CommandReturnObject result;
106
107 LoadCommandDictionary ();
108
Chris Lattner24943d22010-06-08 16:52:24 +0000109 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000110 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
111 if (cmd_obj_sp)
112 {
113 AddAlias ("q", cmd_obj_sp);
114 AddAlias ("exit", cmd_obj_sp);
115 }
116
117 cmd_obj_sp = GetCommandSPExact ("process continue", false);
118 if (cmd_obj_sp)
119 {
120 AddAlias ("c", cmd_obj_sp);
121 AddAlias ("continue", cmd_obj_sp);
122 }
123
124 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
125 if (cmd_obj_sp)
126 AddAlias ("b", cmd_obj_sp);
127
128 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
129 if (cmd_obj_sp)
130 AddAlias ("bt", cmd_obj_sp);
131
132 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
133 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000134 {
135 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000136 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000137 }
138
139 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
140 if (cmd_obj_sp)
141 {
142 AddAlias ("nexti", cmd_obj_sp);
143 AddAlias ("ni", cmd_obj_sp);
144 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000145
146 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
147 if (cmd_obj_sp)
148 {
149 AddAlias ("s", cmd_obj_sp);
150 AddAlias ("step", cmd_obj_sp);
151 }
152
153 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
154 if (cmd_obj_sp)
155 {
156 AddAlias ("n", cmd_obj_sp);
157 AddAlias ("next", cmd_obj_sp);
158 }
159
160 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
161 if (cmd_obj_sp)
162 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000163 AddAlias ("finish", cmd_obj_sp);
164 }
165
Jim Ingham59355252011-12-02 01:12:59 +0000166 cmd_obj_sp = GetCommandSPExact ("frame select", false);
167 if (cmd_obj_sp)
168 {
169 AddAlias ("f", cmd_obj_sp);
170 }
171
Caroline Tice5ddbe212011-05-06 21:37:15 +0000172 cmd_obj_sp = GetCommandSPExact ("source list", false);
173 if (cmd_obj_sp)
174 {
175 AddAlias ("l", cmd_obj_sp);
176 AddAlias ("list", cmd_obj_sp);
177 }
178
179 cmd_obj_sp = GetCommandSPExact ("memory read", false);
180 if (cmd_obj_sp)
181 AddAlias ("x", cmd_obj_sp);
182
183 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
184 if (cmd_obj_sp)
185 AddAlias ("up", cmd_obj_sp);
186
187 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
188 if (cmd_obj_sp)
189 AddAlias ("down", cmd_obj_sp);
190
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000191 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000192 if (cmd_obj_sp)
193 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000194
195 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
196 if (cmd_obj_sp)
197 AddAlias ("dis", cmd_obj_sp);
198
199 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
200 if (cmd_obj_sp)
201 AddAlias ("di", cmd_obj_sp);
202
203
Jason Molenda730cae02011-10-22 01:30:52 +0000204
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000205 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000206 if (cmd_obj_sp)
207 AddAlias ("undisplay", cmd_obj_sp);
208
Caroline Tice5ddbe212011-05-06 21:37:15 +0000209 cmd_obj_sp = GetCommandSPExact ("target create", false);
210 if (cmd_obj_sp)
211 AddAlias ("file", cmd_obj_sp);
212
213 cmd_obj_sp = GetCommandSPExact ("target modules", false);
214 if (cmd_obj_sp)
215 AddAlias ("image", cmd_obj_sp);
216
217
218 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000219
Caroline Tice5ddbe212011-05-06 21:37:15 +0000220 cmd_obj_sp = GetCommandSPExact ("expression", false);
221 if (cmd_obj_sp)
222 {
223 AddAlias ("expr", cmd_obj_sp);
224
225 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
226 AddAlias ("p", cmd_obj_sp);
227 AddAlias ("print", cmd_obj_sp);
228 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
229 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
230
231 alias_arguments_vector_sp.reset (new OptionArgVector);
232 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
233 AddAlias ("po", cmd_obj_sp);
234 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
235 }
236
237 cmd_obj_sp = GetCommandSPExact ("process launch", false);
238 if (cmd_obj_sp)
239 {
240 alias_arguments_vector_sp.reset (new OptionArgVector);
241 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
242 AddAlias ("r", cmd_obj_sp);
243 AddAlias ("run", cmd_obj_sp);
244 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
245 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
246 }
Chris Lattner24943d22010-06-08 16:52:24 +0000247}
248
Chris Lattner24943d22010-06-08 16:52:24 +0000249const char *
250CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
251{
252 // This function has not yet been implemented.
253
254 // Look for any embedded script command
255 // If found,
256 // get interpreter object from the command dictionary,
257 // call execute_one_command on it,
258 // get the results as a string,
259 // substitute that string for current stuff.
260
261 return arg;
262}
263
264
265void
266CommandInterpreter::LoadCommandDictionary ()
267{
268 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
269
270 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
271 //
272 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
273 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
274 // the cross-referencing stuff) are created!!!
275 //
276 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
277
278
279 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
280 // are created. This is so that when another command is created that needs to go into a crossref object,
281 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
282 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
283
Chris Lattner24943d22010-06-08 16:52:24 +0000284 // Non-CommandObjectCrossref commands can now be created.
285
Caroline Tice5bc8c972010-09-20 20:44:43 +0000286 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000287
Greg Clayton238c0a12010-09-18 01:14:36 +0000288 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000289 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000290 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000291 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000292 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
293 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000294// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000295 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000296 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000297 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000298 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
299 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000300 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000301 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000302 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000303 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000304 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000305 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000306 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000307 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
308 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000309 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000310 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000311 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000312
313 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000314 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000315 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000316 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000317 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000318 if (break_regex_cmd_ap.get())
319 {
320 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
321 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
322 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000323 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000324 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000325 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000326 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
327 {
328 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
329 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
330 }
331 }
Jim Inghame56493f2011-03-22 02:29:32 +0000332
333 std::auto_ptr<CommandObjectRegexCommand>
334 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000335 "_regexp-down",
336 "Go down \"n\" frames in the stack (1 frame by default).",
337 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000338 if (down_regex_cmd_ap.get())
339 {
340 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
341 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
342 {
343 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
344 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
345 }
346 }
347
348 std::auto_ptr<CommandObjectRegexCommand>
349 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000350 "_regexp-up",
351 "Go up \"n\" frames in the stack (1 frame by default).",
352 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000353 if (up_regex_cmd_ap.get())
354 {
355 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
356 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
357 {
358 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
359 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
360 }
361 }
Jason Molenda730cae02011-10-22 01:30:52 +0000362
363 std::auto_ptr<CommandObjectRegexCommand>
364 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000365 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000366 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000367 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000368 if (display_regex_cmd_ap.get())
369 {
370 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
371 {
372 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
373 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
374 }
375 }
376
377 std::auto_ptr<CommandObjectRegexCommand>
378 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000379 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000380 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000381 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000382 if (undisplay_regex_cmd_ap.get())
383 {
384 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
385 {
386 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
387 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
388 }
389 }
390
Chris Lattner24943d22010-06-08 16:52:24 +0000391}
392
393int
394CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
395 StringList &matches)
396{
397 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
398
399 if (include_aliases)
400 {
401 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
402 }
403
404 return matches.GetSize();
405}
406
407CommandObjectSP
408CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
409{
410 CommandObject::CommandMap::iterator pos;
411 CommandObjectSP ret_val;
412
413 std::string cmd(cmd_cstr);
414
415 if (HasCommands())
416 {
417 pos = m_command_dict.find(cmd);
418 if (pos != m_command_dict.end())
419 ret_val = pos->second;
420 }
421
422 if (include_aliases && HasAliases())
423 {
424 pos = m_alias_dict.find(cmd);
425 if (pos != m_alias_dict.end())
426 ret_val = pos->second;
427 }
428
429 if (HasUserCommands())
430 {
431 pos = m_user_dict.find(cmd);
432 if (pos != m_user_dict.end())
433 ret_val = pos->second;
434 }
435
436 if (!exact && ret_val == NULL)
437 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000438 // We will only get into here if we didn't find any exact matches.
439
440 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
441
Chris Lattner24943d22010-06-08 16:52:24 +0000442 StringList local_matches;
443 if (matches == NULL)
444 matches = &local_matches;
445
Jim Inghamd40f8a62010-07-06 22:46:59 +0000446 unsigned int num_cmd_matches = 0;
447 unsigned int num_alias_matches = 0;
448 unsigned int num_user_matches = 0;
449
450 // Look through the command dictionaries one by one, and if we get only one match from any of
451 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
452
Chris Lattner24943d22010-06-08 16:52:24 +0000453 if (HasCommands())
454 {
455 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
456 }
457
458 if (num_cmd_matches == 1)
459 {
460 cmd.assign(matches->GetStringAtIndex(0));
461 pos = m_command_dict.find(cmd);
462 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000463 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000464 }
465
Jim Ingham9a574172010-06-24 20:28:42 +0000466 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000467 {
468 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
469
470 }
471
Jim Inghamd40f8a62010-07-06 22:46:59 +0000472 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000473 {
474 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
475 pos = m_alias_dict.find(cmd);
476 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000477 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000478 }
479
Jim Ingham9a574172010-06-24 20:28:42 +0000480 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000481 {
482 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
483 }
484
Jim Inghamd40f8a62010-07-06 22:46:59 +0000485 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000486 {
487 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
488
489 pos = m_user_dict.find (cmd);
490 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000491 user_match_sp = pos->second;
492 }
493
494 // If we got exactly one match, return that, otherwise return the match list.
495
496 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
497 {
498 if (num_cmd_matches)
499 return real_match_sp;
500 else if (num_alias_matches)
501 return alias_match_sp;
502 else
503 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000504 }
505 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000506 else if (matches && ret_val != NULL)
507 {
508 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000509 }
510
511
512 return ret_val;
513}
514
Greg Claytond12aeab2011-04-20 16:37:46 +0000515bool
516CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
517{
518 if (name && name[0])
519 {
520 std::string name_sstr(name);
521 if (!can_replace)
522 {
523 if (m_command_dict.find (name_sstr) != m_command_dict.end())
524 return false;
525 }
526 m_command_dict[name_sstr] = cmd_sp;
527 return true;
528 }
529 return false;
530}
531
Enrico Granata6b1596d2011-08-16 23:24:13 +0000532bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000533CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000534 const lldb::CommandObjectSP &cmd_sp,
535 bool can_replace)
536{
Enrico Granata6010ace2011-11-07 22:57:04 +0000537 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000538 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000539
540 const char* name_cstr = name.c_str();
541
542 // do not allow replacement of internal commands
543 if (CommandExists(name_cstr))
544 return false;
545
546 if (can_replace == false && UserCommandExists(name_cstr))
547 return false;
548
549 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000550 return true;
551 }
552 return false;
553}
Greg Claytond12aeab2011-04-20 16:37:46 +0000554
Jim Inghamd40f8a62010-07-06 22:46:59 +0000555CommandObjectSP
556CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000557{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000558 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
559 CommandObjectSP ret_val; // Possibly empty return value.
560
561 if (cmd_cstr == NULL)
562 return ret_val;
563
564 if (cmd_words.GetArgumentCount() == 1)
565 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
566 else
567 {
568 // We have a multi-word command (seemingly), so we need to do more work.
569 // First, get the cmd_obj_sp for the first word in the command.
570 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
571 if (cmd_obj_sp.get() != NULL)
572 {
573 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
574 // command name), and find the appropriate sub-command SP for each command word....
575 size_t end = cmd_words.GetArgumentCount();
576 for (size_t j= 1; j < end; ++j)
577 {
578 if (cmd_obj_sp->IsMultiwordObject())
579 {
580 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
581 (cmd_words.GetArgumentAtIndex (j));
582 if (cmd_obj_sp.get() == NULL)
583 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
584 return ret_val;
585 }
586 else
587 // We have more words in the command name, but we don't have a multiword object. Fail and return
588 // empty 'ret_val'.
589 return ret_val;
590 }
591 // We successfully looped through all the command words and got valid command objects for them. Assign the
592 // last object retrieved to 'ret_val'.
593 ret_val = cmd_obj_sp;
594 }
595 }
596 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000597}
598
599CommandObject *
600CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
601{
602 return GetCommandSPExact (cmd_cstr, include_aliases).get();
603}
604
605CommandObject *
606CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
607{
608 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
609
610 // If we didn't find an exact match to the command string in the commands, look in
611 // the aliases.
612
613 if (command_obj == NULL)
614 {
615 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
616 }
617
618 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
619 // in both the commands and the aliases.
620
621 if (command_obj == NULL)
622 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
623
624 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000625}
626
627bool
628CommandInterpreter::CommandExists (const char *cmd)
629{
630 return m_command_dict.find(cmd) != m_command_dict.end();
631}
632
633bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000634CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
635 const char *options_args,
636 OptionArgVectorSP &option_arg_vector_sp)
637{
638 bool success = true;
639 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
640
641 if (!options_args || (strlen (options_args) < 1))
642 return true;
643
644 std::string options_string (options_args);
645 Args args (options_args);
646 CommandReturnObject result;
647 // Check to see if the command being aliased can take any command options.
648 Options *options = cmd_obj_sp->GetOptions ();
649 if (options)
650 {
651 // See if any options were specified as part of the alias; if so, handle them appropriately.
652 options->NotifyOptionParsingStarting ();
653 args.Unshift ("dummy_arg");
654 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
655 args.Shift ();
656 if (result.Succeeded())
657 options->VerifyPartialOptions (result);
658 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
659 {
660 result.AppendError ("Unable to create requested alias.\n");
661 return false;
662 }
663 }
664
Greg Clayton7268b4c2011-10-28 21:38:01 +0000665 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000666 {
667 if (cmd_obj_sp->WantsRawCommandString ())
668 option_arg_vector->push_back (OptionArgPair ("<argument>",
669 OptionArgValue (-1,
670 options_string)));
671 else
672 {
673 int argc = args.GetArgumentCount();
674 for (size_t i = 0; i < argc; ++i)
675 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
676 option_arg_vector->push_back
677 (OptionArgPair ("<argument>",
678 OptionArgValue (-1,
679 std::string (args.GetArgumentAtIndex (i)))));
680 }
681 }
682
683 return success;
684}
685
686bool
Chris Lattner24943d22010-06-08 16:52:24 +0000687CommandInterpreter::AliasExists (const char *cmd)
688{
689 return m_alias_dict.find(cmd) != m_alias_dict.end();
690}
691
692bool
693CommandInterpreter::UserCommandExists (const char *cmd)
694{
695 return m_user_dict.find(cmd) != m_user_dict.end();
696}
697
698void
699CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
700{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000701 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000702 m_alias_dict[alias_name] = command_obj_sp;
703}
704
705bool
706CommandInterpreter::RemoveAlias (const char *alias_name)
707{
708 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
709 if (pos != m_alias_dict.end())
710 {
711 m_alias_dict.erase(pos);
712 return true;
713 }
714 return false;
715}
716bool
717CommandInterpreter::RemoveUser (const char *alias_name)
718{
719 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
720 if (pos != m_user_dict.end())
721 {
722 m_user_dict.erase(pos);
723 return true;
724 }
725 return false;
726}
727
Chris Lattner24943d22010-06-08 16:52:24 +0000728void
729CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
730{
731 help_string.Printf ("'%s", command_name);
732 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
733
734 if (option_arg_vector_sp != NULL)
735 {
736 OptionArgVector *options = option_arg_vector_sp.get();
737 for (int i = 0; i < options->size(); ++i)
738 {
739 OptionArgPair cur_option = (*options)[i];
740 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000741 OptionArgValue value_pair = cur_option.second;
742 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000743 if (opt.compare("<argument>") == 0)
744 {
745 help_string.Printf (" %s", value.c_str());
746 }
747 else
748 {
749 help_string.Printf (" %s", opt.c_str());
750 if ((value.compare ("<no-argument>") != 0)
751 && (value.compare ("<need-argument") != 0))
752 {
753 help_string.Printf (" %s", value.c_str());
754 }
755 }
756 }
757 }
758
759 help_string.Printf ("'");
760}
761
Greg Clayton65124ea2010-08-26 22:05:43 +0000762size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000763CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
764{
765 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000766 CommandObject::CommandMap::const_iterator end = dict.end();
767 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000768
Greg Clayton65124ea2010-08-26 22:05:43 +0000769 for (pos = dict.begin(); pos != end; ++pos)
770 {
771 size_t len = pos->first.size();
772 if (max_len < len)
773 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000774 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000775 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000776}
777
778void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000779CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000780 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000781{
782 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000783 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000784
785 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000786 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000787
788 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
789 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000790
Enrico Granata6b1596d2011-08-16 23:24:13 +0000791 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
792 {
793 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
794 max_len);
795 }
796 result.AppendMessage("");
797
798 }
799
Greg Clayton7268b4c2011-10-28 21:38:01 +0000800 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000801 {
Jim Inghame3663e82010-10-22 18:47:16 +0000802 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000803 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000804 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000805 max_len = FindLongestCommandWord (m_alias_dict);
806
Chris Lattner24943d22010-06-08 16:52:24 +0000807 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
808 {
809 StreamString sstr;
810 StreamString translation_and_help;
811 std::string entry_name = pos->first;
812 std::string second_entry = pos->second.get()->GetCommandName();
813 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
814
815 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
816 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
817 translation_and_help.GetData(), max_len);
818 }
819 result.AppendMessage("");
820 }
821
Greg Clayton7268b4c2011-10-28 21:38:01 +0000822 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000823 {
824 result.AppendMessage ("The following is a list of your current user-defined commands:");
825 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000826 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000827 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
828 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000829 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
830 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000831 }
832 result.AppendMessage("");
833 }
834
835 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
836}
837
Caroline Ticee0da7a52010-12-09 22:52:49 +0000838CommandObject *
839CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000840{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000841 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
842 // eventually be invoked by the given command line.
843
844 CommandObject *cmd_obj = NULL;
845 std::string white_space (" \t\v");
846 size_t start = command_string.find_first_not_of (white_space);
847 size_t end = 0;
848 bool done = false;
849 while (!done)
850 {
851 if (start != std::string::npos)
852 {
853 // Get the next word from command_string.
854 end = command_string.find_first_of (white_space, start);
855 if (end == std::string::npos)
856 end = command_string.size();
857 std::string cmd_word = command_string.substr (start, end - start);
858
859 if (cmd_obj == NULL)
860 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
861 // command or alias.
862 cmd_obj = GetCommandObject (cmd_word.c_str());
863 else if (cmd_obj->IsMultiwordObject ())
864 {
865 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
866 CommandObject *sub_cmd_obj =
867 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
868 if (sub_cmd_obj)
869 cmd_obj = sub_cmd_obj;
870 else // cmd_word was not a valid sub-command word, so we are donee
871 done = true;
872 }
873 else
874 // We have a cmd_obj and it is not a multi-word object, so we are done.
875 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000876
Caroline Ticee0da7a52010-12-09 22:52:49 +0000877 // If we didn't find a valid command object, or our command object is not a multi-word object, or
878 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
879 // next word.
880
881 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
882 done = true;
883 else
884 start = command_string.find_first_not_of (white_space, end);
885 }
886 else
887 // Unable to find any more words.
888 done = true;
889 }
890
891 if (end == command_string.size())
892 command_string.clear();
893 else
894 command_string = command_string.substr(end);
895
896 return cmd_obj;
897}
898
Greg Clayton9d855c62011-10-25 00:36:27 +0000899static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000900static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000901static void
902StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000903{
Greg Clayton9d855c62011-10-25 00:36:27 +0000904 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000905 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000906 size_t pos = s.find_first_not_of (k_white_space);
907 if (pos == std::string::npos)
908 s.clear();
909 else if (pos == 0)
910 return;
911 s.erase (0, pos);
912 }
913}
914
Greg Clayton3840cd72011-11-09 23:25:03 +0000915static size_t
916FindArgumentTerminator (const std::string &s)
917{
Greg Clayton3840cd72011-11-09 23:25:03 +0000918 const size_t s_len = s.size();
919 size_t offset = 0;
920 while (offset < s_len)
921 {
922 size_t pos = s.find ("--", offset);
923 if (pos == std::string::npos)
924 break;
925 if (pos > 0)
926 {
927 if (isspace(s[pos-1]))
928 {
929 // Check if the string ends "\s--" (where \s is a space character)
930 // or if we have "\s--\s".
931 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
932 {
Greg Clayton3840cd72011-11-09 23:25:03 +0000933 return pos;
934 }
935 }
936 }
937 offset = pos + 2;
938 }
Greg Clayton3840cd72011-11-09 23:25:03 +0000939 return std::string::npos;
940}
941
Greg Clayton9d855c62011-10-25 00:36:27 +0000942static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000943ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000944{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000945 command.clear();
946 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000947 StripLeadingSpaces (command_string);
948
949 bool result = false;
950 quote_char = '\0';
951
952 if (!command_string.empty())
953 {
954 const char first_char = command_string[0];
955 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000956 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000957 quote_char = first_char;
958 const size_t end_quote_pos = command_string.find (quote_char, 1);
959 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000960 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000961 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000962 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000963 }
964 else
965 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000966 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +0000967 if (end_quote_pos + 1 < command_string.size())
968 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
969 else
970 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000971 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000972 }
973 else
974 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000975 const size_t first_space_pos = command_string.find_first_of (k_white_space);
976 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000977 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000978 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000979 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +0000980 }
981 else
982 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000983 command.assign (command_string, 0, first_space_pos);
984 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +0000985 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000986 }
Greg Clayton9d855c62011-10-25 00:36:27 +0000987 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000988 }
Greg Clayton7268b4c2011-10-28 21:38:01 +0000989
990
991 if (!command.empty())
992 {
993 // actual commands can't start with '-' or '_'
994 if (command[0] != '-' && command[0] != '_')
995 {
996 size_t pos = command.find_first_not_of(k_valid_command_chars);
997 if (pos > 0 && pos != std::string::npos)
998 {
999 suffix.assign (command.begin() + pos, command.end());
1000 command.erase (pos);
1001 }
1002 }
1003 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001004
1005 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001006}
1007
Greg Clayton7268b4c2011-10-28 21:38:01 +00001008CommandObject *
1009CommandInterpreter::BuildAliasResult (const char *alias_name,
1010 std::string &raw_input_string,
1011 std::string &alias_result,
1012 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001013{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001014 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001015 Args cmd_args (raw_input_string.c_str());
1016 alias_cmd_obj = GetCommandObject (alias_name);
1017 StreamString result_str;
1018
1019 if (alias_cmd_obj)
1020 {
1021 std::string alias_name_str = alias_name;
1022 if ((cmd_args.GetArgumentCount() == 0)
1023 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1024 cmd_args.Unshift (alias_name);
1025
1026 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1027 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1028
1029 if (option_arg_vector_sp.get())
1030 {
1031 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1032
1033 for (int i = 0; i < option_arg_vector->size(); ++i)
1034 {
1035 OptionArgPair option_pair = (*option_arg_vector)[i];
1036 OptionArgValue value_pair = option_pair.second;
1037 int value_type = value_pair.first;
1038 std::string option = option_pair.first;
1039 std::string value = value_pair.second;
1040 if (option.compare ("<argument>") == 0)
1041 result_str.Printf (" %s", value.c_str());
1042 else
1043 {
1044 result_str.Printf (" %s", option.c_str());
1045 if (value_type != optional_argument)
1046 result_str.Printf (" ");
1047 if (value.compare ("<no_argument>") != 0)
1048 {
1049 int index = GetOptionArgumentPosition (value.c_str());
1050 if (index == 0)
1051 result_str.Printf ("%s", value.c_str());
1052 else if (index >= cmd_args.GetArgumentCount())
1053 {
1054
1055 result.AppendErrorWithFormat
1056 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1057 index);
1058 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001059 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001060 }
1061 else
1062 {
1063 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1064 if (strpos != std::string::npos)
1065 raw_input_string = raw_input_string.erase (strpos,
1066 strlen (cmd_args.GetArgumentAtIndex (index)));
1067 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1068 }
1069 }
1070 }
1071 }
1072 }
1073
1074 alias_result = result_str.GetData();
1075 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001076 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001077}
1078
Greg Claytonf5c0c722011-10-14 07:41:33 +00001079Error
1080CommandInterpreter::PreprocessCommand (std::string &command)
1081{
1082 // The command preprocessor needs to do things to the command
1083 // line before any parsing of arguments or anything else is done.
1084 // The only current stuff that gets proprocessed is anyting enclosed
1085 // in backtick ('`') characters is evaluated as an expression and
1086 // the result of the expression must be a scalar that can be substituted
1087 // into the command. An example would be:
1088 // (lldb) memory read `$rsp + 20`
1089 Error error; // Error for any expressions that might not evaluate
1090 size_t start_backtick;
1091 size_t pos = 0;
1092 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1093 {
1094 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1095 {
1096 // The backtick was preceeded by a '\' character, remove the slash
1097 // and don't treat the backtick as the start of an expression
1098 command.erase(start_backtick-1, 1);
1099 // No need to add one to start_backtick since we just deleted a char
1100 pos = start_backtick;
1101 }
1102 else
1103 {
1104 const size_t expr_content_start = start_backtick + 1;
1105 const size_t end_backtick = command.find ('`', expr_content_start);
1106 if (end_backtick == std::string::npos)
1107 return error;
1108 else if (end_backtick == expr_content_start)
1109 {
1110 // Empty expression (two backticks in a row)
1111 command.erase (start_backtick, 2);
1112 }
1113 else
1114 {
1115 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1116
1117 Target *target = m_exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001118 // Get a dummy target to allow for calculator mode while processing backticks.
1119 // This also helps break the infinite loop caused when target is null.
1120 if (!target)
1121 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001122 if (target)
1123 {
Sean Callanandaa6efe2011-12-21 22:22:58 +00001124 const bool coerce_to_id = false;
Greg Claytonf5c0c722011-10-14 07:41:33 +00001125 const bool unwind_on_error = true;
1126 const bool keep_in_memory = false;
1127 ValueObjectSP expr_result_valobj_sp;
1128 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1129 m_exe_ctx.GetFramePtr(),
1130 eExecutionPolicyOnlyWhenNeeded,
Sean Callanandaa6efe2011-12-21 22:22:58 +00001131 coerce_to_id,
1132 unwind_on_error,
1133 keep_in_memory,
Greg Claytonf5c0c722011-10-14 07:41:33 +00001134 eNoDynamicValues,
1135 expr_result_valobj_sp);
1136 if (expr_result == eExecutionCompleted)
1137 {
1138 Scalar scalar;
1139 if (expr_result_valobj_sp->ResolveValue (scalar))
1140 {
1141 command.erase (start_backtick, end_backtick - start_backtick + 1);
1142 StreamString value_strm;
1143 const bool show_type = false;
1144 scalar.GetValue (&value_strm, show_type);
1145 size_t value_string_size = value_strm.GetSize();
1146 if (value_string_size)
1147 {
1148 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1149 pos = start_backtick + value_string_size;
1150 continue;
1151 }
1152 else
1153 {
1154 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1155 }
1156 }
1157 else
1158 {
1159 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1160 }
1161 }
1162 else
1163 {
1164 if (expr_result_valobj_sp)
1165 error = expr_result_valobj_sp->GetError();
1166 if (error.Success())
1167 {
1168
1169 switch (expr_result)
1170 {
1171 case eExecutionSetupError:
1172 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1173 break;
1174 case eExecutionCompleted:
1175 break;
1176 case eExecutionDiscarded:
1177 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1178 break;
1179 case eExecutionInterrupted:
1180 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1181 break;
1182 case eExecutionTimedOut:
1183 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1184 break;
1185 }
1186 }
1187 }
1188 }
1189 }
1190 if (error.Fail())
1191 break;
1192 }
1193 }
1194 return error;
1195}
1196
1197
Caroline Ticee0da7a52010-12-09 22:52:49 +00001198bool
1199CommandInterpreter::HandleCommand (const char *command_line,
1200 bool add_to_history,
1201 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001202 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001203 bool repeat_on_empty_command,
1204 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001205
Caroline Ticee0da7a52010-12-09 22:52:49 +00001206{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001207
Caroline Ticee0da7a52010-12-09 22:52:49 +00001208 bool done = false;
1209 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001210 bool wants_raw_input = false;
1211 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001212 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001213
1214 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001215 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1216
1217 // Make a scoped cleanup object that will clear the crash description string
1218 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001219 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001220
Caroline Ticee0da7a52010-12-09 22:52:49 +00001221 if (log)
1222 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001223
Jim Inghamabab14b2010-11-04 23:08:45 +00001224 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1225
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001226 if (!no_context_switching)
1227 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +00001228
Jim Ingham949d5ac2011-02-18 00:54:25 +00001229 bool empty_command = false;
1230 bool comment_command = false;
1231 if (command_string.empty())
1232 empty_command = true;
1233 else
Chris Lattner24943d22010-06-08 16:52:24 +00001234 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001235 const char *k_space_characters = "\t\n\v\f\r ";
1236
1237 size_t non_space = command_string.find_first_not_of (k_space_characters);
1238 // Check for empty line or comment line (lines whose first
1239 // non-space character is the comment character for this interpreter)
1240 if (non_space == std::string::npos)
1241 empty_command = true;
1242 else if (command_string[non_space] == m_comment_char)
1243 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001244 else if (command_string[non_space] == m_repeat_char)
1245 {
1246 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1247 if (history_string == NULL)
1248 {
1249 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1250 result.SetStatus(eReturnStatusFailed);
1251 return false;
1252 }
1253 add_to_history = false;
1254 command_string = history_string;
1255 original_command_string = history_string;
1256 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001257 }
1258
1259 if (empty_command)
1260 {
1261 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001262 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001263 if (m_command_history.empty())
1264 {
1265 result.AppendError ("empty command");
1266 result.SetStatus(eReturnStatusFailed);
1267 return false;
1268 }
1269 else
1270 {
1271 command_line = m_repeat_command.c_str();
1272 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001273 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001274 if (m_repeat_command.empty())
1275 {
1276 result.AppendErrorWithFormat("No auto repeat.\n");
1277 result.SetStatus (eReturnStatusFailed);
1278 return false;
1279 }
1280 }
1281 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001282 }
1283 else
1284 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001285 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1286 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001287 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001288 }
1289 else if (comment_command)
1290 {
1291 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1292 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001293 }
Caroline Tice649116c2011-05-11 16:07:06 +00001294
Greg Claytonf5c0c722011-10-14 07:41:33 +00001295
1296 Error error (PreprocessCommand (command_string));
1297
1298 if (error.Fail())
1299 {
1300 result.AppendError (error.AsCString());
1301 result.SetStatus(eReturnStatusFailed);
1302 return false;
1303 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001304 // Phase 1.
1305
1306 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1307 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1308 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1309 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1310 // 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 +00001311 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001312 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001313
Caroline Ticee0da7a52010-12-09 22:52:49 +00001314 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001315 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001316 std::string next_word;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001317 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001318 {
Caroline Tice649116c2011-05-11 16:07:06 +00001319 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001320 std::string suffix;
1321 ExtractCommand (command_string, next_word, suffix, quote_char);
1322 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001323 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001324 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001325 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001326 std::string alias_result;
1327 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1328 revised_command_line.Printf ("%s", alias_result.c_str());
1329 if (cmd_obj)
1330 {
1331 wants_raw_input = cmd_obj->WantsRawCommandString ();
1332 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1333 }
Chris Lattner24943d22010-06-08 16:52:24 +00001334 }
1335 else
1336 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001337 cmd_obj = GetCommandObject (next_word.c_str());
1338 if (cmd_obj)
1339 {
1340 actual_cmd_name_len += next_word.length();
1341 revised_command_line.Printf ("%s", next_word.c_str());
1342 wants_raw_input = cmd_obj->WantsRawCommandString ();
1343 }
Caroline Tice649116c2011-05-11 16:07:06 +00001344 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001345 {
1346 revised_command_line.Printf ("%s", next_word.c_str());
1347 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001348 }
1349 }
1350 else
1351 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001352 if (cmd_obj->IsMultiwordObject ())
1353 {
1354 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1355 if (sub_cmd_obj)
1356 {
1357 actual_cmd_name_len += next_word.length() + 1;
1358 revised_command_line.Printf (" %s", next_word.c_str());
1359 cmd_obj = sub_cmd_obj;
1360 wants_raw_input = cmd_obj->WantsRawCommandString ();
1361 }
1362 else
1363 {
1364 if (quote_char)
1365 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1366 else
1367 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1368 done = true;
1369 }
1370 }
Caroline Tice649116c2011-05-11 16:07:06 +00001371 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001372 {
1373 if (quote_char)
1374 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1375 else
1376 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1377 done = true;
1378 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001379 }
1380
1381 if (cmd_obj == NULL)
1382 {
1383 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1384 result.SetStatus (eReturnStatusFailed);
1385 return false;
1386 }
1387
Greg Clayton7268b4c2011-10-28 21:38:01 +00001388 if (cmd_obj->IsMultiwordObject ())
1389 {
1390 if (!suffix.empty())
1391 {
1392
1393 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1394 next_word.c_str(),
1395 suffix.c_str());
1396 result.SetStatus (eReturnStatusFailed);
1397 return false;
1398 }
1399 }
1400 else
1401 {
1402 // If we found a normal command, we are done
1403 done = true;
1404 if (!suffix.empty())
1405 {
1406 switch (suffix[0])
1407 {
1408 case '/':
1409 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001410 {
1411 Options *command_options = cmd_obj->GetOptions();
1412 if (command_options && command_options->SupportsLongOption("gdb-format"))
1413 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001414 std::string gdb_format_option ("--gdb-format=");
1415 gdb_format_option += (suffix.c_str() + 1);
1416
1417 bool inserted = false;
1418 std::string &cmd = revised_command_line.GetString();
1419 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1420 if (arg_terminator_idx != std::string::npos)
1421 {
1422 // Insert the gdb format option before the "--" that terminates options
1423 gdb_format_option.append(1,' ');
1424 cmd.insert(arg_terminator_idx, gdb_format_option);
1425 inserted = true;
1426 }
1427
1428 if (!inserted)
1429 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1430
1431 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1432 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001433 }
1434 else
1435 {
1436 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1437 cmd_obj->GetCommandName());
1438 result.SetStatus (eReturnStatusFailed);
1439 return false;
1440 }
1441 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001442 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001443
1444 default:
1445 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1446 suffix.c_str());
1447 result.SetStatus (eReturnStatusFailed);
1448 return false;
1449
Greg Clayton7268b4c2011-10-28 21:38:01 +00001450 }
1451 }
1452 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001453 if (command_string.length() == 0)
1454 done = true;
1455
Chris Lattner24943d22010-06-08 16:52:24 +00001456 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001457
Greg Clayton7268b4c2011-10-28 21:38:01 +00001458 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001459 revised_command_line.Printf (" %s", command_string.c_str());
1460
1461 // End of Phase 1.
1462 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1463 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1464 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1465 // wants_raw_input specifies whether the Execute method expects raw input or not.
1466
1467
1468 if (log)
1469 {
1470 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1471 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1472 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1473 }
1474
1475 // Phase 2.
1476 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1477 // CommandObject, with the appropriate arguments.
1478
1479 if (cmd_obj != NULL)
1480 {
1481 if (add_to_history)
1482 {
1483 Args command_args (revised_command_line.GetData());
1484 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1485 if (repeat_command != NULL)
1486 m_repeat_command.assign(repeat_command);
1487 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001488 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001489
Jim Ingham6247dbe2011-07-12 03:12:18 +00001490 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001491 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001492 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001493 }
1494
1495 command_string = revised_command_line.GetData();
1496 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001497 std::string remainder;
1498 if (actual_cmd_name_len < command_string.length())
1499 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1500 // than cmd_obj->GetCommandName(), because name completion
1501 // allows users to enter short versions of the names,
1502 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001503
1504 // Remove any initial spaces
1505 std::string white_space (" \t\v");
1506 size_t pos = remainder.find_first_not_of (white_space);
1507 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001508 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001509
1510 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001511 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001512
1513
Greg Claytonf1252502012-02-29 04:21:24 +00001514 CommandOverrideCallback command_callback = cmd_obj->GetOverrideCallback();
1515 bool handled = false;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001516 if (wants_raw_input)
Greg Claytonf1252502012-02-29 04:21:24 +00001517 {
1518 if (command_callback)
1519 {
1520 std::string full_command (cmd_obj->GetCommandName ());
1521 full_command += ' ';
1522 full_command += remainder;
1523 const char *argv[2] = { NULL, NULL };
1524 argv[0] = full_command.c_str();
1525 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), argv);
1526 }
1527 if (!handled)
1528 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1529 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001530 else
1531 {
1532 Args cmd_args (remainder.c_str());
Greg Claytonf1252502012-02-29 04:21:24 +00001533 if (command_callback)
1534 {
1535 Args full_args (cmd_obj->GetCommandName ());
1536 full_args.AppendArguments(cmd_args);
1537 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), full_args.GetConstArgumentVector());
1538 }
1539 if (!handled)
1540 cmd_obj->ExecuteWithOptions (cmd_args, result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001541 }
1542 }
1543 else
1544 {
1545 // We didn't find the first command object, so complete the first argument.
1546 Args command_args (revised_command_line.GetData());
1547 StringList matches;
1548 int num_matches;
1549 int cursor_index = 0;
1550 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1551 bool word_complete;
1552 num_matches = HandleCompletionMatches (command_args,
1553 cursor_index,
1554 cursor_char_position,
1555 0,
1556 -1,
1557 word_complete,
1558 matches);
1559
1560 if (num_matches > 0)
1561 {
1562 std::string error_msg;
1563 error_msg.assign ("ambiguous command '");
1564 error_msg.append(command_args.GetArgumentAtIndex(0));
1565 error_msg.append ("'.");
1566
1567 error_msg.append (" Possible completions:");
1568 for (int i = 0; i < num_matches; i++)
1569 {
1570 error_msg.append ("\n\t");
1571 error_msg.append (matches.GetStringAtIndex (i));
1572 }
1573 error_msg.append ("\n");
1574 result.AppendRawError (error_msg.c_str(), error_msg.size());
1575 }
1576 else
1577 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1578
1579 result.SetStatus (eReturnStatusFailed);
1580 }
1581
Jason Molenda24c991c2011-08-25 00:20:04 +00001582 if (log)
1583 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1584
Chris Lattner24943d22010-06-08 16:52:24 +00001585 return result.Succeeded();
1586}
1587
1588int
1589CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1590 int &cursor_index,
1591 int &cursor_char_position,
1592 int match_start_point,
1593 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001594 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001595 StringList &matches)
1596{
1597 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001598 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001599
1600 // For any of the command completions a unique match will be a complete word.
1601 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001602
1603 if (cursor_index == -1)
1604 {
1605 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001606 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001607 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1608 }
1609 else if (cursor_index == 0)
1610 {
1611 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001612 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001613 num_command_matches = matches.GetSize();
1614
1615 if (num_command_matches == 1
1616 && cmd_obj && cmd_obj->IsMultiwordObject()
1617 && matches.GetStringAtIndex(0) != NULL
1618 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1619 {
1620 look_for_subcommand = true;
1621 num_command_matches = 0;
1622 matches.DeleteStringAtIndex(0);
1623 parsed_line.AppendArgument ("");
1624 cursor_index++;
1625 cursor_char_position = 0;
1626 }
1627 }
1628
1629 if (cursor_index > 0 || look_for_subcommand)
1630 {
1631 // We are completing further on into a commands arguments, so find the command and tell it
1632 // to complete the command.
1633 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001634 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001635 if (command_object == NULL)
1636 {
1637 return 0;
1638 }
1639 else
1640 {
1641 parsed_line.Shift();
1642 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001643 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001644 cursor_index,
1645 cursor_char_position,
1646 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001647 max_return_elements,
1648 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001649 matches);
1650 }
1651 }
1652
1653 return num_command_matches;
1654
1655}
1656
1657int
1658CommandInterpreter::HandleCompletion (const char *current_line,
1659 const char *cursor,
1660 const char *last_char,
1661 int match_start_point,
1662 int max_return_elements,
1663 StringList &matches)
1664{
1665 // We parse the argument up to the cursor, so the last argument in parsed_line is
1666 // the one containing the cursor, and the cursor is after the last character.
1667
1668 Args parsed_line(current_line, last_char - current_line);
1669 Args partial_parsed_line(current_line, cursor - current_line);
1670
Jim Ingham6247dbe2011-07-12 03:12:18 +00001671 // Don't complete comments, and if the line we are completing is just the history repeat character,
1672 // substitute the appropriate history line.
1673 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1674 if (first_arg)
1675 {
1676 if (first_arg[0] == m_comment_char)
1677 return 0;
1678 else if (first_arg[0] == m_repeat_char)
1679 {
1680 const char *history_string = FindHistoryString (first_arg);
1681 if (history_string != NULL)
1682 {
1683 matches.Clear();
1684 matches.InsertStringAtIndex(0, history_string);
1685 return -2;
1686 }
1687 else
1688 return 0;
1689
1690 }
1691 }
1692
1693
Chris Lattner24943d22010-06-08 16:52:24 +00001694 int num_args = partial_parsed_line.GetArgumentCount();
1695 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1696 int cursor_char_position;
1697
1698 if (cursor_index == -1)
1699 cursor_char_position = 0;
1700 else
1701 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001702
1703 if (cursor > current_line && cursor[-1] == ' ')
1704 {
1705 // We are just after a space. If we are in an argument, then we will continue
1706 // parsing, but if we are between arguments, then we have to complete whatever the next
1707 // element would be.
1708 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1709 // protected by a quote) then the space will also be in the parsed argument...
1710
1711 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1712 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1713 {
1714 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1715 cursor_index++;
1716 cursor_char_position = 0;
1717 }
1718 }
Chris Lattner24943d22010-06-08 16:52:24 +00001719
1720 int num_command_matches;
1721
1722 matches.Clear();
1723
1724 // Only max_return_elements == -1 is supported at present:
1725 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001726 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001727 num_command_matches = HandleCompletionMatches (parsed_line,
1728 cursor_index,
1729 cursor_char_position,
1730 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001731 max_return_elements,
1732 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001733 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001734
1735 if (num_command_matches <= 0)
1736 return num_command_matches;
1737
1738 if (num_args == 0)
1739 {
1740 // If we got an empty string, insert nothing.
1741 matches.InsertStringAtIndex(0, "");
1742 }
1743 else
1744 {
1745 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1746 // put an empty string in element 0.
1747 std::string command_partial_str;
1748 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001749 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1750 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001751
1752 std::string common_prefix;
1753 matches.LongestCommonPrefix (common_prefix);
1754 int partial_name_len = command_partial_str.size();
1755
1756 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001757 // Only do this if the completer told us this was a complete word, however...
1758 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001759 {
1760 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1761 if (quote_char != '\0')
1762 common_prefix.push_back(quote_char);
1763
1764 common_prefix.push_back(' ');
1765 }
1766 common_prefix.erase (0, partial_name_len);
1767 matches.InsertStringAtIndex(0, common_prefix.c_str());
1768 }
1769 return num_command_matches;
1770}
1771
Chris Lattner24943d22010-06-08 16:52:24 +00001772
1773CommandInterpreter::~CommandInterpreter ()
1774{
1775}
1776
1777const char *
1778CommandInterpreter::GetPrompt ()
1779{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001780 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001781}
1782
1783void
1784CommandInterpreter::SetPrompt (const char *new_prompt)
1785{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001786 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001787}
1788
Jim Ingham5e16ef52010-10-04 19:49:29 +00001789size_t
Greg Clayton58928562011-02-09 01:08:52 +00001790CommandInterpreter::GetConfirmationInputReaderCallback
1791(
1792 void *baton,
1793 InputReader &reader,
1794 lldb::InputReaderAction action,
1795 const char *bytes,
1796 size_t bytes_len
1797)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001798{
Greg Clayton58928562011-02-09 01:08:52 +00001799 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001800 bool *response_ptr = (bool *) baton;
1801
1802 switch (action)
1803 {
1804 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001805 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001806 {
1807 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001808 {
Greg Clayton58928562011-02-09 01:08:52 +00001809 out_file.Printf ("%s", reader.GetPrompt());
1810 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001811 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001812 }
1813 break;
1814
1815 case eInputReaderDeactivate:
1816 break;
1817
1818 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001819 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001820 {
Greg Clayton58928562011-02-09 01:08:52 +00001821 out_file.Printf ("%s", reader.GetPrompt());
1822 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001823 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001824 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001825
1826 case eInputReaderAsynchronousOutputWritten:
1827 break;
1828
Jim Ingham5e16ef52010-10-04 19:49:29 +00001829 case eInputReaderGotToken:
1830 if (bytes_len == 0)
1831 {
1832 reader.SetIsDone(true);
1833 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001834 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001835 {
1836 *response_ptr = true;
1837 reader.SetIsDone(true);
1838 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001839 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001840 {
1841 *response_ptr = false;
1842 reader.SetIsDone(true);
1843 }
1844 else
1845 {
Greg Clayton58928562011-02-09 01:08:52 +00001846 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001847 {
Jim Ingham26183802011-11-17 01:22:00 +00001848 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001849 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001850 }
1851 }
1852 break;
1853
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001854 case eInputReaderInterrupt:
1855 case eInputReaderEndOfFile:
1856 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1857 reader.SetIsDone (true);
1858 break;
1859
Jim Ingham5e16ef52010-10-04 19:49:29 +00001860 case eInputReaderDone:
1861 break;
1862 }
1863
1864 return bytes_len;
1865
1866}
1867
1868bool
1869CommandInterpreter::Confirm (const char *message, bool default_answer)
1870{
Jim Ingham93057472010-10-04 22:44:14 +00001871 // Check AutoConfirm first:
1872 if (m_debugger.GetAutoConfirm())
1873 return default_answer;
1874
Jim Ingham5e16ef52010-10-04 19:49:29 +00001875 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1876 bool response = default_answer;
1877 if (reader_sp)
1878 {
1879 std::string prompt(message);
1880 prompt.append(": [");
1881 if (default_answer)
1882 prompt.append ("Y/n] ");
1883 else
1884 prompt.append ("y/N] ");
1885
1886 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1887 &response, // baton
1888 eInputReaderGranularityLine, // token size, to pass to callback function
1889 NULL, // end token
1890 prompt.c_str(), // prompt
1891 true)); // echo input
1892 if (err.Success())
1893 {
1894 GetDebugger().PushInputReader (reader_sp);
1895 }
1896 reader_sp->WaitOnReaderIsDone();
1897 }
1898 return response;
1899}
1900
1901
Chris Lattner24943d22010-06-08 16:52:24 +00001902void
1903CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1904{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001905 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001906
1907 if (cmd_obj_sp != NULL)
1908 {
1909 CommandObject *cmd_obj = cmd_obj_sp.get();
1910 if (cmd_obj->IsCrossRefObject ())
1911 cmd_obj->AddObject (object_type);
1912 }
1913}
1914
Chris Lattner24943d22010-06-08 16:52:24 +00001915OptionArgVectorSP
1916CommandInterpreter::GetAliasOptions (const char *alias_name)
1917{
1918 OptionArgMap::iterator pos;
1919 OptionArgVectorSP ret_val;
1920
1921 std::string alias (alias_name);
1922
1923 if (HasAliasOptions())
1924 {
1925 pos = m_alias_options.find (alias);
1926 if (pos != m_alias_options.end())
1927 ret_val = pos->second;
1928 }
1929
1930 return ret_val;
1931}
1932
1933void
1934CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1935{
1936 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1937 if (pos != m_alias_options.end())
1938 {
1939 m_alias_options.erase (pos);
1940 }
1941}
1942
1943void
1944CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1945{
1946 m_alias_options[alias_name] = option_arg_vector_sp;
1947}
1948
1949bool
1950CommandInterpreter::HasCommands ()
1951{
1952 return (!m_command_dict.empty());
1953}
1954
1955bool
1956CommandInterpreter::HasAliases ()
1957{
1958 return (!m_alias_dict.empty());
1959}
1960
1961bool
1962CommandInterpreter::HasUserCommands ()
1963{
1964 return (!m_user_dict.empty());
1965}
1966
1967bool
1968CommandInterpreter::HasAliasOptions ()
1969{
1970 return (!m_alias_options.empty());
1971}
1972
Chris Lattner24943d22010-06-08 16:52:24 +00001973void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001974CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1975 const char *alias_name,
1976 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001977 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001978 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001979{
1980 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001981
1982 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001983
Caroline Tice44c841d2010-12-07 19:58:26 +00001984 // Make sure that the alias name is the 0th element in cmd_args
1985 std::string alias_name_str = alias_name;
1986 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1987 cmd_args.Unshift (alias_name);
1988
1989 Args new_args (alias_cmd_obj->GetCommandName());
1990 if (new_args.GetArgumentCount() == 2)
1991 new_args.Shift();
1992
Chris Lattner24943d22010-06-08 16:52:24 +00001993 if (option_arg_vector_sp.get())
1994 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001995 if (wants_raw_input)
1996 {
1997 // We have a command that both has command options and takes raw input. Make *sure* it has a
1998 // " -- " in the right place in the raw_input_string.
1999 size_t pos = raw_input_string.find(" -- ");
2000 if (pos == std::string::npos)
2001 {
2002 // None found; assume it goes at the beginning of the raw input string
2003 raw_input_string.insert (0, " -- ");
2004 }
2005 }
Chris Lattner24943d22010-06-08 16:52:24 +00002006
2007 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2008 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002009 std::vector<bool> used (old_size + 1, false);
2010
2011 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002012
2013 for (int i = 0; i < option_arg_vector->size(); ++i)
2014 {
2015 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002016 OptionArgValue value_pair = option_pair.second;
2017 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002018 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002019 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002020 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002021 {
2022 if (!wants_raw_input
2023 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2024 new_args.AppendArgument (value.c_str());
2025 }
Chris Lattner24943d22010-06-08 16:52:24 +00002026 else
2027 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002028 if (value_type != optional_argument)
2029 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002030 if (value.compare ("<no-argument>") != 0)
2031 {
2032 int index = GetOptionArgumentPosition (value.c_str());
2033 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002034 {
Chris Lattner24943d22010-06-08 16:52:24 +00002035 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002036 if (value_type != optional_argument)
2037 new_args.AppendArgument (value.c_str());
2038 else
2039 {
2040 char buffer[255];
2041 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2042 new_args.AppendArgument (buffer);
2043 }
2044
2045 }
Chris Lattner24943d22010-06-08 16:52:24 +00002046 else if (index >= cmd_args.GetArgumentCount())
2047 {
2048 result.AppendErrorWithFormat
2049 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2050 index);
2051 result.SetStatus (eReturnStatusFailed);
2052 return;
2053 }
2054 else
2055 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002056 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2057 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2058 if (strpos != std::string::npos)
2059 {
2060 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2061 }
2062
2063 if (value_type != optional_argument)
2064 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2065 else
2066 {
2067 char buffer[255];
2068 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2069 cmd_args.GetArgumentAtIndex (index));
2070 new_args.AppendArgument (buffer);
2071 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002072 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002073 }
2074 }
2075 }
2076 }
2077
2078 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2079 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002080 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002081 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2082 }
2083
2084 cmd_args.Clear();
2085 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2086 }
2087 else
2088 {
2089 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002090 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2091 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2092 // input string.
2093 if (wants_raw_input)
2094 {
2095 cmd_args.Clear();
2096 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2097 }
Chris Lattner24943d22010-06-08 16:52:24 +00002098 return;
2099 }
2100
2101 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2102 return;
2103}
2104
2105
2106int
2107CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2108{
2109 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2110 // of zero.
2111
2112 char *cptr = (char *) in_string;
2113
2114 // Does it start with '%'
2115 if (cptr[0] == '%')
2116 {
2117 ++cptr;
2118
2119 // Is the rest of it entirely digits?
2120 if (isdigit (cptr[0]))
2121 {
2122 const char *start = cptr;
2123 while (isdigit (cptr[0]))
2124 ++cptr;
2125
2126 // We've gotten to the end of the digits; are we at the end of the string?
2127 if (cptr[0] == '\0')
2128 position = atoi (start);
2129 }
2130 }
2131
2132 return position;
2133}
2134
2135void
2136CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2137{
Jim Ingham574c3d62011-08-12 23:34:31 +00002138 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002139 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002140 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002141 // In the current working directory we don't load any program specific
2142 // .lldbinit files, we only look for a "./.lldbinit" file.
2143 if (m_skip_lldbinit_files)
2144 return;
2145
2146 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002147 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002148 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002149 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002150 // If we aren't looking in the current working directory we are looking
2151 // in the home directory. We will first see if there is an application
2152 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2153 // "-" and the name of the program. If this file doesn't exist, we fall
2154 // back to just the "~/.lldbinit" file. We also obey any requests to not
2155 // load the init files.
2156 const char *init_file_path = "~/.lldbinit";
2157
2158 if (m_skip_app_init_files == false)
2159 {
2160 FileSpec program_file_spec (Host::GetProgramFileSpec());
2161 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002162
Greg Claytond6edcb52011-09-11 00:01:44 +00002163 if (program_name)
2164 {
2165 char program_init_file_name[PATH_MAX];
2166 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2167 init_file.SetFile (program_init_file_name, true);
2168 if (!init_file.Exists())
2169 init_file.Clear();
2170 }
2171 }
2172
2173 if (!init_file && !m_skip_lldbinit_files)
2174 init_file.SetFile (init_file_path, true);
2175 }
2176
Chris Lattner24943d22010-06-08 16:52:24 +00002177 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2178 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2179
2180 if (init_file.Exists())
2181 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002182 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2183 bool stop_on_continue = true;
2184 bool stop_on_error = false;
2185 bool echo_commands = false;
2186 bool print_results = false;
2187
2188 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002189 }
2190 else
2191 {
2192 // nothing to be done if the file doesn't exist
2193 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2194 }
2195}
2196
Greg Claytonb72d0f02011-04-12 05:54:46 +00002197PlatformSP
2198CommandInterpreter::GetPlatform (bool prefer_target_platform)
2199{
2200 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002201 if (prefer_target_platform)
2202 {
2203 Target *target = m_exe_ctx.GetTargetPtr();
2204 if (target)
2205 platform_sp = target->GetPlatform();
2206 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002207
2208 if (!platform_sp)
2209 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2210 return platform_sp;
2211}
2212
Jim Ingham949d5ac2011-02-18 00:54:25 +00002213void
Jim Inghama4fede32011-03-11 01:51:49 +00002214CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002215 ExecutionContext *override_context,
2216 bool stop_on_continue,
2217 bool stop_on_error,
2218 bool echo_commands,
2219 bool print_results,
2220 CommandReturnObject &result)
2221{
2222 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002223
2224 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2225 // Make sure you reset this value anywhere you return from the function.
2226
2227 bool old_async_execution = m_debugger.GetAsyncExecution();
2228
2229 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2230 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2231
2232 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002233 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002234
2235 if (!stop_on_continue)
2236 {
2237 m_debugger.SetAsyncExecution (false);
2238 }
2239
2240 for (int idx = 0; idx < num_lines; idx++)
2241 {
2242 const char *cmd = commands.GetStringAtIndex(idx);
2243 if (cmd[0] == '\0')
2244 continue;
2245
Jim Ingham949d5ac2011-02-18 00:54:25 +00002246 if (echo_commands)
2247 {
2248 result.AppendMessageWithFormat ("%s %s\n",
2249 GetPrompt(),
2250 cmd);
2251 }
2252
Greg Claytonaa378b12011-02-20 02:15:07 +00002253 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002254 // If override_context is not NULL, pass no_context_switching = true for
2255 // HandleCommand() since we updated our context already.
2256 bool success = HandleCommand(cmd, false, tmp_result,
2257 NULL, /* override_context */
2258 true, /* repeat_on_empty_command */
2259 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002260
2261 if (print_results)
2262 {
2263 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002264 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002265 }
2266
2267 if (!success || !tmp_result.Succeeded())
2268 {
2269 if (stop_on_error)
2270 {
2271 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
2272 idx, cmd);
2273 result.SetStatus (eReturnStatusFailed);
2274 m_debugger.SetAsyncExecution (old_async_execution);
2275 return;
2276 }
2277 else if (print_results)
2278 {
2279 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
2280 idx + 1,
2281 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002282 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002283 }
2284 }
2285
Caroline Tice4a348082011-05-02 20:41:46 +00002286 if (result.GetImmediateOutputStream())
2287 result.GetImmediateOutputStream()->Flush();
2288
2289 if (result.GetImmediateErrorStream())
2290 result.GetImmediateErrorStream()->Flush();
2291
Jim Ingham949d5ac2011-02-18 00:54:25 +00002292 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2293 // could be running (for instance in Breakpoint Commands.
2294 // So we check the return value to see if it is has running in it.
2295 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2296 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2297 {
2298 if (stop_on_continue)
2299 {
2300 // If we caused the target to proceed, and we're going to stop in that case, set the
2301 // status in our real result before returning. This is an error if the continue was not the
2302 // last command in the set of commands to be run.
2303 if (idx != num_lines - 1)
2304 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2305 idx + 1, cmd);
2306 else
2307 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2308
2309 result.SetStatus(tmp_result.GetStatus());
2310 m_debugger.SetAsyncExecution (old_async_execution);
2311
2312 return;
2313 }
2314 }
2315
2316 }
2317
2318 result.SetStatus (eReturnStatusSuccessFinishResult);
2319 m_debugger.SetAsyncExecution (old_async_execution);
2320
2321 return;
2322}
2323
2324void
2325CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2326 ExecutionContext *context,
2327 bool stop_on_continue,
2328 bool stop_on_error,
2329 bool echo_command,
2330 bool print_result,
2331 CommandReturnObject &result)
2332{
2333 if (cmd_file.Exists())
2334 {
2335 bool success;
2336 StringList commands;
2337 success = commands.ReadFileLines(cmd_file);
2338 if (!success)
2339 {
2340 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2341 result.SetStatus (eReturnStatusFailed);
2342 return;
2343 }
2344 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
2345 }
2346 else
2347 {
2348 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2349 cmd_file.GetFilename().AsCString());
2350 result.SetStatus (eReturnStatusFailed);
2351 return;
2352 }
2353}
2354
Chris Lattner24943d22010-06-08 16:52:24 +00002355ScriptInterpreter *
2356CommandInterpreter::GetScriptInterpreter ()
2357{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002358 if (m_script_interpreter_ap.get() != NULL)
2359 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002360
Caroline Tice0aa2e552011-01-14 00:29:16 +00002361 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2362 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002363 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002364 case eScriptLanguagePython:
2365#ifndef LLDB_DISABLE_PYTHON
2366 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2367 break;
2368#else
2369 // Fall through to the None case when python is disabled
2370#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002371 case eScriptLanguageNone:
2372 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2373 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002374 default:
2375 break;
2376 };
2377
2378 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002379}
2380
2381
2382
2383bool
2384CommandInterpreter::GetSynchronous ()
2385{
2386 return m_synchronous_execution;
2387}
2388
2389void
2390CommandInterpreter::SetSynchronous (bool value)
2391{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002392 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002393}
2394
2395void
2396CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2397 const char *word_text,
2398 const char *separator,
2399 const char *help_text,
2400 uint32_t max_word_len)
2401{
Greg Clayton238c0a12010-09-18 01:14:36 +00002402 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2403
Chris Lattner24943d22010-06-08 16:52:24 +00002404 int indent_size = max_word_len + strlen (separator) + 2;
2405
2406 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002407
2408 StreamString text_strm;
2409 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2410
2411 size_t len = text_strm.GetSize();
2412 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002413 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002414 {
2415 text_strm.EOL();
2416 len = text_strm.GetSize();
2417 }
Chris Lattner24943d22010-06-08 16:52:24 +00002418
2419 if (len < max_columns)
2420 {
2421 // Output it as a single line.
2422 strm.Printf ("%s", text);
2423 }
2424 else
2425 {
2426 // We need to break it up into multiple lines.
2427 bool first_line = true;
2428 int text_width;
2429 int start = 0;
2430 int end = start;
2431 int final_end = strlen (text);
2432 int sub_len;
2433
2434 while (end < final_end)
2435 {
2436 if (first_line)
2437 text_width = max_columns - 1;
2438 else
2439 text_width = max_columns - indent_size - 1;
2440
2441 // Don't start the 'text' on a space, since we're already outputting the indentation.
2442 if (!first_line)
2443 {
2444 while ((start < final_end) && (text[start] == ' '))
2445 start++;
2446 }
2447
2448 end = start + text_width;
2449 if (end > final_end)
2450 end = final_end;
2451 else
2452 {
2453 // If we're not at the end of the text, make sure we break the line on white space.
2454 while (end > start
2455 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2456 end--;
2457 }
2458
2459 sub_len = end - start;
2460 if (start != 0)
2461 strm.EOL();
2462 if (!first_line)
2463 strm.Indent();
2464 else
2465 first_line = false;
2466 assert (start <= final_end);
2467 assert (start + sub_len <= final_end);
2468 if (sub_len > 0)
2469 strm.Write (text + start, sub_len);
2470 start = end + 1;
2471 }
2472 }
2473 strm.EOL();
2474 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002475}
2476
2477void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002478CommandInterpreter::OutputHelpText (Stream &strm,
2479 const char *word_text,
2480 const char *separator,
2481 const char *help_text,
2482 uint32_t max_word_len)
2483{
2484 int indent_size = max_word_len + strlen (separator) + 2;
2485
2486 strm.IndentMore (indent_size);
2487
2488 StreamString text_strm;
2489 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2490
2491 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2492 bool first_line = true;
2493
2494 size_t len = text_strm.GetSize();
2495 const char *text = text_strm.GetData();
2496
2497 uint32_t chars_left = max_columns;
2498
2499 for (uint32_t i = 0; i < len; i++)
2500 {
2501 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2502 {
2503 first_line = false;
2504 chars_left = max_columns - indent_size;
2505 strm.EOL();
2506 strm.Indent();
2507 }
2508 else
2509 {
2510 strm.PutChar(text[i]);
2511 chars_left--;
2512 }
2513
2514 }
2515
2516 strm.EOL();
2517 strm.IndentLess(indent_size);
2518}
2519
2520void
Chris Lattner24943d22010-06-08 16:52:24 +00002521CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2522 StringList &commands_found, StringList &commands_help)
2523{
2524 CommandObject::CommandMap::const_iterator pos;
2525 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2526 CommandObject *sub_cmd_obj;
2527
2528 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2529 {
2530 const char * command_name = pos->first.c_str();
2531 sub_cmd_obj = pos->second.get();
2532 StreamString complete_command_name;
2533
2534 complete_command_name.Printf ("%s %s", prefix, command_name);
2535
Greg Clayton238c0a12010-09-18 01:14:36 +00002536 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002537 {
2538 commands_found.AppendString (complete_command_name.GetData());
2539 commands_help.AppendString (sub_cmd_obj->GetHelp());
2540 }
2541
2542 if (sub_cmd_obj->IsMultiwordObject())
2543 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2544 commands_help);
2545 }
2546
2547}
2548
2549void
2550CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2551 StringList &commands_help)
2552{
2553 CommandObject::CommandMap::const_iterator pos;
2554
2555 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2556 {
2557 const char *command_name = pos->first.c_str();
2558 CommandObject *cmd_obj = pos->second.get();
2559
Greg Clayton238c0a12010-09-18 01:14:36 +00002560 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002561 {
2562 commands_found.AppendString (command_name);
2563 commands_help.AppendString (cmd_obj->GetHelp());
2564 }
2565
2566 if (cmd_obj->IsMultiwordObject())
2567 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2568
2569 }
2570}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002571
2572
2573void
2574CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2575{
2576 m_exe_ctx.Clear();
2577
2578 if (override_context != NULL)
2579 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002580 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002581 }
2582 else
2583 {
2584 TargetSP target_sp (m_debugger.GetSelectedTarget());
2585 if (target_sp)
2586 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002587 m_exe_ctx.SetTargetSP (target_sp);
2588 ProcessSP process_sp (target_sp->GetProcessSP());
2589 m_exe_ctx.SetProcessSP (process_sp);
2590 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002591 {
Greg Clayton13d24fb2012-01-29 20:56:30 +00002592 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
Greg Clayton567e7f32011-09-22 04:58:26 +00002593 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002594 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002595 m_exe_ctx.SetThreadSP (thread_sp);
2596 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2597 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002598 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002599 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002600 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002601 if (frame_sp)
2602 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002603 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002604 if (frame_sp)
2605 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002606 }
2607 }
2608 }
2609 }
2610}
2611
Jim Ingham6247dbe2011-07-12 03:12:18 +00002612void
2613CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2614{
2615 DumpHistory (stream, 0, count - 1);
2616}
2617
2618void
2619CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2620{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002621 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2622 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002623 {
2624 if (!m_command_history[i].empty())
2625 {
2626 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002627 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002628 }
2629 }
2630}
2631
2632const char *
2633CommandInterpreter::FindHistoryString (const char *input_str) const
2634{
2635 if (input_str[0] != m_repeat_char)
2636 return NULL;
2637 if (input_str[1] == '-')
2638 {
2639 bool success;
2640 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2641 if (!success)
2642 return NULL;
2643 if (idx > m_command_history.size())
2644 return NULL;
2645 idx = m_command_history.size() - idx;
2646 return m_command_history[idx].c_str();
2647
2648 }
2649 else if (input_str[1] == m_repeat_char)
2650 {
2651 if (m_command_history.empty())
2652 return NULL;
2653 else
2654 return m_command_history.back().c_str();
2655 }
2656 else
2657 {
2658 bool success;
2659 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2660 if (!success)
2661 return NULL;
2662 if (idx >= m_command_history.size())
2663 return NULL;
2664 return m_command_history[idx].c_str();
2665 }
2666}