blob: 033322b299de61693b1dfaed1eb40c97780aed14 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include <string>
Caroline Ticebd5c63e2010-10-12 21:57:09 +000011#include <vector>
Chris Lattner24943d22010-06-08 16:52:24 +000012
13#include <getopt.h>
14#include <stdlib.h>
15
Greg Clayton5c28dd12011-06-23 17:59:56 +000016#include "CommandObjectScript.h"
Peter Collingbourne921fac02011-06-23 20:37:26 +000017#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000018
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectApropos.h"
20#include "../Commands/CommandObjectArgs.h"
21#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
25#include "../Commands/CommandObjectHelp.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectLog.h"
27#include "../Commands/CommandObjectMemory.h"
Greg Claytonb1888f22011-03-19 01:12:21 +000028#include "../Commands/CommandObjectPlatform.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000029#include "../Commands/CommandObjectProcess.h"
30#include "../Commands/CommandObjectQuit.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectRegister.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000034#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSyntax.h"
36#include "../Commands/CommandObjectTarget.h"
37#include "../Commands/CommandObjectThread.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000038#include "../Commands/CommandObjectType.h"
Johnny Chen902e0182010-12-23 20:21:44 +000039#include "../Commands/CommandObjectVersion.h"
Johnny Chen01acfa72011-09-22 18:04:58 +000040#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
Jim Ingham84cdc152010-06-15 19:49:27 +000042#include "lldb/Interpreter/Args.h"
Caroline Tice5ddbe212011-05-06 21:37:15 +000043#include "lldb/Interpreter/Options.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000045#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046#include "lldb/Core/Stream.h"
47#include "lldb/Core/Timer.h"
Greg Claytoncd548032011-02-01 01:31:41 +000048#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049#include "lldb/Target/Process.h"
50#include "lldb/Target/Thread.h"
51#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000052#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000053
54#include "lldb/Interpreter/CommandReturnObject.h"
55#include "lldb/Interpreter/CommandInterpreter.h"
Caroline Tice0aa2e552011-01-14 00:29:16 +000056#include "lldb/Interpreter/ScriptInterpreterNone.h"
57#include "lldb/Interpreter/ScriptInterpreterPython.h"
Chris Lattner24943d22010-06-08 16:52:24 +000058
59using namespace lldb;
60using namespace lldb_private;
61
Jim Ingham5a15e692012-02-16 06:50:00 +000062ConstString &
63CommandInterpreter::GetStaticBroadcasterClass ()
64{
65 static ConstString class_name ("lldb.commandInterpreter");
66 return class_name;
67}
68
Chris Lattner24943d22010-06-08 16:52:24 +000069CommandInterpreter::CommandInterpreter
70(
Greg Clayton63094e02010-06-23 01:19:29 +000071 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000072 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000073 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000074) :
Jim Ingham5a15e692012-02-16 06:50:00 +000075 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000076 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000077 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000078 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000079 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000080 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +000081 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +000082 m_repeat_char ('!'),
Enrico Granata293a7b32011-08-15 19:24:02 +000083 m_batch_command_mode (false),
84 m_truncation_warning(eNoTruncation)
Chris Lattner24943d22010-06-08 16:52:24 +000085{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000086 const char *dbg_name = debugger.GetInstanceName().AsCString();
87 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
88 StreamString var_name;
89 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000090 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000091 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000092 m_debugger.GetInstanceName().AsCString());
93 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
94 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
95 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham5a15e692012-02-16 06:50:00 +000096
97 CheckInWithManager ();
Chris Lattner24943d22010-06-08 16:52:24 +000098}
99
100void
101CommandInterpreter::Initialize ()
102{
103 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
104
105 CommandReturnObject result;
106
107 LoadCommandDictionary ();
108
Chris Lattner24943d22010-06-08 16:52:24 +0000109 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000110 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
111 if (cmd_obj_sp)
112 {
113 AddAlias ("q", cmd_obj_sp);
114 AddAlias ("exit", cmd_obj_sp);
115 }
116
117 cmd_obj_sp = GetCommandSPExact ("process continue", false);
118 if (cmd_obj_sp)
119 {
120 AddAlias ("c", cmd_obj_sp);
121 AddAlias ("continue", cmd_obj_sp);
122 }
123
124 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
125 if (cmd_obj_sp)
126 AddAlias ("b", cmd_obj_sp);
127
128 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
129 if (cmd_obj_sp)
130 AddAlias ("bt", cmd_obj_sp);
131
132 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
133 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000134 {
135 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000136 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000137 }
138
139 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
140 if (cmd_obj_sp)
141 {
142 AddAlias ("nexti", cmd_obj_sp);
143 AddAlias ("ni", cmd_obj_sp);
144 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000145
146 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
147 if (cmd_obj_sp)
148 {
149 AddAlias ("s", cmd_obj_sp);
150 AddAlias ("step", cmd_obj_sp);
151 }
152
153 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
154 if (cmd_obj_sp)
155 {
156 AddAlias ("n", cmd_obj_sp);
157 AddAlias ("next", cmd_obj_sp);
158 }
159
160 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
161 if (cmd_obj_sp)
162 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000163 AddAlias ("finish", cmd_obj_sp);
164 }
165
Jim Ingham59355252011-12-02 01:12:59 +0000166 cmd_obj_sp = GetCommandSPExact ("frame select", false);
167 if (cmd_obj_sp)
168 {
169 AddAlias ("f", cmd_obj_sp);
170 }
171
Caroline Tice5ddbe212011-05-06 21:37:15 +0000172 cmd_obj_sp = GetCommandSPExact ("source list", false);
173 if (cmd_obj_sp)
174 {
175 AddAlias ("l", cmd_obj_sp);
176 AddAlias ("list", cmd_obj_sp);
177 }
178
179 cmd_obj_sp = GetCommandSPExact ("memory read", false);
180 if (cmd_obj_sp)
181 AddAlias ("x", cmd_obj_sp);
182
183 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
184 if (cmd_obj_sp)
185 AddAlias ("up", cmd_obj_sp);
186
187 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
188 if (cmd_obj_sp)
189 AddAlias ("down", cmd_obj_sp);
190
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000191 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000192 if (cmd_obj_sp)
193 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000194
195 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
196 if (cmd_obj_sp)
197 AddAlias ("dis", cmd_obj_sp);
198
199 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
200 if (cmd_obj_sp)
201 AddAlias ("di", cmd_obj_sp);
202
203
Jason Molenda730cae02011-10-22 01:30:52 +0000204
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000205 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000206 if (cmd_obj_sp)
207 AddAlias ("undisplay", cmd_obj_sp);
208
Caroline Tice5ddbe212011-05-06 21:37:15 +0000209 cmd_obj_sp = GetCommandSPExact ("target create", false);
210 if (cmd_obj_sp)
211 AddAlias ("file", cmd_obj_sp);
212
213 cmd_obj_sp = GetCommandSPExact ("target modules", false);
214 if (cmd_obj_sp)
215 AddAlias ("image", cmd_obj_sp);
216
217
218 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000219
Caroline Tice5ddbe212011-05-06 21:37:15 +0000220 cmd_obj_sp = GetCommandSPExact ("expression", false);
221 if (cmd_obj_sp)
222 {
223 AddAlias ("expr", cmd_obj_sp);
224
225 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
226 AddAlias ("p", cmd_obj_sp);
227 AddAlias ("print", cmd_obj_sp);
228 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
229 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
230
231 alias_arguments_vector_sp.reset (new OptionArgVector);
232 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
233 AddAlias ("po", cmd_obj_sp);
234 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
235 }
236
237 cmd_obj_sp = GetCommandSPExact ("process launch", false);
238 if (cmd_obj_sp)
239 {
240 alias_arguments_vector_sp.reset (new OptionArgVector);
241 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
242 AddAlias ("r", cmd_obj_sp);
243 AddAlias ("run", cmd_obj_sp);
244 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
245 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
246 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000247
248 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
249 if (cmd_obj_sp)
250 {
251 AddAlias ("add-dsym", cmd_obj_sp);
252 }
Chris Lattner24943d22010-06-08 16:52:24 +0000253}
254
Chris Lattner24943d22010-06-08 16:52:24 +0000255const char *
256CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
257{
258 // This function has not yet been implemented.
259
260 // Look for any embedded script command
261 // If found,
262 // get interpreter object from the command dictionary,
263 // call execute_one_command on it,
264 // get the results as a string,
265 // substitute that string for current stuff.
266
267 return arg;
268}
269
270
271void
272CommandInterpreter::LoadCommandDictionary ()
273{
274 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
275
276 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
277 //
278 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
279 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
280 // the cross-referencing stuff) are created!!!
281 //
282 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
283
284
285 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
286 // are created. This is so that when another command is created that needs to go into a crossref object,
287 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
288 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
289
Chris Lattner24943d22010-06-08 16:52:24 +0000290 // Non-CommandObjectCrossref commands can now be created.
291
Caroline Tice5bc8c972010-09-20 20:44:43 +0000292 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000293
Greg Clayton238c0a12010-09-18 01:14:36 +0000294 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000295 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000296 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000297 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000298 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
299 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000300// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000301 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000302 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000303 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000304 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
305 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000306 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000307 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000308 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000309 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000310 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000311 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000312 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000313 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
314 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000315 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000316 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000317 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000318
319 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000320 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000321 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000322 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000323 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000324 if (break_regex_cmd_ap.get())
325 {
326 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
327 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
328 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000329 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000330 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000331 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000332 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
333 {
334 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
335 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
336 }
337 }
Jim Inghame56493f2011-03-22 02:29:32 +0000338
339 std::auto_ptr<CommandObjectRegexCommand>
340 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000341 "_regexp-down",
342 "Go down \"n\" frames in the stack (1 frame by default).",
343 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000344 if (down_regex_cmd_ap.get())
345 {
346 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
347 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
348 {
349 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
350 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
351 }
352 }
353
354 std::auto_ptr<CommandObjectRegexCommand>
355 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000356 "_regexp-up",
357 "Go up \"n\" frames in the stack (1 frame by default).",
358 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000359 if (up_regex_cmd_ap.get())
360 {
361 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
362 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
363 {
364 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
365 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
366 }
367 }
Jason Molenda730cae02011-10-22 01:30:52 +0000368
369 std::auto_ptr<CommandObjectRegexCommand>
370 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000371 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000372 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000373 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000374 if (display_regex_cmd_ap.get())
375 {
376 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
377 {
378 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
379 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
380 }
381 }
382
383 std::auto_ptr<CommandObjectRegexCommand>
384 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000385 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000386 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000387 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000388 if (undisplay_regex_cmd_ap.get())
389 {
390 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
391 {
392 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
393 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
394 }
395 }
396
Chris Lattner24943d22010-06-08 16:52:24 +0000397}
398
399int
400CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
401 StringList &matches)
402{
403 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
404
405 if (include_aliases)
406 {
407 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
408 }
409
410 return matches.GetSize();
411}
412
413CommandObjectSP
414CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
415{
416 CommandObject::CommandMap::iterator pos;
417 CommandObjectSP ret_val;
418
419 std::string cmd(cmd_cstr);
420
421 if (HasCommands())
422 {
423 pos = m_command_dict.find(cmd);
424 if (pos != m_command_dict.end())
425 ret_val = pos->second;
426 }
427
428 if (include_aliases && HasAliases())
429 {
430 pos = m_alias_dict.find(cmd);
431 if (pos != m_alias_dict.end())
432 ret_val = pos->second;
433 }
434
435 if (HasUserCommands())
436 {
437 pos = m_user_dict.find(cmd);
438 if (pos != m_user_dict.end())
439 ret_val = pos->second;
440 }
441
442 if (!exact && ret_val == NULL)
443 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000444 // We will only get into here if we didn't find any exact matches.
445
446 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
447
Chris Lattner24943d22010-06-08 16:52:24 +0000448 StringList local_matches;
449 if (matches == NULL)
450 matches = &local_matches;
451
Jim Inghamd40f8a62010-07-06 22:46:59 +0000452 unsigned int num_cmd_matches = 0;
453 unsigned int num_alias_matches = 0;
454 unsigned int num_user_matches = 0;
455
456 // Look through the command dictionaries one by one, and if we get only one match from any of
457 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
458
Chris Lattner24943d22010-06-08 16:52:24 +0000459 if (HasCommands())
460 {
461 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
462 }
463
464 if (num_cmd_matches == 1)
465 {
466 cmd.assign(matches->GetStringAtIndex(0));
467 pos = m_command_dict.find(cmd);
468 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000469 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000470 }
471
Jim Ingham9a574172010-06-24 20:28:42 +0000472 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000473 {
474 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
475
476 }
477
Jim Inghamd40f8a62010-07-06 22:46:59 +0000478 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000479 {
480 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
481 pos = m_alias_dict.find(cmd);
482 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000483 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000484 }
485
Jim Ingham9a574172010-06-24 20:28:42 +0000486 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000487 {
488 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
489 }
490
Jim Inghamd40f8a62010-07-06 22:46:59 +0000491 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000492 {
493 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
494
495 pos = m_user_dict.find (cmd);
496 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000497 user_match_sp = pos->second;
498 }
499
500 // If we got exactly one match, return that, otherwise return the match list.
501
502 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
503 {
504 if (num_cmd_matches)
505 return real_match_sp;
506 else if (num_alias_matches)
507 return alias_match_sp;
508 else
509 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000510 }
511 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000512 else if (matches && ret_val != NULL)
513 {
514 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000515 }
516
517
518 return ret_val;
519}
520
Greg Claytond12aeab2011-04-20 16:37:46 +0000521bool
522CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
523{
524 if (name && name[0])
525 {
526 std::string name_sstr(name);
527 if (!can_replace)
528 {
529 if (m_command_dict.find (name_sstr) != m_command_dict.end())
530 return false;
531 }
532 m_command_dict[name_sstr] = cmd_sp;
533 return true;
534 }
535 return false;
536}
537
Enrico Granata6b1596d2011-08-16 23:24:13 +0000538bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000539CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000540 const lldb::CommandObjectSP &cmd_sp,
541 bool can_replace)
542{
Enrico Granata6010ace2011-11-07 22:57:04 +0000543 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000544 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000545
546 const char* name_cstr = name.c_str();
547
548 // do not allow replacement of internal commands
549 if (CommandExists(name_cstr))
550 return false;
551
552 if (can_replace == false && UserCommandExists(name_cstr))
553 return false;
554
555 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000556 return true;
557 }
558 return false;
559}
Greg Claytond12aeab2011-04-20 16:37:46 +0000560
Jim Inghamd40f8a62010-07-06 22:46:59 +0000561CommandObjectSP
562CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000563{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000564 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
565 CommandObjectSP ret_val; // Possibly empty return value.
566
567 if (cmd_cstr == NULL)
568 return ret_val;
569
570 if (cmd_words.GetArgumentCount() == 1)
571 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
572 else
573 {
574 // We have a multi-word command (seemingly), so we need to do more work.
575 // First, get the cmd_obj_sp for the first word in the command.
576 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
577 if (cmd_obj_sp.get() != NULL)
578 {
579 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
580 // command name), and find the appropriate sub-command SP for each command word....
581 size_t end = cmd_words.GetArgumentCount();
582 for (size_t j= 1; j < end; ++j)
583 {
584 if (cmd_obj_sp->IsMultiwordObject())
585 {
586 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
587 (cmd_words.GetArgumentAtIndex (j));
588 if (cmd_obj_sp.get() == NULL)
589 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
590 return ret_val;
591 }
592 else
593 // We have more words in the command name, but we don't have a multiword object. Fail and return
594 // empty 'ret_val'.
595 return ret_val;
596 }
597 // We successfully looped through all the command words and got valid command objects for them. Assign the
598 // last object retrieved to 'ret_val'.
599 ret_val = cmd_obj_sp;
600 }
601 }
602 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000603}
604
605CommandObject *
606CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
607{
608 return GetCommandSPExact (cmd_cstr, include_aliases).get();
609}
610
611CommandObject *
612CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
613{
614 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
615
616 // If we didn't find an exact match to the command string in the commands, look in
617 // the aliases.
618
619 if (command_obj == NULL)
620 {
621 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
622 }
623
624 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
625 // in both the commands and the aliases.
626
627 if (command_obj == NULL)
628 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
629
630 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000631}
632
633bool
634CommandInterpreter::CommandExists (const char *cmd)
635{
636 return m_command_dict.find(cmd) != m_command_dict.end();
637}
638
639bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000640CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
641 const char *options_args,
642 OptionArgVectorSP &option_arg_vector_sp)
643{
644 bool success = true;
645 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
646
647 if (!options_args || (strlen (options_args) < 1))
648 return true;
649
650 std::string options_string (options_args);
651 Args args (options_args);
652 CommandReturnObject result;
653 // Check to see if the command being aliased can take any command options.
654 Options *options = cmd_obj_sp->GetOptions ();
655 if (options)
656 {
657 // See if any options were specified as part of the alias; if so, handle them appropriately.
658 options->NotifyOptionParsingStarting ();
659 args.Unshift ("dummy_arg");
660 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
661 args.Shift ();
662 if (result.Succeeded())
663 options->VerifyPartialOptions (result);
664 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
665 {
666 result.AppendError ("Unable to create requested alias.\n");
667 return false;
668 }
669 }
670
Greg Clayton7268b4c2011-10-28 21:38:01 +0000671 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000672 {
673 if (cmd_obj_sp->WantsRawCommandString ())
674 option_arg_vector->push_back (OptionArgPair ("<argument>",
675 OptionArgValue (-1,
676 options_string)));
677 else
678 {
679 int argc = args.GetArgumentCount();
680 for (size_t i = 0; i < argc; ++i)
681 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
682 option_arg_vector->push_back
683 (OptionArgPair ("<argument>",
684 OptionArgValue (-1,
685 std::string (args.GetArgumentAtIndex (i)))));
686 }
687 }
688
689 return success;
690}
691
692bool
Chris Lattner24943d22010-06-08 16:52:24 +0000693CommandInterpreter::AliasExists (const char *cmd)
694{
695 return m_alias_dict.find(cmd) != m_alias_dict.end();
696}
697
698bool
699CommandInterpreter::UserCommandExists (const char *cmd)
700{
701 return m_user_dict.find(cmd) != m_user_dict.end();
702}
703
704void
705CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
706{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000707 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000708 m_alias_dict[alias_name] = command_obj_sp;
709}
710
711bool
712CommandInterpreter::RemoveAlias (const char *alias_name)
713{
714 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
715 if (pos != m_alias_dict.end())
716 {
717 m_alias_dict.erase(pos);
718 return true;
719 }
720 return false;
721}
722bool
723CommandInterpreter::RemoveUser (const char *alias_name)
724{
725 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
726 if (pos != m_user_dict.end())
727 {
728 m_user_dict.erase(pos);
729 return true;
730 }
731 return false;
732}
733
Chris Lattner24943d22010-06-08 16:52:24 +0000734void
735CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
736{
737 help_string.Printf ("'%s", command_name);
738 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
739
740 if (option_arg_vector_sp != NULL)
741 {
742 OptionArgVector *options = option_arg_vector_sp.get();
743 for (int i = 0; i < options->size(); ++i)
744 {
745 OptionArgPair cur_option = (*options)[i];
746 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000747 OptionArgValue value_pair = cur_option.second;
748 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000749 if (opt.compare("<argument>") == 0)
750 {
751 help_string.Printf (" %s", value.c_str());
752 }
753 else
754 {
755 help_string.Printf (" %s", opt.c_str());
756 if ((value.compare ("<no-argument>") != 0)
757 && (value.compare ("<need-argument") != 0))
758 {
759 help_string.Printf (" %s", value.c_str());
760 }
761 }
762 }
763 }
764
765 help_string.Printf ("'");
766}
767
Greg Clayton65124ea2010-08-26 22:05:43 +0000768size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000769CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
770{
771 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000772 CommandObject::CommandMap::const_iterator end = dict.end();
773 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000774
Greg Clayton65124ea2010-08-26 22:05:43 +0000775 for (pos = dict.begin(); pos != end; ++pos)
776 {
777 size_t len = pos->first.size();
778 if (max_len < len)
779 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000780 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000781 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000782}
783
784void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000785CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000786 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000787{
788 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000789 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000790
791 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000792 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000793
794 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
795 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000796
Enrico Granata6b1596d2011-08-16 23:24:13 +0000797 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
798 {
799 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
800 max_len);
801 }
802 result.AppendMessage("");
803
804 }
805
Greg Clayton7268b4c2011-10-28 21:38:01 +0000806 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000807 {
Jim Inghame3663e82010-10-22 18:47:16 +0000808 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000809 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000810 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000811 max_len = FindLongestCommandWord (m_alias_dict);
812
Chris Lattner24943d22010-06-08 16:52:24 +0000813 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
814 {
815 StreamString sstr;
816 StreamString translation_and_help;
817 std::string entry_name = pos->first;
818 std::string second_entry = pos->second.get()->GetCommandName();
819 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
820
821 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
822 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
823 translation_and_help.GetData(), max_len);
824 }
825 result.AppendMessage("");
826 }
827
Greg Clayton7268b4c2011-10-28 21:38:01 +0000828 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000829 {
830 result.AppendMessage ("The following is a list of your current user-defined commands:");
831 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000832 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000833 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
834 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000835 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
836 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000837 }
838 result.AppendMessage("");
839 }
840
841 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
842}
843
Caroline Ticee0da7a52010-12-09 22:52:49 +0000844CommandObject *
845CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000846{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000847 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
848 // eventually be invoked by the given command line.
849
850 CommandObject *cmd_obj = NULL;
851 std::string white_space (" \t\v");
852 size_t start = command_string.find_first_not_of (white_space);
853 size_t end = 0;
854 bool done = false;
855 while (!done)
856 {
857 if (start != std::string::npos)
858 {
859 // Get the next word from command_string.
860 end = command_string.find_first_of (white_space, start);
861 if (end == std::string::npos)
862 end = command_string.size();
863 std::string cmd_word = command_string.substr (start, end - start);
864
865 if (cmd_obj == NULL)
866 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
867 // command or alias.
868 cmd_obj = GetCommandObject (cmd_word.c_str());
869 else if (cmd_obj->IsMultiwordObject ())
870 {
871 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
872 CommandObject *sub_cmd_obj =
873 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
874 if (sub_cmd_obj)
875 cmd_obj = sub_cmd_obj;
876 else // cmd_word was not a valid sub-command word, so we are donee
877 done = true;
878 }
879 else
880 // We have a cmd_obj and it is not a multi-word object, so we are done.
881 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000882
Caroline Ticee0da7a52010-12-09 22:52:49 +0000883 // If we didn't find a valid command object, or our command object is not a multi-word object, or
884 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
885 // next word.
886
887 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
888 done = true;
889 else
890 start = command_string.find_first_not_of (white_space, end);
891 }
892 else
893 // Unable to find any more words.
894 done = true;
895 }
896
897 if (end == command_string.size())
898 command_string.clear();
899 else
900 command_string = command_string.substr(end);
901
902 return cmd_obj;
903}
904
Greg Clayton9d855c62011-10-25 00:36:27 +0000905static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000906static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000907static void
908StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000909{
Greg Clayton9d855c62011-10-25 00:36:27 +0000910 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000911 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000912 size_t pos = s.find_first_not_of (k_white_space);
913 if (pos == std::string::npos)
914 s.clear();
915 else if (pos == 0)
916 return;
917 s.erase (0, pos);
918 }
919}
920
Greg Clayton3840cd72011-11-09 23:25:03 +0000921static size_t
922FindArgumentTerminator (const std::string &s)
923{
Greg Clayton3840cd72011-11-09 23:25:03 +0000924 const size_t s_len = s.size();
925 size_t offset = 0;
926 while (offset < s_len)
927 {
928 size_t pos = s.find ("--", offset);
929 if (pos == std::string::npos)
930 break;
931 if (pos > 0)
932 {
933 if (isspace(s[pos-1]))
934 {
935 // Check if the string ends "\s--" (where \s is a space character)
936 // or if we have "\s--\s".
937 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
938 {
Greg Clayton3840cd72011-11-09 23:25:03 +0000939 return pos;
940 }
941 }
942 }
943 offset = pos + 2;
944 }
Greg Clayton3840cd72011-11-09 23:25:03 +0000945 return std::string::npos;
946}
947
Greg Clayton9d855c62011-10-25 00:36:27 +0000948static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000949ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000950{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000951 command.clear();
952 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000953 StripLeadingSpaces (command_string);
954
955 bool result = false;
956 quote_char = '\0';
957
958 if (!command_string.empty())
959 {
960 const char first_char = command_string[0];
961 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000962 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000963 quote_char = first_char;
964 const size_t end_quote_pos = command_string.find (quote_char, 1);
965 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000966 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000967 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000968 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000969 }
970 else
971 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000972 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +0000973 if (end_quote_pos + 1 < command_string.size())
974 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
975 else
976 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000977 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000978 }
979 else
980 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000981 const size_t first_space_pos = command_string.find_first_of (k_white_space);
982 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000983 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000984 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000985 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +0000986 }
987 else
988 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000989 command.assign (command_string, 0, first_space_pos);
990 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +0000991 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000992 }
Greg Clayton9d855c62011-10-25 00:36:27 +0000993 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000994 }
Greg Clayton7268b4c2011-10-28 21:38:01 +0000995
996
997 if (!command.empty())
998 {
999 // actual commands can't start with '-' or '_'
1000 if (command[0] != '-' && command[0] != '_')
1001 {
1002 size_t pos = command.find_first_not_of(k_valid_command_chars);
1003 if (pos > 0 && pos != std::string::npos)
1004 {
1005 suffix.assign (command.begin() + pos, command.end());
1006 command.erase (pos);
1007 }
1008 }
1009 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001010
1011 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001012}
1013
Greg Clayton7268b4c2011-10-28 21:38:01 +00001014CommandObject *
1015CommandInterpreter::BuildAliasResult (const char *alias_name,
1016 std::string &raw_input_string,
1017 std::string &alias_result,
1018 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001019{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001020 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001021 Args cmd_args (raw_input_string.c_str());
1022 alias_cmd_obj = GetCommandObject (alias_name);
1023 StreamString result_str;
1024
1025 if (alias_cmd_obj)
1026 {
1027 std::string alias_name_str = alias_name;
1028 if ((cmd_args.GetArgumentCount() == 0)
1029 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1030 cmd_args.Unshift (alias_name);
1031
1032 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1033 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1034
1035 if (option_arg_vector_sp.get())
1036 {
1037 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1038
1039 for (int i = 0; i < option_arg_vector->size(); ++i)
1040 {
1041 OptionArgPair option_pair = (*option_arg_vector)[i];
1042 OptionArgValue value_pair = option_pair.second;
1043 int value_type = value_pair.first;
1044 std::string option = option_pair.first;
1045 std::string value = value_pair.second;
1046 if (option.compare ("<argument>") == 0)
1047 result_str.Printf (" %s", value.c_str());
1048 else
1049 {
1050 result_str.Printf (" %s", option.c_str());
1051 if (value_type != optional_argument)
1052 result_str.Printf (" ");
1053 if (value.compare ("<no_argument>") != 0)
1054 {
1055 int index = GetOptionArgumentPosition (value.c_str());
1056 if (index == 0)
1057 result_str.Printf ("%s", value.c_str());
1058 else if (index >= cmd_args.GetArgumentCount())
1059 {
1060
1061 result.AppendErrorWithFormat
1062 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1063 index);
1064 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001065 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001066 }
1067 else
1068 {
1069 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1070 if (strpos != std::string::npos)
1071 raw_input_string = raw_input_string.erase (strpos,
1072 strlen (cmd_args.GetArgumentAtIndex (index)));
1073 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1074 }
1075 }
1076 }
1077 }
1078 }
1079
1080 alias_result = result_str.GetData();
1081 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001082 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001083}
1084
Greg Claytonf5c0c722011-10-14 07:41:33 +00001085Error
1086CommandInterpreter::PreprocessCommand (std::string &command)
1087{
1088 // The command preprocessor needs to do things to the command
1089 // line before any parsing of arguments or anything else is done.
1090 // The only current stuff that gets proprocessed is anyting enclosed
1091 // in backtick ('`') characters is evaluated as an expression and
1092 // the result of the expression must be a scalar that can be substituted
1093 // into the command. An example would be:
1094 // (lldb) memory read `$rsp + 20`
1095 Error error; // Error for any expressions that might not evaluate
1096 size_t start_backtick;
1097 size_t pos = 0;
1098 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1099 {
1100 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1101 {
1102 // The backtick was preceeded by a '\' character, remove the slash
1103 // and don't treat the backtick as the start of an expression
1104 command.erase(start_backtick-1, 1);
1105 // No need to add one to start_backtick since we just deleted a char
1106 pos = start_backtick;
1107 }
1108 else
1109 {
1110 const size_t expr_content_start = start_backtick + 1;
1111 const size_t end_backtick = command.find ('`', expr_content_start);
1112 if (end_backtick == std::string::npos)
1113 return error;
1114 else if (end_backtick == expr_content_start)
1115 {
1116 // Empty expression (two backticks in a row)
1117 command.erase (start_backtick, 2);
1118 }
1119 else
1120 {
1121 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1122
1123 Target *target = m_exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001124 // Get a dummy target to allow for calculator mode while processing backticks.
1125 // This also helps break the infinite loop caused when target is null.
1126 if (!target)
1127 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001128 if (target)
1129 {
Sean Callanandaa6efe2011-12-21 22:22:58 +00001130 const bool coerce_to_id = false;
Greg Claytonf5c0c722011-10-14 07:41:33 +00001131 const bool unwind_on_error = true;
1132 const bool keep_in_memory = false;
1133 ValueObjectSP expr_result_valobj_sp;
1134 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1135 m_exe_ctx.GetFramePtr(),
1136 eExecutionPolicyOnlyWhenNeeded,
Sean Callanandaa6efe2011-12-21 22:22:58 +00001137 coerce_to_id,
1138 unwind_on_error,
1139 keep_in_memory,
Greg Claytonf5c0c722011-10-14 07:41:33 +00001140 eNoDynamicValues,
1141 expr_result_valobj_sp);
1142 if (expr_result == eExecutionCompleted)
1143 {
1144 Scalar scalar;
1145 if (expr_result_valobj_sp->ResolveValue (scalar))
1146 {
1147 command.erase (start_backtick, end_backtick - start_backtick + 1);
1148 StreamString value_strm;
1149 const bool show_type = false;
1150 scalar.GetValue (&value_strm, show_type);
1151 size_t value_string_size = value_strm.GetSize();
1152 if (value_string_size)
1153 {
1154 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1155 pos = start_backtick + value_string_size;
1156 continue;
1157 }
1158 else
1159 {
1160 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1161 }
1162 }
1163 else
1164 {
1165 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1166 }
1167 }
1168 else
1169 {
1170 if (expr_result_valobj_sp)
1171 error = expr_result_valobj_sp->GetError();
1172 if (error.Success())
1173 {
1174
1175 switch (expr_result)
1176 {
1177 case eExecutionSetupError:
1178 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1179 break;
1180 case eExecutionCompleted:
1181 break;
1182 case eExecutionDiscarded:
1183 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1184 break;
1185 case eExecutionInterrupted:
1186 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1187 break;
1188 case eExecutionTimedOut:
1189 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1190 break;
1191 }
1192 }
1193 }
1194 }
1195 }
1196 if (error.Fail())
1197 break;
1198 }
1199 }
1200 return error;
1201}
1202
1203
Caroline Ticee0da7a52010-12-09 22:52:49 +00001204bool
1205CommandInterpreter::HandleCommand (const char *command_line,
1206 bool add_to_history,
1207 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001208 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001209 bool repeat_on_empty_command,
1210 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001211
Caroline Ticee0da7a52010-12-09 22:52:49 +00001212{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001213
Caroline Ticee0da7a52010-12-09 22:52:49 +00001214 bool done = false;
1215 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001216 bool wants_raw_input = false;
1217 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001218 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001219
1220 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001221 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1222
1223 // Make a scoped cleanup object that will clear the crash description string
1224 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001225 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001226
Caroline Ticee0da7a52010-12-09 22:52:49 +00001227 if (log)
1228 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001229
Jim Inghamabab14b2010-11-04 23:08:45 +00001230 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1231
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001232 if (!no_context_switching)
1233 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +00001234
Jim Ingham949d5ac2011-02-18 00:54:25 +00001235 bool empty_command = false;
1236 bool comment_command = false;
1237 if (command_string.empty())
1238 empty_command = true;
1239 else
Chris Lattner24943d22010-06-08 16:52:24 +00001240 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001241 const char *k_space_characters = "\t\n\v\f\r ";
1242
1243 size_t non_space = command_string.find_first_not_of (k_space_characters);
1244 // Check for empty line or comment line (lines whose first
1245 // non-space character is the comment character for this interpreter)
1246 if (non_space == std::string::npos)
1247 empty_command = true;
1248 else if (command_string[non_space] == m_comment_char)
1249 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001250 else if (command_string[non_space] == m_repeat_char)
1251 {
1252 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1253 if (history_string == NULL)
1254 {
1255 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1256 result.SetStatus(eReturnStatusFailed);
1257 return false;
1258 }
1259 add_to_history = false;
1260 command_string = history_string;
1261 original_command_string = history_string;
1262 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001263 }
1264
1265 if (empty_command)
1266 {
1267 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001268 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001269 if (m_command_history.empty())
1270 {
1271 result.AppendError ("empty command");
1272 result.SetStatus(eReturnStatusFailed);
1273 return false;
1274 }
1275 else
1276 {
1277 command_line = m_repeat_command.c_str();
1278 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001279 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001280 if (m_repeat_command.empty())
1281 {
1282 result.AppendErrorWithFormat("No auto repeat.\n");
1283 result.SetStatus (eReturnStatusFailed);
1284 return false;
1285 }
1286 }
1287 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001288 }
1289 else
1290 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001291 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1292 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001293 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001294 }
1295 else if (comment_command)
1296 {
1297 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1298 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001299 }
Caroline Tice649116c2011-05-11 16:07:06 +00001300
Greg Claytonf5c0c722011-10-14 07:41:33 +00001301
1302 Error error (PreprocessCommand (command_string));
1303
1304 if (error.Fail())
1305 {
1306 result.AppendError (error.AsCString());
1307 result.SetStatus(eReturnStatusFailed);
1308 return false;
1309 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001310 // Phase 1.
1311
1312 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1313 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1314 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1315 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1316 // 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 +00001317 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001318 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001319
Caroline Ticee0da7a52010-12-09 22:52:49 +00001320 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001321 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001322 std::string next_word;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001323 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001324 {
Caroline Tice649116c2011-05-11 16:07:06 +00001325 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001326 std::string suffix;
1327 ExtractCommand (command_string, next_word, suffix, quote_char);
1328 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001329 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001330 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001331 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001332 std::string alias_result;
1333 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1334 revised_command_line.Printf ("%s", alias_result.c_str());
1335 if (cmd_obj)
1336 {
1337 wants_raw_input = cmd_obj->WantsRawCommandString ();
1338 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1339 }
Chris Lattner24943d22010-06-08 16:52:24 +00001340 }
1341 else
1342 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001343 cmd_obj = GetCommandObject (next_word.c_str());
1344 if (cmd_obj)
1345 {
1346 actual_cmd_name_len += next_word.length();
1347 revised_command_line.Printf ("%s", next_word.c_str());
1348 wants_raw_input = cmd_obj->WantsRawCommandString ();
1349 }
Caroline Tice649116c2011-05-11 16:07:06 +00001350 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001351 {
1352 revised_command_line.Printf ("%s", next_word.c_str());
1353 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001354 }
1355 }
1356 else
1357 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001358 if (cmd_obj->IsMultiwordObject ())
1359 {
1360 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1361 if (sub_cmd_obj)
1362 {
1363 actual_cmd_name_len += next_word.length() + 1;
1364 revised_command_line.Printf (" %s", next_word.c_str());
1365 cmd_obj = sub_cmd_obj;
1366 wants_raw_input = cmd_obj->WantsRawCommandString ();
1367 }
1368 else
1369 {
1370 if (quote_char)
1371 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1372 else
1373 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1374 done = true;
1375 }
1376 }
Caroline Tice649116c2011-05-11 16:07:06 +00001377 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001378 {
1379 if (quote_char)
1380 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1381 else
1382 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1383 done = true;
1384 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001385 }
1386
1387 if (cmd_obj == NULL)
1388 {
1389 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1390 result.SetStatus (eReturnStatusFailed);
1391 return false;
1392 }
1393
Greg Clayton7268b4c2011-10-28 21:38:01 +00001394 if (cmd_obj->IsMultiwordObject ())
1395 {
1396 if (!suffix.empty())
1397 {
1398
1399 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1400 next_word.c_str(),
1401 suffix.c_str());
1402 result.SetStatus (eReturnStatusFailed);
1403 return false;
1404 }
1405 }
1406 else
1407 {
1408 // If we found a normal command, we are done
1409 done = true;
1410 if (!suffix.empty())
1411 {
1412 switch (suffix[0])
1413 {
1414 case '/':
1415 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001416 {
1417 Options *command_options = cmd_obj->GetOptions();
1418 if (command_options && command_options->SupportsLongOption("gdb-format"))
1419 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001420 std::string gdb_format_option ("--gdb-format=");
1421 gdb_format_option += (suffix.c_str() + 1);
1422
1423 bool inserted = false;
1424 std::string &cmd = revised_command_line.GetString();
1425 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1426 if (arg_terminator_idx != std::string::npos)
1427 {
1428 // Insert the gdb format option before the "--" that terminates options
1429 gdb_format_option.append(1,' ');
1430 cmd.insert(arg_terminator_idx, gdb_format_option);
1431 inserted = true;
1432 }
1433
1434 if (!inserted)
1435 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1436
1437 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1438 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001439 }
1440 else
1441 {
1442 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1443 cmd_obj->GetCommandName());
1444 result.SetStatus (eReturnStatusFailed);
1445 return false;
1446 }
1447 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001448 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001449
1450 default:
1451 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1452 suffix.c_str());
1453 result.SetStatus (eReturnStatusFailed);
1454 return false;
1455
Greg Clayton7268b4c2011-10-28 21:38:01 +00001456 }
1457 }
1458 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001459 if (command_string.length() == 0)
1460 done = true;
1461
Chris Lattner24943d22010-06-08 16:52:24 +00001462 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001463
Greg Clayton7268b4c2011-10-28 21:38:01 +00001464 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001465 revised_command_line.Printf (" %s", command_string.c_str());
1466
1467 // End of Phase 1.
1468 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1469 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1470 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1471 // wants_raw_input specifies whether the Execute method expects raw input or not.
1472
1473
1474 if (log)
1475 {
1476 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1477 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1478 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1479 }
1480
1481 // Phase 2.
1482 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1483 // CommandObject, with the appropriate arguments.
1484
1485 if (cmd_obj != NULL)
1486 {
1487 if (add_to_history)
1488 {
1489 Args command_args (revised_command_line.GetData());
1490 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1491 if (repeat_command != NULL)
1492 m_repeat_command.assign(repeat_command);
1493 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001494 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001495
Jim Ingham6247dbe2011-07-12 03:12:18 +00001496 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001497 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001498 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001499 }
1500
1501 command_string = revised_command_line.GetData();
1502 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001503 std::string remainder;
1504 if (actual_cmd_name_len < command_string.length())
1505 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1506 // than cmd_obj->GetCommandName(), because name completion
1507 // allows users to enter short versions of the names,
1508 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001509
1510 // Remove any initial spaces
1511 std::string white_space (" \t\v");
1512 size_t pos = remainder.find_first_not_of (white_space);
1513 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001514 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001515
1516 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001517 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001518
1519
Greg Claytonf1252502012-02-29 04:21:24 +00001520 CommandOverrideCallback command_callback = cmd_obj->GetOverrideCallback();
1521 bool handled = false;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001522 if (wants_raw_input)
Greg Claytonf1252502012-02-29 04:21:24 +00001523 {
1524 if (command_callback)
1525 {
1526 std::string full_command (cmd_obj->GetCommandName ());
1527 full_command += ' ';
1528 full_command += remainder;
1529 const char *argv[2] = { NULL, NULL };
1530 argv[0] = full_command.c_str();
1531 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), argv);
1532 }
1533 if (!handled)
1534 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1535 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001536 else
1537 {
1538 Args cmd_args (remainder.c_str());
Greg Claytonf1252502012-02-29 04:21:24 +00001539 if (command_callback)
1540 {
1541 Args full_args (cmd_obj->GetCommandName ());
1542 full_args.AppendArguments(cmd_args);
1543 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), full_args.GetConstArgumentVector());
1544 }
1545 if (!handled)
1546 cmd_obj->ExecuteWithOptions (cmd_args, result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001547 }
1548 }
1549 else
1550 {
1551 // We didn't find the first command object, so complete the first argument.
1552 Args command_args (revised_command_line.GetData());
1553 StringList matches;
1554 int num_matches;
1555 int cursor_index = 0;
1556 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1557 bool word_complete;
1558 num_matches = HandleCompletionMatches (command_args,
1559 cursor_index,
1560 cursor_char_position,
1561 0,
1562 -1,
1563 word_complete,
1564 matches);
1565
1566 if (num_matches > 0)
1567 {
1568 std::string error_msg;
1569 error_msg.assign ("ambiguous command '");
1570 error_msg.append(command_args.GetArgumentAtIndex(0));
1571 error_msg.append ("'.");
1572
1573 error_msg.append (" Possible completions:");
1574 for (int i = 0; i < num_matches; i++)
1575 {
1576 error_msg.append ("\n\t");
1577 error_msg.append (matches.GetStringAtIndex (i));
1578 }
1579 error_msg.append ("\n");
1580 result.AppendRawError (error_msg.c_str(), error_msg.size());
1581 }
1582 else
1583 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1584
1585 result.SetStatus (eReturnStatusFailed);
1586 }
1587
Jason Molenda24c991c2011-08-25 00:20:04 +00001588 if (log)
1589 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1590
Chris Lattner24943d22010-06-08 16:52:24 +00001591 return result.Succeeded();
1592}
1593
1594int
1595CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1596 int &cursor_index,
1597 int &cursor_char_position,
1598 int match_start_point,
1599 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001600 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001601 StringList &matches)
1602{
1603 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001604 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001605
1606 // For any of the command completions a unique match will be a complete word.
1607 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001608
1609 if (cursor_index == -1)
1610 {
1611 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001612 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001613 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1614 }
1615 else if (cursor_index == 0)
1616 {
1617 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001618 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001619 num_command_matches = matches.GetSize();
1620
1621 if (num_command_matches == 1
1622 && cmd_obj && cmd_obj->IsMultiwordObject()
1623 && matches.GetStringAtIndex(0) != NULL
1624 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1625 {
1626 look_for_subcommand = true;
1627 num_command_matches = 0;
1628 matches.DeleteStringAtIndex(0);
1629 parsed_line.AppendArgument ("");
1630 cursor_index++;
1631 cursor_char_position = 0;
1632 }
1633 }
1634
1635 if (cursor_index > 0 || look_for_subcommand)
1636 {
1637 // We are completing further on into a commands arguments, so find the command and tell it
1638 // to complete the command.
1639 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001640 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001641 if (command_object == NULL)
1642 {
1643 return 0;
1644 }
1645 else
1646 {
1647 parsed_line.Shift();
1648 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001649 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001650 cursor_index,
1651 cursor_char_position,
1652 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001653 max_return_elements,
1654 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001655 matches);
1656 }
1657 }
1658
1659 return num_command_matches;
1660
1661}
1662
1663int
1664CommandInterpreter::HandleCompletion (const char *current_line,
1665 const char *cursor,
1666 const char *last_char,
1667 int match_start_point,
1668 int max_return_elements,
1669 StringList &matches)
1670{
1671 // We parse the argument up to the cursor, so the last argument in parsed_line is
1672 // the one containing the cursor, and the cursor is after the last character.
1673
1674 Args parsed_line(current_line, last_char - current_line);
1675 Args partial_parsed_line(current_line, cursor - current_line);
1676
Jim Ingham6247dbe2011-07-12 03:12:18 +00001677 // Don't complete comments, and if the line we are completing is just the history repeat character,
1678 // substitute the appropriate history line.
1679 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1680 if (first_arg)
1681 {
1682 if (first_arg[0] == m_comment_char)
1683 return 0;
1684 else if (first_arg[0] == m_repeat_char)
1685 {
1686 const char *history_string = FindHistoryString (first_arg);
1687 if (history_string != NULL)
1688 {
1689 matches.Clear();
1690 matches.InsertStringAtIndex(0, history_string);
1691 return -2;
1692 }
1693 else
1694 return 0;
1695
1696 }
1697 }
1698
1699
Chris Lattner24943d22010-06-08 16:52:24 +00001700 int num_args = partial_parsed_line.GetArgumentCount();
1701 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1702 int cursor_char_position;
1703
1704 if (cursor_index == -1)
1705 cursor_char_position = 0;
1706 else
1707 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001708
1709 if (cursor > current_line && cursor[-1] == ' ')
1710 {
1711 // We are just after a space. If we are in an argument, then we will continue
1712 // parsing, but if we are between arguments, then we have to complete whatever the next
1713 // element would be.
1714 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1715 // protected by a quote) then the space will also be in the parsed argument...
1716
1717 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1718 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1719 {
1720 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1721 cursor_index++;
1722 cursor_char_position = 0;
1723 }
1724 }
Chris Lattner24943d22010-06-08 16:52:24 +00001725
1726 int num_command_matches;
1727
1728 matches.Clear();
1729
1730 // Only max_return_elements == -1 is supported at present:
1731 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001732 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001733 num_command_matches = HandleCompletionMatches (parsed_line,
1734 cursor_index,
1735 cursor_char_position,
1736 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001737 max_return_elements,
1738 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001739 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001740
1741 if (num_command_matches <= 0)
1742 return num_command_matches;
1743
1744 if (num_args == 0)
1745 {
1746 // If we got an empty string, insert nothing.
1747 matches.InsertStringAtIndex(0, "");
1748 }
1749 else
1750 {
1751 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1752 // put an empty string in element 0.
1753 std::string command_partial_str;
1754 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001755 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1756 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001757
1758 std::string common_prefix;
1759 matches.LongestCommonPrefix (common_prefix);
1760 int partial_name_len = command_partial_str.size();
1761
1762 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001763 // Only do this if the completer told us this was a complete word, however...
1764 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001765 {
1766 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1767 if (quote_char != '\0')
1768 common_prefix.push_back(quote_char);
1769
1770 common_prefix.push_back(' ');
1771 }
1772 common_prefix.erase (0, partial_name_len);
1773 matches.InsertStringAtIndex(0, common_prefix.c_str());
1774 }
1775 return num_command_matches;
1776}
1777
Chris Lattner24943d22010-06-08 16:52:24 +00001778
1779CommandInterpreter::~CommandInterpreter ()
1780{
1781}
1782
1783const char *
1784CommandInterpreter::GetPrompt ()
1785{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001786 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001787}
1788
1789void
1790CommandInterpreter::SetPrompt (const char *new_prompt)
1791{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001792 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001793}
1794
Jim Ingham5e16ef52010-10-04 19:49:29 +00001795size_t
Greg Clayton58928562011-02-09 01:08:52 +00001796CommandInterpreter::GetConfirmationInputReaderCallback
1797(
1798 void *baton,
1799 InputReader &reader,
1800 lldb::InputReaderAction action,
1801 const char *bytes,
1802 size_t bytes_len
1803)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001804{
Greg Clayton58928562011-02-09 01:08:52 +00001805 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001806 bool *response_ptr = (bool *) baton;
1807
1808 switch (action)
1809 {
1810 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001811 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001812 {
1813 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001814 {
Greg Clayton58928562011-02-09 01:08:52 +00001815 out_file.Printf ("%s", reader.GetPrompt());
1816 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001817 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001818 }
1819 break;
1820
1821 case eInputReaderDeactivate:
1822 break;
1823
1824 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001825 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001826 {
Greg Clayton58928562011-02-09 01:08:52 +00001827 out_file.Printf ("%s", reader.GetPrompt());
1828 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001829 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001830 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001831
1832 case eInputReaderAsynchronousOutputWritten:
1833 break;
1834
Jim Ingham5e16ef52010-10-04 19:49:29 +00001835 case eInputReaderGotToken:
1836 if (bytes_len == 0)
1837 {
1838 reader.SetIsDone(true);
1839 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001840 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001841 {
1842 *response_ptr = true;
1843 reader.SetIsDone(true);
1844 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001845 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001846 {
1847 *response_ptr = false;
1848 reader.SetIsDone(true);
1849 }
1850 else
1851 {
Greg Clayton58928562011-02-09 01:08:52 +00001852 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001853 {
Jim Ingham26183802011-11-17 01:22:00 +00001854 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001855 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001856 }
1857 }
1858 break;
1859
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001860 case eInputReaderInterrupt:
1861 case eInputReaderEndOfFile:
1862 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1863 reader.SetIsDone (true);
1864 break;
1865
Jim Ingham5e16ef52010-10-04 19:49:29 +00001866 case eInputReaderDone:
1867 break;
1868 }
1869
1870 return bytes_len;
1871
1872}
1873
1874bool
1875CommandInterpreter::Confirm (const char *message, bool default_answer)
1876{
Jim Ingham93057472010-10-04 22:44:14 +00001877 // Check AutoConfirm first:
1878 if (m_debugger.GetAutoConfirm())
1879 return default_answer;
1880
Jim Ingham5e16ef52010-10-04 19:49:29 +00001881 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1882 bool response = default_answer;
1883 if (reader_sp)
1884 {
1885 std::string prompt(message);
1886 prompt.append(": [");
1887 if (default_answer)
1888 prompt.append ("Y/n] ");
1889 else
1890 prompt.append ("y/N] ");
1891
1892 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1893 &response, // baton
1894 eInputReaderGranularityLine, // token size, to pass to callback function
1895 NULL, // end token
1896 prompt.c_str(), // prompt
1897 true)); // echo input
1898 if (err.Success())
1899 {
1900 GetDebugger().PushInputReader (reader_sp);
1901 }
1902 reader_sp->WaitOnReaderIsDone();
1903 }
1904 return response;
1905}
1906
1907
Chris Lattner24943d22010-06-08 16:52:24 +00001908void
1909CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1910{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001911 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001912
1913 if (cmd_obj_sp != NULL)
1914 {
1915 CommandObject *cmd_obj = cmd_obj_sp.get();
1916 if (cmd_obj->IsCrossRefObject ())
1917 cmd_obj->AddObject (object_type);
1918 }
1919}
1920
Chris Lattner24943d22010-06-08 16:52:24 +00001921OptionArgVectorSP
1922CommandInterpreter::GetAliasOptions (const char *alias_name)
1923{
1924 OptionArgMap::iterator pos;
1925 OptionArgVectorSP ret_val;
1926
1927 std::string alias (alias_name);
1928
1929 if (HasAliasOptions())
1930 {
1931 pos = m_alias_options.find (alias);
1932 if (pos != m_alias_options.end())
1933 ret_val = pos->second;
1934 }
1935
1936 return ret_val;
1937}
1938
1939void
1940CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1941{
1942 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1943 if (pos != m_alias_options.end())
1944 {
1945 m_alias_options.erase (pos);
1946 }
1947}
1948
1949void
1950CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1951{
1952 m_alias_options[alias_name] = option_arg_vector_sp;
1953}
1954
1955bool
1956CommandInterpreter::HasCommands ()
1957{
1958 return (!m_command_dict.empty());
1959}
1960
1961bool
1962CommandInterpreter::HasAliases ()
1963{
1964 return (!m_alias_dict.empty());
1965}
1966
1967bool
1968CommandInterpreter::HasUserCommands ()
1969{
1970 return (!m_user_dict.empty());
1971}
1972
1973bool
1974CommandInterpreter::HasAliasOptions ()
1975{
1976 return (!m_alias_options.empty());
1977}
1978
Chris Lattner24943d22010-06-08 16:52:24 +00001979void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001980CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1981 const char *alias_name,
1982 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001983 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001984 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001985{
1986 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001987
1988 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001989
Caroline Tice44c841d2010-12-07 19:58:26 +00001990 // Make sure that the alias name is the 0th element in cmd_args
1991 std::string alias_name_str = alias_name;
1992 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1993 cmd_args.Unshift (alias_name);
1994
1995 Args new_args (alias_cmd_obj->GetCommandName());
1996 if (new_args.GetArgumentCount() == 2)
1997 new_args.Shift();
1998
Chris Lattner24943d22010-06-08 16:52:24 +00001999 if (option_arg_vector_sp.get())
2000 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002001 if (wants_raw_input)
2002 {
2003 // We have a command that both has command options and takes raw input. Make *sure* it has a
2004 // " -- " in the right place in the raw_input_string.
2005 size_t pos = raw_input_string.find(" -- ");
2006 if (pos == std::string::npos)
2007 {
2008 // None found; assume it goes at the beginning of the raw input string
2009 raw_input_string.insert (0, " -- ");
2010 }
2011 }
Chris Lattner24943d22010-06-08 16:52:24 +00002012
2013 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2014 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002015 std::vector<bool> used (old_size + 1, false);
2016
2017 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002018
2019 for (int i = 0; i < option_arg_vector->size(); ++i)
2020 {
2021 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002022 OptionArgValue value_pair = option_pair.second;
2023 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002024 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002025 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002026 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002027 {
2028 if (!wants_raw_input
2029 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2030 new_args.AppendArgument (value.c_str());
2031 }
Chris Lattner24943d22010-06-08 16:52:24 +00002032 else
2033 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002034 if (value_type != optional_argument)
2035 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002036 if (value.compare ("<no-argument>") != 0)
2037 {
2038 int index = GetOptionArgumentPosition (value.c_str());
2039 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002040 {
Chris Lattner24943d22010-06-08 16:52:24 +00002041 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002042 if (value_type != optional_argument)
2043 new_args.AppendArgument (value.c_str());
2044 else
2045 {
2046 char buffer[255];
2047 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2048 new_args.AppendArgument (buffer);
2049 }
2050
2051 }
Chris Lattner24943d22010-06-08 16:52:24 +00002052 else if (index >= cmd_args.GetArgumentCount())
2053 {
2054 result.AppendErrorWithFormat
2055 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2056 index);
2057 result.SetStatus (eReturnStatusFailed);
2058 return;
2059 }
2060 else
2061 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002062 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2063 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2064 if (strpos != std::string::npos)
2065 {
2066 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2067 }
2068
2069 if (value_type != optional_argument)
2070 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2071 else
2072 {
2073 char buffer[255];
2074 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2075 cmd_args.GetArgumentAtIndex (index));
2076 new_args.AppendArgument (buffer);
2077 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002078 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002079 }
2080 }
2081 }
2082 }
2083
2084 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2085 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002086 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002087 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2088 }
2089
2090 cmd_args.Clear();
2091 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2092 }
2093 else
2094 {
2095 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002096 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2097 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2098 // input string.
2099 if (wants_raw_input)
2100 {
2101 cmd_args.Clear();
2102 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2103 }
Chris Lattner24943d22010-06-08 16:52:24 +00002104 return;
2105 }
2106
2107 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2108 return;
2109}
2110
2111
2112int
2113CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2114{
2115 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2116 // of zero.
2117
2118 char *cptr = (char *) in_string;
2119
2120 // Does it start with '%'
2121 if (cptr[0] == '%')
2122 {
2123 ++cptr;
2124
2125 // Is the rest of it entirely digits?
2126 if (isdigit (cptr[0]))
2127 {
2128 const char *start = cptr;
2129 while (isdigit (cptr[0]))
2130 ++cptr;
2131
2132 // We've gotten to the end of the digits; are we at the end of the string?
2133 if (cptr[0] == '\0')
2134 position = atoi (start);
2135 }
2136 }
2137
2138 return position;
2139}
2140
2141void
2142CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2143{
Jim Ingham574c3d62011-08-12 23:34:31 +00002144 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002145 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002146 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002147 // In the current working directory we don't load any program specific
2148 // .lldbinit files, we only look for a "./.lldbinit" file.
2149 if (m_skip_lldbinit_files)
2150 return;
2151
2152 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002153 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002154 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002155 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002156 // If we aren't looking in the current working directory we are looking
2157 // in the home directory. We will first see if there is an application
2158 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2159 // "-" and the name of the program. If this file doesn't exist, we fall
2160 // back to just the "~/.lldbinit" file. We also obey any requests to not
2161 // load the init files.
2162 const char *init_file_path = "~/.lldbinit";
2163
2164 if (m_skip_app_init_files == false)
2165 {
2166 FileSpec program_file_spec (Host::GetProgramFileSpec());
2167 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002168
Greg Claytond6edcb52011-09-11 00:01:44 +00002169 if (program_name)
2170 {
2171 char program_init_file_name[PATH_MAX];
2172 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2173 init_file.SetFile (program_init_file_name, true);
2174 if (!init_file.Exists())
2175 init_file.Clear();
2176 }
2177 }
2178
2179 if (!init_file && !m_skip_lldbinit_files)
2180 init_file.SetFile (init_file_path, true);
2181 }
2182
Chris Lattner24943d22010-06-08 16:52:24 +00002183 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2184 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2185
2186 if (init_file.Exists())
2187 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002188 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2189 bool stop_on_continue = true;
2190 bool stop_on_error = false;
2191 bool echo_commands = false;
2192 bool print_results = false;
2193
2194 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002195 }
2196 else
2197 {
2198 // nothing to be done if the file doesn't exist
2199 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2200 }
2201}
2202
Greg Claytonb72d0f02011-04-12 05:54:46 +00002203PlatformSP
2204CommandInterpreter::GetPlatform (bool prefer_target_platform)
2205{
2206 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002207 if (prefer_target_platform)
2208 {
2209 Target *target = m_exe_ctx.GetTargetPtr();
2210 if (target)
2211 platform_sp = target->GetPlatform();
2212 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002213
2214 if (!platform_sp)
2215 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2216 return platform_sp;
2217}
2218
Jim Ingham949d5ac2011-02-18 00:54:25 +00002219void
Jim Inghama4fede32011-03-11 01:51:49 +00002220CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002221 ExecutionContext *override_context,
2222 bool stop_on_continue,
2223 bool stop_on_error,
2224 bool echo_commands,
2225 bool print_results,
2226 CommandReturnObject &result)
2227{
2228 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002229
2230 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2231 // Make sure you reset this value anywhere you return from the function.
2232
2233 bool old_async_execution = m_debugger.GetAsyncExecution();
2234
2235 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2236 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2237
2238 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002239 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002240
2241 if (!stop_on_continue)
2242 {
2243 m_debugger.SetAsyncExecution (false);
2244 }
2245
2246 for (int idx = 0; idx < num_lines; idx++)
2247 {
2248 const char *cmd = commands.GetStringAtIndex(idx);
2249 if (cmd[0] == '\0')
2250 continue;
2251
Jim Ingham949d5ac2011-02-18 00:54:25 +00002252 if (echo_commands)
2253 {
2254 result.AppendMessageWithFormat ("%s %s\n",
2255 GetPrompt(),
2256 cmd);
2257 }
2258
Greg Claytonaa378b12011-02-20 02:15:07 +00002259 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002260 // If override_context is not NULL, pass no_context_switching = true for
2261 // HandleCommand() since we updated our context already.
2262 bool success = HandleCommand(cmd, false, tmp_result,
2263 NULL, /* override_context */
2264 true, /* repeat_on_empty_command */
2265 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002266
2267 if (print_results)
2268 {
2269 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002270 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002271 }
2272
2273 if (!success || !tmp_result.Succeeded())
2274 {
2275 if (stop_on_error)
2276 {
2277 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
2278 idx, cmd);
2279 result.SetStatus (eReturnStatusFailed);
2280 m_debugger.SetAsyncExecution (old_async_execution);
2281 return;
2282 }
2283 else if (print_results)
2284 {
2285 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
2286 idx + 1,
2287 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002288 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002289 }
2290 }
2291
Caroline Tice4a348082011-05-02 20:41:46 +00002292 if (result.GetImmediateOutputStream())
2293 result.GetImmediateOutputStream()->Flush();
2294
2295 if (result.GetImmediateErrorStream())
2296 result.GetImmediateErrorStream()->Flush();
2297
Jim Ingham949d5ac2011-02-18 00:54:25 +00002298 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2299 // could be running (for instance in Breakpoint Commands.
2300 // So we check the return value to see if it is has running in it.
2301 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2302 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2303 {
2304 if (stop_on_continue)
2305 {
2306 // If we caused the target to proceed, and we're going to stop in that case, set the
2307 // status in our real result before returning. This is an error if the continue was not the
2308 // last command in the set of commands to be run.
2309 if (idx != num_lines - 1)
2310 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2311 idx + 1, cmd);
2312 else
2313 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2314
2315 result.SetStatus(tmp_result.GetStatus());
2316 m_debugger.SetAsyncExecution (old_async_execution);
2317
2318 return;
2319 }
2320 }
2321
2322 }
2323
2324 result.SetStatus (eReturnStatusSuccessFinishResult);
2325 m_debugger.SetAsyncExecution (old_async_execution);
2326
2327 return;
2328}
2329
2330void
2331CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2332 ExecutionContext *context,
2333 bool stop_on_continue,
2334 bool stop_on_error,
2335 bool echo_command,
2336 bool print_result,
2337 CommandReturnObject &result)
2338{
2339 if (cmd_file.Exists())
2340 {
2341 bool success;
2342 StringList commands;
2343 success = commands.ReadFileLines(cmd_file);
2344 if (!success)
2345 {
2346 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2347 result.SetStatus (eReturnStatusFailed);
2348 return;
2349 }
2350 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
2351 }
2352 else
2353 {
2354 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2355 cmd_file.GetFilename().AsCString());
2356 result.SetStatus (eReturnStatusFailed);
2357 return;
2358 }
2359}
2360
Chris Lattner24943d22010-06-08 16:52:24 +00002361ScriptInterpreter *
2362CommandInterpreter::GetScriptInterpreter ()
2363{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002364 if (m_script_interpreter_ap.get() != NULL)
2365 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002366
Caroline Tice0aa2e552011-01-14 00:29:16 +00002367 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2368 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002369 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002370 case eScriptLanguagePython:
2371#ifndef LLDB_DISABLE_PYTHON
2372 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2373 break;
2374#else
2375 // Fall through to the None case when python is disabled
2376#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002377 case eScriptLanguageNone:
2378 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2379 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002380 default:
2381 break;
2382 };
2383
2384 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002385}
2386
2387
2388
2389bool
2390CommandInterpreter::GetSynchronous ()
2391{
2392 return m_synchronous_execution;
2393}
2394
2395void
2396CommandInterpreter::SetSynchronous (bool value)
2397{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002398 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002399}
2400
2401void
2402CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2403 const char *word_text,
2404 const char *separator,
2405 const char *help_text,
2406 uint32_t max_word_len)
2407{
Greg Clayton238c0a12010-09-18 01:14:36 +00002408 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2409
Chris Lattner24943d22010-06-08 16:52:24 +00002410 int indent_size = max_word_len + strlen (separator) + 2;
2411
2412 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002413
2414 StreamString text_strm;
2415 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2416
2417 size_t len = text_strm.GetSize();
2418 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002419 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002420 {
2421 text_strm.EOL();
2422 len = text_strm.GetSize();
2423 }
Chris Lattner24943d22010-06-08 16:52:24 +00002424
2425 if (len < max_columns)
2426 {
2427 // Output it as a single line.
2428 strm.Printf ("%s", text);
2429 }
2430 else
2431 {
2432 // We need to break it up into multiple lines.
2433 bool first_line = true;
2434 int text_width;
2435 int start = 0;
2436 int end = start;
2437 int final_end = strlen (text);
2438 int sub_len;
2439
2440 while (end < final_end)
2441 {
2442 if (first_line)
2443 text_width = max_columns - 1;
2444 else
2445 text_width = max_columns - indent_size - 1;
2446
2447 // Don't start the 'text' on a space, since we're already outputting the indentation.
2448 if (!first_line)
2449 {
2450 while ((start < final_end) && (text[start] == ' '))
2451 start++;
2452 }
2453
2454 end = start + text_width;
2455 if (end > final_end)
2456 end = final_end;
2457 else
2458 {
2459 // If we're not at the end of the text, make sure we break the line on white space.
2460 while (end > start
2461 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2462 end--;
2463 }
2464
2465 sub_len = end - start;
2466 if (start != 0)
2467 strm.EOL();
2468 if (!first_line)
2469 strm.Indent();
2470 else
2471 first_line = false;
2472 assert (start <= final_end);
2473 assert (start + sub_len <= final_end);
2474 if (sub_len > 0)
2475 strm.Write (text + start, sub_len);
2476 start = end + 1;
2477 }
2478 }
2479 strm.EOL();
2480 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002481}
2482
2483void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002484CommandInterpreter::OutputHelpText (Stream &strm,
2485 const char *word_text,
2486 const char *separator,
2487 const char *help_text,
2488 uint32_t max_word_len)
2489{
2490 int indent_size = max_word_len + strlen (separator) + 2;
2491
2492 strm.IndentMore (indent_size);
2493
2494 StreamString text_strm;
2495 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2496
2497 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2498 bool first_line = true;
2499
2500 size_t len = text_strm.GetSize();
2501 const char *text = text_strm.GetData();
2502
2503 uint32_t chars_left = max_columns;
2504
2505 for (uint32_t i = 0; i < len; i++)
2506 {
2507 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2508 {
2509 first_line = false;
2510 chars_left = max_columns - indent_size;
2511 strm.EOL();
2512 strm.Indent();
2513 }
2514 else
2515 {
2516 strm.PutChar(text[i]);
2517 chars_left--;
2518 }
2519
2520 }
2521
2522 strm.EOL();
2523 strm.IndentLess(indent_size);
2524}
2525
2526void
Chris Lattner24943d22010-06-08 16:52:24 +00002527CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2528 StringList &commands_found, StringList &commands_help)
2529{
2530 CommandObject::CommandMap::const_iterator pos;
2531 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2532 CommandObject *sub_cmd_obj;
2533
2534 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2535 {
2536 const char * command_name = pos->first.c_str();
2537 sub_cmd_obj = pos->second.get();
2538 StreamString complete_command_name;
2539
2540 complete_command_name.Printf ("%s %s", prefix, command_name);
2541
Greg Clayton238c0a12010-09-18 01:14:36 +00002542 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002543 {
2544 commands_found.AppendString (complete_command_name.GetData());
2545 commands_help.AppendString (sub_cmd_obj->GetHelp());
2546 }
2547
2548 if (sub_cmd_obj->IsMultiwordObject())
2549 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2550 commands_help);
2551 }
2552
2553}
2554
2555void
2556CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2557 StringList &commands_help)
2558{
2559 CommandObject::CommandMap::const_iterator pos;
2560
2561 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2562 {
2563 const char *command_name = pos->first.c_str();
2564 CommandObject *cmd_obj = pos->second.get();
2565
Greg Clayton238c0a12010-09-18 01:14:36 +00002566 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002567 {
2568 commands_found.AppendString (command_name);
2569 commands_help.AppendString (cmd_obj->GetHelp());
2570 }
2571
2572 if (cmd_obj->IsMultiwordObject())
2573 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2574
2575 }
2576}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002577
2578
2579void
2580CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2581{
2582 m_exe_ctx.Clear();
2583
2584 if (override_context != NULL)
2585 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002586 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002587 }
2588 else
2589 {
2590 TargetSP target_sp (m_debugger.GetSelectedTarget());
2591 if (target_sp)
2592 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002593 m_exe_ctx.SetTargetSP (target_sp);
2594 ProcessSP process_sp (target_sp->GetProcessSP());
2595 m_exe_ctx.SetProcessSP (process_sp);
2596 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002597 {
Greg Clayton13d24fb2012-01-29 20:56:30 +00002598 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
Greg Clayton567e7f32011-09-22 04:58:26 +00002599 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002600 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002601 m_exe_ctx.SetThreadSP (thread_sp);
2602 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2603 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002604 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002605 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002606 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002607 if (frame_sp)
2608 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002609 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002610 if (frame_sp)
2611 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002612 }
2613 }
2614 }
2615 }
2616}
2617
Jim Ingham6247dbe2011-07-12 03:12:18 +00002618void
2619CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2620{
2621 DumpHistory (stream, 0, count - 1);
2622}
2623
2624void
2625CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2626{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002627 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2628 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002629 {
2630 if (!m_command_history[i].empty())
2631 {
2632 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002633 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002634 }
2635 }
2636}
2637
2638const char *
2639CommandInterpreter::FindHistoryString (const char *input_str) const
2640{
2641 if (input_str[0] != m_repeat_char)
2642 return NULL;
2643 if (input_str[1] == '-')
2644 {
2645 bool success;
2646 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2647 if (!success)
2648 return NULL;
2649 if (idx > m_command_history.size())
2650 return NULL;
2651 idx = m_command_history.size() - idx;
2652 return m_command_history[idx].c_str();
2653
2654 }
2655 else if (input_str[1] == m_repeat_char)
2656 {
2657 if (m_command_history.empty())
2658 return NULL;
2659 else
2660 return m_command_history.back().c_str();
2661 }
2662 else
2663 {
2664 bool success;
2665 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2666 if (!success)
2667 return NULL;
2668 if (idx >= m_command_history.size())
2669 return NULL;
2670 return m_command_history[idx].c_str();
2671 }
2672}