blob: 3e6597b2c6db1da17be5b3d8470e37e7e1350e3d [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);
Greg Clayton86c50d72012-05-18 00:04:38 +0000247 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000248 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 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000259
260 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
261 if (cmd_obj_sp)
262 {
263 alias_arguments_vector_sp.reset (new OptionArgVector);
264 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
265 AddAlias ("rb", cmd_obj_sp);
266 AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
267 }
Chris Lattner24943d22010-06-08 16:52:24 +0000268}
269
Chris Lattner24943d22010-06-08 16:52:24 +0000270const char *
271CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
272{
273 // This function has not yet been implemented.
274
275 // Look for any embedded script command
276 // If found,
277 // get interpreter object from the command dictionary,
278 // call execute_one_command on it,
279 // get the results as a string,
280 // substitute that string for current stuff.
281
282 return arg;
283}
284
285
286void
287CommandInterpreter::LoadCommandDictionary ()
288{
289 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
290
291 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
292 //
293 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
294 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
295 // the cross-referencing stuff) are created!!!
296 //
297 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
298
299
300 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
301 // are created. This is so that when another command is created that needs to go into a crossref object,
302 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
303 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
304
Chris Lattner24943d22010-06-08 16:52:24 +0000305 // Non-CommandObjectCrossref commands can now be created.
306
Caroline Tice5bc8c972010-09-20 20:44:43 +0000307 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000308
Greg Clayton238c0a12010-09-18 01:14:36 +0000309 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000310 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000311 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000312 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000313 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
314 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000315// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000316 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000317 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000318 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000319 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
320 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000321 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000322 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000323 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000324 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000325 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000326 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000327 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000328 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
329 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000330 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000331 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000332 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000333
334 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000335 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000336 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000337 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000338 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000339 if (break_regex_cmd_ap.get())
340 {
341 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
342 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
343 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000344 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000345 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000346 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000347 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
348 {
349 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
350 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
351 }
352 }
Jim Inghame56493f2011-03-22 02:29:32 +0000353
354 std::auto_ptr<CommandObjectRegexCommand>
355 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000356 "_regexp-down",
357 "Go down \"n\" frames in the stack (1 frame by default).",
358 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000359 if (down_regex_cmd_ap.get())
360 {
361 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
362 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
363 {
364 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
365 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
366 }
367 }
368
369 std::auto_ptr<CommandObjectRegexCommand>
370 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000371 "_regexp-up",
372 "Go up \"n\" frames in the stack (1 frame by default).",
373 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000374 if (up_regex_cmd_ap.get())
375 {
376 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
377 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
378 {
379 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
380 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
381 }
382 }
Jason Molenda730cae02011-10-22 01:30:52 +0000383
384 std::auto_ptr<CommandObjectRegexCommand>
385 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000386 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000387 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000388 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000389 if (display_regex_cmd_ap.get())
390 {
391 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
392 {
393 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
394 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
395 }
396 }
397
398 std::auto_ptr<CommandObjectRegexCommand>
399 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000400 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000401 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000402 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000403 if (undisplay_regex_cmd_ap.get())
404 {
405 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
406 {
407 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
408 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
409 }
410 }
411
Chris Lattner24943d22010-06-08 16:52:24 +0000412}
413
414int
415CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
416 StringList &matches)
417{
418 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
419
420 if (include_aliases)
421 {
422 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
423 }
424
425 return matches.GetSize();
426}
427
428CommandObjectSP
429CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
430{
431 CommandObject::CommandMap::iterator pos;
432 CommandObjectSP ret_val;
433
434 std::string cmd(cmd_cstr);
435
436 if (HasCommands())
437 {
438 pos = m_command_dict.find(cmd);
439 if (pos != m_command_dict.end())
440 ret_val = pos->second;
441 }
442
443 if (include_aliases && HasAliases())
444 {
445 pos = m_alias_dict.find(cmd);
446 if (pos != m_alias_dict.end())
447 ret_val = pos->second;
448 }
449
450 if (HasUserCommands())
451 {
452 pos = m_user_dict.find(cmd);
453 if (pos != m_user_dict.end())
454 ret_val = pos->second;
455 }
456
457 if (!exact && ret_val == NULL)
458 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000459 // We will only get into here if we didn't find any exact matches.
460
461 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
462
Chris Lattner24943d22010-06-08 16:52:24 +0000463 StringList local_matches;
464 if (matches == NULL)
465 matches = &local_matches;
466
Jim Inghamd40f8a62010-07-06 22:46:59 +0000467 unsigned int num_cmd_matches = 0;
468 unsigned int num_alias_matches = 0;
469 unsigned int num_user_matches = 0;
470
471 // Look through the command dictionaries one by one, and if we get only one match from any of
472 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
473
Chris Lattner24943d22010-06-08 16:52:24 +0000474 if (HasCommands())
475 {
476 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
477 }
478
479 if (num_cmd_matches == 1)
480 {
481 cmd.assign(matches->GetStringAtIndex(0));
482 pos = m_command_dict.find(cmd);
483 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000484 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000485 }
486
Jim Ingham9a574172010-06-24 20:28:42 +0000487 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000488 {
489 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
490
491 }
492
Jim Inghamd40f8a62010-07-06 22:46:59 +0000493 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000494 {
495 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
496 pos = m_alias_dict.find(cmd);
497 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000498 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000499 }
500
Jim Ingham9a574172010-06-24 20:28:42 +0000501 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000502 {
503 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
504 }
505
Jim Inghamd40f8a62010-07-06 22:46:59 +0000506 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000507 {
508 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
509
510 pos = m_user_dict.find (cmd);
511 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000512 user_match_sp = pos->second;
513 }
514
515 // If we got exactly one match, return that, otherwise return the match list.
516
517 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
518 {
519 if (num_cmd_matches)
520 return real_match_sp;
521 else if (num_alias_matches)
522 return alias_match_sp;
523 else
524 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000525 }
526 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000527 else if (matches && ret_val != NULL)
528 {
529 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000530 }
531
532
533 return ret_val;
534}
535
Greg Claytond12aeab2011-04-20 16:37:46 +0000536bool
537CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
538{
539 if (name && name[0])
540 {
541 std::string name_sstr(name);
542 if (!can_replace)
543 {
544 if (m_command_dict.find (name_sstr) != m_command_dict.end())
545 return false;
546 }
547 m_command_dict[name_sstr] = cmd_sp;
548 return true;
549 }
550 return false;
551}
552
Enrico Granata6b1596d2011-08-16 23:24:13 +0000553bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000554CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000555 const lldb::CommandObjectSP &cmd_sp,
556 bool can_replace)
557{
Enrico Granata6010ace2011-11-07 22:57:04 +0000558 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000559 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000560
561 const char* name_cstr = name.c_str();
562
563 // do not allow replacement of internal commands
564 if (CommandExists(name_cstr))
565 return false;
566
567 if (can_replace == false && UserCommandExists(name_cstr))
568 return false;
569
570 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000571 return true;
572 }
573 return false;
574}
Greg Claytond12aeab2011-04-20 16:37:46 +0000575
Jim Inghamd40f8a62010-07-06 22:46:59 +0000576CommandObjectSP
577CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000578{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000579 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
580 CommandObjectSP ret_val; // Possibly empty return value.
581
582 if (cmd_cstr == NULL)
583 return ret_val;
584
585 if (cmd_words.GetArgumentCount() == 1)
586 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
587 else
588 {
589 // We have a multi-word command (seemingly), so we need to do more work.
590 // First, get the cmd_obj_sp for the first word in the command.
591 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
592 if (cmd_obj_sp.get() != NULL)
593 {
594 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
595 // command name), and find the appropriate sub-command SP for each command word....
596 size_t end = cmd_words.GetArgumentCount();
597 for (size_t j= 1; j < end; ++j)
598 {
599 if (cmd_obj_sp->IsMultiwordObject())
600 {
601 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
602 (cmd_words.GetArgumentAtIndex (j));
603 if (cmd_obj_sp.get() == NULL)
604 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
605 return ret_val;
606 }
607 else
608 // We have more words in the command name, but we don't have a multiword object. Fail and return
609 // empty 'ret_val'.
610 return ret_val;
611 }
612 // We successfully looped through all the command words and got valid command objects for them. Assign the
613 // last object retrieved to 'ret_val'.
614 ret_val = cmd_obj_sp;
615 }
616 }
617 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000618}
619
620CommandObject *
621CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
622{
623 return GetCommandSPExact (cmd_cstr, include_aliases).get();
624}
625
626CommandObject *
627CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
628{
629 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
630
631 // If we didn't find an exact match to the command string in the commands, look in
632 // the aliases.
633
634 if (command_obj == NULL)
635 {
636 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
637 }
638
639 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
640 // in both the commands and the aliases.
641
642 if (command_obj == NULL)
643 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
644
645 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000646}
647
648bool
649CommandInterpreter::CommandExists (const char *cmd)
650{
651 return m_command_dict.find(cmd) != m_command_dict.end();
652}
653
654bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000655CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
656 const char *options_args,
657 OptionArgVectorSP &option_arg_vector_sp)
658{
659 bool success = true;
660 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
661
662 if (!options_args || (strlen (options_args) < 1))
663 return true;
664
665 std::string options_string (options_args);
666 Args args (options_args);
667 CommandReturnObject result;
668 // Check to see if the command being aliased can take any command options.
669 Options *options = cmd_obj_sp->GetOptions ();
670 if (options)
671 {
672 // See if any options were specified as part of the alias; if so, handle them appropriately.
673 options->NotifyOptionParsingStarting ();
674 args.Unshift ("dummy_arg");
675 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
676 args.Shift ();
677 if (result.Succeeded())
678 options->VerifyPartialOptions (result);
679 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
680 {
681 result.AppendError ("Unable to create requested alias.\n");
682 return false;
683 }
684 }
685
Greg Clayton7268b4c2011-10-28 21:38:01 +0000686 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000687 {
688 if (cmd_obj_sp->WantsRawCommandString ())
689 option_arg_vector->push_back (OptionArgPair ("<argument>",
690 OptionArgValue (-1,
691 options_string)));
692 else
693 {
694 int argc = args.GetArgumentCount();
695 for (size_t i = 0; i < argc; ++i)
696 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
697 option_arg_vector->push_back
698 (OptionArgPair ("<argument>",
699 OptionArgValue (-1,
700 std::string (args.GetArgumentAtIndex (i)))));
701 }
702 }
703
704 return success;
705}
706
707bool
Chris Lattner24943d22010-06-08 16:52:24 +0000708CommandInterpreter::AliasExists (const char *cmd)
709{
710 return m_alias_dict.find(cmd) != m_alias_dict.end();
711}
712
713bool
714CommandInterpreter::UserCommandExists (const char *cmd)
715{
716 return m_user_dict.find(cmd) != m_user_dict.end();
717}
718
719void
720CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
721{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000722 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000723 m_alias_dict[alias_name] = command_obj_sp;
724}
725
726bool
727CommandInterpreter::RemoveAlias (const char *alias_name)
728{
729 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
730 if (pos != m_alias_dict.end())
731 {
732 m_alias_dict.erase(pos);
733 return true;
734 }
735 return false;
736}
737bool
738CommandInterpreter::RemoveUser (const char *alias_name)
739{
740 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
741 if (pos != m_user_dict.end())
742 {
743 m_user_dict.erase(pos);
744 return true;
745 }
746 return false;
747}
748
Chris Lattner24943d22010-06-08 16:52:24 +0000749void
750CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
751{
752 help_string.Printf ("'%s", command_name);
753 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
754
755 if (option_arg_vector_sp != NULL)
756 {
757 OptionArgVector *options = option_arg_vector_sp.get();
758 for (int i = 0; i < options->size(); ++i)
759 {
760 OptionArgPair cur_option = (*options)[i];
761 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000762 OptionArgValue value_pair = cur_option.second;
763 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000764 if (opt.compare("<argument>") == 0)
765 {
766 help_string.Printf (" %s", value.c_str());
767 }
768 else
769 {
770 help_string.Printf (" %s", opt.c_str());
771 if ((value.compare ("<no-argument>") != 0)
772 && (value.compare ("<need-argument") != 0))
773 {
774 help_string.Printf (" %s", value.c_str());
775 }
776 }
777 }
778 }
779
780 help_string.Printf ("'");
781}
782
Greg Clayton65124ea2010-08-26 22:05:43 +0000783size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000784CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
785{
786 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000787 CommandObject::CommandMap::const_iterator end = dict.end();
788 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000789
Greg Clayton65124ea2010-08-26 22:05:43 +0000790 for (pos = dict.begin(); pos != end; ++pos)
791 {
792 size_t len = pos->first.size();
793 if (max_len < len)
794 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000795 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000796 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000797}
798
799void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000800CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000801 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000802{
803 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000804 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000805
806 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000807 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000808
809 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
810 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000811
Enrico Granata6b1596d2011-08-16 23:24:13 +0000812 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
813 {
814 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
815 max_len);
816 }
817 result.AppendMessage("");
818
819 }
820
Greg Clayton7268b4c2011-10-28 21:38:01 +0000821 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000822 {
Jim Inghame3663e82010-10-22 18:47:16 +0000823 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000824 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000825 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000826 max_len = FindLongestCommandWord (m_alias_dict);
827
Chris Lattner24943d22010-06-08 16:52:24 +0000828 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
829 {
830 StreamString sstr;
831 StreamString translation_and_help;
832 std::string entry_name = pos->first;
833 std::string second_entry = pos->second.get()->GetCommandName();
834 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
835
836 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
837 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
838 translation_and_help.GetData(), max_len);
839 }
840 result.AppendMessage("");
841 }
842
Greg Clayton7268b4c2011-10-28 21:38:01 +0000843 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000844 {
845 result.AppendMessage ("The following is a list of your current user-defined commands:");
846 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000847 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000848 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
849 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000850 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
851 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000852 }
853 result.AppendMessage("");
854 }
855
856 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
857}
858
Caroline Ticee0da7a52010-12-09 22:52:49 +0000859CommandObject *
860CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000861{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000862 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
863 // eventually be invoked by the given command line.
864
865 CommandObject *cmd_obj = NULL;
866 std::string white_space (" \t\v");
867 size_t start = command_string.find_first_not_of (white_space);
868 size_t end = 0;
869 bool done = false;
870 while (!done)
871 {
872 if (start != std::string::npos)
873 {
874 // Get the next word from command_string.
875 end = command_string.find_first_of (white_space, start);
876 if (end == std::string::npos)
877 end = command_string.size();
878 std::string cmd_word = command_string.substr (start, end - start);
879
880 if (cmd_obj == NULL)
881 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
882 // command or alias.
883 cmd_obj = GetCommandObject (cmd_word.c_str());
884 else if (cmd_obj->IsMultiwordObject ())
885 {
886 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
887 CommandObject *sub_cmd_obj =
888 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
889 if (sub_cmd_obj)
890 cmd_obj = sub_cmd_obj;
891 else // cmd_word was not a valid sub-command word, so we are donee
892 done = true;
893 }
894 else
895 // We have a cmd_obj and it is not a multi-word object, so we are done.
896 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000897
Caroline Ticee0da7a52010-12-09 22:52:49 +0000898 // If we didn't find a valid command object, or our command object is not a multi-word object, or
899 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
900 // next word.
901
902 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
903 done = true;
904 else
905 start = command_string.find_first_not_of (white_space, end);
906 }
907 else
908 // Unable to find any more words.
909 done = true;
910 }
911
912 if (end == command_string.size())
913 command_string.clear();
914 else
915 command_string = command_string.substr(end);
916
917 return cmd_obj;
918}
919
Greg Clayton9d855c62011-10-25 00:36:27 +0000920static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000921static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000922static void
923StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000924{
Greg Clayton9d855c62011-10-25 00:36:27 +0000925 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000926 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000927 size_t pos = s.find_first_not_of (k_white_space);
928 if (pos == std::string::npos)
929 s.clear();
930 else if (pos == 0)
931 return;
932 s.erase (0, pos);
933 }
934}
935
Greg Clayton3840cd72011-11-09 23:25:03 +0000936static size_t
937FindArgumentTerminator (const std::string &s)
938{
Greg Clayton3840cd72011-11-09 23:25:03 +0000939 const size_t s_len = s.size();
940 size_t offset = 0;
941 while (offset < s_len)
942 {
943 size_t pos = s.find ("--", offset);
944 if (pos == std::string::npos)
945 break;
946 if (pos > 0)
947 {
948 if (isspace(s[pos-1]))
949 {
950 // Check if the string ends "\s--" (where \s is a space character)
951 // or if we have "\s--\s".
952 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
953 {
Greg Clayton3840cd72011-11-09 23:25:03 +0000954 return pos;
955 }
956 }
957 }
958 offset = pos + 2;
959 }
Greg Clayton3840cd72011-11-09 23:25:03 +0000960 return std::string::npos;
961}
962
Greg Clayton9d855c62011-10-25 00:36:27 +0000963static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000964ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000965{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000966 command.clear();
967 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000968 StripLeadingSpaces (command_string);
969
970 bool result = false;
971 quote_char = '\0';
972
973 if (!command_string.empty())
974 {
975 const char first_char = command_string[0];
976 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000977 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000978 quote_char = first_char;
979 const size_t end_quote_pos = command_string.find (quote_char, 1);
980 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000981 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000982 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000983 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000984 }
985 else
986 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000987 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +0000988 if (end_quote_pos + 1 < command_string.size())
989 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
990 else
991 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000992 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000993 }
994 else
995 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000996 const size_t first_space_pos = command_string.find_first_of (k_white_space);
997 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000998 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000999 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001000 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001001 }
1002 else
1003 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001004 command.assign (command_string, 0, first_space_pos);
1005 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001006 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001007 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001008 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001009 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001010
1011
1012 if (!command.empty())
1013 {
1014 // actual commands can't start with '-' or '_'
1015 if (command[0] != '-' && command[0] != '_')
1016 {
1017 size_t pos = command.find_first_not_of(k_valid_command_chars);
1018 if (pos > 0 && pos != std::string::npos)
1019 {
1020 suffix.assign (command.begin() + pos, command.end());
1021 command.erase (pos);
1022 }
1023 }
1024 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001025
1026 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001027}
1028
Greg Clayton7268b4c2011-10-28 21:38:01 +00001029CommandObject *
1030CommandInterpreter::BuildAliasResult (const char *alias_name,
1031 std::string &raw_input_string,
1032 std::string &alias_result,
1033 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001034{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001035 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001036 Args cmd_args (raw_input_string.c_str());
1037 alias_cmd_obj = GetCommandObject (alias_name);
1038 StreamString result_str;
1039
1040 if (alias_cmd_obj)
1041 {
1042 std::string alias_name_str = alias_name;
1043 if ((cmd_args.GetArgumentCount() == 0)
1044 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1045 cmd_args.Unshift (alias_name);
1046
1047 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1048 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1049
1050 if (option_arg_vector_sp.get())
1051 {
1052 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1053
1054 for (int i = 0; i < option_arg_vector->size(); ++i)
1055 {
1056 OptionArgPair option_pair = (*option_arg_vector)[i];
1057 OptionArgValue value_pair = option_pair.second;
1058 int value_type = value_pair.first;
1059 std::string option = option_pair.first;
1060 std::string value = value_pair.second;
1061 if (option.compare ("<argument>") == 0)
1062 result_str.Printf (" %s", value.c_str());
1063 else
1064 {
1065 result_str.Printf (" %s", option.c_str());
1066 if (value_type != optional_argument)
1067 result_str.Printf (" ");
1068 if (value.compare ("<no_argument>") != 0)
1069 {
1070 int index = GetOptionArgumentPosition (value.c_str());
1071 if (index == 0)
1072 result_str.Printf ("%s", value.c_str());
1073 else if (index >= cmd_args.GetArgumentCount())
1074 {
1075
1076 result.AppendErrorWithFormat
1077 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1078 index);
1079 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001080 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001081 }
1082 else
1083 {
1084 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1085 if (strpos != std::string::npos)
1086 raw_input_string = raw_input_string.erase (strpos,
1087 strlen (cmd_args.GetArgumentAtIndex (index)));
1088 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1089 }
1090 }
1091 }
1092 }
1093 }
1094
1095 alias_result = result_str.GetData();
1096 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001097 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001098}
1099
Greg Claytonf5c0c722011-10-14 07:41:33 +00001100Error
1101CommandInterpreter::PreprocessCommand (std::string &command)
1102{
1103 // The command preprocessor needs to do things to the command
1104 // line before any parsing of arguments or anything else is done.
1105 // The only current stuff that gets proprocessed is anyting enclosed
1106 // in backtick ('`') characters is evaluated as an expression and
1107 // the result of the expression must be a scalar that can be substituted
1108 // into the command. An example would be:
1109 // (lldb) memory read `$rsp + 20`
1110 Error error; // Error for any expressions that might not evaluate
1111 size_t start_backtick;
1112 size_t pos = 0;
1113 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1114 {
1115 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1116 {
1117 // The backtick was preceeded by a '\' character, remove the slash
1118 // and don't treat the backtick as the start of an expression
1119 command.erase(start_backtick-1, 1);
1120 // No need to add one to start_backtick since we just deleted a char
1121 pos = start_backtick;
1122 }
1123 else
1124 {
1125 const size_t expr_content_start = start_backtick + 1;
1126 const size_t end_backtick = command.find ('`', expr_content_start);
1127 if (end_backtick == std::string::npos)
1128 return error;
1129 else if (end_backtick == expr_content_start)
1130 {
1131 // Empty expression (two backticks in a row)
1132 command.erase (start_backtick, 2);
1133 }
1134 else
1135 {
1136 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1137
1138 Target *target = m_exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001139 // Get a dummy target to allow for calculator mode while processing backticks.
1140 // This also helps break the infinite loop caused when target is null.
1141 if (!target)
1142 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001143 if (target)
1144 {
Sean Callanandaa6efe2011-12-21 22:22:58 +00001145 const bool coerce_to_id = false;
Greg Claytonf5c0c722011-10-14 07:41:33 +00001146 const bool unwind_on_error = true;
1147 const bool keep_in_memory = false;
1148 ValueObjectSP expr_result_valobj_sp;
1149 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1150 m_exe_ctx.GetFramePtr(),
1151 eExecutionPolicyOnlyWhenNeeded,
Sean Callanandaa6efe2011-12-21 22:22:58 +00001152 coerce_to_id,
1153 unwind_on_error,
1154 keep_in_memory,
Greg Claytonf5c0c722011-10-14 07:41:33 +00001155 eNoDynamicValues,
1156 expr_result_valobj_sp);
1157 if (expr_result == eExecutionCompleted)
1158 {
1159 Scalar scalar;
1160 if (expr_result_valobj_sp->ResolveValue (scalar))
1161 {
1162 command.erase (start_backtick, end_backtick - start_backtick + 1);
1163 StreamString value_strm;
1164 const bool show_type = false;
1165 scalar.GetValue (&value_strm, show_type);
1166 size_t value_string_size = value_strm.GetSize();
1167 if (value_string_size)
1168 {
1169 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1170 pos = start_backtick + value_string_size;
1171 continue;
1172 }
1173 else
1174 {
1175 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1176 }
1177 }
1178 else
1179 {
1180 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1181 }
1182 }
1183 else
1184 {
1185 if (expr_result_valobj_sp)
1186 error = expr_result_valobj_sp->GetError();
1187 if (error.Success())
1188 {
1189
1190 switch (expr_result)
1191 {
1192 case eExecutionSetupError:
1193 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1194 break;
1195 case eExecutionCompleted:
1196 break;
1197 case eExecutionDiscarded:
1198 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1199 break;
1200 case eExecutionInterrupted:
1201 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1202 break;
1203 case eExecutionTimedOut:
1204 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1205 break;
1206 }
1207 }
1208 }
1209 }
1210 }
1211 if (error.Fail())
1212 break;
1213 }
1214 }
1215 return error;
1216}
1217
1218
Caroline Ticee0da7a52010-12-09 22:52:49 +00001219bool
1220CommandInterpreter::HandleCommand (const char *command_line,
1221 bool add_to_history,
1222 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001223 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001224 bool repeat_on_empty_command,
1225 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001226
Caroline Ticee0da7a52010-12-09 22:52:49 +00001227{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001228
Caroline Ticee0da7a52010-12-09 22:52:49 +00001229 bool done = false;
1230 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001231 bool wants_raw_input = false;
1232 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001233 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001234
1235 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001236 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1237
1238 // Make a scoped cleanup object that will clear the crash description string
1239 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001240 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001241
Caroline Ticee0da7a52010-12-09 22:52:49 +00001242 if (log)
1243 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001244
Jim Inghamabab14b2010-11-04 23:08:45 +00001245 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1246
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001247 if (!no_context_switching)
1248 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +00001249
Jim Ingham949d5ac2011-02-18 00:54:25 +00001250 bool empty_command = false;
1251 bool comment_command = false;
1252 if (command_string.empty())
1253 empty_command = true;
1254 else
Chris Lattner24943d22010-06-08 16:52:24 +00001255 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001256 const char *k_space_characters = "\t\n\v\f\r ";
1257
1258 size_t non_space = command_string.find_first_not_of (k_space_characters);
1259 // Check for empty line or comment line (lines whose first
1260 // non-space character is the comment character for this interpreter)
1261 if (non_space == std::string::npos)
1262 empty_command = true;
1263 else if (command_string[non_space] == m_comment_char)
1264 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001265 else if (command_string[non_space] == m_repeat_char)
1266 {
1267 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1268 if (history_string == NULL)
1269 {
1270 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1271 result.SetStatus(eReturnStatusFailed);
1272 return false;
1273 }
1274 add_to_history = false;
1275 command_string = history_string;
1276 original_command_string = history_string;
1277 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001278 }
1279
1280 if (empty_command)
1281 {
1282 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001283 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001284 if (m_command_history.empty())
1285 {
1286 result.AppendError ("empty command");
1287 result.SetStatus(eReturnStatusFailed);
1288 return false;
1289 }
1290 else
1291 {
1292 command_line = m_repeat_command.c_str();
1293 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001294 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001295 if (m_repeat_command.empty())
1296 {
1297 result.AppendErrorWithFormat("No auto repeat.\n");
1298 result.SetStatus (eReturnStatusFailed);
1299 return false;
1300 }
1301 }
1302 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001303 }
1304 else
1305 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001306 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1307 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001308 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001309 }
1310 else if (comment_command)
1311 {
1312 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1313 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001314 }
Caroline Tice649116c2011-05-11 16:07:06 +00001315
Greg Claytonf5c0c722011-10-14 07:41:33 +00001316
1317 Error error (PreprocessCommand (command_string));
1318
1319 if (error.Fail())
1320 {
1321 result.AppendError (error.AsCString());
1322 result.SetStatus(eReturnStatusFailed);
1323 return false;
1324 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001325 // Phase 1.
1326
1327 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1328 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1329 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1330 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1331 // 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 +00001332 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001333 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001334
Caroline Ticee0da7a52010-12-09 22:52:49 +00001335 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001336 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001337 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001338 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001339 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001340 {
Caroline Tice649116c2011-05-11 16:07:06 +00001341 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001342 std::string suffix;
1343 ExtractCommand (command_string, next_word, suffix, quote_char);
1344 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001345 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001346 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001347 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001348 std::string alias_result;
1349 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1350 revised_command_line.Printf ("%s", alias_result.c_str());
1351 if (cmd_obj)
1352 {
1353 wants_raw_input = cmd_obj->WantsRawCommandString ();
1354 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1355 }
Chris Lattner24943d22010-06-08 16:52:24 +00001356 }
1357 else
1358 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001359 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001360 if (cmd_obj)
1361 {
1362 actual_cmd_name_len += next_word.length();
1363 revised_command_line.Printf ("%s", next_word.c_str());
1364 wants_raw_input = cmd_obj->WantsRawCommandString ();
1365 }
Caroline Tice649116c2011-05-11 16:07:06 +00001366 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001367 {
1368 revised_command_line.Printf ("%s", next_word.c_str());
1369 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001370 }
1371 }
1372 else
1373 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001374 if (cmd_obj->IsMultiwordObject ())
1375 {
1376 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1377 if (sub_cmd_obj)
1378 {
1379 actual_cmd_name_len += next_word.length() + 1;
1380 revised_command_line.Printf (" %s", next_word.c_str());
1381 cmd_obj = sub_cmd_obj;
1382 wants_raw_input = cmd_obj->WantsRawCommandString ();
1383 }
1384 else
1385 {
1386 if (quote_char)
1387 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1388 else
1389 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1390 done = true;
1391 }
1392 }
Caroline Tice649116c2011-05-11 16:07:06 +00001393 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001394 {
1395 if (quote_char)
1396 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1397 else
1398 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1399 done = true;
1400 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001401 }
1402
1403 if (cmd_obj == NULL)
1404 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001405 uint32_t num_matches = matches.GetSize();
1406 if (matches.GetSize() > 1) {
1407 std::string error_msg;
1408 error_msg.assign ("Ambiguous command '");
1409 error_msg.append(next_word.c_str());
1410 error_msg.append ("'.");
1411
1412 error_msg.append (" Possible matches:");
1413
1414 for (uint32_t i = 0; i < num_matches; ++i) {
1415 error_msg.append ("\n\t");
1416 error_msg.append (matches.GetStringAtIndex(i));
1417 }
1418 error_msg.append ("\n");
1419 result.AppendRawError (error_msg.c_str(), error_msg.size());
1420 } else {
1421 // We didn't have only one match, otherwise we wouldn't get here.
1422 assert(num_matches == 0);
1423 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1424 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001425 result.SetStatus (eReturnStatusFailed);
1426 return false;
1427 }
1428
Greg Clayton7268b4c2011-10-28 21:38:01 +00001429 if (cmd_obj->IsMultiwordObject ())
1430 {
1431 if (!suffix.empty())
1432 {
1433
1434 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1435 next_word.c_str(),
1436 suffix.c_str());
1437 result.SetStatus (eReturnStatusFailed);
1438 return false;
1439 }
1440 }
1441 else
1442 {
1443 // If we found a normal command, we are done
1444 done = true;
1445 if (!suffix.empty())
1446 {
1447 switch (suffix[0])
1448 {
1449 case '/':
1450 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001451 {
1452 Options *command_options = cmd_obj->GetOptions();
1453 if (command_options && command_options->SupportsLongOption("gdb-format"))
1454 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001455 std::string gdb_format_option ("--gdb-format=");
1456 gdb_format_option += (suffix.c_str() + 1);
1457
1458 bool inserted = false;
1459 std::string &cmd = revised_command_line.GetString();
1460 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1461 if (arg_terminator_idx != std::string::npos)
1462 {
1463 // Insert the gdb format option before the "--" that terminates options
1464 gdb_format_option.append(1,' ');
1465 cmd.insert(arg_terminator_idx, gdb_format_option);
1466 inserted = true;
1467 }
1468
1469 if (!inserted)
1470 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1471
1472 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1473 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001474 }
1475 else
1476 {
1477 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1478 cmd_obj->GetCommandName());
1479 result.SetStatus (eReturnStatusFailed);
1480 return false;
1481 }
1482 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001483 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001484
1485 default:
1486 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1487 suffix.c_str());
1488 result.SetStatus (eReturnStatusFailed);
1489 return false;
1490
Greg Clayton7268b4c2011-10-28 21:38:01 +00001491 }
1492 }
1493 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001494 if (command_string.length() == 0)
1495 done = true;
1496
Chris Lattner24943d22010-06-08 16:52:24 +00001497 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001498
Greg Clayton7268b4c2011-10-28 21:38:01 +00001499 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001500 revised_command_line.Printf (" %s", command_string.c_str());
1501
1502 // End of Phase 1.
1503 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1504 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1505 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1506 // wants_raw_input specifies whether the Execute method expects raw input or not.
1507
1508
1509 if (log)
1510 {
1511 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1512 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1513 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1514 }
1515
1516 // Phase 2.
1517 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1518 // CommandObject, with the appropriate arguments.
1519
1520 if (cmd_obj != NULL)
1521 {
1522 if (add_to_history)
1523 {
1524 Args command_args (revised_command_line.GetData());
1525 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1526 if (repeat_command != NULL)
1527 m_repeat_command.assign(repeat_command);
1528 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001529 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001530
Jim Ingham6247dbe2011-07-12 03:12:18 +00001531 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001532 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001533 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001534 }
1535
1536 command_string = revised_command_line.GetData();
1537 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001538 std::string remainder;
1539 if (actual_cmd_name_len < command_string.length())
1540 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1541 // than cmd_obj->GetCommandName(), because name completion
1542 // allows users to enter short versions of the names,
1543 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001544
1545 // Remove any initial spaces
1546 std::string white_space (" \t\v");
1547 size_t pos = remainder.find_first_not_of (white_space);
1548 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001549 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001550
1551 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001552 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001553
1554
Greg Claytonf1252502012-02-29 04:21:24 +00001555 CommandOverrideCallback command_callback = cmd_obj->GetOverrideCallback();
1556 bool handled = false;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001557 if (wants_raw_input)
Greg Claytonf1252502012-02-29 04:21:24 +00001558 {
1559 if (command_callback)
1560 {
1561 std::string full_command (cmd_obj->GetCommandName ());
1562 full_command += ' ';
1563 full_command += remainder;
1564 const char *argv[2] = { NULL, NULL };
1565 argv[0] = full_command.c_str();
1566 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), argv);
1567 }
1568 if (!handled)
1569 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1570 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001571 else
1572 {
1573 Args cmd_args (remainder.c_str());
Greg Claytonf1252502012-02-29 04:21:24 +00001574 if (command_callback)
1575 {
1576 Args full_args (cmd_obj->GetCommandName ());
1577 full_args.AppendArguments(cmd_args);
1578 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), full_args.GetConstArgumentVector());
1579 }
1580 if (!handled)
1581 cmd_obj->ExecuteWithOptions (cmd_args, result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001582 }
1583 }
1584 else
1585 {
1586 // We didn't find the first command object, so complete the first argument.
1587 Args command_args (revised_command_line.GetData());
1588 StringList matches;
1589 int num_matches;
1590 int cursor_index = 0;
1591 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1592 bool word_complete;
1593 num_matches = HandleCompletionMatches (command_args,
1594 cursor_index,
1595 cursor_char_position,
1596 0,
1597 -1,
1598 word_complete,
1599 matches);
1600
1601 if (num_matches > 0)
1602 {
1603 std::string error_msg;
1604 error_msg.assign ("ambiguous command '");
1605 error_msg.append(command_args.GetArgumentAtIndex(0));
1606 error_msg.append ("'.");
1607
1608 error_msg.append (" Possible completions:");
1609 for (int i = 0; i < num_matches; i++)
1610 {
1611 error_msg.append ("\n\t");
1612 error_msg.append (matches.GetStringAtIndex (i));
1613 }
1614 error_msg.append ("\n");
1615 result.AppendRawError (error_msg.c_str(), error_msg.size());
1616 }
1617 else
1618 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1619
1620 result.SetStatus (eReturnStatusFailed);
1621 }
1622
Jason Molenda24c991c2011-08-25 00:20:04 +00001623 if (log)
1624 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1625
Chris Lattner24943d22010-06-08 16:52:24 +00001626 return result.Succeeded();
1627}
1628
1629int
1630CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1631 int &cursor_index,
1632 int &cursor_char_position,
1633 int match_start_point,
1634 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001635 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001636 StringList &matches)
1637{
1638 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001639 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001640
1641 // For any of the command completions a unique match will be a complete word.
1642 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001643
1644 if (cursor_index == -1)
1645 {
1646 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001647 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001648 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1649 }
1650 else if (cursor_index == 0)
1651 {
1652 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001653 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001654 num_command_matches = matches.GetSize();
1655
1656 if (num_command_matches == 1
1657 && cmd_obj && cmd_obj->IsMultiwordObject()
1658 && matches.GetStringAtIndex(0) != NULL
1659 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1660 {
1661 look_for_subcommand = true;
1662 num_command_matches = 0;
1663 matches.DeleteStringAtIndex(0);
1664 parsed_line.AppendArgument ("");
1665 cursor_index++;
1666 cursor_char_position = 0;
1667 }
1668 }
1669
1670 if (cursor_index > 0 || look_for_subcommand)
1671 {
1672 // We are completing further on into a commands arguments, so find the command and tell it
1673 // to complete the command.
1674 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001675 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001676 if (command_object == NULL)
1677 {
1678 return 0;
1679 }
1680 else
1681 {
1682 parsed_line.Shift();
1683 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001684 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001685 cursor_index,
1686 cursor_char_position,
1687 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001688 max_return_elements,
1689 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001690 matches);
1691 }
1692 }
1693
1694 return num_command_matches;
1695
1696}
1697
1698int
1699CommandInterpreter::HandleCompletion (const char *current_line,
1700 const char *cursor,
1701 const char *last_char,
1702 int match_start_point,
1703 int max_return_elements,
1704 StringList &matches)
1705{
1706 // We parse the argument up to the cursor, so the last argument in parsed_line is
1707 // the one containing the cursor, and the cursor is after the last character.
1708
1709 Args parsed_line(current_line, last_char - current_line);
1710 Args partial_parsed_line(current_line, cursor - current_line);
1711
Jim Ingham6247dbe2011-07-12 03:12:18 +00001712 // Don't complete comments, and if the line we are completing is just the history repeat character,
1713 // substitute the appropriate history line.
1714 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1715 if (first_arg)
1716 {
1717 if (first_arg[0] == m_comment_char)
1718 return 0;
1719 else if (first_arg[0] == m_repeat_char)
1720 {
1721 const char *history_string = FindHistoryString (first_arg);
1722 if (history_string != NULL)
1723 {
1724 matches.Clear();
1725 matches.InsertStringAtIndex(0, history_string);
1726 return -2;
1727 }
1728 else
1729 return 0;
1730
1731 }
1732 }
1733
1734
Chris Lattner24943d22010-06-08 16:52:24 +00001735 int num_args = partial_parsed_line.GetArgumentCount();
1736 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1737 int cursor_char_position;
1738
1739 if (cursor_index == -1)
1740 cursor_char_position = 0;
1741 else
1742 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001743
1744 if (cursor > current_line && cursor[-1] == ' ')
1745 {
1746 // We are just after a space. If we are in an argument, then we will continue
1747 // parsing, but if we are between arguments, then we have to complete whatever the next
1748 // element would be.
1749 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1750 // protected by a quote) then the space will also be in the parsed argument...
1751
1752 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1753 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1754 {
1755 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1756 cursor_index++;
1757 cursor_char_position = 0;
1758 }
1759 }
Chris Lattner24943d22010-06-08 16:52:24 +00001760
1761 int num_command_matches;
1762
1763 matches.Clear();
1764
1765 // Only max_return_elements == -1 is supported at present:
1766 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001767 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001768 num_command_matches = HandleCompletionMatches (parsed_line,
1769 cursor_index,
1770 cursor_char_position,
1771 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001772 max_return_elements,
1773 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001774 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001775
1776 if (num_command_matches <= 0)
1777 return num_command_matches;
1778
1779 if (num_args == 0)
1780 {
1781 // If we got an empty string, insert nothing.
1782 matches.InsertStringAtIndex(0, "");
1783 }
1784 else
1785 {
1786 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1787 // put an empty string in element 0.
1788 std::string command_partial_str;
1789 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001790 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1791 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001792
1793 std::string common_prefix;
1794 matches.LongestCommonPrefix (common_prefix);
1795 int partial_name_len = command_partial_str.size();
1796
1797 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001798 // Only do this if the completer told us this was a complete word, however...
1799 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001800 {
1801 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1802 if (quote_char != '\0')
1803 common_prefix.push_back(quote_char);
1804
1805 common_prefix.push_back(' ');
1806 }
1807 common_prefix.erase (0, partial_name_len);
1808 matches.InsertStringAtIndex(0, common_prefix.c_str());
1809 }
1810 return num_command_matches;
1811}
1812
Chris Lattner24943d22010-06-08 16:52:24 +00001813
1814CommandInterpreter::~CommandInterpreter ()
1815{
1816}
1817
1818const char *
1819CommandInterpreter::GetPrompt ()
1820{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001821 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001822}
1823
1824void
1825CommandInterpreter::SetPrompt (const char *new_prompt)
1826{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001827 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001828}
1829
Jim Ingham5e16ef52010-10-04 19:49:29 +00001830size_t
Greg Clayton58928562011-02-09 01:08:52 +00001831CommandInterpreter::GetConfirmationInputReaderCallback
1832(
1833 void *baton,
1834 InputReader &reader,
1835 lldb::InputReaderAction action,
1836 const char *bytes,
1837 size_t bytes_len
1838)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001839{
Greg Clayton58928562011-02-09 01:08:52 +00001840 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001841 bool *response_ptr = (bool *) baton;
1842
1843 switch (action)
1844 {
1845 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001846 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001847 {
1848 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001849 {
Greg Clayton58928562011-02-09 01:08:52 +00001850 out_file.Printf ("%s", reader.GetPrompt());
1851 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001852 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001853 }
1854 break;
1855
1856 case eInputReaderDeactivate:
1857 break;
1858
1859 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001860 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001861 {
Greg Clayton58928562011-02-09 01:08:52 +00001862 out_file.Printf ("%s", reader.GetPrompt());
1863 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001864 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001865 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001866
1867 case eInputReaderAsynchronousOutputWritten:
1868 break;
1869
Jim Ingham5e16ef52010-10-04 19:49:29 +00001870 case eInputReaderGotToken:
1871 if (bytes_len == 0)
1872 {
1873 reader.SetIsDone(true);
1874 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001875 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001876 {
1877 *response_ptr = true;
1878 reader.SetIsDone(true);
1879 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001880 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001881 {
1882 *response_ptr = false;
1883 reader.SetIsDone(true);
1884 }
1885 else
1886 {
Greg Clayton58928562011-02-09 01:08:52 +00001887 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001888 {
Jim Ingham26183802011-11-17 01:22:00 +00001889 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001890 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001891 }
1892 }
1893 break;
1894
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001895 case eInputReaderInterrupt:
1896 case eInputReaderEndOfFile:
1897 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1898 reader.SetIsDone (true);
1899 break;
1900
Jim Ingham5e16ef52010-10-04 19:49:29 +00001901 case eInputReaderDone:
1902 break;
1903 }
1904
1905 return bytes_len;
1906
1907}
1908
1909bool
1910CommandInterpreter::Confirm (const char *message, bool default_answer)
1911{
Jim Ingham93057472010-10-04 22:44:14 +00001912 // Check AutoConfirm first:
1913 if (m_debugger.GetAutoConfirm())
1914 return default_answer;
1915
Jim Ingham5e16ef52010-10-04 19:49:29 +00001916 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1917 bool response = default_answer;
1918 if (reader_sp)
1919 {
1920 std::string prompt(message);
1921 prompt.append(": [");
1922 if (default_answer)
1923 prompt.append ("Y/n] ");
1924 else
1925 prompt.append ("y/N] ");
1926
1927 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1928 &response, // baton
1929 eInputReaderGranularityLine, // token size, to pass to callback function
1930 NULL, // end token
1931 prompt.c_str(), // prompt
1932 true)); // echo input
1933 if (err.Success())
1934 {
1935 GetDebugger().PushInputReader (reader_sp);
1936 }
1937 reader_sp->WaitOnReaderIsDone();
1938 }
1939 return response;
1940}
1941
1942
Chris Lattner24943d22010-06-08 16:52:24 +00001943void
1944CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1945{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001946 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001947
1948 if (cmd_obj_sp != NULL)
1949 {
1950 CommandObject *cmd_obj = cmd_obj_sp.get();
1951 if (cmd_obj->IsCrossRefObject ())
1952 cmd_obj->AddObject (object_type);
1953 }
1954}
1955
Chris Lattner24943d22010-06-08 16:52:24 +00001956OptionArgVectorSP
1957CommandInterpreter::GetAliasOptions (const char *alias_name)
1958{
1959 OptionArgMap::iterator pos;
1960 OptionArgVectorSP ret_val;
1961
1962 std::string alias (alias_name);
1963
1964 if (HasAliasOptions())
1965 {
1966 pos = m_alias_options.find (alias);
1967 if (pos != m_alias_options.end())
1968 ret_val = pos->second;
1969 }
1970
1971 return ret_val;
1972}
1973
1974void
1975CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1976{
1977 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1978 if (pos != m_alias_options.end())
1979 {
1980 m_alias_options.erase (pos);
1981 }
1982}
1983
1984void
1985CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1986{
1987 m_alias_options[alias_name] = option_arg_vector_sp;
1988}
1989
1990bool
1991CommandInterpreter::HasCommands ()
1992{
1993 return (!m_command_dict.empty());
1994}
1995
1996bool
1997CommandInterpreter::HasAliases ()
1998{
1999 return (!m_alias_dict.empty());
2000}
2001
2002bool
2003CommandInterpreter::HasUserCommands ()
2004{
2005 return (!m_user_dict.empty());
2006}
2007
2008bool
2009CommandInterpreter::HasAliasOptions ()
2010{
2011 return (!m_alias_options.empty());
2012}
2013
Chris Lattner24943d22010-06-08 16:52:24 +00002014void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002015CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2016 const char *alias_name,
2017 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002018 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002019 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002020{
2021 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002022
2023 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002024
Caroline Tice44c841d2010-12-07 19:58:26 +00002025 // Make sure that the alias name is the 0th element in cmd_args
2026 std::string alias_name_str = alias_name;
2027 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2028 cmd_args.Unshift (alias_name);
2029
2030 Args new_args (alias_cmd_obj->GetCommandName());
2031 if (new_args.GetArgumentCount() == 2)
2032 new_args.Shift();
2033
Chris Lattner24943d22010-06-08 16:52:24 +00002034 if (option_arg_vector_sp.get())
2035 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002036 if (wants_raw_input)
2037 {
2038 // We have a command that both has command options and takes raw input. Make *sure* it has a
2039 // " -- " in the right place in the raw_input_string.
2040 size_t pos = raw_input_string.find(" -- ");
2041 if (pos == std::string::npos)
2042 {
2043 // None found; assume it goes at the beginning of the raw input string
2044 raw_input_string.insert (0, " -- ");
2045 }
2046 }
Chris Lattner24943d22010-06-08 16:52:24 +00002047
2048 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2049 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002050 std::vector<bool> used (old_size + 1, false);
2051
2052 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002053
2054 for (int i = 0; i < option_arg_vector->size(); ++i)
2055 {
2056 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002057 OptionArgValue value_pair = option_pair.second;
2058 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002059 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002060 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002061 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002062 {
2063 if (!wants_raw_input
2064 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2065 new_args.AppendArgument (value.c_str());
2066 }
Chris Lattner24943d22010-06-08 16:52:24 +00002067 else
2068 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002069 if (value_type != optional_argument)
2070 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002071 if (value.compare ("<no-argument>") != 0)
2072 {
2073 int index = GetOptionArgumentPosition (value.c_str());
2074 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002075 {
Chris Lattner24943d22010-06-08 16:52:24 +00002076 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002077 if (value_type != optional_argument)
2078 new_args.AppendArgument (value.c_str());
2079 else
2080 {
2081 char buffer[255];
2082 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2083 new_args.AppendArgument (buffer);
2084 }
2085
2086 }
Chris Lattner24943d22010-06-08 16:52:24 +00002087 else if (index >= cmd_args.GetArgumentCount())
2088 {
2089 result.AppendErrorWithFormat
2090 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2091 index);
2092 result.SetStatus (eReturnStatusFailed);
2093 return;
2094 }
2095 else
2096 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002097 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2098 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2099 if (strpos != std::string::npos)
2100 {
2101 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2102 }
2103
2104 if (value_type != optional_argument)
2105 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2106 else
2107 {
2108 char buffer[255];
2109 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2110 cmd_args.GetArgumentAtIndex (index));
2111 new_args.AppendArgument (buffer);
2112 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002113 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002114 }
2115 }
2116 }
2117 }
2118
2119 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2120 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002121 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002122 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2123 }
2124
2125 cmd_args.Clear();
2126 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2127 }
2128 else
2129 {
2130 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002131 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2132 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2133 // input string.
2134 if (wants_raw_input)
2135 {
2136 cmd_args.Clear();
2137 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2138 }
Chris Lattner24943d22010-06-08 16:52:24 +00002139 return;
2140 }
2141
2142 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2143 return;
2144}
2145
2146
2147int
2148CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2149{
2150 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2151 // of zero.
2152
2153 char *cptr = (char *) in_string;
2154
2155 // Does it start with '%'
2156 if (cptr[0] == '%')
2157 {
2158 ++cptr;
2159
2160 // Is the rest of it entirely digits?
2161 if (isdigit (cptr[0]))
2162 {
2163 const char *start = cptr;
2164 while (isdigit (cptr[0]))
2165 ++cptr;
2166
2167 // We've gotten to the end of the digits; are we at the end of the string?
2168 if (cptr[0] == '\0')
2169 position = atoi (start);
2170 }
2171 }
2172
2173 return position;
2174}
2175
2176void
2177CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2178{
Jim Ingham574c3d62011-08-12 23:34:31 +00002179 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002180 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002181 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002182 // In the current working directory we don't load any program specific
2183 // .lldbinit files, we only look for a "./.lldbinit" file.
2184 if (m_skip_lldbinit_files)
2185 return;
2186
2187 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002188 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002189 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002190 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002191 // If we aren't looking in the current working directory we are looking
2192 // in the home directory. We will first see if there is an application
2193 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2194 // "-" and the name of the program. If this file doesn't exist, we fall
2195 // back to just the "~/.lldbinit" file. We also obey any requests to not
2196 // load the init files.
2197 const char *init_file_path = "~/.lldbinit";
2198
2199 if (m_skip_app_init_files == false)
2200 {
2201 FileSpec program_file_spec (Host::GetProgramFileSpec());
2202 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002203
Greg Claytond6edcb52011-09-11 00:01:44 +00002204 if (program_name)
2205 {
2206 char program_init_file_name[PATH_MAX];
2207 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2208 init_file.SetFile (program_init_file_name, true);
2209 if (!init_file.Exists())
2210 init_file.Clear();
2211 }
2212 }
2213
2214 if (!init_file && !m_skip_lldbinit_files)
2215 init_file.SetFile (init_file_path, true);
2216 }
2217
Chris Lattner24943d22010-06-08 16:52:24 +00002218 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2219 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2220
2221 if (init_file.Exists())
2222 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002223 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2224 bool stop_on_continue = true;
2225 bool stop_on_error = false;
2226 bool echo_commands = false;
2227 bool print_results = false;
2228
2229 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002230 }
2231 else
2232 {
2233 // nothing to be done if the file doesn't exist
2234 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2235 }
2236}
2237
Greg Claytonb72d0f02011-04-12 05:54:46 +00002238PlatformSP
2239CommandInterpreter::GetPlatform (bool prefer_target_platform)
2240{
2241 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002242 if (prefer_target_platform)
2243 {
2244 Target *target = m_exe_ctx.GetTargetPtr();
2245 if (target)
2246 platform_sp = target->GetPlatform();
2247 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002248
2249 if (!platform_sp)
2250 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2251 return platform_sp;
2252}
2253
Jim Ingham949d5ac2011-02-18 00:54:25 +00002254void
Jim Inghama4fede32011-03-11 01:51:49 +00002255CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002256 ExecutionContext *override_context,
2257 bool stop_on_continue,
2258 bool stop_on_error,
2259 bool echo_commands,
2260 bool print_results,
2261 CommandReturnObject &result)
2262{
2263 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002264
2265 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2266 // Make sure you reset this value anywhere you return from the function.
2267
2268 bool old_async_execution = m_debugger.GetAsyncExecution();
2269
2270 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2271 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2272
2273 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002274 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002275
2276 if (!stop_on_continue)
2277 {
2278 m_debugger.SetAsyncExecution (false);
2279 }
2280
2281 for (int idx = 0; idx < num_lines; idx++)
2282 {
2283 const char *cmd = commands.GetStringAtIndex(idx);
2284 if (cmd[0] == '\0')
2285 continue;
2286
Jim Ingham949d5ac2011-02-18 00:54:25 +00002287 if (echo_commands)
2288 {
2289 result.AppendMessageWithFormat ("%s %s\n",
2290 GetPrompt(),
2291 cmd);
2292 }
2293
Greg Claytonaa378b12011-02-20 02:15:07 +00002294 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002295 // If override_context is not NULL, pass no_context_switching = true for
2296 // HandleCommand() since we updated our context already.
2297 bool success = HandleCommand(cmd, false, tmp_result,
2298 NULL, /* override_context */
2299 true, /* repeat_on_empty_command */
2300 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002301
2302 if (print_results)
2303 {
2304 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002305 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002306 }
2307
2308 if (!success || !tmp_result.Succeeded())
2309 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002310 const char *error_msg = tmp_result.GetErrorData();
2311 if (error_msg == NULL || error_msg[0] == '\0')
2312 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002313 if (stop_on_error)
2314 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002315 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2316 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002317 result.SetStatus (eReturnStatusFailed);
2318 m_debugger.SetAsyncExecution (old_async_execution);
2319 return;
2320 }
2321 else if (print_results)
2322 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002323 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002324 idx + 1,
2325 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002326 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002327 }
2328 }
2329
Caroline Tice4a348082011-05-02 20:41:46 +00002330 if (result.GetImmediateOutputStream())
2331 result.GetImmediateOutputStream()->Flush();
2332
2333 if (result.GetImmediateErrorStream())
2334 result.GetImmediateErrorStream()->Flush();
2335
Jim Ingham949d5ac2011-02-18 00:54:25 +00002336 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2337 // could be running (for instance in Breakpoint Commands.
2338 // So we check the return value to see if it is has running in it.
2339 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2340 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2341 {
2342 if (stop_on_continue)
2343 {
2344 // If we caused the target to proceed, and we're going to stop in that case, set the
2345 // status in our real result before returning. This is an error if the continue was not the
2346 // last command in the set of commands to be run.
2347 if (idx != num_lines - 1)
2348 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2349 idx + 1, cmd);
2350 else
2351 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2352
2353 result.SetStatus(tmp_result.GetStatus());
2354 m_debugger.SetAsyncExecution (old_async_execution);
2355
2356 return;
2357 }
2358 }
2359
2360 }
2361
2362 result.SetStatus (eReturnStatusSuccessFinishResult);
2363 m_debugger.SetAsyncExecution (old_async_execution);
2364
2365 return;
2366}
2367
2368void
2369CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2370 ExecutionContext *context,
2371 bool stop_on_continue,
2372 bool stop_on_error,
2373 bool echo_command,
2374 bool print_result,
2375 CommandReturnObject &result)
2376{
2377 if (cmd_file.Exists())
2378 {
2379 bool success;
2380 StringList commands;
2381 success = commands.ReadFileLines(cmd_file);
2382 if (!success)
2383 {
2384 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2385 result.SetStatus (eReturnStatusFailed);
2386 return;
2387 }
2388 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
2389 }
2390 else
2391 {
2392 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2393 cmd_file.GetFilename().AsCString());
2394 result.SetStatus (eReturnStatusFailed);
2395 return;
2396 }
2397}
2398
Chris Lattner24943d22010-06-08 16:52:24 +00002399ScriptInterpreter *
2400CommandInterpreter::GetScriptInterpreter ()
2401{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002402 if (m_script_interpreter_ap.get() != NULL)
2403 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002404
Caroline Tice0aa2e552011-01-14 00:29:16 +00002405 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2406 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002407 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002408 case eScriptLanguagePython:
2409#ifndef LLDB_DISABLE_PYTHON
2410 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2411 break;
2412#else
2413 // Fall through to the None case when python is disabled
2414#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002415 case eScriptLanguageNone:
2416 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2417 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002418 default:
2419 break;
2420 };
2421
2422 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002423}
2424
2425
2426
2427bool
2428CommandInterpreter::GetSynchronous ()
2429{
2430 return m_synchronous_execution;
2431}
2432
2433void
2434CommandInterpreter::SetSynchronous (bool value)
2435{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002436 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002437}
2438
2439void
2440CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2441 const char *word_text,
2442 const char *separator,
2443 const char *help_text,
2444 uint32_t max_word_len)
2445{
Greg Clayton238c0a12010-09-18 01:14:36 +00002446 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2447
Chris Lattner24943d22010-06-08 16:52:24 +00002448 int indent_size = max_word_len + strlen (separator) + 2;
2449
2450 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002451
2452 StreamString text_strm;
2453 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2454
2455 size_t len = text_strm.GetSize();
2456 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002457 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002458 {
2459 text_strm.EOL();
2460 len = text_strm.GetSize();
2461 }
Chris Lattner24943d22010-06-08 16:52:24 +00002462
2463 if (len < max_columns)
2464 {
2465 // Output it as a single line.
2466 strm.Printf ("%s", text);
2467 }
2468 else
2469 {
2470 // We need to break it up into multiple lines.
2471 bool first_line = true;
2472 int text_width;
2473 int start = 0;
2474 int end = start;
2475 int final_end = strlen (text);
2476 int sub_len;
2477
2478 while (end < final_end)
2479 {
2480 if (first_line)
2481 text_width = max_columns - 1;
2482 else
2483 text_width = max_columns - indent_size - 1;
2484
2485 // Don't start the 'text' on a space, since we're already outputting the indentation.
2486 if (!first_line)
2487 {
2488 while ((start < final_end) && (text[start] == ' '))
2489 start++;
2490 }
2491
2492 end = start + text_width;
2493 if (end > final_end)
2494 end = final_end;
2495 else
2496 {
2497 // If we're not at the end of the text, make sure we break the line on white space.
2498 while (end > start
2499 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2500 end--;
2501 }
2502
2503 sub_len = end - start;
2504 if (start != 0)
2505 strm.EOL();
2506 if (!first_line)
2507 strm.Indent();
2508 else
2509 first_line = false;
2510 assert (start <= final_end);
2511 assert (start + sub_len <= final_end);
2512 if (sub_len > 0)
2513 strm.Write (text + start, sub_len);
2514 start = end + 1;
2515 }
2516 }
2517 strm.EOL();
2518 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002519}
2520
2521void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002522CommandInterpreter::OutputHelpText (Stream &strm,
2523 const char *word_text,
2524 const char *separator,
2525 const char *help_text,
2526 uint32_t max_word_len)
2527{
2528 int indent_size = max_word_len + strlen (separator) + 2;
2529
2530 strm.IndentMore (indent_size);
2531
2532 StreamString text_strm;
2533 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2534
2535 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2536 bool first_line = true;
2537
2538 size_t len = text_strm.GetSize();
2539 const char *text = text_strm.GetData();
2540
2541 uint32_t chars_left = max_columns;
2542
2543 for (uint32_t i = 0; i < len; i++)
2544 {
2545 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2546 {
2547 first_line = false;
2548 chars_left = max_columns - indent_size;
2549 strm.EOL();
2550 strm.Indent();
2551 }
2552 else
2553 {
2554 strm.PutChar(text[i]);
2555 chars_left--;
2556 }
2557
2558 }
2559
2560 strm.EOL();
2561 strm.IndentLess(indent_size);
2562}
2563
2564void
Chris Lattner24943d22010-06-08 16:52:24 +00002565CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2566 StringList &commands_found, StringList &commands_help)
2567{
2568 CommandObject::CommandMap::const_iterator pos;
2569 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2570 CommandObject *sub_cmd_obj;
2571
2572 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2573 {
2574 const char * command_name = pos->first.c_str();
2575 sub_cmd_obj = pos->second.get();
2576 StreamString complete_command_name;
2577
2578 complete_command_name.Printf ("%s %s", prefix, command_name);
2579
Greg Clayton238c0a12010-09-18 01:14:36 +00002580 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002581 {
2582 commands_found.AppendString (complete_command_name.GetData());
2583 commands_help.AppendString (sub_cmd_obj->GetHelp());
2584 }
2585
2586 if (sub_cmd_obj->IsMultiwordObject())
2587 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2588 commands_help);
2589 }
2590
2591}
2592
2593void
2594CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2595 StringList &commands_help)
2596{
2597 CommandObject::CommandMap::const_iterator pos;
2598
2599 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2600 {
2601 const char *command_name = pos->first.c_str();
2602 CommandObject *cmd_obj = pos->second.get();
2603
Greg Clayton238c0a12010-09-18 01:14:36 +00002604 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002605 {
2606 commands_found.AppendString (command_name);
2607 commands_help.AppendString (cmd_obj->GetHelp());
2608 }
2609
2610 if (cmd_obj->IsMultiwordObject())
2611 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2612
2613 }
2614}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002615
2616
2617void
2618CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2619{
2620 m_exe_ctx.Clear();
2621
2622 if (override_context != NULL)
2623 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002624 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002625 }
2626 else
2627 {
2628 TargetSP target_sp (m_debugger.GetSelectedTarget());
2629 if (target_sp)
2630 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002631 m_exe_ctx.SetTargetSP (target_sp);
2632 ProcessSP process_sp (target_sp->GetProcessSP());
2633 m_exe_ctx.SetProcessSP (process_sp);
2634 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002635 {
Greg Clayton13d24fb2012-01-29 20:56:30 +00002636 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
Greg Clayton567e7f32011-09-22 04:58:26 +00002637 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002638 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002639 m_exe_ctx.SetThreadSP (thread_sp);
2640 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2641 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002642 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002643 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002644 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002645 if (frame_sp)
2646 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002647 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002648 if (frame_sp)
2649 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002650 }
2651 }
2652 }
2653 }
2654}
2655
Jim Ingham6247dbe2011-07-12 03:12:18 +00002656void
2657CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2658{
2659 DumpHistory (stream, 0, count - 1);
2660}
2661
2662void
2663CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2664{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002665 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2666 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002667 {
2668 if (!m_command_history[i].empty())
2669 {
2670 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002671 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002672 }
2673 }
2674}
2675
2676const char *
2677CommandInterpreter::FindHistoryString (const char *input_str) const
2678{
2679 if (input_str[0] != m_repeat_char)
2680 return NULL;
2681 if (input_str[1] == '-')
2682 {
2683 bool success;
2684 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2685 if (!success)
2686 return NULL;
2687 if (idx > m_command_history.size())
2688 return NULL;
2689 idx = m_command_history.size() - idx;
2690 return m_command_history[idx].c_str();
2691
2692 }
2693 else if (input_str[1] == m_repeat_char)
2694 {
2695 if (m_command_history.empty())
2696 return NULL;
2697 else
2698 return m_command_history.back().c_str();
2699 }
2700 else
2701 {
2702 bool success;
2703 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2704 if (!success)
2705 return NULL;
2706 if (idx >= m_command_history.size())
2707 return NULL;
2708 return m_command_history[idx].c_str();
2709 }
2710}