blob: 55552385942cf02601a94b1d97ecd46ed5e02bbb [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 }
Sean Callananfc58af22012-05-04 23:15:02 +0000116
117 cmd_obj_sp = GetCommandSPExact ("process attach", false);
118 if (cmd_obj_sp)
119 {
120 AddAlias ("attach", cmd_obj_sp);
121 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000122
123 cmd_obj_sp = GetCommandSPExact ("process continue", false);
124 if (cmd_obj_sp)
125 {
126 AddAlias ("c", cmd_obj_sp);
127 AddAlias ("continue", cmd_obj_sp);
128 }
129
130 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
131 if (cmd_obj_sp)
132 AddAlias ("b", cmd_obj_sp);
133
134 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
135 if (cmd_obj_sp)
136 AddAlias ("bt", cmd_obj_sp);
137
138 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
139 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000140 {
141 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000142 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000143 }
144
145 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
146 if (cmd_obj_sp)
147 {
148 AddAlias ("nexti", cmd_obj_sp);
149 AddAlias ("ni", cmd_obj_sp);
150 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000151
152 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
153 if (cmd_obj_sp)
154 {
155 AddAlias ("s", cmd_obj_sp);
156 AddAlias ("step", cmd_obj_sp);
157 }
158
159 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
160 if (cmd_obj_sp)
161 {
162 AddAlias ("n", cmd_obj_sp);
163 AddAlias ("next", cmd_obj_sp);
164 }
165
166 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
167 if (cmd_obj_sp)
168 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000169 AddAlias ("finish", cmd_obj_sp);
170 }
171
Jim Ingham59355252011-12-02 01:12:59 +0000172 cmd_obj_sp = GetCommandSPExact ("frame select", false);
173 if (cmd_obj_sp)
174 {
175 AddAlias ("f", cmd_obj_sp);
176 }
177
Caroline Tice5ddbe212011-05-06 21:37:15 +0000178 cmd_obj_sp = GetCommandSPExact ("source list", false);
179 if (cmd_obj_sp)
180 {
181 AddAlias ("l", cmd_obj_sp);
182 AddAlias ("list", cmd_obj_sp);
183 }
184
185 cmd_obj_sp = GetCommandSPExact ("memory read", false);
186 if (cmd_obj_sp)
187 AddAlias ("x", cmd_obj_sp);
188
189 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
190 if (cmd_obj_sp)
191 AddAlias ("up", cmd_obj_sp);
192
193 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
194 if (cmd_obj_sp)
195 AddAlias ("down", cmd_obj_sp);
196
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000197 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000198 if (cmd_obj_sp)
199 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000200
201 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
202 if (cmd_obj_sp)
203 AddAlias ("dis", cmd_obj_sp);
204
205 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
206 if (cmd_obj_sp)
207 AddAlias ("di", cmd_obj_sp);
208
209
Jason Molenda730cae02011-10-22 01:30:52 +0000210
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000211 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000212 if (cmd_obj_sp)
213 AddAlias ("undisplay", cmd_obj_sp);
214
Caroline Tice5ddbe212011-05-06 21:37:15 +0000215 cmd_obj_sp = GetCommandSPExact ("target create", false);
216 if (cmd_obj_sp)
217 AddAlias ("file", cmd_obj_sp);
218
219 cmd_obj_sp = GetCommandSPExact ("target modules", false);
220 if (cmd_obj_sp)
221 AddAlias ("image", cmd_obj_sp);
222
223
224 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000225
Caroline Tice5ddbe212011-05-06 21:37:15 +0000226 cmd_obj_sp = GetCommandSPExact ("expression", false);
227 if (cmd_obj_sp)
228 {
229 AddAlias ("expr", cmd_obj_sp);
230
231 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
232 AddAlias ("p", cmd_obj_sp);
233 AddAlias ("print", cmd_obj_sp);
234 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
235 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
236
237 alias_arguments_vector_sp.reset (new OptionArgVector);
238 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
239 AddAlias ("po", cmd_obj_sp);
240 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
241 }
242
243 cmd_obj_sp = GetCommandSPExact ("process launch", false);
244 if (cmd_obj_sp)
245 {
246 alias_arguments_vector_sp.reset (new OptionArgVector);
247 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
248 AddAlias ("r", cmd_obj_sp);
249 AddAlias ("run", cmd_obj_sp);
250 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
251 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
252 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000253
254 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
255 if (cmd_obj_sp)
256 {
257 AddAlias ("add-dsym", cmd_obj_sp);
258 }
Chris Lattner24943d22010-06-08 16:52:24 +0000259}
260
Chris Lattner24943d22010-06-08 16:52:24 +0000261const char *
262CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
263{
264 // This function has not yet been implemented.
265
266 // Look for any embedded script command
267 // If found,
268 // get interpreter object from the command dictionary,
269 // call execute_one_command on it,
270 // get the results as a string,
271 // substitute that string for current stuff.
272
273 return arg;
274}
275
276
277void
278CommandInterpreter::LoadCommandDictionary ()
279{
280 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
281
282 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
283 //
284 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
285 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
286 // the cross-referencing stuff) are created!!!
287 //
288 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
289
290
291 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
292 // are created. This is so that when another command is created that needs to go into a crossref object,
293 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
294 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
295
Chris Lattner24943d22010-06-08 16:52:24 +0000296 // Non-CommandObjectCrossref commands can now be created.
297
Caroline Tice5bc8c972010-09-20 20:44:43 +0000298 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000299
Greg Clayton238c0a12010-09-18 01:14:36 +0000300 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000301 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000302 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000303 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000304 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
305 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000306// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000307 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000308 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000309 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000310 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
311 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000312 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000313 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000314 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000315 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000316 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000317 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000318 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000319 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
320 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000321 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000322 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000323 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000324
325 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000326 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000327 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000328 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000329 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000330 if (break_regex_cmd_ap.get())
331 {
332 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
333 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
334 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000335 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000336 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000337 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000338 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
339 {
340 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
341 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
342 }
343 }
Jim Inghame56493f2011-03-22 02:29:32 +0000344
345 std::auto_ptr<CommandObjectRegexCommand>
346 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000347 "_regexp-down",
348 "Go down \"n\" frames in the stack (1 frame by default).",
349 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000350 if (down_regex_cmd_ap.get())
351 {
352 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
353 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
354 {
355 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
356 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
357 }
358 }
359
360 std::auto_ptr<CommandObjectRegexCommand>
361 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000362 "_regexp-up",
363 "Go up \"n\" frames in the stack (1 frame by default).",
364 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000365 if (up_regex_cmd_ap.get())
366 {
367 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
368 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
369 {
370 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
371 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
372 }
373 }
Jason Molenda730cae02011-10-22 01:30:52 +0000374
375 std::auto_ptr<CommandObjectRegexCommand>
376 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000377 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000378 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000379 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000380 if (display_regex_cmd_ap.get())
381 {
382 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
383 {
384 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
385 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
386 }
387 }
388
389 std::auto_ptr<CommandObjectRegexCommand>
390 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000391 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000392 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000393 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000394 if (undisplay_regex_cmd_ap.get())
395 {
396 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
397 {
398 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
399 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
400 }
401 }
402
Chris Lattner24943d22010-06-08 16:52:24 +0000403}
404
405int
406CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
407 StringList &matches)
408{
409 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
410
411 if (include_aliases)
412 {
413 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
414 }
415
416 return matches.GetSize();
417}
418
419CommandObjectSP
420CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
421{
422 CommandObject::CommandMap::iterator pos;
423 CommandObjectSP ret_val;
424
425 std::string cmd(cmd_cstr);
426
427 if (HasCommands())
428 {
429 pos = m_command_dict.find(cmd);
430 if (pos != m_command_dict.end())
431 ret_val = pos->second;
432 }
433
434 if (include_aliases && HasAliases())
435 {
436 pos = m_alias_dict.find(cmd);
437 if (pos != m_alias_dict.end())
438 ret_val = pos->second;
439 }
440
441 if (HasUserCommands())
442 {
443 pos = m_user_dict.find(cmd);
444 if (pos != m_user_dict.end())
445 ret_val = pos->second;
446 }
447
448 if (!exact && ret_val == NULL)
449 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000450 // We will only get into here if we didn't find any exact matches.
451
452 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
453
Chris Lattner24943d22010-06-08 16:52:24 +0000454 StringList local_matches;
455 if (matches == NULL)
456 matches = &local_matches;
457
Jim Inghamd40f8a62010-07-06 22:46:59 +0000458 unsigned int num_cmd_matches = 0;
459 unsigned int num_alias_matches = 0;
460 unsigned int num_user_matches = 0;
461
462 // Look through the command dictionaries one by one, and if we get only one match from any of
463 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
464
Chris Lattner24943d22010-06-08 16:52:24 +0000465 if (HasCommands())
466 {
467 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
468 }
469
470 if (num_cmd_matches == 1)
471 {
472 cmd.assign(matches->GetStringAtIndex(0));
473 pos = m_command_dict.find(cmd);
474 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000475 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000476 }
477
Jim Ingham9a574172010-06-24 20:28:42 +0000478 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000479 {
480 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
481
482 }
483
Jim Inghamd40f8a62010-07-06 22:46:59 +0000484 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000485 {
486 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
487 pos = m_alias_dict.find(cmd);
488 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000489 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000490 }
491
Jim Ingham9a574172010-06-24 20:28:42 +0000492 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000493 {
494 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
495 }
496
Jim Inghamd40f8a62010-07-06 22:46:59 +0000497 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000498 {
499 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
500
501 pos = m_user_dict.find (cmd);
502 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000503 user_match_sp = pos->second;
504 }
505
506 // If we got exactly one match, return that, otherwise return the match list.
507
508 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
509 {
510 if (num_cmd_matches)
511 return real_match_sp;
512 else if (num_alias_matches)
513 return alias_match_sp;
514 else
515 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000516 }
517 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000518 else if (matches && ret_val != NULL)
519 {
520 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000521 }
522
523
524 return ret_val;
525}
526
Greg Claytond12aeab2011-04-20 16:37:46 +0000527bool
528CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
529{
530 if (name && name[0])
531 {
532 std::string name_sstr(name);
533 if (!can_replace)
534 {
535 if (m_command_dict.find (name_sstr) != m_command_dict.end())
536 return false;
537 }
538 m_command_dict[name_sstr] = cmd_sp;
539 return true;
540 }
541 return false;
542}
543
Enrico Granata6b1596d2011-08-16 23:24:13 +0000544bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000545CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000546 const lldb::CommandObjectSP &cmd_sp,
547 bool can_replace)
548{
Enrico Granata6010ace2011-11-07 22:57:04 +0000549 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000550 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000551
552 const char* name_cstr = name.c_str();
553
554 // do not allow replacement of internal commands
555 if (CommandExists(name_cstr))
556 return false;
557
558 if (can_replace == false && UserCommandExists(name_cstr))
559 return false;
560
561 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000562 return true;
563 }
564 return false;
565}
Greg Claytond12aeab2011-04-20 16:37:46 +0000566
Jim Inghamd40f8a62010-07-06 22:46:59 +0000567CommandObjectSP
568CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000569{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000570 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
571 CommandObjectSP ret_val; // Possibly empty return value.
572
573 if (cmd_cstr == NULL)
574 return ret_val;
575
576 if (cmd_words.GetArgumentCount() == 1)
577 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
578 else
579 {
580 // We have a multi-word command (seemingly), so we need to do more work.
581 // First, get the cmd_obj_sp for the first word in the command.
582 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
583 if (cmd_obj_sp.get() != NULL)
584 {
585 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
586 // command name), and find the appropriate sub-command SP for each command word....
587 size_t end = cmd_words.GetArgumentCount();
588 for (size_t j= 1; j < end; ++j)
589 {
590 if (cmd_obj_sp->IsMultiwordObject())
591 {
592 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
593 (cmd_words.GetArgumentAtIndex (j));
594 if (cmd_obj_sp.get() == NULL)
595 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
596 return ret_val;
597 }
598 else
599 // We have more words in the command name, but we don't have a multiword object. Fail and return
600 // empty 'ret_val'.
601 return ret_val;
602 }
603 // We successfully looped through all the command words and got valid command objects for them. Assign the
604 // last object retrieved to 'ret_val'.
605 ret_val = cmd_obj_sp;
606 }
607 }
608 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000609}
610
611CommandObject *
612CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
613{
614 return GetCommandSPExact (cmd_cstr, include_aliases).get();
615}
616
617CommandObject *
618CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
619{
620 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
621
622 // If we didn't find an exact match to the command string in the commands, look in
623 // the aliases.
624
625 if (command_obj == NULL)
626 {
627 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
628 }
629
630 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
631 // in both the commands and the aliases.
632
633 if (command_obj == NULL)
634 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
635
636 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000637}
638
639bool
640CommandInterpreter::CommandExists (const char *cmd)
641{
642 return m_command_dict.find(cmd) != m_command_dict.end();
643}
644
645bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000646CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
647 const char *options_args,
648 OptionArgVectorSP &option_arg_vector_sp)
649{
650 bool success = true;
651 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
652
653 if (!options_args || (strlen (options_args) < 1))
654 return true;
655
656 std::string options_string (options_args);
657 Args args (options_args);
658 CommandReturnObject result;
659 // Check to see if the command being aliased can take any command options.
660 Options *options = cmd_obj_sp->GetOptions ();
661 if (options)
662 {
663 // See if any options were specified as part of the alias; if so, handle them appropriately.
664 options->NotifyOptionParsingStarting ();
665 args.Unshift ("dummy_arg");
666 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
667 args.Shift ();
668 if (result.Succeeded())
669 options->VerifyPartialOptions (result);
670 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
671 {
672 result.AppendError ("Unable to create requested alias.\n");
673 return false;
674 }
675 }
676
Greg Clayton7268b4c2011-10-28 21:38:01 +0000677 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000678 {
679 if (cmd_obj_sp->WantsRawCommandString ())
680 option_arg_vector->push_back (OptionArgPair ("<argument>",
681 OptionArgValue (-1,
682 options_string)));
683 else
684 {
685 int argc = args.GetArgumentCount();
686 for (size_t i = 0; i < argc; ++i)
687 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
688 option_arg_vector->push_back
689 (OptionArgPair ("<argument>",
690 OptionArgValue (-1,
691 std::string (args.GetArgumentAtIndex (i)))));
692 }
693 }
694
695 return success;
696}
697
698bool
Chris Lattner24943d22010-06-08 16:52:24 +0000699CommandInterpreter::AliasExists (const char *cmd)
700{
701 return m_alias_dict.find(cmd) != m_alias_dict.end();
702}
703
704bool
705CommandInterpreter::UserCommandExists (const char *cmd)
706{
707 return m_user_dict.find(cmd) != m_user_dict.end();
708}
709
710void
711CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
712{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000713 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000714 m_alias_dict[alias_name] = command_obj_sp;
715}
716
717bool
718CommandInterpreter::RemoveAlias (const char *alias_name)
719{
720 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
721 if (pos != m_alias_dict.end())
722 {
723 m_alias_dict.erase(pos);
724 return true;
725 }
726 return false;
727}
728bool
729CommandInterpreter::RemoveUser (const char *alias_name)
730{
731 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
732 if (pos != m_user_dict.end())
733 {
734 m_user_dict.erase(pos);
735 return true;
736 }
737 return false;
738}
739
Chris Lattner24943d22010-06-08 16:52:24 +0000740void
741CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
742{
743 help_string.Printf ("'%s", command_name);
744 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
745
746 if (option_arg_vector_sp != NULL)
747 {
748 OptionArgVector *options = option_arg_vector_sp.get();
749 for (int i = 0; i < options->size(); ++i)
750 {
751 OptionArgPair cur_option = (*options)[i];
752 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000753 OptionArgValue value_pair = cur_option.second;
754 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000755 if (opt.compare("<argument>") == 0)
756 {
757 help_string.Printf (" %s", value.c_str());
758 }
759 else
760 {
761 help_string.Printf (" %s", opt.c_str());
762 if ((value.compare ("<no-argument>") != 0)
763 && (value.compare ("<need-argument") != 0))
764 {
765 help_string.Printf (" %s", value.c_str());
766 }
767 }
768 }
769 }
770
771 help_string.Printf ("'");
772}
773
Greg Clayton65124ea2010-08-26 22:05:43 +0000774size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000775CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
776{
777 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000778 CommandObject::CommandMap::const_iterator end = dict.end();
779 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000780
Greg Clayton65124ea2010-08-26 22:05:43 +0000781 for (pos = dict.begin(); pos != end; ++pos)
782 {
783 size_t len = pos->first.size();
784 if (max_len < len)
785 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000786 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000787 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000788}
789
790void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000791CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000792 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000793{
794 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000795 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000796
797 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000798 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000799
800 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
801 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000802
Enrico Granata6b1596d2011-08-16 23:24:13 +0000803 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
804 {
805 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
806 max_len);
807 }
808 result.AppendMessage("");
809
810 }
811
Greg Clayton7268b4c2011-10-28 21:38:01 +0000812 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000813 {
Jim Inghame3663e82010-10-22 18:47:16 +0000814 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000815 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000816 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000817 max_len = FindLongestCommandWord (m_alias_dict);
818
Chris Lattner24943d22010-06-08 16:52:24 +0000819 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
820 {
821 StreamString sstr;
822 StreamString translation_and_help;
823 std::string entry_name = pos->first;
824 std::string second_entry = pos->second.get()->GetCommandName();
825 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
826
827 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
828 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
829 translation_and_help.GetData(), max_len);
830 }
831 result.AppendMessage("");
832 }
833
Greg Clayton7268b4c2011-10-28 21:38:01 +0000834 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000835 {
836 result.AppendMessage ("The following is a list of your current user-defined commands:");
837 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000838 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000839 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
840 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000841 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
842 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000843 }
844 result.AppendMessage("");
845 }
846
847 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
848}
849
Caroline Ticee0da7a52010-12-09 22:52:49 +0000850CommandObject *
851CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000852{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000853 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
854 // eventually be invoked by the given command line.
855
856 CommandObject *cmd_obj = NULL;
857 std::string white_space (" \t\v");
858 size_t start = command_string.find_first_not_of (white_space);
859 size_t end = 0;
860 bool done = false;
861 while (!done)
862 {
863 if (start != std::string::npos)
864 {
865 // Get the next word from command_string.
866 end = command_string.find_first_of (white_space, start);
867 if (end == std::string::npos)
868 end = command_string.size();
869 std::string cmd_word = command_string.substr (start, end - start);
870
871 if (cmd_obj == NULL)
872 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
873 // command or alias.
874 cmd_obj = GetCommandObject (cmd_word.c_str());
875 else if (cmd_obj->IsMultiwordObject ())
876 {
877 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
878 CommandObject *sub_cmd_obj =
879 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
880 if (sub_cmd_obj)
881 cmd_obj = sub_cmd_obj;
882 else // cmd_word was not a valid sub-command word, so we are donee
883 done = true;
884 }
885 else
886 // We have a cmd_obj and it is not a multi-word object, so we are done.
887 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000888
Caroline Ticee0da7a52010-12-09 22:52:49 +0000889 // If we didn't find a valid command object, or our command object is not a multi-word object, or
890 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
891 // next word.
892
893 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
894 done = true;
895 else
896 start = command_string.find_first_not_of (white_space, end);
897 }
898 else
899 // Unable to find any more words.
900 done = true;
901 }
902
903 if (end == command_string.size())
904 command_string.clear();
905 else
906 command_string = command_string.substr(end);
907
908 return cmd_obj;
909}
910
Greg Clayton9d855c62011-10-25 00:36:27 +0000911static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000912static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000913static void
914StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000915{
Greg Clayton9d855c62011-10-25 00:36:27 +0000916 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000917 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000918 size_t pos = s.find_first_not_of (k_white_space);
919 if (pos == std::string::npos)
920 s.clear();
921 else if (pos == 0)
922 return;
923 s.erase (0, pos);
924 }
925}
926
Greg Clayton3840cd72011-11-09 23:25:03 +0000927static size_t
928FindArgumentTerminator (const std::string &s)
929{
Greg Clayton3840cd72011-11-09 23:25:03 +0000930 const size_t s_len = s.size();
931 size_t offset = 0;
932 while (offset < s_len)
933 {
934 size_t pos = s.find ("--", offset);
935 if (pos == std::string::npos)
936 break;
937 if (pos > 0)
938 {
939 if (isspace(s[pos-1]))
940 {
941 // Check if the string ends "\s--" (where \s is a space character)
942 // or if we have "\s--\s".
943 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
944 {
Greg Clayton3840cd72011-11-09 23:25:03 +0000945 return pos;
946 }
947 }
948 }
949 offset = pos + 2;
950 }
Greg Clayton3840cd72011-11-09 23:25:03 +0000951 return std::string::npos;
952}
953
Greg Clayton9d855c62011-10-25 00:36:27 +0000954static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000955ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000956{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000957 command.clear();
958 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000959 StripLeadingSpaces (command_string);
960
961 bool result = false;
962 quote_char = '\0';
963
964 if (!command_string.empty())
965 {
966 const char first_char = command_string[0];
967 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000968 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000969 quote_char = first_char;
970 const size_t end_quote_pos = command_string.find (quote_char, 1);
971 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000972 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000973 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000974 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000975 }
976 else
977 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000978 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +0000979 if (end_quote_pos + 1 < command_string.size())
980 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
981 else
982 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000983 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000984 }
985 else
986 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000987 const size_t first_space_pos = command_string.find_first_of (k_white_space);
988 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000989 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000990 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000991 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +0000992 }
993 else
994 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000995 command.assign (command_string, 0, first_space_pos);
996 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +0000997 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000998 }
Greg Clayton9d855c62011-10-25 00:36:27 +0000999 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001000 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001001
1002
1003 if (!command.empty())
1004 {
1005 // actual commands can't start with '-' or '_'
1006 if (command[0] != '-' && command[0] != '_')
1007 {
1008 size_t pos = command.find_first_not_of(k_valid_command_chars);
1009 if (pos > 0 && pos != std::string::npos)
1010 {
1011 suffix.assign (command.begin() + pos, command.end());
1012 command.erase (pos);
1013 }
1014 }
1015 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001016
1017 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001018}
1019
Greg Clayton7268b4c2011-10-28 21:38:01 +00001020CommandObject *
1021CommandInterpreter::BuildAliasResult (const char *alias_name,
1022 std::string &raw_input_string,
1023 std::string &alias_result,
1024 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001025{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001026 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001027 Args cmd_args (raw_input_string.c_str());
1028 alias_cmd_obj = GetCommandObject (alias_name);
1029 StreamString result_str;
1030
1031 if (alias_cmd_obj)
1032 {
1033 std::string alias_name_str = alias_name;
1034 if ((cmd_args.GetArgumentCount() == 0)
1035 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1036 cmd_args.Unshift (alias_name);
1037
1038 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1039 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1040
1041 if (option_arg_vector_sp.get())
1042 {
1043 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1044
1045 for (int i = 0; i < option_arg_vector->size(); ++i)
1046 {
1047 OptionArgPair option_pair = (*option_arg_vector)[i];
1048 OptionArgValue value_pair = option_pair.second;
1049 int value_type = value_pair.first;
1050 std::string option = option_pair.first;
1051 std::string value = value_pair.second;
1052 if (option.compare ("<argument>") == 0)
1053 result_str.Printf (" %s", value.c_str());
1054 else
1055 {
1056 result_str.Printf (" %s", option.c_str());
1057 if (value_type != optional_argument)
1058 result_str.Printf (" ");
1059 if (value.compare ("<no_argument>") != 0)
1060 {
1061 int index = GetOptionArgumentPosition (value.c_str());
1062 if (index == 0)
1063 result_str.Printf ("%s", value.c_str());
1064 else if (index >= cmd_args.GetArgumentCount())
1065 {
1066
1067 result.AppendErrorWithFormat
1068 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1069 index);
1070 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001071 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001072 }
1073 else
1074 {
1075 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1076 if (strpos != std::string::npos)
1077 raw_input_string = raw_input_string.erase (strpos,
1078 strlen (cmd_args.GetArgumentAtIndex (index)));
1079 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1080 }
1081 }
1082 }
1083 }
1084 }
1085
1086 alias_result = result_str.GetData();
1087 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001088 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001089}
1090
Greg Claytonf5c0c722011-10-14 07:41:33 +00001091Error
1092CommandInterpreter::PreprocessCommand (std::string &command)
1093{
1094 // The command preprocessor needs to do things to the command
1095 // line before any parsing of arguments or anything else is done.
1096 // The only current stuff that gets proprocessed is anyting enclosed
1097 // in backtick ('`') characters is evaluated as an expression and
1098 // the result of the expression must be a scalar that can be substituted
1099 // into the command. An example would be:
1100 // (lldb) memory read `$rsp + 20`
1101 Error error; // Error for any expressions that might not evaluate
1102 size_t start_backtick;
1103 size_t pos = 0;
1104 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1105 {
1106 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1107 {
1108 // The backtick was preceeded by a '\' character, remove the slash
1109 // and don't treat the backtick as the start of an expression
1110 command.erase(start_backtick-1, 1);
1111 // No need to add one to start_backtick since we just deleted a char
1112 pos = start_backtick;
1113 }
1114 else
1115 {
1116 const size_t expr_content_start = start_backtick + 1;
1117 const size_t end_backtick = command.find ('`', expr_content_start);
1118 if (end_backtick == std::string::npos)
1119 return error;
1120 else if (end_backtick == expr_content_start)
1121 {
1122 // Empty expression (two backticks in a row)
1123 command.erase (start_backtick, 2);
1124 }
1125 else
1126 {
1127 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1128
1129 Target *target = m_exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001130 // Get a dummy target to allow for calculator mode while processing backticks.
1131 // This also helps break the infinite loop caused when target is null.
1132 if (!target)
1133 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001134 if (target)
1135 {
Sean Callanandaa6efe2011-12-21 22:22:58 +00001136 const bool coerce_to_id = false;
Greg Claytonf5c0c722011-10-14 07:41:33 +00001137 const bool unwind_on_error = true;
1138 const bool keep_in_memory = false;
1139 ValueObjectSP expr_result_valobj_sp;
1140 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1141 m_exe_ctx.GetFramePtr(),
1142 eExecutionPolicyOnlyWhenNeeded,
Sean Callanandaa6efe2011-12-21 22:22:58 +00001143 coerce_to_id,
1144 unwind_on_error,
1145 keep_in_memory,
Greg Claytonf5c0c722011-10-14 07:41:33 +00001146 eNoDynamicValues,
1147 expr_result_valobj_sp);
1148 if (expr_result == eExecutionCompleted)
1149 {
1150 Scalar scalar;
1151 if (expr_result_valobj_sp->ResolveValue (scalar))
1152 {
1153 command.erase (start_backtick, end_backtick - start_backtick + 1);
1154 StreamString value_strm;
1155 const bool show_type = false;
1156 scalar.GetValue (&value_strm, show_type);
1157 size_t value_string_size = value_strm.GetSize();
1158 if (value_string_size)
1159 {
1160 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1161 pos = start_backtick + value_string_size;
1162 continue;
1163 }
1164 else
1165 {
1166 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1167 }
1168 }
1169 else
1170 {
1171 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1172 }
1173 }
1174 else
1175 {
1176 if (expr_result_valobj_sp)
1177 error = expr_result_valobj_sp->GetError();
1178 if (error.Success())
1179 {
1180
1181 switch (expr_result)
1182 {
1183 case eExecutionSetupError:
1184 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1185 break;
1186 case eExecutionCompleted:
1187 break;
1188 case eExecutionDiscarded:
1189 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1190 break;
1191 case eExecutionInterrupted:
1192 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1193 break;
1194 case eExecutionTimedOut:
1195 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1196 break;
1197 }
1198 }
1199 }
1200 }
1201 }
1202 if (error.Fail())
1203 break;
1204 }
1205 }
1206 return error;
1207}
1208
1209
Caroline Ticee0da7a52010-12-09 22:52:49 +00001210bool
1211CommandInterpreter::HandleCommand (const char *command_line,
1212 bool add_to_history,
1213 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001214 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001215 bool repeat_on_empty_command,
1216 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001217
Caroline Ticee0da7a52010-12-09 22:52:49 +00001218{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001219
Caroline Ticee0da7a52010-12-09 22:52:49 +00001220 bool done = false;
1221 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001222 bool wants_raw_input = false;
1223 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001224 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001225
1226 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001227 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1228
1229 // Make a scoped cleanup object that will clear the crash description string
1230 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001231 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001232
Caroline Ticee0da7a52010-12-09 22:52:49 +00001233 if (log)
1234 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001235
Jim Inghamabab14b2010-11-04 23:08:45 +00001236 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1237
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001238 if (!no_context_switching)
1239 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +00001240
Jim Ingham949d5ac2011-02-18 00:54:25 +00001241 bool empty_command = false;
1242 bool comment_command = false;
1243 if (command_string.empty())
1244 empty_command = true;
1245 else
Chris Lattner24943d22010-06-08 16:52:24 +00001246 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001247 const char *k_space_characters = "\t\n\v\f\r ";
1248
1249 size_t non_space = command_string.find_first_not_of (k_space_characters);
1250 // Check for empty line or comment line (lines whose first
1251 // non-space character is the comment character for this interpreter)
1252 if (non_space == std::string::npos)
1253 empty_command = true;
1254 else if (command_string[non_space] == m_comment_char)
1255 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001256 else if (command_string[non_space] == m_repeat_char)
1257 {
1258 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1259 if (history_string == NULL)
1260 {
1261 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1262 result.SetStatus(eReturnStatusFailed);
1263 return false;
1264 }
1265 add_to_history = false;
1266 command_string = history_string;
1267 original_command_string = history_string;
1268 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001269 }
1270
1271 if (empty_command)
1272 {
1273 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001274 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001275 if (m_command_history.empty())
1276 {
1277 result.AppendError ("empty command");
1278 result.SetStatus(eReturnStatusFailed);
1279 return false;
1280 }
1281 else
1282 {
1283 command_line = m_repeat_command.c_str();
1284 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001285 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001286 if (m_repeat_command.empty())
1287 {
1288 result.AppendErrorWithFormat("No auto repeat.\n");
1289 result.SetStatus (eReturnStatusFailed);
1290 return false;
1291 }
1292 }
1293 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001294 }
1295 else
1296 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001297 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1298 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001299 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001300 }
1301 else if (comment_command)
1302 {
1303 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1304 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001305 }
Caroline Tice649116c2011-05-11 16:07:06 +00001306
Greg Claytonf5c0c722011-10-14 07:41:33 +00001307
1308 Error error (PreprocessCommand (command_string));
1309
1310 if (error.Fail())
1311 {
1312 result.AppendError (error.AsCString());
1313 result.SetStatus(eReturnStatusFailed);
1314 return false;
1315 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001316 // Phase 1.
1317
1318 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1319 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1320 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1321 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1322 // 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 +00001323 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001324 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001325
Caroline Ticee0da7a52010-12-09 22:52:49 +00001326 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001327 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001328 std::string next_word;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001329 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001330 {
Caroline Tice649116c2011-05-11 16:07:06 +00001331 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001332 std::string suffix;
1333 ExtractCommand (command_string, next_word, suffix, quote_char);
1334 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001335 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001336 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001337 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001338 std::string alias_result;
1339 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1340 revised_command_line.Printf ("%s", alias_result.c_str());
1341 if (cmd_obj)
1342 {
1343 wants_raw_input = cmd_obj->WantsRawCommandString ();
1344 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1345 }
Chris Lattner24943d22010-06-08 16:52:24 +00001346 }
1347 else
1348 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001349 cmd_obj = GetCommandObject (next_word.c_str());
1350 if (cmd_obj)
1351 {
1352 actual_cmd_name_len += next_word.length();
1353 revised_command_line.Printf ("%s", next_word.c_str());
1354 wants_raw_input = cmd_obj->WantsRawCommandString ();
1355 }
Caroline Tice649116c2011-05-11 16:07:06 +00001356 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001357 {
1358 revised_command_line.Printf ("%s", next_word.c_str());
1359 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001360 }
1361 }
1362 else
1363 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001364 if (cmd_obj->IsMultiwordObject ())
1365 {
1366 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1367 if (sub_cmd_obj)
1368 {
1369 actual_cmd_name_len += next_word.length() + 1;
1370 revised_command_line.Printf (" %s", next_word.c_str());
1371 cmd_obj = sub_cmd_obj;
1372 wants_raw_input = cmd_obj->WantsRawCommandString ();
1373 }
1374 else
1375 {
1376 if (quote_char)
1377 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1378 else
1379 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1380 done = true;
1381 }
1382 }
Caroline Tice649116c2011-05-11 16:07:06 +00001383 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001384 {
1385 if (quote_char)
1386 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1387 else
1388 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1389 done = true;
1390 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001391 }
1392
1393 if (cmd_obj == NULL)
1394 {
1395 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1396 result.SetStatus (eReturnStatusFailed);
1397 return false;
1398 }
1399
Greg Clayton7268b4c2011-10-28 21:38:01 +00001400 if (cmd_obj->IsMultiwordObject ())
1401 {
1402 if (!suffix.empty())
1403 {
1404
1405 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1406 next_word.c_str(),
1407 suffix.c_str());
1408 result.SetStatus (eReturnStatusFailed);
1409 return false;
1410 }
1411 }
1412 else
1413 {
1414 // If we found a normal command, we are done
1415 done = true;
1416 if (!suffix.empty())
1417 {
1418 switch (suffix[0])
1419 {
1420 case '/':
1421 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001422 {
1423 Options *command_options = cmd_obj->GetOptions();
1424 if (command_options && command_options->SupportsLongOption("gdb-format"))
1425 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001426 std::string gdb_format_option ("--gdb-format=");
1427 gdb_format_option += (suffix.c_str() + 1);
1428
1429 bool inserted = false;
1430 std::string &cmd = revised_command_line.GetString();
1431 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1432 if (arg_terminator_idx != std::string::npos)
1433 {
1434 // Insert the gdb format option before the "--" that terminates options
1435 gdb_format_option.append(1,' ');
1436 cmd.insert(arg_terminator_idx, gdb_format_option);
1437 inserted = true;
1438 }
1439
1440 if (!inserted)
1441 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1442
1443 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1444 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001445 }
1446 else
1447 {
1448 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1449 cmd_obj->GetCommandName());
1450 result.SetStatus (eReturnStatusFailed);
1451 return false;
1452 }
1453 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001454 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001455
1456 default:
1457 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1458 suffix.c_str());
1459 result.SetStatus (eReturnStatusFailed);
1460 return false;
1461
Greg Clayton7268b4c2011-10-28 21:38:01 +00001462 }
1463 }
1464 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001465 if (command_string.length() == 0)
1466 done = true;
1467
Chris Lattner24943d22010-06-08 16:52:24 +00001468 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001469
Greg Clayton7268b4c2011-10-28 21:38:01 +00001470 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001471 revised_command_line.Printf (" %s", command_string.c_str());
1472
1473 // End of Phase 1.
1474 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1475 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1476 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1477 // wants_raw_input specifies whether the Execute method expects raw input or not.
1478
1479
1480 if (log)
1481 {
1482 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1483 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1484 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1485 }
1486
1487 // Phase 2.
1488 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1489 // CommandObject, with the appropriate arguments.
1490
1491 if (cmd_obj != NULL)
1492 {
1493 if (add_to_history)
1494 {
1495 Args command_args (revised_command_line.GetData());
1496 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1497 if (repeat_command != NULL)
1498 m_repeat_command.assign(repeat_command);
1499 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001500 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001501
Jim Ingham6247dbe2011-07-12 03:12:18 +00001502 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001503 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001504 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001505 }
1506
1507 command_string = revised_command_line.GetData();
1508 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001509 std::string remainder;
1510 if (actual_cmd_name_len < command_string.length())
1511 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1512 // than cmd_obj->GetCommandName(), because name completion
1513 // allows users to enter short versions of the names,
1514 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001515
1516 // Remove any initial spaces
1517 std::string white_space (" \t\v");
1518 size_t pos = remainder.find_first_not_of (white_space);
1519 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001520 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001521
1522 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001523 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001524
1525
Greg Claytonf1252502012-02-29 04:21:24 +00001526 CommandOverrideCallback command_callback = cmd_obj->GetOverrideCallback();
1527 bool handled = false;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001528 if (wants_raw_input)
Greg Claytonf1252502012-02-29 04:21:24 +00001529 {
1530 if (command_callback)
1531 {
1532 std::string full_command (cmd_obj->GetCommandName ());
1533 full_command += ' ';
1534 full_command += remainder;
1535 const char *argv[2] = { NULL, NULL };
1536 argv[0] = full_command.c_str();
1537 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), argv);
1538 }
1539 if (!handled)
1540 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1541 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001542 else
1543 {
1544 Args cmd_args (remainder.c_str());
Greg Claytonf1252502012-02-29 04:21:24 +00001545 if (command_callback)
1546 {
1547 Args full_args (cmd_obj->GetCommandName ());
1548 full_args.AppendArguments(cmd_args);
1549 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), full_args.GetConstArgumentVector());
1550 }
1551 if (!handled)
1552 cmd_obj->ExecuteWithOptions (cmd_args, result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001553 }
1554 }
1555 else
1556 {
1557 // We didn't find the first command object, so complete the first argument.
1558 Args command_args (revised_command_line.GetData());
1559 StringList matches;
1560 int num_matches;
1561 int cursor_index = 0;
1562 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1563 bool word_complete;
1564 num_matches = HandleCompletionMatches (command_args,
1565 cursor_index,
1566 cursor_char_position,
1567 0,
1568 -1,
1569 word_complete,
1570 matches);
1571
1572 if (num_matches > 0)
1573 {
1574 std::string error_msg;
1575 error_msg.assign ("ambiguous command '");
1576 error_msg.append(command_args.GetArgumentAtIndex(0));
1577 error_msg.append ("'.");
1578
1579 error_msg.append (" Possible completions:");
1580 for (int i = 0; i < num_matches; i++)
1581 {
1582 error_msg.append ("\n\t");
1583 error_msg.append (matches.GetStringAtIndex (i));
1584 }
1585 error_msg.append ("\n");
1586 result.AppendRawError (error_msg.c_str(), error_msg.size());
1587 }
1588 else
1589 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1590
1591 result.SetStatus (eReturnStatusFailed);
1592 }
1593
Jason Molenda24c991c2011-08-25 00:20:04 +00001594 if (log)
1595 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1596
Chris Lattner24943d22010-06-08 16:52:24 +00001597 return result.Succeeded();
1598}
1599
1600int
1601CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1602 int &cursor_index,
1603 int &cursor_char_position,
1604 int match_start_point,
1605 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001606 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001607 StringList &matches)
1608{
1609 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001610 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001611
1612 // For any of the command completions a unique match will be a complete word.
1613 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001614
1615 if (cursor_index == -1)
1616 {
1617 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001618 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001619 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1620 }
1621 else if (cursor_index == 0)
1622 {
1623 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001624 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001625 num_command_matches = matches.GetSize();
1626
1627 if (num_command_matches == 1
1628 && cmd_obj && cmd_obj->IsMultiwordObject()
1629 && matches.GetStringAtIndex(0) != NULL
1630 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1631 {
1632 look_for_subcommand = true;
1633 num_command_matches = 0;
1634 matches.DeleteStringAtIndex(0);
1635 parsed_line.AppendArgument ("");
1636 cursor_index++;
1637 cursor_char_position = 0;
1638 }
1639 }
1640
1641 if (cursor_index > 0 || look_for_subcommand)
1642 {
1643 // We are completing further on into a commands arguments, so find the command and tell it
1644 // to complete the command.
1645 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001646 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001647 if (command_object == NULL)
1648 {
1649 return 0;
1650 }
1651 else
1652 {
1653 parsed_line.Shift();
1654 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001655 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001656 cursor_index,
1657 cursor_char_position,
1658 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001659 max_return_elements,
1660 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001661 matches);
1662 }
1663 }
1664
1665 return num_command_matches;
1666
1667}
1668
1669int
1670CommandInterpreter::HandleCompletion (const char *current_line,
1671 const char *cursor,
1672 const char *last_char,
1673 int match_start_point,
1674 int max_return_elements,
1675 StringList &matches)
1676{
1677 // We parse the argument up to the cursor, so the last argument in parsed_line is
1678 // the one containing the cursor, and the cursor is after the last character.
1679
1680 Args parsed_line(current_line, last_char - current_line);
1681 Args partial_parsed_line(current_line, cursor - current_line);
1682
Jim Ingham6247dbe2011-07-12 03:12:18 +00001683 // Don't complete comments, and if the line we are completing is just the history repeat character,
1684 // substitute the appropriate history line.
1685 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1686 if (first_arg)
1687 {
1688 if (first_arg[0] == m_comment_char)
1689 return 0;
1690 else if (first_arg[0] == m_repeat_char)
1691 {
1692 const char *history_string = FindHistoryString (first_arg);
1693 if (history_string != NULL)
1694 {
1695 matches.Clear();
1696 matches.InsertStringAtIndex(0, history_string);
1697 return -2;
1698 }
1699 else
1700 return 0;
1701
1702 }
1703 }
1704
1705
Chris Lattner24943d22010-06-08 16:52:24 +00001706 int num_args = partial_parsed_line.GetArgumentCount();
1707 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1708 int cursor_char_position;
1709
1710 if (cursor_index == -1)
1711 cursor_char_position = 0;
1712 else
1713 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001714
1715 if (cursor > current_line && cursor[-1] == ' ')
1716 {
1717 // We are just after a space. If we are in an argument, then we will continue
1718 // parsing, but if we are between arguments, then we have to complete whatever the next
1719 // element would be.
1720 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1721 // protected by a quote) then the space will also be in the parsed argument...
1722
1723 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1724 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1725 {
1726 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1727 cursor_index++;
1728 cursor_char_position = 0;
1729 }
1730 }
Chris Lattner24943d22010-06-08 16:52:24 +00001731
1732 int num_command_matches;
1733
1734 matches.Clear();
1735
1736 // Only max_return_elements == -1 is supported at present:
1737 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001738 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001739 num_command_matches = HandleCompletionMatches (parsed_line,
1740 cursor_index,
1741 cursor_char_position,
1742 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001743 max_return_elements,
1744 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001745 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001746
1747 if (num_command_matches <= 0)
1748 return num_command_matches;
1749
1750 if (num_args == 0)
1751 {
1752 // If we got an empty string, insert nothing.
1753 matches.InsertStringAtIndex(0, "");
1754 }
1755 else
1756 {
1757 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1758 // put an empty string in element 0.
1759 std::string command_partial_str;
1760 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001761 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1762 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001763
1764 std::string common_prefix;
1765 matches.LongestCommonPrefix (common_prefix);
1766 int partial_name_len = command_partial_str.size();
1767
1768 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001769 // Only do this if the completer told us this was a complete word, however...
1770 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001771 {
1772 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1773 if (quote_char != '\0')
1774 common_prefix.push_back(quote_char);
1775
1776 common_prefix.push_back(' ');
1777 }
1778 common_prefix.erase (0, partial_name_len);
1779 matches.InsertStringAtIndex(0, common_prefix.c_str());
1780 }
1781 return num_command_matches;
1782}
1783
Chris Lattner24943d22010-06-08 16:52:24 +00001784
1785CommandInterpreter::~CommandInterpreter ()
1786{
1787}
1788
1789const char *
1790CommandInterpreter::GetPrompt ()
1791{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001792 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001793}
1794
1795void
1796CommandInterpreter::SetPrompt (const char *new_prompt)
1797{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001798 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001799}
1800
Jim Ingham5e16ef52010-10-04 19:49:29 +00001801size_t
Greg Clayton58928562011-02-09 01:08:52 +00001802CommandInterpreter::GetConfirmationInputReaderCallback
1803(
1804 void *baton,
1805 InputReader &reader,
1806 lldb::InputReaderAction action,
1807 const char *bytes,
1808 size_t bytes_len
1809)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001810{
Greg Clayton58928562011-02-09 01:08:52 +00001811 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001812 bool *response_ptr = (bool *) baton;
1813
1814 switch (action)
1815 {
1816 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001817 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001818 {
1819 if (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 }
1825 break;
1826
1827 case eInputReaderDeactivate:
1828 break;
1829
1830 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001831 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001832 {
Greg Clayton58928562011-02-09 01:08:52 +00001833 out_file.Printf ("%s", reader.GetPrompt());
1834 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001835 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001836 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001837
1838 case eInputReaderAsynchronousOutputWritten:
1839 break;
1840
Jim Ingham5e16ef52010-10-04 19:49:29 +00001841 case eInputReaderGotToken:
1842 if (bytes_len == 0)
1843 {
1844 reader.SetIsDone(true);
1845 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001846 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001847 {
1848 *response_ptr = true;
1849 reader.SetIsDone(true);
1850 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001851 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001852 {
1853 *response_ptr = false;
1854 reader.SetIsDone(true);
1855 }
1856 else
1857 {
Greg Clayton58928562011-02-09 01:08:52 +00001858 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001859 {
Jim Ingham26183802011-11-17 01:22:00 +00001860 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001861 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001862 }
1863 }
1864 break;
1865
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001866 case eInputReaderInterrupt:
1867 case eInputReaderEndOfFile:
1868 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1869 reader.SetIsDone (true);
1870 break;
1871
Jim Ingham5e16ef52010-10-04 19:49:29 +00001872 case eInputReaderDone:
1873 break;
1874 }
1875
1876 return bytes_len;
1877
1878}
1879
1880bool
1881CommandInterpreter::Confirm (const char *message, bool default_answer)
1882{
Jim Ingham93057472010-10-04 22:44:14 +00001883 // Check AutoConfirm first:
1884 if (m_debugger.GetAutoConfirm())
1885 return default_answer;
1886
Jim Ingham5e16ef52010-10-04 19:49:29 +00001887 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1888 bool response = default_answer;
1889 if (reader_sp)
1890 {
1891 std::string prompt(message);
1892 prompt.append(": [");
1893 if (default_answer)
1894 prompt.append ("Y/n] ");
1895 else
1896 prompt.append ("y/N] ");
1897
1898 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1899 &response, // baton
1900 eInputReaderGranularityLine, // token size, to pass to callback function
1901 NULL, // end token
1902 prompt.c_str(), // prompt
1903 true)); // echo input
1904 if (err.Success())
1905 {
1906 GetDebugger().PushInputReader (reader_sp);
1907 }
1908 reader_sp->WaitOnReaderIsDone();
1909 }
1910 return response;
1911}
1912
1913
Chris Lattner24943d22010-06-08 16:52:24 +00001914void
1915CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1916{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001917 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001918
1919 if (cmd_obj_sp != NULL)
1920 {
1921 CommandObject *cmd_obj = cmd_obj_sp.get();
1922 if (cmd_obj->IsCrossRefObject ())
1923 cmd_obj->AddObject (object_type);
1924 }
1925}
1926
Chris Lattner24943d22010-06-08 16:52:24 +00001927OptionArgVectorSP
1928CommandInterpreter::GetAliasOptions (const char *alias_name)
1929{
1930 OptionArgMap::iterator pos;
1931 OptionArgVectorSP ret_val;
1932
1933 std::string alias (alias_name);
1934
1935 if (HasAliasOptions())
1936 {
1937 pos = m_alias_options.find (alias);
1938 if (pos != m_alias_options.end())
1939 ret_val = pos->second;
1940 }
1941
1942 return ret_val;
1943}
1944
1945void
1946CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1947{
1948 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1949 if (pos != m_alias_options.end())
1950 {
1951 m_alias_options.erase (pos);
1952 }
1953}
1954
1955void
1956CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1957{
1958 m_alias_options[alias_name] = option_arg_vector_sp;
1959}
1960
1961bool
1962CommandInterpreter::HasCommands ()
1963{
1964 return (!m_command_dict.empty());
1965}
1966
1967bool
1968CommandInterpreter::HasAliases ()
1969{
1970 return (!m_alias_dict.empty());
1971}
1972
1973bool
1974CommandInterpreter::HasUserCommands ()
1975{
1976 return (!m_user_dict.empty());
1977}
1978
1979bool
1980CommandInterpreter::HasAliasOptions ()
1981{
1982 return (!m_alias_options.empty());
1983}
1984
Chris Lattner24943d22010-06-08 16:52:24 +00001985void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001986CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1987 const char *alias_name,
1988 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001989 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001990 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001991{
1992 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001993
1994 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001995
Caroline Tice44c841d2010-12-07 19:58:26 +00001996 // Make sure that the alias name is the 0th element in cmd_args
1997 std::string alias_name_str = alias_name;
1998 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1999 cmd_args.Unshift (alias_name);
2000
2001 Args new_args (alias_cmd_obj->GetCommandName());
2002 if (new_args.GetArgumentCount() == 2)
2003 new_args.Shift();
2004
Chris Lattner24943d22010-06-08 16:52:24 +00002005 if (option_arg_vector_sp.get())
2006 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002007 if (wants_raw_input)
2008 {
2009 // We have a command that both has command options and takes raw input. Make *sure* it has a
2010 // " -- " in the right place in the raw_input_string.
2011 size_t pos = raw_input_string.find(" -- ");
2012 if (pos == std::string::npos)
2013 {
2014 // None found; assume it goes at the beginning of the raw input string
2015 raw_input_string.insert (0, " -- ");
2016 }
2017 }
Chris Lattner24943d22010-06-08 16:52:24 +00002018
2019 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2020 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002021 std::vector<bool> used (old_size + 1, false);
2022
2023 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002024
2025 for (int i = 0; i < option_arg_vector->size(); ++i)
2026 {
2027 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002028 OptionArgValue value_pair = option_pair.second;
2029 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002030 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002031 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002032 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002033 {
2034 if (!wants_raw_input
2035 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2036 new_args.AppendArgument (value.c_str());
2037 }
Chris Lattner24943d22010-06-08 16:52:24 +00002038 else
2039 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002040 if (value_type != optional_argument)
2041 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002042 if (value.compare ("<no-argument>") != 0)
2043 {
2044 int index = GetOptionArgumentPosition (value.c_str());
2045 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002046 {
Chris Lattner24943d22010-06-08 16:52:24 +00002047 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002048 if (value_type != optional_argument)
2049 new_args.AppendArgument (value.c_str());
2050 else
2051 {
2052 char buffer[255];
2053 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2054 new_args.AppendArgument (buffer);
2055 }
2056
2057 }
Chris Lattner24943d22010-06-08 16:52:24 +00002058 else if (index >= cmd_args.GetArgumentCount())
2059 {
2060 result.AppendErrorWithFormat
2061 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2062 index);
2063 result.SetStatus (eReturnStatusFailed);
2064 return;
2065 }
2066 else
2067 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002068 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2069 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2070 if (strpos != std::string::npos)
2071 {
2072 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2073 }
2074
2075 if (value_type != optional_argument)
2076 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2077 else
2078 {
2079 char buffer[255];
2080 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2081 cmd_args.GetArgumentAtIndex (index));
2082 new_args.AppendArgument (buffer);
2083 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002084 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002085 }
2086 }
2087 }
2088 }
2089
2090 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2091 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002092 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002093 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2094 }
2095
2096 cmd_args.Clear();
2097 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2098 }
2099 else
2100 {
2101 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002102 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2103 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2104 // input string.
2105 if (wants_raw_input)
2106 {
2107 cmd_args.Clear();
2108 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2109 }
Chris Lattner24943d22010-06-08 16:52:24 +00002110 return;
2111 }
2112
2113 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2114 return;
2115}
2116
2117
2118int
2119CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2120{
2121 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2122 // of zero.
2123
2124 char *cptr = (char *) in_string;
2125
2126 // Does it start with '%'
2127 if (cptr[0] == '%')
2128 {
2129 ++cptr;
2130
2131 // Is the rest of it entirely digits?
2132 if (isdigit (cptr[0]))
2133 {
2134 const char *start = cptr;
2135 while (isdigit (cptr[0]))
2136 ++cptr;
2137
2138 // We've gotten to the end of the digits; are we at the end of the string?
2139 if (cptr[0] == '\0')
2140 position = atoi (start);
2141 }
2142 }
2143
2144 return position;
2145}
2146
2147void
2148CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2149{
Jim Ingham574c3d62011-08-12 23:34:31 +00002150 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002151 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002152 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002153 // In the current working directory we don't load any program specific
2154 // .lldbinit files, we only look for a "./.lldbinit" file.
2155 if (m_skip_lldbinit_files)
2156 return;
2157
2158 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002159 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002160 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002161 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002162 // If we aren't looking in the current working directory we are looking
2163 // in the home directory. We will first see if there is an application
2164 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2165 // "-" and the name of the program. If this file doesn't exist, we fall
2166 // back to just the "~/.lldbinit" file. We also obey any requests to not
2167 // load the init files.
2168 const char *init_file_path = "~/.lldbinit";
2169
2170 if (m_skip_app_init_files == false)
2171 {
2172 FileSpec program_file_spec (Host::GetProgramFileSpec());
2173 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002174
Greg Claytond6edcb52011-09-11 00:01:44 +00002175 if (program_name)
2176 {
2177 char program_init_file_name[PATH_MAX];
2178 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2179 init_file.SetFile (program_init_file_name, true);
2180 if (!init_file.Exists())
2181 init_file.Clear();
2182 }
2183 }
2184
2185 if (!init_file && !m_skip_lldbinit_files)
2186 init_file.SetFile (init_file_path, true);
2187 }
2188
Chris Lattner24943d22010-06-08 16:52:24 +00002189 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2190 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2191
2192 if (init_file.Exists())
2193 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002194 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2195 bool stop_on_continue = true;
2196 bool stop_on_error = false;
2197 bool echo_commands = false;
2198 bool print_results = false;
2199
2200 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002201 }
2202 else
2203 {
2204 // nothing to be done if the file doesn't exist
2205 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2206 }
2207}
2208
Greg Claytonb72d0f02011-04-12 05:54:46 +00002209PlatformSP
2210CommandInterpreter::GetPlatform (bool prefer_target_platform)
2211{
2212 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002213 if (prefer_target_platform)
2214 {
2215 Target *target = m_exe_ctx.GetTargetPtr();
2216 if (target)
2217 platform_sp = target->GetPlatform();
2218 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002219
2220 if (!platform_sp)
2221 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2222 return platform_sp;
2223}
2224
Jim Ingham949d5ac2011-02-18 00:54:25 +00002225void
Jim Inghama4fede32011-03-11 01:51:49 +00002226CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002227 ExecutionContext *override_context,
2228 bool stop_on_continue,
2229 bool stop_on_error,
2230 bool echo_commands,
2231 bool print_results,
2232 CommandReturnObject &result)
2233{
2234 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002235
2236 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2237 // Make sure you reset this value anywhere you return from the function.
2238
2239 bool old_async_execution = m_debugger.GetAsyncExecution();
2240
2241 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2242 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2243
2244 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002245 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002246
2247 if (!stop_on_continue)
2248 {
2249 m_debugger.SetAsyncExecution (false);
2250 }
2251
2252 for (int idx = 0; idx < num_lines; idx++)
2253 {
2254 const char *cmd = commands.GetStringAtIndex(idx);
2255 if (cmd[0] == '\0')
2256 continue;
2257
Jim Ingham949d5ac2011-02-18 00:54:25 +00002258 if (echo_commands)
2259 {
2260 result.AppendMessageWithFormat ("%s %s\n",
2261 GetPrompt(),
2262 cmd);
2263 }
2264
Greg Claytonaa378b12011-02-20 02:15:07 +00002265 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002266 // If override_context is not NULL, pass no_context_switching = true for
2267 // HandleCommand() since we updated our context already.
2268 bool success = HandleCommand(cmd, false, tmp_result,
2269 NULL, /* override_context */
2270 true, /* repeat_on_empty_command */
2271 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002272
2273 if (print_results)
2274 {
2275 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002276 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002277 }
2278
2279 if (!success || !tmp_result.Succeeded())
2280 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002281 const char *error_msg = tmp_result.GetErrorData();
2282 if (error_msg == NULL || error_msg[0] == '\0')
2283 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002284 if (stop_on_error)
2285 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002286 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2287 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002288 result.SetStatus (eReturnStatusFailed);
2289 m_debugger.SetAsyncExecution (old_async_execution);
2290 return;
2291 }
2292 else if (print_results)
2293 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002294 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002295 idx + 1,
2296 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002297 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002298 }
2299 }
2300
Caroline Tice4a348082011-05-02 20:41:46 +00002301 if (result.GetImmediateOutputStream())
2302 result.GetImmediateOutputStream()->Flush();
2303
2304 if (result.GetImmediateErrorStream())
2305 result.GetImmediateErrorStream()->Flush();
2306
Jim Ingham949d5ac2011-02-18 00:54:25 +00002307 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2308 // could be running (for instance in Breakpoint Commands.
2309 // So we check the return value to see if it is has running in it.
2310 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2311 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2312 {
2313 if (stop_on_continue)
2314 {
2315 // If we caused the target to proceed, and we're going to stop in that case, set the
2316 // status in our real result before returning. This is an error if the continue was not the
2317 // last command in the set of commands to be run.
2318 if (idx != num_lines - 1)
2319 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2320 idx + 1, cmd);
2321 else
2322 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2323
2324 result.SetStatus(tmp_result.GetStatus());
2325 m_debugger.SetAsyncExecution (old_async_execution);
2326
2327 return;
2328 }
2329 }
2330
2331 }
2332
2333 result.SetStatus (eReturnStatusSuccessFinishResult);
2334 m_debugger.SetAsyncExecution (old_async_execution);
2335
2336 return;
2337}
2338
2339void
2340CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2341 ExecutionContext *context,
2342 bool stop_on_continue,
2343 bool stop_on_error,
2344 bool echo_command,
2345 bool print_result,
2346 CommandReturnObject &result)
2347{
2348 if (cmd_file.Exists())
2349 {
2350 bool success;
2351 StringList commands;
2352 success = commands.ReadFileLines(cmd_file);
2353 if (!success)
2354 {
2355 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2356 result.SetStatus (eReturnStatusFailed);
2357 return;
2358 }
2359 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
2360 }
2361 else
2362 {
2363 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2364 cmd_file.GetFilename().AsCString());
2365 result.SetStatus (eReturnStatusFailed);
2366 return;
2367 }
2368}
2369
Chris Lattner24943d22010-06-08 16:52:24 +00002370ScriptInterpreter *
2371CommandInterpreter::GetScriptInterpreter ()
2372{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002373 if (m_script_interpreter_ap.get() != NULL)
2374 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002375
Caroline Tice0aa2e552011-01-14 00:29:16 +00002376 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2377 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002378 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002379 case eScriptLanguagePython:
2380#ifndef LLDB_DISABLE_PYTHON
2381 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2382 break;
2383#else
2384 // Fall through to the None case when python is disabled
2385#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002386 case eScriptLanguageNone:
2387 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2388 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002389 default:
2390 break;
2391 };
2392
2393 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002394}
2395
2396
2397
2398bool
2399CommandInterpreter::GetSynchronous ()
2400{
2401 return m_synchronous_execution;
2402}
2403
2404void
2405CommandInterpreter::SetSynchronous (bool value)
2406{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002407 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002408}
2409
2410void
2411CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2412 const char *word_text,
2413 const char *separator,
2414 const char *help_text,
2415 uint32_t max_word_len)
2416{
Greg Clayton238c0a12010-09-18 01:14:36 +00002417 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2418
Chris Lattner24943d22010-06-08 16:52:24 +00002419 int indent_size = max_word_len + strlen (separator) + 2;
2420
2421 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002422
2423 StreamString text_strm;
2424 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2425
2426 size_t len = text_strm.GetSize();
2427 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002428 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002429 {
2430 text_strm.EOL();
2431 len = text_strm.GetSize();
2432 }
Chris Lattner24943d22010-06-08 16:52:24 +00002433
2434 if (len < max_columns)
2435 {
2436 // Output it as a single line.
2437 strm.Printf ("%s", text);
2438 }
2439 else
2440 {
2441 // We need to break it up into multiple lines.
2442 bool first_line = true;
2443 int text_width;
2444 int start = 0;
2445 int end = start;
2446 int final_end = strlen (text);
2447 int sub_len;
2448
2449 while (end < final_end)
2450 {
2451 if (first_line)
2452 text_width = max_columns - 1;
2453 else
2454 text_width = max_columns - indent_size - 1;
2455
2456 // Don't start the 'text' on a space, since we're already outputting the indentation.
2457 if (!first_line)
2458 {
2459 while ((start < final_end) && (text[start] == ' '))
2460 start++;
2461 }
2462
2463 end = start + text_width;
2464 if (end > final_end)
2465 end = final_end;
2466 else
2467 {
2468 // If we're not at the end of the text, make sure we break the line on white space.
2469 while (end > start
2470 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2471 end--;
2472 }
2473
2474 sub_len = end - start;
2475 if (start != 0)
2476 strm.EOL();
2477 if (!first_line)
2478 strm.Indent();
2479 else
2480 first_line = false;
2481 assert (start <= final_end);
2482 assert (start + sub_len <= final_end);
2483 if (sub_len > 0)
2484 strm.Write (text + start, sub_len);
2485 start = end + 1;
2486 }
2487 }
2488 strm.EOL();
2489 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002490}
2491
2492void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002493CommandInterpreter::OutputHelpText (Stream &strm,
2494 const char *word_text,
2495 const char *separator,
2496 const char *help_text,
2497 uint32_t max_word_len)
2498{
2499 int indent_size = max_word_len + strlen (separator) + 2;
2500
2501 strm.IndentMore (indent_size);
2502
2503 StreamString text_strm;
2504 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2505
2506 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2507 bool first_line = true;
2508
2509 size_t len = text_strm.GetSize();
2510 const char *text = text_strm.GetData();
2511
2512 uint32_t chars_left = max_columns;
2513
2514 for (uint32_t i = 0; i < len; i++)
2515 {
2516 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2517 {
2518 first_line = false;
2519 chars_left = max_columns - indent_size;
2520 strm.EOL();
2521 strm.Indent();
2522 }
2523 else
2524 {
2525 strm.PutChar(text[i]);
2526 chars_left--;
2527 }
2528
2529 }
2530
2531 strm.EOL();
2532 strm.IndentLess(indent_size);
2533}
2534
2535void
Chris Lattner24943d22010-06-08 16:52:24 +00002536CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2537 StringList &commands_found, StringList &commands_help)
2538{
2539 CommandObject::CommandMap::const_iterator pos;
2540 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2541 CommandObject *sub_cmd_obj;
2542
2543 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2544 {
2545 const char * command_name = pos->first.c_str();
2546 sub_cmd_obj = pos->second.get();
2547 StreamString complete_command_name;
2548
2549 complete_command_name.Printf ("%s %s", prefix, command_name);
2550
Greg Clayton238c0a12010-09-18 01:14:36 +00002551 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002552 {
2553 commands_found.AppendString (complete_command_name.GetData());
2554 commands_help.AppendString (sub_cmd_obj->GetHelp());
2555 }
2556
2557 if (sub_cmd_obj->IsMultiwordObject())
2558 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2559 commands_help);
2560 }
2561
2562}
2563
2564void
2565CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2566 StringList &commands_help)
2567{
2568 CommandObject::CommandMap::const_iterator pos;
2569
2570 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2571 {
2572 const char *command_name = pos->first.c_str();
2573 CommandObject *cmd_obj = pos->second.get();
2574
Greg Clayton238c0a12010-09-18 01:14:36 +00002575 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002576 {
2577 commands_found.AppendString (command_name);
2578 commands_help.AppendString (cmd_obj->GetHelp());
2579 }
2580
2581 if (cmd_obj->IsMultiwordObject())
2582 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2583
2584 }
2585}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002586
2587
2588void
2589CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2590{
2591 m_exe_ctx.Clear();
2592
2593 if (override_context != NULL)
2594 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002595 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002596 }
2597 else
2598 {
2599 TargetSP target_sp (m_debugger.GetSelectedTarget());
2600 if (target_sp)
2601 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002602 m_exe_ctx.SetTargetSP (target_sp);
2603 ProcessSP process_sp (target_sp->GetProcessSP());
2604 m_exe_ctx.SetProcessSP (process_sp);
2605 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002606 {
Greg Clayton13d24fb2012-01-29 20:56:30 +00002607 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
Greg Clayton567e7f32011-09-22 04:58:26 +00002608 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002609 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002610 m_exe_ctx.SetThreadSP (thread_sp);
2611 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2612 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002613 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002614 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002615 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002616 if (frame_sp)
2617 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002618 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002619 if (frame_sp)
2620 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002621 }
2622 }
2623 }
2624 }
2625}
2626
Jim Ingham6247dbe2011-07-12 03:12:18 +00002627void
2628CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2629{
2630 DumpHistory (stream, 0, count - 1);
2631}
2632
2633void
2634CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2635{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002636 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2637 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002638 {
2639 if (!m_command_history[i].empty())
2640 {
2641 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002642 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002643 }
2644 }
2645}
2646
2647const char *
2648CommandInterpreter::FindHistoryString (const char *input_str) const
2649{
2650 if (input_str[0] != m_repeat_char)
2651 return NULL;
2652 if (input_str[1] == '-')
2653 {
2654 bool success;
2655 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2656 if (!success)
2657 return NULL;
2658 if (idx > m_command_history.size())
2659 return NULL;
2660 idx = m_command_history.size() - idx;
2661 return m_command_history[idx].c_str();
2662
2663 }
2664 else if (input_str[1] == m_repeat_char)
2665 {
2666 if (m_command_history.empty())
2667 return NULL;
2668 else
2669 return m_command_history.back().c_str();
2670 }
2671 else
2672 {
2673 bool success;
2674 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2675 if (!success)
2676 return NULL;
2677 if (idx >= m_command_history.size())
2678 return NULL;
2679 return m_command_history[idx].c_str();
2680 }
2681}