blob: 4f266452f5e3fe2bf9223ba75dc1e9d18833e8ff [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 Granata01bc2d42012-05-31 01:09:06 +000083 m_truncation_warning(eNoTruncation),
84 m_command_source_depth (0)
Chris Lattner24943d22010-06-08 16:52:24 +000085{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000086 const char *dbg_name = debugger.GetInstanceName().AsCString();
87 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
88 StreamString var_name;
89 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000090 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000091 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000092 m_debugger.GetInstanceName().AsCString());
93 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
94 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
95 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham5a15e692012-02-16 06:50:00 +000096
97 CheckInWithManager ();
Chris Lattner24943d22010-06-08 16:52:24 +000098}
99
100void
101CommandInterpreter::Initialize ()
102{
103 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
104
105 CommandReturnObject result;
106
107 LoadCommandDictionary ();
108
Chris Lattner24943d22010-06-08 16:52:24 +0000109 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000110 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
111 if (cmd_obj_sp)
112 {
113 AddAlias ("q", cmd_obj_sp);
114 AddAlias ("exit", cmd_obj_sp);
115 }
Sean Callananfc58af22012-05-04 23:15:02 +0000116
117 cmd_obj_sp = GetCommandSPExact ("process attach", false);
118 if (cmd_obj_sp)
119 {
120 AddAlias ("attach", cmd_obj_sp);
121 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000122
123 cmd_obj_sp = GetCommandSPExact ("process continue", false);
124 if (cmd_obj_sp)
125 {
126 AddAlias ("c", cmd_obj_sp);
127 AddAlias ("continue", cmd_obj_sp);
128 }
129
130 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
131 if (cmd_obj_sp)
132 AddAlias ("b", cmd_obj_sp);
133
134 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
135 if (cmd_obj_sp)
136 AddAlias ("bt", cmd_obj_sp);
137
138 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
139 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000140 {
141 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000142 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000143 }
144
145 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
146 if (cmd_obj_sp)
147 {
148 AddAlias ("nexti", cmd_obj_sp);
149 AddAlias ("ni", cmd_obj_sp);
150 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000151
152 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
153 if (cmd_obj_sp)
154 {
155 AddAlias ("s", cmd_obj_sp);
156 AddAlias ("step", cmd_obj_sp);
157 }
158
159 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
160 if (cmd_obj_sp)
161 {
162 AddAlias ("n", cmd_obj_sp);
163 AddAlias ("next", cmd_obj_sp);
164 }
165
166 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
167 if (cmd_obj_sp)
168 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000169 AddAlias ("finish", cmd_obj_sp);
170 }
171
Jim Ingham59355252011-12-02 01:12:59 +0000172 cmd_obj_sp = GetCommandSPExact ("frame select", false);
173 if (cmd_obj_sp)
174 {
175 AddAlias ("f", cmd_obj_sp);
176 }
177
Caroline Tice5ddbe212011-05-06 21:37:15 +0000178 cmd_obj_sp = GetCommandSPExact ("source list", false);
179 if (cmd_obj_sp)
180 {
181 AddAlias ("l", cmd_obj_sp);
182 AddAlias ("list", cmd_obj_sp);
183 }
184
185 cmd_obj_sp = GetCommandSPExact ("memory read", false);
186 if (cmd_obj_sp)
187 AddAlias ("x", cmd_obj_sp);
188
189 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
190 if (cmd_obj_sp)
191 AddAlias ("up", cmd_obj_sp);
192
193 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
194 if (cmd_obj_sp)
195 AddAlias ("down", cmd_obj_sp);
196
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000197 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000198 if (cmd_obj_sp)
199 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000200
201 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
202 if (cmd_obj_sp)
203 AddAlias ("dis", cmd_obj_sp);
204
205 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
206 if (cmd_obj_sp)
207 AddAlias ("di", cmd_obj_sp);
208
209
Jason Molenda730cae02011-10-22 01:30:52 +0000210
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000211 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000212 if (cmd_obj_sp)
213 AddAlias ("undisplay", cmd_obj_sp);
214
Caroline Tice5ddbe212011-05-06 21:37:15 +0000215 cmd_obj_sp = GetCommandSPExact ("target create", false);
216 if (cmd_obj_sp)
217 AddAlias ("file", cmd_obj_sp);
218
219 cmd_obj_sp = GetCommandSPExact ("target modules", false);
220 if (cmd_obj_sp)
221 AddAlias ("image", cmd_obj_sp);
222
223
224 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000225
Caroline Tice5ddbe212011-05-06 21:37:15 +0000226 cmd_obj_sp = GetCommandSPExact ("expression", false);
227 if (cmd_obj_sp)
228 {
229 AddAlias ("expr", cmd_obj_sp);
230
231 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
232 AddAlias ("p", cmd_obj_sp);
233 AddAlias ("print", cmd_obj_sp);
234 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
235 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
236
237 alias_arguments_vector_sp.reset (new OptionArgVector);
238 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
239 AddAlias ("po", cmd_obj_sp);
240 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
241 }
242
243 cmd_obj_sp = GetCommandSPExact ("process launch", false);
244 if (cmd_obj_sp)
245 {
246 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton86c50d72012-05-18 00:04:38 +0000247 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000248 AddAlias ("r", cmd_obj_sp);
249 AddAlias ("run", cmd_obj_sp);
250 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
251 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
252 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000253
254 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
255 if (cmd_obj_sp)
256 {
257 AddAlias ("add-dsym", cmd_obj_sp);
258 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000259
260 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
261 if (cmd_obj_sp)
262 {
263 alias_arguments_vector_sp.reset (new OptionArgVector);
264 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
265 AddAlias ("rb", cmd_obj_sp);
266 AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
267 }
Chris Lattner24943d22010-06-08 16:52:24 +0000268}
269
Chris Lattner24943d22010-06-08 16:52:24 +0000270const char *
271CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
272{
273 // This function has not yet been implemented.
274
275 // Look for any embedded script command
276 // If found,
277 // get interpreter object from the command dictionary,
278 // call execute_one_command on it,
279 // get the results as a string,
280 // substitute that string for current stuff.
281
282 return arg;
283}
284
285
286void
287CommandInterpreter::LoadCommandDictionary ()
288{
289 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
290
291 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
292 //
293 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
294 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
295 // the cross-referencing stuff) are created!!!
296 //
297 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
298
299
300 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
301 // are created. This is so that when another command is created that needs to go into a crossref object,
302 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
303 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
304
Chris Lattner24943d22010-06-08 16:52:24 +0000305 // Non-CommandObjectCrossref commands can now be created.
306
Caroline Tice5bc8c972010-09-20 20:44:43 +0000307 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000308
Greg Clayton238c0a12010-09-18 01:14:36 +0000309 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000310 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000311 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000312 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000313 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
314 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000315// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000316 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000317 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000318 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000319 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
320 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000321 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000322 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000323 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000324 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000325 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000326 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000327 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000328 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
329 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000330 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000331 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000332 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000333
334 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000335 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000336 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000337 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000338 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000339 if (break_regex_cmd_ap.get())
340 {
341 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
342 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
343 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000344 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000345 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000346 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000347 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
348 {
349 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
350 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
351 }
352 }
Jim Inghame56493f2011-03-22 02:29:32 +0000353
354 std::auto_ptr<CommandObjectRegexCommand>
355 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000356 "_regexp-down",
357 "Go down \"n\" frames in the stack (1 frame by default).",
358 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000359 if (down_regex_cmd_ap.get())
360 {
361 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
362 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
363 {
364 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
365 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
366 }
367 }
368
369 std::auto_ptr<CommandObjectRegexCommand>
370 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000371 "_regexp-up",
372 "Go up \"n\" frames in the stack (1 frame by default).",
373 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000374 if (up_regex_cmd_ap.get())
375 {
376 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
377 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
378 {
379 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
380 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
381 }
382 }
Jason Molenda730cae02011-10-22 01:30:52 +0000383
384 std::auto_ptr<CommandObjectRegexCommand>
385 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000386 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000387 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000388 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000389 if (display_regex_cmd_ap.get())
390 {
391 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
392 {
393 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
394 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
395 }
396 }
397
398 std::auto_ptr<CommandObjectRegexCommand>
399 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000400 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000401 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000402 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000403 if (undisplay_regex_cmd_ap.get())
404 {
405 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
406 {
407 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
408 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
409 }
410 }
411
Chris Lattner24943d22010-06-08 16:52:24 +0000412}
413
414int
415CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
416 StringList &matches)
417{
418 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
419
420 if (include_aliases)
421 {
422 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
423 }
424
425 return matches.GetSize();
426}
427
428CommandObjectSP
429CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
430{
431 CommandObject::CommandMap::iterator pos;
432 CommandObjectSP ret_val;
433
434 std::string cmd(cmd_cstr);
435
436 if (HasCommands())
437 {
438 pos = m_command_dict.find(cmd);
439 if (pos != m_command_dict.end())
440 ret_val = pos->second;
441 }
442
443 if (include_aliases && HasAliases())
444 {
445 pos = m_alias_dict.find(cmd);
446 if (pos != m_alias_dict.end())
447 ret_val = pos->second;
448 }
449
450 if (HasUserCommands())
451 {
452 pos = m_user_dict.find(cmd);
453 if (pos != m_user_dict.end())
454 ret_val = pos->second;
455 }
456
457 if (!exact && ret_val == NULL)
458 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000459 // We will only get into here if we didn't find any exact matches.
460
461 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
462
Chris Lattner24943d22010-06-08 16:52:24 +0000463 StringList local_matches;
464 if (matches == NULL)
465 matches = &local_matches;
466
Jim Inghamd40f8a62010-07-06 22:46:59 +0000467 unsigned int num_cmd_matches = 0;
468 unsigned int num_alias_matches = 0;
469 unsigned int num_user_matches = 0;
470
471 // Look through the command dictionaries one by one, and if we get only one match from any of
472 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
473
Chris Lattner24943d22010-06-08 16:52:24 +0000474 if (HasCommands())
475 {
476 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
477 }
478
479 if (num_cmd_matches == 1)
480 {
481 cmd.assign(matches->GetStringAtIndex(0));
482 pos = m_command_dict.find(cmd);
483 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000484 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000485 }
486
Jim Ingham9a574172010-06-24 20:28:42 +0000487 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000488 {
489 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
490
491 }
492
Jim Inghamd40f8a62010-07-06 22:46:59 +0000493 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000494 {
495 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
496 pos = m_alias_dict.find(cmd);
497 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000498 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000499 }
500
Jim Ingham9a574172010-06-24 20:28:42 +0000501 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000502 {
503 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
504 }
505
Jim Inghamd40f8a62010-07-06 22:46:59 +0000506 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000507 {
508 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
509
510 pos = m_user_dict.find (cmd);
511 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000512 user_match_sp = pos->second;
513 }
514
515 // If we got exactly one match, return that, otherwise return the match list.
516
517 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
518 {
519 if (num_cmd_matches)
520 return real_match_sp;
521 else if (num_alias_matches)
522 return alias_match_sp;
523 else
524 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000525 }
526 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000527 else if (matches && ret_val != NULL)
528 {
529 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000530 }
531
532
533 return ret_val;
534}
535
Greg Claytond12aeab2011-04-20 16:37:46 +0000536bool
537CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
538{
539 if (name && name[0])
540 {
541 std::string name_sstr(name);
542 if (!can_replace)
543 {
544 if (m_command_dict.find (name_sstr) != m_command_dict.end())
545 return false;
546 }
547 m_command_dict[name_sstr] = cmd_sp;
548 return true;
549 }
550 return false;
551}
552
Enrico Granata6b1596d2011-08-16 23:24:13 +0000553bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000554CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000555 const lldb::CommandObjectSP &cmd_sp,
556 bool can_replace)
557{
Enrico Granata6010ace2011-11-07 22:57:04 +0000558 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000559 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000560
561 const char* name_cstr = name.c_str();
562
563 // do not allow replacement of internal commands
564 if (CommandExists(name_cstr))
565 return false;
566
567 if (can_replace == false && UserCommandExists(name_cstr))
568 return false;
569
570 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000571 return true;
572 }
573 return false;
574}
Greg Claytond12aeab2011-04-20 16:37:46 +0000575
Jim Inghamd40f8a62010-07-06 22:46:59 +0000576CommandObjectSP
577CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000578{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000579 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
580 CommandObjectSP ret_val; // Possibly empty return value.
581
582 if (cmd_cstr == NULL)
583 return ret_val;
584
585 if (cmd_words.GetArgumentCount() == 1)
586 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
587 else
588 {
589 // We have a multi-word command (seemingly), so we need to do more work.
590 // First, get the cmd_obj_sp for the first word in the command.
591 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
592 if (cmd_obj_sp.get() != NULL)
593 {
594 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
595 // command name), and find the appropriate sub-command SP for each command word....
596 size_t end = cmd_words.GetArgumentCount();
597 for (size_t j= 1; j < end; ++j)
598 {
599 if (cmd_obj_sp->IsMultiwordObject())
600 {
601 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
602 (cmd_words.GetArgumentAtIndex (j));
603 if (cmd_obj_sp.get() == NULL)
604 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
605 return ret_val;
606 }
607 else
608 // We have more words in the command name, but we don't have a multiword object. Fail and return
609 // empty 'ret_val'.
610 return ret_val;
611 }
612 // We successfully looped through all the command words and got valid command objects for them. Assign the
613 // last object retrieved to 'ret_val'.
614 ret_val = cmd_obj_sp;
615 }
616 }
617 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000618}
619
620CommandObject *
621CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
622{
623 return GetCommandSPExact (cmd_cstr, include_aliases).get();
624}
625
626CommandObject *
627CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
628{
629 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
630
631 // If we didn't find an exact match to the command string in the commands, look in
632 // the aliases.
633
634 if (command_obj == NULL)
635 {
636 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
637 }
638
639 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
640 // in both the commands and the aliases.
641
642 if (command_obj == NULL)
643 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
644
645 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000646}
647
648bool
649CommandInterpreter::CommandExists (const char *cmd)
650{
651 return m_command_dict.find(cmd) != m_command_dict.end();
652}
653
654bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000655CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
656 const char *options_args,
657 OptionArgVectorSP &option_arg_vector_sp)
658{
659 bool success = true;
660 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
661
662 if (!options_args || (strlen (options_args) < 1))
663 return true;
664
665 std::string options_string (options_args);
666 Args args (options_args);
667 CommandReturnObject result;
668 // Check to see if the command being aliased can take any command options.
669 Options *options = cmd_obj_sp->GetOptions ();
670 if (options)
671 {
672 // See if any options were specified as part of the alias; if so, handle them appropriately.
673 options->NotifyOptionParsingStarting ();
674 args.Unshift ("dummy_arg");
675 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
676 args.Shift ();
677 if (result.Succeeded())
678 options->VerifyPartialOptions (result);
679 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
680 {
681 result.AppendError ("Unable to create requested alias.\n");
682 return false;
683 }
684 }
685
Greg Clayton7268b4c2011-10-28 21:38:01 +0000686 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000687 {
688 if (cmd_obj_sp->WantsRawCommandString ())
689 option_arg_vector->push_back (OptionArgPair ("<argument>",
690 OptionArgValue (-1,
691 options_string)));
692 else
693 {
694 int argc = args.GetArgumentCount();
695 for (size_t i = 0; i < argc; ++i)
696 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
697 option_arg_vector->push_back
698 (OptionArgPair ("<argument>",
699 OptionArgValue (-1,
700 std::string (args.GetArgumentAtIndex (i)))));
701 }
702 }
703
704 return success;
705}
706
707bool
Chris Lattner24943d22010-06-08 16:52:24 +0000708CommandInterpreter::AliasExists (const char *cmd)
709{
710 return m_alias_dict.find(cmd) != m_alias_dict.end();
711}
712
713bool
714CommandInterpreter::UserCommandExists (const char *cmd)
715{
716 return m_user_dict.find(cmd) != m_user_dict.end();
717}
718
719void
720CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
721{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000722 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000723 m_alias_dict[alias_name] = command_obj_sp;
724}
725
726bool
727CommandInterpreter::RemoveAlias (const char *alias_name)
728{
729 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
730 if (pos != m_alias_dict.end())
731 {
732 m_alias_dict.erase(pos);
733 return true;
734 }
735 return false;
736}
737bool
738CommandInterpreter::RemoveUser (const char *alias_name)
739{
740 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
741 if (pos != m_user_dict.end())
742 {
743 m_user_dict.erase(pos);
744 return true;
745 }
746 return false;
747}
748
Chris Lattner24943d22010-06-08 16:52:24 +0000749void
750CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
751{
752 help_string.Printf ("'%s", command_name);
753 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
754
755 if (option_arg_vector_sp != NULL)
756 {
757 OptionArgVector *options = option_arg_vector_sp.get();
758 for (int i = 0; i < options->size(); ++i)
759 {
760 OptionArgPair cur_option = (*options)[i];
761 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000762 OptionArgValue value_pair = cur_option.second;
763 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000764 if (opt.compare("<argument>") == 0)
765 {
766 help_string.Printf (" %s", value.c_str());
767 }
768 else
769 {
770 help_string.Printf (" %s", opt.c_str());
771 if ((value.compare ("<no-argument>") != 0)
772 && (value.compare ("<need-argument") != 0))
773 {
774 help_string.Printf (" %s", value.c_str());
775 }
776 }
777 }
778 }
779
780 help_string.Printf ("'");
781}
782
Greg Clayton65124ea2010-08-26 22:05:43 +0000783size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000784CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
785{
786 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000787 CommandObject::CommandMap::const_iterator end = dict.end();
788 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000789
Greg Clayton65124ea2010-08-26 22:05:43 +0000790 for (pos = dict.begin(); pos != end; ++pos)
791 {
792 size_t len = pos->first.size();
793 if (max_len < len)
794 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000795 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000796 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000797}
798
799void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000800CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000801 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000802{
803 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000804 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000805
806 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000807 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000808
809 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
810 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000811
Enrico Granata6b1596d2011-08-16 23:24:13 +0000812 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
813 {
814 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
815 max_len);
816 }
817 result.AppendMessage("");
818
819 }
820
Greg Clayton7268b4c2011-10-28 21:38:01 +0000821 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000822 {
Jim Inghame3663e82010-10-22 18:47:16 +0000823 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000824 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000825 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000826 max_len = FindLongestCommandWord (m_alias_dict);
827
Chris Lattner24943d22010-06-08 16:52:24 +0000828 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
829 {
830 StreamString sstr;
831 StreamString translation_and_help;
832 std::string entry_name = pos->first;
833 std::string second_entry = pos->second.get()->GetCommandName();
834 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
835
836 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
837 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
838 translation_and_help.GetData(), max_len);
839 }
840 result.AppendMessage("");
841 }
842
Greg Clayton7268b4c2011-10-28 21:38:01 +0000843 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000844 {
845 result.AppendMessage ("The following is a list of your current user-defined commands:");
846 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000847 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000848 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
849 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000850 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
851 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000852 }
853 result.AppendMessage("");
854 }
855
856 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
857}
858
Caroline Ticee0da7a52010-12-09 22:52:49 +0000859CommandObject *
860CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000861{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000862 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
863 // eventually be invoked by the given command line.
864
865 CommandObject *cmd_obj = NULL;
866 std::string white_space (" \t\v");
867 size_t start = command_string.find_first_not_of (white_space);
868 size_t end = 0;
869 bool done = false;
870 while (!done)
871 {
872 if (start != std::string::npos)
873 {
874 // Get the next word from command_string.
875 end = command_string.find_first_of (white_space, start);
876 if (end == std::string::npos)
877 end = command_string.size();
878 std::string cmd_word = command_string.substr (start, end - start);
879
880 if (cmd_obj == NULL)
881 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
882 // command or alias.
883 cmd_obj = GetCommandObject (cmd_word.c_str());
884 else if (cmd_obj->IsMultiwordObject ())
885 {
886 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
887 CommandObject *sub_cmd_obj =
888 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
889 if (sub_cmd_obj)
890 cmd_obj = sub_cmd_obj;
891 else // cmd_word was not a valid sub-command word, so we are donee
892 done = true;
893 }
894 else
895 // We have a cmd_obj and it is not a multi-word object, so we are done.
896 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000897
Caroline Ticee0da7a52010-12-09 22:52:49 +0000898 // If we didn't find a valid command object, or our command object is not a multi-word object, or
899 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
900 // next word.
901
902 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
903 done = true;
904 else
905 start = command_string.find_first_not_of (white_space, end);
906 }
907 else
908 // Unable to find any more words.
909 done = true;
910 }
911
912 if (end == command_string.size())
913 command_string.clear();
914 else
915 command_string = command_string.substr(end);
916
917 return cmd_obj;
918}
919
Greg Clayton9d855c62011-10-25 00:36:27 +0000920static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000921static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000922static void
923StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000924{
Greg Clayton9d855c62011-10-25 00:36:27 +0000925 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000926 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000927 size_t pos = s.find_first_not_of (k_white_space);
928 if (pos == std::string::npos)
929 s.clear();
930 else if (pos == 0)
931 return;
932 s.erase (0, pos);
933 }
934}
935
Greg Clayton3840cd72011-11-09 23:25:03 +0000936static size_t
937FindArgumentTerminator (const std::string &s)
938{
Greg Clayton3840cd72011-11-09 23:25:03 +0000939 const size_t s_len = s.size();
940 size_t offset = 0;
941 while (offset < s_len)
942 {
943 size_t pos = s.find ("--", offset);
944 if (pos == std::string::npos)
945 break;
946 if (pos > 0)
947 {
948 if (isspace(s[pos-1]))
949 {
950 // Check if the string ends "\s--" (where \s is a space character)
951 // or if we have "\s--\s".
952 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
953 {
Greg Clayton3840cd72011-11-09 23:25:03 +0000954 return pos;
955 }
956 }
957 }
958 offset = pos + 2;
959 }
Greg Clayton3840cd72011-11-09 23:25:03 +0000960 return std::string::npos;
961}
962
Greg Clayton9d855c62011-10-25 00:36:27 +0000963static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000964ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000965{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000966 command.clear();
967 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000968 StripLeadingSpaces (command_string);
969
970 bool result = false;
971 quote_char = '\0';
972
973 if (!command_string.empty())
974 {
975 const char first_char = command_string[0];
976 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000977 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000978 quote_char = first_char;
979 const size_t end_quote_pos = command_string.find (quote_char, 1);
980 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000981 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000982 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000983 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000984 }
985 else
986 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000987 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +0000988 if (end_quote_pos + 1 < command_string.size())
989 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
990 else
991 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000992 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000993 }
994 else
995 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000996 const size_t first_space_pos = command_string.find_first_of (k_white_space);
997 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000998 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000999 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001000 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001001 }
1002 else
1003 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001004 command.assign (command_string, 0, first_space_pos);
1005 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001006 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001007 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001008 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001009 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001010
1011
1012 if (!command.empty())
1013 {
1014 // actual commands can't start with '-' or '_'
1015 if (command[0] != '-' && command[0] != '_')
1016 {
1017 size_t pos = command.find_first_not_of(k_valid_command_chars);
1018 if (pos > 0 && pos != std::string::npos)
1019 {
1020 suffix.assign (command.begin() + pos, command.end());
1021 command.erase (pos);
1022 }
1023 }
1024 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001025
1026 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001027}
1028
Greg Clayton7268b4c2011-10-28 21:38:01 +00001029CommandObject *
1030CommandInterpreter::BuildAliasResult (const char *alias_name,
1031 std::string &raw_input_string,
1032 std::string &alias_result,
1033 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001034{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001035 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001036 Args cmd_args (raw_input_string.c_str());
1037 alias_cmd_obj = GetCommandObject (alias_name);
1038 StreamString result_str;
1039
1040 if (alias_cmd_obj)
1041 {
1042 std::string alias_name_str = alias_name;
1043 if ((cmd_args.GetArgumentCount() == 0)
1044 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1045 cmd_args.Unshift (alias_name);
1046
1047 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1048 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1049
1050 if (option_arg_vector_sp.get())
1051 {
1052 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1053
1054 for (int i = 0; i < option_arg_vector->size(); ++i)
1055 {
1056 OptionArgPair option_pair = (*option_arg_vector)[i];
1057 OptionArgValue value_pair = option_pair.second;
1058 int value_type = value_pair.first;
1059 std::string option = option_pair.first;
1060 std::string value = value_pair.second;
1061 if (option.compare ("<argument>") == 0)
1062 result_str.Printf (" %s", value.c_str());
1063 else
1064 {
1065 result_str.Printf (" %s", option.c_str());
1066 if (value_type != optional_argument)
1067 result_str.Printf (" ");
1068 if (value.compare ("<no_argument>") != 0)
1069 {
1070 int index = GetOptionArgumentPosition (value.c_str());
1071 if (index == 0)
1072 result_str.Printf ("%s", value.c_str());
1073 else if (index >= cmd_args.GetArgumentCount())
1074 {
1075
1076 result.AppendErrorWithFormat
1077 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1078 index);
1079 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001080 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001081 }
1082 else
1083 {
1084 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1085 if (strpos != std::string::npos)
1086 raw_input_string = raw_input_string.erase (strpos,
1087 strlen (cmd_args.GetArgumentAtIndex (index)));
1088 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1089 }
1090 }
1091 }
1092 }
1093 }
1094
1095 alias_result = result_str.GetData();
1096 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001097 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001098}
1099
Greg Claytonf5c0c722011-10-14 07:41:33 +00001100Error
1101CommandInterpreter::PreprocessCommand (std::string &command)
1102{
1103 // The command preprocessor needs to do things to the command
1104 // line before any parsing of arguments or anything else is done.
1105 // The only current stuff that gets proprocessed is anyting enclosed
1106 // in backtick ('`') characters is evaluated as an expression and
1107 // the result of the expression must be a scalar that can be substituted
1108 // into the command. An example would be:
1109 // (lldb) memory read `$rsp + 20`
1110 Error error; // Error for any expressions that might not evaluate
1111 size_t start_backtick;
1112 size_t pos = 0;
1113 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1114 {
1115 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1116 {
1117 // The backtick was preceeded by a '\' character, remove the slash
1118 // and don't treat the backtick as the start of an expression
1119 command.erase(start_backtick-1, 1);
1120 // No need to add one to start_backtick since we just deleted a char
1121 pos = start_backtick;
1122 }
1123 else
1124 {
1125 const size_t expr_content_start = start_backtick + 1;
1126 const size_t end_backtick = command.find ('`', expr_content_start);
1127 if (end_backtick == std::string::npos)
1128 return error;
1129 else if (end_backtick == expr_content_start)
1130 {
1131 // Empty expression (two backticks in a row)
1132 command.erase (start_backtick, 2);
1133 }
1134 else
1135 {
1136 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1137
1138 Target *target = m_exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001139 // Get a dummy target to allow for calculator mode while processing backticks.
1140 // This also helps break the infinite loop caused when target is null.
1141 if (!target)
1142 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001143 if (target)
1144 {
Sean Callanandaa6efe2011-12-21 22:22:58 +00001145 const bool coerce_to_id = false;
Greg Claytonf5c0c722011-10-14 07:41:33 +00001146 const bool unwind_on_error = true;
1147 const bool keep_in_memory = false;
1148 ValueObjectSP expr_result_valobj_sp;
1149 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1150 m_exe_ctx.GetFramePtr(),
1151 eExecutionPolicyOnlyWhenNeeded,
Sean Callanandaa6efe2011-12-21 22:22:58 +00001152 coerce_to_id,
1153 unwind_on_error,
1154 keep_in_memory,
Greg Claytonf5c0c722011-10-14 07:41:33 +00001155 eNoDynamicValues,
1156 expr_result_valobj_sp);
1157 if (expr_result == eExecutionCompleted)
1158 {
1159 Scalar scalar;
1160 if (expr_result_valobj_sp->ResolveValue (scalar))
1161 {
1162 command.erase (start_backtick, end_backtick - start_backtick + 1);
1163 StreamString value_strm;
1164 const bool show_type = false;
1165 scalar.GetValue (&value_strm, show_type);
1166 size_t value_string_size = value_strm.GetSize();
1167 if (value_string_size)
1168 {
1169 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1170 pos = start_backtick + value_string_size;
1171 continue;
1172 }
1173 else
1174 {
1175 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1176 }
1177 }
1178 else
1179 {
1180 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1181 }
1182 }
1183 else
1184 {
1185 if (expr_result_valobj_sp)
1186 error = expr_result_valobj_sp->GetError();
1187 if (error.Success())
1188 {
1189
1190 switch (expr_result)
1191 {
1192 case eExecutionSetupError:
1193 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1194 break;
1195 case eExecutionCompleted:
1196 break;
1197 case eExecutionDiscarded:
1198 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1199 break;
1200 case eExecutionInterrupted:
1201 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1202 break;
1203 case eExecutionTimedOut:
1204 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1205 break;
1206 }
1207 }
1208 }
1209 }
1210 }
1211 if (error.Fail())
1212 break;
1213 }
1214 }
1215 return error;
1216}
1217
1218
Caroline Ticee0da7a52010-12-09 22:52:49 +00001219bool
1220CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001221 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001222 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001223 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001224 bool repeat_on_empty_command,
1225 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001226
Caroline Ticee0da7a52010-12-09 22:52:49 +00001227{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001228
Caroline Ticee0da7a52010-12-09 22:52:49 +00001229 bool done = false;
1230 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001231 bool wants_raw_input = false;
1232 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001233 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001234
1235 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001236 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1237
1238 // Make a scoped cleanup object that will clear the crash description string
1239 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001240 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001241
Caroline Ticee0da7a52010-12-09 22:52:49 +00001242 if (log)
1243 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001244
Jim Inghamabab14b2010-11-04 23:08:45 +00001245 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1246
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001247 if (!no_context_switching)
1248 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001249
1250 // <rdar://problem/11328896>
1251 bool add_to_history;
1252 if (lazy_add_to_history == eLazyBoolCalculate)
1253 add_to_history = (m_command_source_depth == 0);
1254 else
1255 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1256
Jim Ingham949d5ac2011-02-18 00:54:25 +00001257 bool empty_command = false;
1258 bool comment_command = false;
1259 if (command_string.empty())
1260 empty_command = true;
1261 else
Chris Lattner24943d22010-06-08 16:52:24 +00001262 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001263 const char *k_space_characters = "\t\n\v\f\r ";
1264
1265 size_t non_space = command_string.find_first_not_of (k_space_characters);
1266 // Check for empty line or comment line (lines whose first
1267 // non-space character is the comment character for this interpreter)
1268 if (non_space == std::string::npos)
1269 empty_command = true;
1270 else if (command_string[non_space] == m_comment_char)
1271 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001272 else if (command_string[non_space] == m_repeat_char)
1273 {
1274 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1275 if (history_string == NULL)
1276 {
1277 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1278 result.SetStatus(eReturnStatusFailed);
1279 return false;
1280 }
1281 add_to_history = false;
1282 command_string = history_string;
1283 original_command_string = history_string;
1284 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001285 }
1286
1287 if (empty_command)
1288 {
1289 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001290 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001291 if (m_command_history.empty())
1292 {
1293 result.AppendError ("empty command");
1294 result.SetStatus(eReturnStatusFailed);
1295 return false;
1296 }
1297 else
1298 {
1299 command_line = m_repeat_command.c_str();
1300 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001301 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001302 if (m_repeat_command.empty())
1303 {
1304 result.AppendErrorWithFormat("No auto repeat.\n");
1305 result.SetStatus (eReturnStatusFailed);
1306 return false;
1307 }
1308 }
1309 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001310 }
1311 else
1312 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001313 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1314 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001315 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001316 }
1317 else if (comment_command)
1318 {
1319 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1320 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001321 }
Caroline Tice649116c2011-05-11 16:07:06 +00001322
Greg Claytonf5c0c722011-10-14 07:41:33 +00001323
1324 Error error (PreprocessCommand (command_string));
1325
1326 if (error.Fail())
1327 {
1328 result.AppendError (error.AsCString());
1329 result.SetStatus(eReturnStatusFailed);
1330 return false;
1331 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001332 // Phase 1.
1333
1334 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1335 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1336 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1337 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1338 // 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 +00001339 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001340 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001341
Caroline Ticee0da7a52010-12-09 22:52:49 +00001342 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001343 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001344 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001345 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001346 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001347 {
Caroline Tice649116c2011-05-11 16:07:06 +00001348 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001349 std::string suffix;
1350 ExtractCommand (command_string, next_word, suffix, quote_char);
1351 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001352 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001353 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001354 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001355 std::string alias_result;
1356 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1357 revised_command_line.Printf ("%s", alias_result.c_str());
1358 if (cmd_obj)
1359 {
1360 wants_raw_input = cmd_obj->WantsRawCommandString ();
1361 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1362 }
Chris Lattner24943d22010-06-08 16:52:24 +00001363 }
1364 else
1365 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001366 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001367 if (cmd_obj)
1368 {
1369 actual_cmd_name_len += next_word.length();
1370 revised_command_line.Printf ("%s", next_word.c_str());
1371 wants_raw_input = cmd_obj->WantsRawCommandString ();
1372 }
Caroline Tice649116c2011-05-11 16:07:06 +00001373 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001374 {
1375 revised_command_line.Printf ("%s", next_word.c_str());
1376 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001377 }
1378 }
1379 else
1380 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001381 if (cmd_obj->IsMultiwordObject ())
1382 {
1383 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1384 if (sub_cmd_obj)
1385 {
1386 actual_cmd_name_len += next_word.length() + 1;
1387 revised_command_line.Printf (" %s", next_word.c_str());
1388 cmd_obj = sub_cmd_obj;
1389 wants_raw_input = cmd_obj->WantsRawCommandString ();
1390 }
1391 else
1392 {
1393 if (quote_char)
1394 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1395 else
1396 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1397 done = true;
1398 }
1399 }
Caroline Tice649116c2011-05-11 16:07:06 +00001400 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001401 {
1402 if (quote_char)
1403 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1404 else
1405 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1406 done = true;
1407 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001408 }
1409
1410 if (cmd_obj == NULL)
1411 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001412 uint32_t num_matches = matches.GetSize();
1413 if (matches.GetSize() > 1) {
1414 std::string error_msg;
1415 error_msg.assign ("Ambiguous command '");
1416 error_msg.append(next_word.c_str());
1417 error_msg.append ("'.");
1418
1419 error_msg.append (" Possible matches:");
1420
1421 for (uint32_t i = 0; i < num_matches; ++i) {
1422 error_msg.append ("\n\t");
1423 error_msg.append (matches.GetStringAtIndex(i));
1424 }
1425 error_msg.append ("\n");
1426 result.AppendRawError (error_msg.c_str(), error_msg.size());
1427 } else {
1428 // We didn't have only one match, otherwise we wouldn't get here.
1429 assert(num_matches == 0);
1430 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1431 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001432 result.SetStatus (eReturnStatusFailed);
1433 return false;
1434 }
1435
Greg Clayton7268b4c2011-10-28 21:38:01 +00001436 if (cmd_obj->IsMultiwordObject ())
1437 {
1438 if (!suffix.empty())
1439 {
1440
1441 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1442 next_word.c_str(),
1443 suffix.c_str());
1444 result.SetStatus (eReturnStatusFailed);
1445 return false;
1446 }
1447 }
1448 else
1449 {
1450 // If we found a normal command, we are done
1451 done = true;
1452 if (!suffix.empty())
1453 {
1454 switch (suffix[0])
1455 {
1456 case '/':
1457 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001458 {
1459 Options *command_options = cmd_obj->GetOptions();
1460 if (command_options && command_options->SupportsLongOption("gdb-format"))
1461 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001462 std::string gdb_format_option ("--gdb-format=");
1463 gdb_format_option += (suffix.c_str() + 1);
1464
1465 bool inserted = false;
1466 std::string &cmd = revised_command_line.GetString();
1467 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1468 if (arg_terminator_idx != std::string::npos)
1469 {
1470 // Insert the gdb format option before the "--" that terminates options
1471 gdb_format_option.append(1,' ');
1472 cmd.insert(arg_terminator_idx, gdb_format_option);
1473 inserted = true;
1474 }
1475
1476 if (!inserted)
1477 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1478
1479 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1480 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001481 }
1482 else
1483 {
1484 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1485 cmd_obj->GetCommandName());
1486 result.SetStatus (eReturnStatusFailed);
1487 return false;
1488 }
1489 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001490 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001491
1492 default:
1493 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1494 suffix.c_str());
1495 result.SetStatus (eReturnStatusFailed);
1496 return false;
1497
Greg Clayton7268b4c2011-10-28 21:38:01 +00001498 }
1499 }
1500 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001501 if (command_string.length() == 0)
1502 done = true;
1503
Chris Lattner24943d22010-06-08 16:52:24 +00001504 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001505
Greg Clayton7268b4c2011-10-28 21:38:01 +00001506 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001507 revised_command_line.Printf (" %s", command_string.c_str());
1508
1509 // End of Phase 1.
1510 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1511 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1512 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1513 // wants_raw_input specifies whether the Execute method expects raw input or not.
1514
1515
1516 if (log)
1517 {
1518 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1519 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1520 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1521 }
1522
1523 // Phase 2.
1524 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1525 // CommandObject, with the appropriate arguments.
1526
1527 if (cmd_obj != NULL)
1528 {
1529 if (add_to_history)
1530 {
1531 Args command_args (revised_command_line.GetData());
1532 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1533 if (repeat_command != NULL)
1534 m_repeat_command.assign(repeat_command);
1535 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001536 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001537
Jim Ingham6247dbe2011-07-12 03:12:18 +00001538 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001539 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001540 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001541 }
1542
1543 command_string = revised_command_line.GetData();
1544 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001545 std::string remainder;
1546 if (actual_cmd_name_len < command_string.length())
1547 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1548 // than cmd_obj->GetCommandName(), because name completion
1549 // allows users to enter short versions of the names,
1550 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001551
1552 // Remove any initial spaces
1553 std::string white_space (" \t\v");
1554 size_t pos = remainder.find_first_not_of (white_space);
1555 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001556 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001557
1558 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001559 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001560
1561
Greg Claytonf1252502012-02-29 04:21:24 +00001562 CommandOverrideCallback command_callback = cmd_obj->GetOverrideCallback();
1563 bool handled = false;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001564 if (wants_raw_input)
Greg Claytonf1252502012-02-29 04:21:24 +00001565 {
1566 if (command_callback)
1567 {
1568 std::string full_command (cmd_obj->GetCommandName ());
1569 full_command += ' ';
1570 full_command += remainder;
1571 const char *argv[2] = { NULL, NULL };
1572 argv[0] = full_command.c_str();
1573 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), argv);
1574 }
1575 if (!handled)
1576 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1577 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001578 else
1579 {
1580 Args cmd_args (remainder.c_str());
Greg Claytonf1252502012-02-29 04:21:24 +00001581 if (command_callback)
1582 {
1583 Args full_args (cmd_obj->GetCommandName ());
1584 full_args.AppendArguments(cmd_args);
1585 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), full_args.GetConstArgumentVector());
1586 }
1587 if (!handled)
1588 cmd_obj->ExecuteWithOptions (cmd_args, result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001589 }
1590 }
1591 else
1592 {
1593 // We didn't find the first command object, so complete the first argument.
1594 Args command_args (revised_command_line.GetData());
1595 StringList matches;
1596 int num_matches;
1597 int cursor_index = 0;
1598 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1599 bool word_complete;
1600 num_matches = HandleCompletionMatches (command_args,
1601 cursor_index,
1602 cursor_char_position,
1603 0,
1604 -1,
1605 word_complete,
1606 matches);
1607
1608 if (num_matches > 0)
1609 {
1610 std::string error_msg;
1611 error_msg.assign ("ambiguous command '");
1612 error_msg.append(command_args.GetArgumentAtIndex(0));
1613 error_msg.append ("'.");
1614
1615 error_msg.append (" Possible completions:");
1616 for (int i = 0; i < num_matches; i++)
1617 {
1618 error_msg.append ("\n\t");
1619 error_msg.append (matches.GetStringAtIndex (i));
1620 }
1621 error_msg.append ("\n");
1622 result.AppendRawError (error_msg.c_str(), error_msg.size());
1623 }
1624 else
1625 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1626
1627 result.SetStatus (eReturnStatusFailed);
1628 }
1629
Jason Molenda24c991c2011-08-25 00:20:04 +00001630 if (log)
1631 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1632
Chris Lattner24943d22010-06-08 16:52:24 +00001633 return result.Succeeded();
1634}
1635
1636int
1637CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1638 int &cursor_index,
1639 int &cursor_char_position,
1640 int match_start_point,
1641 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001642 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001643 StringList &matches)
1644{
1645 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001646 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001647
1648 // For any of the command completions a unique match will be a complete word.
1649 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001650
1651 if (cursor_index == -1)
1652 {
1653 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001654 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001655 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1656 }
1657 else if (cursor_index == 0)
1658 {
1659 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001660 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001661 num_command_matches = matches.GetSize();
1662
1663 if (num_command_matches == 1
1664 && cmd_obj && cmd_obj->IsMultiwordObject()
1665 && matches.GetStringAtIndex(0) != NULL
1666 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1667 {
1668 look_for_subcommand = true;
1669 num_command_matches = 0;
1670 matches.DeleteStringAtIndex(0);
1671 parsed_line.AppendArgument ("");
1672 cursor_index++;
1673 cursor_char_position = 0;
1674 }
1675 }
1676
1677 if (cursor_index > 0 || look_for_subcommand)
1678 {
1679 // We are completing further on into a commands arguments, so find the command and tell it
1680 // to complete the command.
1681 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001682 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001683 if (command_object == NULL)
1684 {
1685 return 0;
1686 }
1687 else
1688 {
1689 parsed_line.Shift();
1690 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001691 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001692 cursor_index,
1693 cursor_char_position,
1694 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001695 max_return_elements,
1696 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001697 matches);
1698 }
1699 }
1700
1701 return num_command_matches;
1702
1703}
1704
1705int
1706CommandInterpreter::HandleCompletion (const char *current_line,
1707 const char *cursor,
1708 const char *last_char,
1709 int match_start_point,
1710 int max_return_elements,
1711 StringList &matches)
1712{
1713 // We parse the argument up to the cursor, so the last argument in parsed_line is
1714 // the one containing the cursor, and the cursor is after the last character.
1715
1716 Args parsed_line(current_line, last_char - current_line);
1717 Args partial_parsed_line(current_line, cursor - current_line);
1718
Jim Ingham6247dbe2011-07-12 03:12:18 +00001719 // Don't complete comments, and if the line we are completing is just the history repeat character,
1720 // substitute the appropriate history line.
1721 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1722 if (first_arg)
1723 {
1724 if (first_arg[0] == m_comment_char)
1725 return 0;
1726 else if (first_arg[0] == m_repeat_char)
1727 {
1728 const char *history_string = FindHistoryString (first_arg);
1729 if (history_string != NULL)
1730 {
1731 matches.Clear();
1732 matches.InsertStringAtIndex(0, history_string);
1733 return -2;
1734 }
1735 else
1736 return 0;
1737
1738 }
1739 }
1740
1741
Chris Lattner24943d22010-06-08 16:52:24 +00001742 int num_args = partial_parsed_line.GetArgumentCount();
1743 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1744 int cursor_char_position;
1745
1746 if (cursor_index == -1)
1747 cursor_char_position = 0;
1748 else
1749 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001750
1751 if (cursor > current_line && cursor[-1] == ' ')
1752 {
1753 // We are just after a space. If we are in an argument, then we will continue
1754 // parsing, but if we are between arguments, then we have to complete whatever the next
1755 // element would be.
1756 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1757 // protected by a quote) then the space will also be in the parsed argument...
1758
1759 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1760 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1761 {
1762 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1763 cursor_index++;
1764 cursor_char_position = 0;
1765 }
1766 }
Chris Lattner24943d22010-06-08 16:52:24 +00001767
1768 int num_command_matches;
1769
1770 matches.Clear();
1771
1772 // Only max_return_elements == -1 is supported at present:
1773 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001774 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001775 num_command_matches = HandleCompletionMatches (parsed_line,
1776 cursor_index,
1777 cursor_char_position,
1778 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001779 max_return_elements,
1780 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001781 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001782
1783 if (num_command_matches <= 0)
1784 return num_command_matches;
1785
1786 if (num_args == 0)
1787 {
1788 // If we got an empty string, insert nothing.
1789 matches.InsertStringAtIndex(0, "");
1790 }
1791 else
1792 {
1793 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1794 // put an empty string in element 0.
1795 std::string command_partial_str;
1796 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001797 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1798 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001799
1800 std::string common_prefix;
1801 matches.LongestCommonPrefix (common_prefix);
1802 int partial_name_len = command_partial_str.size();
1803
1804 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001805 // Only do this if the completer told us this was a complete word, however...
1806 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001807 {
1808 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1809 if (quote_char != '\0')
1810 common_prefix.push_back(quote_char);
1811
1812 common_prefix.push_back(' ');
1813 }
1814 common_prefix.erase (0, partial_name_len);
1815 matches.InsertStringAtIndex(0, common_prefix.c_str());
1816 }
1817 return num_command_matches;
1818}
1819
Chris Lattner24943d22010-06-08 16:52:24 +00001820
1821CommandInterpreter::~CommandInterpreter ()
1822{
1823}
1824
1825const char *
1826CommandInterpreter::GetPrompt ()
1827{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001828 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001829}
1830
1831void
1832CommandInterpreter::SetPrompt (const char *new_prompt)
1833{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001834 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001835}
1836
Jim Ingham5e16ef52010-10-04 19:49:29 +00001837size_t
Greg Clayton58928562011-02-09 01:08:52 +00001838CommandInterpreter::GetConfirmationInputReaderCallback
1839(
1840 void *baton,
1841 InputReader &reader,
1842 lldb::InputReaderAction action,
1843 const char *bytes,
1844 size_t bytes_len
1845)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001846{
Greg Clayton58928562011-02-09 01:08:52 +00001847 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001848 bool *response_ptr = (bool *) baton;
1849
1850 switch (action)
1851 {
1852 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001853 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001854 {
1855 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001856 {
Greg Clayton58928562011-02-09 01:08:52 +00001857 out_file.Printf ("%s", reader.GetPrompt());
1858 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001859 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001860 }
1861 break;
1862
1863 case eInputReaderDeactivate:
1864 break;
1865
1866 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001867 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001868 {
Greg Clayton58928562011-02-09 01:08:52 +00001869 out_file.Printf ("%s", reader.GetPrompt());
1870 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001871 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001872 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001873
1874 case eInputReaderAsynchronousOutputWritten:
1875 break;
1876
Jim Ingham5e16ef52010-10-04 19:49:29 +00001877 case eInputReaderGotToken:
1878 if (bytes_len == 0)
1879 {
1880 reader.SetIsDone(true);
1881 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001882 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001883 {
1884 *response_ptr = true;
1885 reader.SetIsDone(true);
1886 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001887 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001888 {
1889 *response_ptr = false;
1890 reader.SetIsDone(true);
1891 }
1892 else
1893 {
Greg Clayton58928562011-02-09 01:08:52 +00001894 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001895 {
Jim Ingham26183802011-11-17 01:22:00 +00001896 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001897 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001898 }
1899 }
1900 break;
1901
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001902 case eInputReaderInterrupt:
1903 case eInputReaderEndOfFile:
1904 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1905 reader.SetIsDone (true);
1906 break;
1907
Jim Ingham5e16ef52010-10-04 19:49:29 +00001908 case eInputReaderDone:
1909 break;
1910 }
1911
1912 return bytes_len;
1913
1914}
1915
1916bool
1917CommandInterpreter::Confirm (const char *message, bool default_answer)
1918{
Jim Ingham93057472010-10-04 22:44:14 +00001919 // Check AutoConfirm first:
1920 if (m_debugger.GetAutoConfirm())
1921 return default_answer;
1922
Jim Ingham5e16ef52010-10-04 19:49:29 +00001923 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1924 bool response = default_answer;
1925 if (reader_sp)
1926 {
1927 std::string prompt(message);
1928 prompt.append(": [");
1929 if (default_answer)
1930 prompt.append ("Y/n] ");
1931 else
1932 prompt.append ("y/N] ");
1933
1934 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1935 &response, // baton
1936 eInputReaderGranularityLine, // token size, to pass to callback function
1937 NULL, // end token
1938 prompt.c_str(), // prompt
1939 true)); // echo input
1940 if (err.Success())
1941 {
1942 GetDebugger().PushInputReader (reader_sp);
1943 }
1944 reader_sp->WaitOnReaderIsDone();
1945 }
1946 return response;
1947}
1948
1949
Chris Lattner24943d22010-06-08 16:52:24 +00001950void
1951CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1952{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001953 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001954
1955 if (cmd_obj_sp != NULL)
1956 {
1957 CommandObject *cmd_obj = cmd_obj_sp.get();
1958 if (cmd_obj->IsCrossRefObject ())
1959 cmd_obj->AddObject (object_type);
1960 }
1961}
1962
Chris Lattner24943d22010-06-08 16:52:24 +00001963OptionArgVectorSP
1964CommandInterpreter::GetAliasOptions (const char *alias_name)
1965{
1966 OptionArgMap::iterator pos;
1967 OptionArgVectorSP ret_val;
1968
1969 std::string alias (alias_name);
1970
1971 if (HasAliasOptions())
1972 {
1973 pos = m_alias_options.find (alias);
1974 if (pos != m_alias_options.end())
1975 ret_val = pos->second;
1976 }
1977
1978 return ret_val;
1979}
1980
1981void
1982CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1983{
1984 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1985 if (pos != m_alias_options.end())
1986 {
1987 m_alias_options.erase (pos);
1988 }
1989}
1990
1991void
1992CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1993{
1994 m_alias_options[alias_name] = option_arg_vector_sp;
1995}
1996
1997bool
1998CommandInterpreter::HasCommands ()
1999{
2000 return (!m_command_dict.empty());
2001}
2002
2003bool
2004CommandInterpreter::HasAliases ()
2005{
2006 return (!m_alias_dict.empty());
2007}
2008
2009bool
2010CommandInterpreter::HasUserCommands ()
2011{
2012 return (!m_user_dict.empty());
2013}
2014
2015bool
2016CommandInterpreter::HasAliasOptions ()
2017{
2018 return (!m_alias_options.empty());
2019}
2020
Chris Lattner24943d22010-06-08 16:52:24 +00002021void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002022CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2023 const char *alias_name,
2024 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002025 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002026 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002027{
2028 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002029
2030 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002031
Caroline Tice44c841d2010-12-07 19:58:26 +00002032 // Make sure that the alias name is the 0th element in cmd_args
2033 std::string alias_name_str = alias_name;
2034 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2035 cmd_args.Unshift (alias_name);
2036
2037 Args new_args (alias_cmd_obj->GetCommandName());
2038 if (new_args.GetArgumentCount() == 2)
2039 new_args.Shift();
2040
Chris Lattner24943d22010-06-08 16:52:24 +00002041 if (option_arg_vector_sp.get())
2042 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002043 if (wants_raw_input)
2044 {
2045 // We have a command that both has command options and takes raw input. Make *sure* it has a
2046 // " -- " in the right place in the raw_input_string.
2047 size_t pos = raw_input_string.find(" -- ");
2048 if (pos == std::string::npos)
2049 {
2050 // None found; assume it goes at the beginning of the raw input string
2051 raw_input_string.insert (0, " -- ");
2052 }
2053 }
Chris Lattner24943d22010-06-08 16:52:24 +00002054
2055 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2056 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002057 std::vector<bool> used (old_size + 1, false);
2058
2059 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002060
2061 for (int i = 0; i < option_arg_vector->size(); ++i)
2062 {
2063 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002064 OptionArgValue value_pair = option_pair.second;
2065 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002066 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002067 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002068 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002069 {
2070 if (!wants_raw_input
2071 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2072 new_args.AppendArgument (value.c_str());
2073 }
Chris Lattner24943d22010-06-08 16:52:24 +00002074 else
2075 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002076 if (value_type != optional_argument)
2077 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002078 if (value.compare ("<no-argument>") != 0)
2079 {
2080 int index = GetOptionArgumentPosition (value.c_str());
2081 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002082 {
Chris Lattner24943d22010-06-08 16:52:24 +00002083 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002084 if (value_type != optional_argument)
2085 new_args.AppendArgument (value.c_str());
2086 else
2087 {
2088 char buffer[255];
2089 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2090 new_args.AppendArgument (buffer);
2091 }
2092
2093 }
Chris Lattner24943d22010-06-08 16:52:24 +00002094 else if (index >= cmd_args.GetArgumentCount())
2095 {
2096 result.AppendErrorWithFormat
2097 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2098 index);
2099 result.SetStatus (eReturnStatusFailed);
2100 return;
2101 }
2102 else
2103 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002104 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2105 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2106 if (strpos != std::string::npos)
2107 {
2108 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2109 }
2110
2111 if (value_type != optional_argument)
2112 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2113 else
2114 {
2115 char buffer[255];
2116 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2117 cmd_args.GetArgumentAtIndex (index));
2118 new_args.AppendArgument (buffer);
2119 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002120 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002121 }
2122 }
2123 }
2124 }
2125
2126 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2127 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002128 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002129 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2130 }
2131
2132 cmd_args.Clear();
2133 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2134 }
2135 else
2136 {
2137 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002138 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2139 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2140 // input string.
2141 if (wants_raw_input)
2142 {
2143 cmd_args.Clear();
2144 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2145 }
Chris Lattner24943d22010-06-08 16:52:24 +00002146 return;
2147 }
2148
2149 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2150 return;
2151}
2152
2153
2154int
2155CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2156{
2157 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2158 // of zero.
2159
2160 char *cptr = (char *) in_string;
2161
2162 // Does it start with '%'
2163 if (cptr[0] == '%')
2164 {
2165 ++cptr;
2166
2167 // Is the rest of it entirely digits?
2168 if (isdigit (cptr[0]))
2169 {
2170 const char *start = cptr;
2171 while (isdigit (cptr[0]))
2172 ++cptr;
2173
2174 // We've gotten to the end of the digits; are we at the end of the string?
2175 if (cptr[0] == '\0')
2176 position = atoi (start);
2177 }
2178 }
2179
2180 return position;
2181}
2182
2183void
2184CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2185{
Jim Ingham574c3d62011-08-12 23:34:31 +00002186 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002187 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002188 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002189 // In the current working directory we don't load any program specific
2190 // .lldbinit files, we only look for a "./.lldbinit" file.
2191 if (m_skip_lldbinit_files)
2192 return;
2193
2194 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002195 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002196 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002197 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002198 // If we aren't looking in the current working directory we are looking
2199 // in the home directory. We will first see if there is an application
2200 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2201 // "-" and the name of the program. If this file doesn't exist, we fall
2202 // back to just the "~/.lldbinit" file. We also obey any requests to not
2203 // load the init files.
2204 const char *init_file_path = "~/.lldbinit";
2205
2206 if (m_skip_app_init_files == false)
2207 {
2208 FileSpec program_file_spec (Host::GetProgramFileSpec());
2209 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002210
Greg Claytond6edcb52011-09-11 00:01:44 +00002211 if (program_name)
2212 {
2213 char program_init_file_name[PATH_MAX];
2214 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2215 init_file.SetFile (program_init_file_name, true);
2216 if (!init_file.Exists())
2217 init_file.Clear();
2218 }
2219 }
2220
2221 if (!init_file && !m_skip_lldbinit_files)
2222 init_file.SetFile (init_file_path, true);
2223 }
2224
Chris Lattner24943d22010-06-08 16:52:24 +00002225 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2226 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2227
2228 if (init_file.Exists())
2229 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002230 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2231 bool stop_on_continue = true;
2232 bool stop_on_error = false;
2233 bool echo_commands = false;
2234 bool print_results = false;
2235
Enrico Granata01bc2d42012-05-31 01:09:06 +00002236 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002237 }
2238 else
2239 {
2240 // nothing to be done if the file doesn't exist
2241 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2242 }
2243}
2244
Greg Claytonb72d0f02011-04-12 05:54:46 +00002245PlatformSP
2246CommandInterpreter::GetPlatform (bool prefer_target_platform)
2247{
2248 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002249 if (prefer_target_platform)
2250 {
2251 Target *target = m_exe_ctx.GetTargetPtr();
2252 if (target)
2253 platform_sp = target->GetPlatform();
2254 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002255
2256 if (!platform_sp)
2257 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2258 return platform_sp;
2259}
2260
Jim Ingham949d5ac2011-02-18 00:54:25 +00002261void
Jim Inghama4fede32011-03-11 01:51:49 +00002262CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002263 ExecutionContext *override_context,
2264 bool stop_on_continue,
2265 bool stop_on_error,
2266 bool echo_commands,
2267 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002268 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002269 CommandReturnObject &result)
2270{
2271 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002272
2273 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2274 // Make sure you reset this value anywhere you return from the function.
2275
2276 bool old_async_execution = m_debugger.GetAsyncExecution();
2277
2278 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2279 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2280
2281 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002282 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002283
2284 if (!stop_on_continue)
2285 {
2286 m_debugger.SetAsyncExecution (false);
2287 }
2288
2289 for (int idx = 0; idx < num_lines; idx++)
2290 {
2291 const char *cmd = commands.GetStringAtIndex(idx);
2292 if (cmd[0] == '\0')
2293 continue;
2294
Jim Ingham949d5ac2011-02-18 00:54:25 +00002295 if (echo_commands)
2296 {
2297 result.AppendMessageWithFormat ("%s %s\n",
2298 GetPrompt(),
2299 cmd);
2300 }
2301
Greg Claytonaa378b12011-02-20 02:15:07 +00002302 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002303 // If override_context is not NULL, pass no_context_switching = true for
2304 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002305 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002306 NULL, /* override_context */
2307 true, /* repeat_on_empty_command */
2308 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002309
2310 if (print_results)
2311 {
2312 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002313 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002314 }
2315
2316 if (!success || !tmp_result.Succeeded())
2317 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002318 const char *error_msg = tmp_result.GetErrorData();
2319 if (error_msg == NULL || error_msg[0] == '\0')
2320 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002321 if (stop_on_error)
2322 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002323 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2324 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002325 result.SetStatus (eReturnStatusFailed);
2326 m_debugger.SetAsyncExecution (old_async_execution);
2327 return;
2328 }
2329 else if (print_results)
2330 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002331 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002332 idx + 1,
2333 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002334 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002335 }
2336 }
2337
Caroline Tice4a348082011-05-02 20:41:46 +00002338 if (result.GetImmediateOutputStream())
2339 result.GetImmediateOutputStream()->Flush();
2340
2341 if (result.GetImmediateErrorStream())
2342 result.GetImmediateErrorStream()->Flush();
2343
Jim Ingham949d5ac2011-02-18 00:54:25 +00002344 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2345 // could be running (for instance in Breakpoint Commands.
2346 // So we check the return value to see if it is has running in it.
2347 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2348 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2349 {
2350 if (stop_on_continue)
2351 {
2352 // If we caused the target to proceed, and we're going to stop in that case, set the
2353 // status in our real result before returning. This is an error if the continue was not the
2354 // last command in the set of commands to be run.
2355 if (idx != num_lines - 1)
2356 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2357 idx + 1, cmd);
2358 else
2359 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2360
2361 result.SetStatus(tmp_result.GetStatus());
2362 m_debugger.SetAsyncExecution (old_async_execution);
2363
2364 return;
2365 }
2366 }
2367
2368 }
2369
2370 result.SetStatus (eReturnStatusSuccessFinishResult);
2371 m_debugger.SetAsyncExecution (old_async_execution);
2372
2373 return;
2374}
2375
2376void
2377CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2378 ExecutionContext *context,
2379 bool stop_on_continue,
2380 bool stop_on_error,
2381 bool echo_command,
2382 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002383 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002384 CommandReturnObject &result)
2385{
2386 if (cmd_file.Exists())
2387 {
2388 bool success;
2389 StringList commands;
2390 success = commands.ReadFileLines(cmd_file);
2391 if (!success)
2392 {
2393 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2394 result.SetStatus (eReturnStatusFailed);
2395 return;
2396 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002397 m_command_source_depth++;
2398 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2399 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002400 }
2401 else
2402 {
2403 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2404 cmd_file.GetFilename().AsCString());
2405 result.SetStatus (eReturnStatusFailed);
2406 return;
2407 }
2408}
2409
Chris Lattner24943d22010-06-08 16:52:24 +00002410ScriptInterpreter *
2411CommandInterpreter::GetScriptInterpreter ()
2412{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002413 if (m_script_interpreter_ap.get() != NULL)
2414 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002415
Caroline Tice0aa2e552011-01-14 00:29:16 +00002416 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2417 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002418 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002419 case eScriptLanguagePython:
2420#ifndef LLDB_DISABLE_PYTHON
2421 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2422 break;
2423#else
2424 // Fall through to the None case when python is disabled
2425#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002426 case eScriptLanguageNone:
2427 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2428 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002429 default:
2430 break;
2431 };
2432
2433 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002434}
2435
2436
2437
2438bool
2439CommandInterpreter::GetSynchronous ()
2440{
2441 return m_synchronous_execution;
2442}
2443
2444void
2445CommandInterpreter::SetSynchronous (bool value)
2446{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002447 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002448}
2449
2450void
2451CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2452 const char *word_text,
2453 const char *separator,
2454 const char *help_text,
2455 uint32_t max_word_len)
2456{
Greg Clayton238c0a12010-09-18 01:14:36 +00002457 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2458
Chris Lattner24943d22010-06-08 16:52:24 +00002459 int indent_size = max_word_len + strlen (separator) + 2;
2460
2461 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002462
2463 StreamString text_strm;
2464 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2465
2466 size_t len = text_strm.GetSize();
2467 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002468 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002469 {
2470 text_strm.EOL();
2471 len = text_strm.GetSize();
2472 }
Chris Lattner24943d22010-06-08 16:52:24 +00002473
2474 if (len < max_columns)
2475 {
2476 // Output it as a single line.
2477 strm.Printf ("%s", text);
2478 }
2479 else
2480 {
2481 // We need to break it up into multiple lines.
2482 bool first_line = true;
2483 int text_width;
2484 int start = 0;
2485 int end = start;
2486 int final_end = strlen (text);
2487 int sub_len;
2488
2489 while (end < final_end)
2490 {
2491 if (first_line)
2492 text_width = max_columns - 1;
2493 else
2494 text_width = max_columns - indent_size - 1;
2495
2496 // Don't start the 'text' on a space, since we're already outputting the indentation.
2497 if (!first_line)
2498 {
2499 while ((start < final_end) && (text[start] == ' '))
2500 start++;
2501 }
2502
2503 end = start + text_width;
2504 if (end > final_end)
2505 end = final_end;
2506 else
2507 {
2508 // If we're not at the end of the text, make sure we break the line on white space.
2509 while (end > start
2510 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2511 end--;
2512 }
2513
2514 sub_len = end - start;
2515 if (start != 0)
2516 strm.EOL();
2517 if (!first_line)
2518 strm.Indent();
2519 else
2520 first_line = false;
2521 assert (start <= final_end);
2522 assert (start + sub_len <= final_end);
2523 if (sub_len > 0)
2524 strm.Write (text + start, sub_len);
2525 start = end + 1;
2526 }
2527 }
2528 strm.EOL();
2529 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002530}
2531
2532void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002533CommandInterpreter::OutputHelpText (Stream &strm,
2534 const char *word_text,
2535 const char *separator,
2536 const char *help_text,
2537 uint32_t max_word_len)
2538{
2539 int indent_size = max_word_len + strlen (separator) + 2;
2540
2541 strm.IndentMore (indent_size);
2542
2543 StreamString text_strm;
2544 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2545
2546 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2547 bool first_line = true;
2548
2549 size_t len = text_strm.GetSize();
2550 const char *text = text_strm.GetData();
2551
2552 uint32_t chars_left = max_columns;
2553
2554 for (uint32_t i = 0; i < len; i++)
2555 {
2556 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2557 {
2558 first_line = false;
2559 chars_left = max_columns - indent_size;
2560 strm.EOL();
2561 strm.Indent();
2562 }
2563 else
2564 {
2565 strm.PutChar(text[i]);
2566 chars_left--;
2567 }
2568
2569 }
2570
2571 strm.EOL();
2572 strm.IndentLess(indent_size);
2573}
2574
2575void
Chris Lattner24943d22010-06-08 16:52:24 +00002576CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2577 StringList &commands_found, StringList &commands_help)
2578{
2579 CommandObject::CommandMap::const_iterator pos;
2580 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2581 CommandObject *sub_cmd_obj;
2582
2583 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2584 {
2585 const char * command_name = pos->first.c_str();
2586 sub_cmd_obj = pos->second.get();
2587 StreamString complete_command_name;
2588
2589 complete_command_name.Printf ("%s %s", prefix, command_name);
2590
Greg Clayton238c0a12010-09-18 01:14:36 +00002591 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002592 {
2593 commands_found.AppendString (complete_command_name.GetData());
2594 commands_help.AppendString (sub_cmd_obj->GetHelp());
2595 }
2596
2597 if (sub_cmd_obj->IsMultiwordObject())
2598 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2599 commands_help);
2600 }
2601
2602}
2603
2604void
2605CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2606 StringList &commands_help)
2607{
2608 CommandObject::CommandMap::const_iterator pos;
2609
2610 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2611 {
2612 const char *command_name = pos->first.c_str();
2613 CommandObject *cmd_obj = pos->second.get();
2614
Greg Clayton238c0a12010-09-18 01:14:36 +00002615 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002616 {
2617 commands_found.AppendString (command_name);
2618 commands_help.AppendString (cmd_obj->GetHelp());
2619 }
2620
2621 if (cmd_obj->IsMultiwordObject())
2622 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2623
2624 }
2625}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002626
2627
2628void
2629CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2630{
2631 m_exe_ctx.Clear();
2632
2633 if (override_context != NULL)
2634 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002635 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002636 }
2637 else
2638 {
2639 TargetSP target_sp (m_debugger.GetSelectedTarget());
2640 if (target_sp)
2641 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002642 m_exe_ctx.SetTargetSP (target_sp);
2643 ProcessSP process_sp (target_sp->GetProcessSP());
2644 m_exe_ctx.SetProcessSP (process_sp);
2645 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002646 {
Greg Clayton13d24fb2012-01-29 20:56:30 +00002647 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
Greg Clayton567e7f32011-09-22 04:58:26 +00002648 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002649 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002650 m_exe_ctx.SetThreadSP (thread_sp);
2651 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2652 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002653 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002654 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002655 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002656 if (frame_sp)
2657 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002658 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002659 if (frame_sp)
2660 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002661 }
2662 }
2663 }
2664 }
2665}
2666
Jim Ingham6247dbe2011-07-12 03:12:18 +00002667void
2668CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2669{
2670 DumpHistory (stream, 0, count - 1);
2671}
2672
2673void
2674CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2675{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002676 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2677 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002678 {
2679 if (!m_command_history[i].empty())
2680 {
2681 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002682 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002683 }
2684 }
2685}
2686
2687const char *
2688CommandInterpreter::FindHistoryString (const char *input_str) const
2689{
2690 if (input_str[0] != m_repeat_char)
2691 return NULL;
2692 if (input_str[1] == '-')
2693 {
2694 bool success;
2695 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2696 if (!success)
2697 return NULL;
2698 if (idx > m_command_history.size())
2699 return NULL;
2700 idx = m_command_history.size() - idx;
2701 return m_command_history[idx].c_str();
2702
2703 }
2704 else if (input_str[1] == m_repeat_char)
2705 {
2706 if (m_command_history.empty())
2707 return NULL;
2708 else
2709 return m_command_history.back().c_str();
2710 }
2711 else
2712 {
2713 bool success;
2714 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2715 if (!success)
2716 return NULL;
2717 if (idx >= m_command_history.size())
2718 return NULL;
2719 return m_command_history[idx].c_str();
2720 }
2721}