blob: 3a5b98e0f8958ea1a6ce63d3ff0c07bc7c632549 [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
Sean Callananee301fa2012-06-01 23:29:32 +0000243 cmd_obj_sp = GetCommandSPExact ("process kill", false);
244 if (cmd_obj_sp)
245 AddAlias ("kill", cmd_obj_sp);
246
Caroline Tice5ddbe212011-05-06 21:37:15 +0000247 cmd_obj_sp = GetCommandSPExact ("process launch", false);
248 if (cmd_obj_sp)
249 {
250 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton86c50d72012-05-18 00:04:38 +0000251 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000252 AddAlias ("r", cmd_obj_sp);
253 AddAlias ("run", cmd_obj_sp);
254 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
255 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
256 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000257
258 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
259 if (cmd_obj_sp)
260 {
261 AddAlias ("add-dsym", cmd_obj_sp);
262 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000263
264 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
265 if (cmd_obj_sp)
266 {
267 alias_arguments_vector_sp.reset (new OptionArgVector);
268 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
269 AddAlias ("rb", cmd_obj_sp);
270 AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
271 }
Chris Lattner24943d22010-06-08 16:52:24 +0000272}
273
Chris Lattner24943d22010-06-08 16:52:24 +0000274const char *
275CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
276{
277 // This function has not yet been implemented.
278
279 // Look for any embedded script command
280 // If found,
281 // get interpreter object from the command dictionary,
282 // call execute_one_command on it,
283 // get the results as a string,
284 // substitute that string for current stuff.
285
286 return arg;
287}
288
289
290void
291CommandInterpreter::LoadCommandDictionary ()
292{
293 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
294
295 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
296 //
297 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
298 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
299 // the cross-referencing stuff) are created!!!
300 //
301 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
302
303
304 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
305 // are created. This is so that when another command is created that needs to go into a crossref object,
306 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
307 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
308
Chris Lattner24943d22010-06-08 16:52:24 +0000309 // Non-CommandObjectCrossref commands can now be created.
310
Caroline Tice5bc8c972010-09-20 20:44:43 +0000311 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000312
Greg Clayton238c0a12010-09-18 01:14:36 +0000313 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000314 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000315 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000316 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000317 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
318 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000319// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000320 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000321 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000322 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000323 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
324 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000325 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000326 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000327 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000328 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000329 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000330 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000331 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000332 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
333 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000334 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000335 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000336 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000337
338 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000339 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000340 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000341 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000342 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000343 if (break_regex_cmd_ap.get())
344 {
345 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
346 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
347 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000348 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000349 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000350 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000351 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
352 {
353 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
354 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
355 }
356 }
Jim Inghame56493f2011-03-22 02:29:32 +0000357
358 std::auto_ptr<CommandObjectRegexCommand>
359 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000360 "_regexp-down",
361 "Go down \"n\" frames in the stack (1 frame by default).",
362 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000363 if (down_regex_cmd_ap.get())
364 {
365 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
366 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
367 {
368 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
369 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
370 }
371 }
372
373 std::auto_ptr<CommandObjectRegexCommand>
374 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000375 "_regexp-up",
376 "Go up \"n\" frames in the stack (1 frame by default).",
377 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000378 if (up_regex_cmd_ap.get())
379 {
380 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
381 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
382 {
383 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
384 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
385 }
386 }
Jason Molenda730cae02011-10-22 01:30:52 +0000387
388 std::auto_ptr<CommandObjectRegexCommand>
389 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000390 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000391 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000392 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000393 if (display_regex_cmd_ap.get())
394 {
395 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
396 {
397 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
398 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
399 }
400 }
401
402 std::auto_ptr<CommandObjectRegexCommand>
403 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000404 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000405 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000406 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000407 if (undisplay_regex_cmd_ap.get())
408 {
409 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
410 {
411 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
412 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
413 }
414 }
415
Chris Lattner24943d22010-06-08 16:52:24 +0000416}
417
418int
419CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
420 StringList &matches)
421{
422 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
423
424 if (include_aliases)
425 {
426 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
427 }
428
429 return matches.GetSize();
430}
431
432CommandObjectSP
433CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
434{
435 CommandObject::CommandMap::iterator pos;
436 CommandObjectSP ret_val;
437
438 std::string cmd(cmd_cstr);
439
440 if (HasCommands())
441 {
442 pos = m_command_dict.find(cmd);
443 if (pos != m_command_dict.end())
444 ret_val = pos->second;
445 }
446
447 if (include_aliases && HasAliases())
448 {
449 pos = m_alias_dict.find(cmd);
450 if (pos != m_alias_dict.end())
451 ret_val = pos->second;
452 }
453
454 if (HasUserCommands())
455 {
456 pos = m_user_dict.find(cmd);
457 if (pos != m_user_dict.end())
458 ret_val = pos->second;
459 }
460
461 if (!exact && ret_val == NULL)
462 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000463 // We will only get into here if we didn't find any exact matches.
464
465 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
466
Chris Lattner24943d22010-06-08 16:52:24 +0000467 StringList local_matches;
468 if (matches == NULL)
469 matches = &local_matches;
470
Jim Inghamd40f8a62010-07-06 22:46:59 +0000471 unsigned int num_cmd_matches = 0;
472 unsigned int num_alias_matches = 0;
473 unsigned int num_user_matches = 0;
474
475 // Look through the command dictionaries one by one, and if we get only one match from any of
476 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
477
Chris Lattner24943d22010-06-08 16:52:24 +0000478 if (HasCommands())
479 {
480 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
481 }
482
483 if (num_cmd_matches == 1)
484 {
485 cmd.assign(matches->GetStringAtIndex(0));
486 pos = m_command_dict.find(cmd);
487 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000488 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000489 }
490
Jim Ingham9a574172010-06-24 20:28:42 +0000491 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000492 {
493 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
494
495 }
496
Jim Inghamd40f8a62010-07-06 22:46:59 +0000497 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000498 {
499 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
500 pos = m_alias_dict.find(cmd);
501 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000502 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000503 }
504
Jim Ingham9a574172010-06-24 20:28:42 +0000505 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000506 {
507 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
508 }
509
Jim Inghamd40f8a62010-07-06 22:46:59 +0000510 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000511 {
512 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
513
514 pos = m_user_dict.find (cmd);
515 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000516 user_match_sp = pos->second;
517 }
518
519 // If we got exactly one match, return that, otherwise return the match list.
520
521 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
522 {
523 if (num_cmd_matches)
524 return real_match_sp;
525 else if (num_alias_matches)
526 return alias_match_sp;
527 else
528 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000529 }
530 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000531 else if (matches && ret_val != NULL)
532 {
533 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000534 }
535
536
537 return ret_val;
538}
539
Greg Claytond12aeab2011-04-20 16:37:46 +0000540bool
541CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
542{
543 if (name && name[0])
544 {
545 std::string name_sstr(name);
546 if (!can_replace)
547 {
548 if (m_command_dict.find (name_sstr) != m_command_dict.end())
549 return false;
550 }
551 m_command_dict[name_sstr] = cmd_sp;
552 return true;
553 }
554 return false;
555}
556
Enrico Granata6b1596d2011-08-16 23:24:13 +0000557bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000558CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000559 const lldb::CommandObjectSP &cmd_sp,
560 bool can_replace)
561{
Enrico Granata6010ace2011-11-07 22:57:04 +0000562 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000563 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000564
565 const char* name_cstr = name.c_str();
566
567 // do not allow replacement of internal commands
568 if (CommandExists(name_cstr))
569 return false;
570
571 if (can_replace == false && UserCommandExists(name_cstr))
572 return false;
573
574 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000575 return true;
576 }
577 return false;
578}
Greg Claytond12aeab2011-04-20 16:37:46 +0000579
Jim Inghamd40f8a62010-07-06 22:46:59 +0000580CommandObjectSP
581CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000582{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000583 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
584 CommandObjectSP ret_val; // Possibly empty return value.
585
586 if (cmd_cstr == NULL)
587 return ret_val;
588
589 if (cmd_words.GetArgumentCount() == 1)
590 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
591 else
592 {
593 // We have a multi-word command (seemingly), so we need to do more work.
594 // First, get the cmd_obj_sp for the first word in the command.
595 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
596 if (cmd_obj_sp.get() != NULL)
597 {
598 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
599 // command name), and find the appropriate sub-command SP for each command word....
600 size_t end = cmd_words.GetArgumentCount();
601 for (size_t j= 1; j < end; ++j)
602 {
603 if (cmd_obj_sp->IsMultiwordObject())
604 {
605 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
606 (cmd_words.GetArgumentAtIndex (j));
607 if (cmd_obj_sp.get() == NULL)
608 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
609 return ret_val;
610 }
611 else
612 // We have more words in the command name, but we don't have a multiword object. Fail and return
613 // empty 'ret_val'.
614 return ret_val;
615 }
616 // We successfully looped through all the command words and got valid command objects for them. Assign the
617 // last object retrieved to 'ret_val'.
618 ret_val = cmd_obj_sp;
619 }
620 }
621 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000622}
623
624CommandObject *
625CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
626{
627 return GetCommandSPExact (cmd_cstr, include_aliases).get();
628}
629
630CommandObject *
631CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
632{
633 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
634
635 // If we didn't find an exact match to the command string in the commands, look in
636 // the aliases.
637
638 if (command_obj == NULL)
639 {
640 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
641 }
642
643 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
644 // in both the commands and the aliases.
645
646 if (command_obj == NULL)
647 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
648
649 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000650}
651
652bool
653CommandInterpreter::CommandExists (const char *cmd)
654{
655 return m_command_dict.find(cmd) != m_command_dict.end();
656}
657
658bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000659CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
660 const char *options_args,
661 OptionArgVectorSP &option_arg_vector_sp)
662{
663 bool success = true;
664 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
665
666 if (!options_args || (strlen (options_args) < 1))
667 return true;
668
669 std::string options_string (options_args);
670 Args args (options_args);
671 CommandReturnObject result;
672 // Check to see if the command being aliased can take any command options.
673 Options *options = cmd_obj_sp->GetOptions ();
674 if (options)
675 {
676 // See if any options were specified as part of the alias; if so, handle them appropriately.
677 options->NotifyOptionParsingStarting ();
678 args.Unshift ("dummy_arg");
679 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
680 args.Shift ();
681 if (result.Succeeded())
682 options->VerifyPartialOptions (result);
683 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
684 {
685 result.AppendError ("Unable to create requested alias.\n");
686 return false;
687 }
688 }
689
Greg Clayton7268b4c2011-10-28 21:38:01 +0000690 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000691 {
692 if (cmd_obj_sp->WantsRawCommandString ())
693 option_arg_vector->push_back (OptionArgPair ("<argument>",
694 OptionArgValue (-1,
695 options_string)));
696 else
697 {
698 int argc = args.GetArgumentCount();
699 for (size_t i = 0; i < argc; ++i)
700 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
701 option_arg_vector->push_back
702 (OptionArgPair ("<argument>",
703 OptionArgValue (-1,
704 std::string (args.GetArgumentAtIndex (i)))));
705 }
706 }
707
708 return success;
709}
710
711bool
Chris Lattner24943d22010-06-08 16:52:24 +0000712CommandInterpreter::AliasExists (const char *cmd)
713{
714 return m_alias_dict.find(cmd) != m_alias_dict.end();
715}
716
717bool
718CommandInterpreter::UserCommandExists (const char *cmd)
719{
720 return m_user_dict.find(cmd) != m_user_dict.end();
721}
722
723void
724CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
725{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000726 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000727 m_alias_dict[alias_name] = command_obj_sp;
728}
729
730bool
731CommandInterpreter::RemoveAlias (const char *alias_name)
732{
733 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
734 if (pos != m_alias_dict.end())
735 {
736 m_alias_dict.erase(pos);
737 return true;
738 }
739 return false;
740}
741bool
742CommandInterpreter::RemoveUser (const char *alias_name)
743{
744 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
745 if (pos != m_user_dict.end())
746 {
747 m_user_dict.erase(pos);
748 return true;
749 }
750 return false;
751}
752
Chris Lattner24943d22010-06-08 16:52:24 +0000753void
754CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
755{
756 help_string.Printf ("'%s", command_name);
757 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
758
759 if (option_arg_vector_sp != NULL)
760 {
761 OptionArgVector *options = option_arg_vector_sp.get();
762 for (int i = 0; i < options->size(); ++i)
763 {
764 OptionArgPair cur_option = (*options)[i];
765 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000766 OptionArgValue value_pair = cur_option.second;
767 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000768 if (opt.compare("<argument>") == 0)
769 {
770 help_string.Printf (" %s", value.c_str());
771 }
772 else
773 {
774 help_string.Printf (" %s", opt.c_str());
775 if ((value.compare ("<no-argument>") != 0)
776 && (value.compare ("<need-argument") != 0))
777 {
778 help_string.Printf (" %s", value.c_str());
779 }
780 }
781 }
782 }
783
784 help_string.Printf ("'");
785}
786
Greg Clayton65124ea2010-08-26 22:05:43 +0000787size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000788CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
789{
790 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000791 CommandObject::CommandMap::const_iterator end = dict.end();
792 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000793
Greg Clayton65124ea2010-08-26 22:05:43 +0000794 for (pos = dict.begin(); pos != end; ++pos)
795 {
796 size_t len = pos->first.size();
797 if (max_len < len)
798 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000799 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000800 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000801}
802
803void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000804CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000805 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000806{
807 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000808 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000809
810 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000811 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000812
813 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
814 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000815
Enrico Granata6b1596d2011-08-16 23:24:13 +0000816 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
817 {
818 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
819 max_len);
820 }
821 result.AppendMessage("");
822
823 }
824
Greg Clayton7268b4c2011-10-28 21:38:01 +0000825 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000826 {
Jim Inghame3663e82010-10-22 18:47:16 +0000827 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000828 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000829 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000830 max_len = FindLongestCommandWord (m_alias_dict);
831
Chris Lattner24943d22010-06-08 16:52:24 +0000832 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
833 {
834 StreamString sstr;
835 StreamString translation_and_help;
836 std::string entry_name = pos->first;
837 std::string second_entry = pos->second.get()->GetCommandName();
838 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
839
840 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
841 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
842 translation_and_help.GetData(), max_len);
843 }
844 result.AppendMessage("");
845 }
846
Greg Clayton7268b4c2011-10-28 21:38:01 +0000847 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000848 {
849 result.AppendMessage ("The following is a list of your current user-defined commands:");
850 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000851 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000852 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
853 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000854 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
855 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000856 }
857 result.AppendMessage("");
858 }
859
860 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
861}
862
Caroline Ticee0da7a52010-12-09 22:52:49 +0000863CommandObject *
864CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000865{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000866 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
867 // eventually be invoked by the given command line.
868
869 CommandObject *cmd_obj = NULL;
870 std::string white_space (" \t\v");
871 size_t start = command_string.find_first_not_of (white_space);
872 size_t end = 0;
873 bool done = false;
874 while (!done)
875 {
876 if (start != std::string::npos)
877 {
878 // Get the next word from command_string.
879 end = command_string.find_first_of (white_space, start);
880 if (end == std::string::npos)
881 end = command_string.size();
882 std::string cmd_word = command_string.substr (start, end - start);
883
884 if (cmd_obj == NULL)
885 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
886 // command or alias.
887 cmd_obj = GetCommandObject (cmd_word.c_str());
888 else if (cmd_obj->IsMultiwordObject ())
889 {
890 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
891 CommandObject *sub_cmd_obj =
892 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
893 if (sub_cmd_obj)
894 cmd_obj = sub_cmd_obj;
895 else // cmd_word was not a valid sub-command word, so we are donee
896 done = true;
897 }
898 else
899 // We have a cmd_obj and it is not a multi-word object, so we are done.
900 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000901
Caroline Ticee0da7a52010-12-09 22:52:49 +0000902 // If we didn't find a valid command object, or our command object is not a multi-word object, or
903 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
904 // next word.
905
906 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
907 done = true;
908 else
909 start = command_string.find_first_not_of (white_space, end);
910 }
911 else
912 // Unable to find any more words.
913 done = true;
914 }
915
916 if (end == command_string.size())
917 command_string.clear();
918 else
919 command_string = command_string.substr(end);
920
921 return cmd_obj;
922}
923
Greg Clayton9d855c62011-10-25 00:36:27 +0000924static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000925static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000926static void
927StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000928{
Greg Clayton9d855c62011-10-25 00:36:27 +0000929 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000930 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000931 size_t pos = s.find_first_not_of (k_white_space);
932 if (pos == std::string::npos)
933 s.clear();
934 else if (pos == 0)
935 return;
936 s.erase (0, pos);
937 }
938}
939
Greg Clayton3840cd72011-11-09 23:25:03 +0000940static size_t
941FindArgumentTerminator (const std::string &s)
942{
Greg Clayton3840cd72011-11-09 23:25:03 +0000943 const size_t s_len = s.size();
944 size_t offset = 0;
945 while (offset < s_len)
946 {
947 size_t pos = s.find ("--", offset);
948 if (pos == std::string::npos)
949 break;
950 if (pos > 0)
951 {
952 if (isspace(s[pos-1]))
953 {
954 // Check if the string ends "\s--" (where \s is a space character)
955 // or if we have "\s--\s".
956 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
957 {
Greg Clayton3840cd72011-11-09 23:25:03 +0000958 return pos;
959 }
960 }
961 }
962 offset = pos + 2;
963 }
Greg Clayton3840cd72011-11-09 23:25:03 +0000964 return std::string::npos;
965}
966
Greg Clayton9d855c62011-10-25 00:36:27 +0000967static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000968ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000969{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000970 command.clear();
971 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000972 StripLeadingSpaces (command_string);
973
974 bool result = false;
975 quote_char = '\0';
976
977 if (!command_string.empty())
978 {
979 const char first_char = command_string[0];
980 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000981 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000982 quote_char = first_char;
983 const size_t end_quote_pos = command_string.find (quote_char, 1);
984 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000985 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000986 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000987 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000988 }
989 else
990 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000991 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +0000992 if (end_quote_pos + 1 < command_string.size())
993 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
994 else
995 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000996 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000997 }
998 else
999 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001000 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1001 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001002 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001003 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001004 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001005 }
1006 else
1007 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001008 command.assign (command_string, 0, first_space_pos);
1009 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001010 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001011 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001012 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001013 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001014
1015
1016 if (!command.empty())
1017 {
1018 // actual commands can't start with '-' or '_'
1019 if (command[0] != '-' && command[0] != '_')
1020 {
1021 size_t pos = command.find_first_not_of(k_valid_command_chars);
1022 if (pos > 0 && pos != std::string::npos)
1023 {
1024 suffix.assign (command.begin() + pos, command.end());
1025 command.erase (pos);
1026 }
1027 }
1028 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001029
1030 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001031}
1032
Greg Clayton7268b4c2011-10-28 21:38:01 +00001033CommandObject *
1034CommandInterpreter::BuildAliasResult (const char *alias_name,
1035 std::string &raw_input_string,
1036 std::string &alias_result,
1037 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001038{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001039 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001040 Args cmd_args (raw_input_string.c_str());
1041 alias_cmd_obj = GetCommandObject (alias_name);
1042 StreamString result_str;
1043
1044 if (alias_cmd_obj)
1045 {
1046 std::string alias_name_str = alias_name;
1047 if ((cmd_args.GetArgumentCount() == 0)
1048 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1049 cmd_args.Unshift (alias_name);
1050
1051 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1052 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1053
1054 if (option_arg_vector_sp.get())
1055 {
1056 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1057
1058 for (int i = 0; i < option_arg_vector->size(); ++i)
1059 {
1060 OptionArgPair option_pair = (*option_arg_vector)[i];
1061 OptionArgValue value_pair = option_pair.second;
1062 int value_type = value_pair.first;
1063 std::string option = option_pair.first;
1064 std::string value = value_pair.second;
1065 if (option.compare ("<argument>") == 0)
1066 result_str.Printf (" %s", value.c_str());
1067 else
1068 {
1069 result_str.Printf (" %s", option.c_str());
1070 if (value_type != optional_argument)
1071 result_str.Printf (" ");
1072 if (value.compare ("<no_argument>") != 0)
1073 {
1074 int index = GetOptionArgumentPosition (value.c_str());
1075 if (index == 0)
1076 result_str.Printf ("%s", value.c_str());
1077 else if (index >= cmd_args.GetArgumentCount())
1078 {
1079
1080 result.AppendErrorWithFormat
1081 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1082 index);
1083 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001084 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001085 }
1086 else
1087 {
1088 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1089 if (strpos != std::string::npos)
1090 raw_input_string = raw_input_string.erase (strpos,
1091 strlen (cmd_args.GetArgumentAtIndex (index)));
1092 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1093 }
1094 }
1095 }
1096 }
1097 }
1098
1099 alias_result = result_str.GetData();
1100 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001101 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001102}
1103
Greg Claytonf5c0c722011-10-14 07:41:33 +00001104Error
1105CommandInterpreter::PreprocessCommand (std::string &command)
1106{
1107 // The command preprocessor needs to do things to the command
1108 // line before any parsing of arguments or anything else is done.
1109 // The only current stuff that gets proprocessed is anyting enclosed
1110 // in backtick ('`') characters is evaluated as an expression and
1111 // the result of the expression must be a scalar that can be substituted
1112 // into the command. An example would be:
1113 // (lldb) memory read `$rsp + 20`
1114 Error error; // Error for any expressions that might not evaluate
1115 size_t start_backtick;
1116 size_t pos = 0;
1117 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1118 {
1119 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1120 {
1121 // The backtick was preceeded by a '\' character, remove the slash
1122 // and don't treat the backtick as the start of an expression
1123 command.erase(start_backtick-1, 1);
1124 // No need to add one to start_backtick since we just deleted a char
1125 pos = start_backtick;
1126 }
1127 else
1128 {
1129 const size_t expr_content_start = start_backtick + 1;
1130 const size_t end_backtick = command.find ('`', expr_content_start);
1131 if (end_backtick == std::string::npos)
1132 return error;
1133 else if (end_backtick == expr_content_start)
1134 {
1135 // Empty expression (two backticks in a row)
1136 command.erase (start_backtick, 2);
1137 }
1138 else
1139 {
1140 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1141
1142 Target *target = m_exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001143 // Get a dummy target to allow for calculator mode while processing backticks.
1144 // This also helps break the infinite loop caused when target is null.
1145 if (!target)
1146 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001147 if (target)
1148 {
Sean Callanandaa6efe2011-12-21 22:22:58 +00001149 const bool coerce_to_id = false;
Greg Claytonf5c0c722011-10-14 07:41:33 +00001150 const bool unwind_on_error = true;
1151 const bool keep_in_memory = false;
1152 ValueObjectSP expr_result_valobj_sp;
1153 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1154 m_exe_ctx.GetFramePtr(),
1155 eExecutionPolicyOnlyWhenNeeded,
Sean Callanandaa6efe2011-12-21 22:22:58 +00001156 coerce_to_id,
1157 unwind_on_error,
1158 keep_in_memory,
Greg Claytonf5c0c722011-10-14 07:41:33 +00001159 eNoDynamicValues,
1160 expr_result_valobj_sp);
1161 if (expr_result == eExecutionCompleted)
1162 {
1163 Scalar scalar;
1164 if (expr_result_valobj_sp->ResolveValue (scalar))
1165 {
1166 command.erase (start_backtick, end_backtick - start_backtick + 1);
1167 StreamString value_strm;
1168 const bool show_type = false;
1169 scalar.GetValue (&value_strm, show_type);
1170 size_t value_string_size = value_strm.GetSize();
1171 if (value_string_size)
1172 {
1173 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1174 pos = start_backtick + value_string_size;
1175 continue;
1176 }
1177 else
1178 {
1179 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1180 }
1181 }
1182 else
1183 {
1184 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1185 }
1186 }
1187 else
1188 {
1189 if (expr_result_valobj_sp)
1190 error = expr_result_valobj_sp->GetError();
1191 if (error.Success())
1192 {
1193
1194 switch (expr_result)
1195 {
1196 case eExecutionSetupError:
1197 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1198 break;
1199 case eExecutionCompleted:
1200 break;
1201 case eExecutionDiscarded:
1202 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1203 break;
1204 case eExecutionInterrupted:
1205 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1206 break;
1207 case eExecutionTimedOut:
1208 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1209 break;
1210 }
1211 }
1212 }
1213 }
1214 }
1215 if (error.Fail())
1216 break;
1217 }
1218 }
1219 return error;
1220}
1221
1222
Caroline Ticee0da7a52010-12-09 22:52:49 +00001223bool
1224CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001225 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001226 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001227 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001228 bool repeat_on_empty_command,
1229 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001230
Caroline Ticee0da7a52010-12-09 22:52:49 +00001231{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001232
Caroline Ticee0da7a52010-12-09 22:52:49 +00001233 bool done = false;
1234 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001235 bool wants_raw_input = false;
1236 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001237 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001238
1239 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001240 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1241
1242 // Make a scoped cleanup object that will clear the crash description string
1243 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001244 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001245
Caroline Ticee0da7a52010-12-09 22:52:49 +00001246 if (log)
1247 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001248
Jim Inghamabab14b2010-11-04 23:08:45 +00001249 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1250
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001251 if (!no_context_switching)
1252 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001253
1254 // <rdar://problem/11328896>
1255 bool add_to_history;
1256 if (lazy_add_to_history == eLazyBoolCalculate)
1257 add_to_history = (m_command_source_depth == 0);
1258 else
1259 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1260
Jim Ingham949d5ac2011-02-18 00:54:25 +00001261 bool empty_command = false;
1262 bool comment_command = false;
1263 if (command_string.empty())
1264 empty_command = true;
1265 else
Chris Lattner24943d22010-06-08 16:52:24 +00001266 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001267 const char *k_space_characters = "\t\n\v\f\r ";
1268
1269 size_t non_space = command_string.find_first_not_of (k_space_characters);
1270 // Check for empty line or comment line (lines whose first
1271 // non-space character is the comment character for this interpreter)
1272 if (non_space == std::string::npos)
1273 empty_command = true;
1274 else if (command_string[non_space] == m_comment_char)
1275 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001276 else if (command_string[non_space] == m_repeat_char)
1277 {
1278 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1279 if (history_string == NULL)
1280 {
1281 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1282 result.SetStatus(eReturnStatusFailed);
1283 return false;
1284 }
1285 add_to_history = false;
1286 command_string = history_string;
1287 original_command_string = history_string;
1288 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001289 }
1290
1291 if (empty_command)
1292 {
1293 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001294 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001295 if (m_command_history.empty())
1296 {
1297 result.AppendError ("empty command");
1298 result.SetStatus(eReturnStatusFailed);
1299 return false;
1300 }
1301 else
1302 {
1303 command_line = m_repeat_command.c_str();
1304 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001305 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001306 if (m_repeat_command.empty())
1307 {
1308 result.AppendErrorWithFormat("No auto repeat.\n");
1309 result.SetStatus (eReturnStatusFailed);
1310 return false;
1311 }
1312 }
1313 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001314 }
1315 else
1316 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001317 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1318 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001319 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001320 }
1321 else if (comment_command)
1322 {
1323 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1324 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001325 }
Caroline Tice649116c2011-05-11 16:07:06 +00001326
Greg Claytonf5c0c722011-10-14 07:41:33 +00001327
1328 Error error (PreprocessCommand (command_string));
1329
1330 if (error.Fail())
1331 {
1332 result.AppendError (error.AsCString());
1333 result.SetStatus(eReturnStatusFailed);
1334 return false;
1335 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001336 // Phase 1.
1337
1338 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1339 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1340 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1341 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1342 // 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 +00001343 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001344 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001345
Caroline Ticee0da7a52010-12-09 22:52:49 +00001346 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001347 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001348 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001349 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001350 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001351 {
Caroline Tice649116c2011-05-11 16:07:06 +00001352 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001353 std::string suffix;
1354 ExtractCommand (command_string, next_word, suffix, quote_char);
1355 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001356 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001357 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001358 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001359 std::string alias_result;
1360 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1361 revised_command_line.Printf ("%s", alias_result.c_str());
1362 if (cmd_obj)
1363 {
1364 wants_raw_input = cmd_obj->WantsRawCommandString ();
1365 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1366 }
Chris Lattner24943d22010-06-08 16:52:24 +00001367 }
1368 else
1369 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001370 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001371 if (cmd_obj)
1372 {
1373 actual_cmd_name_len += next_word.length();
1374 revised_command_line.Printf ("%s", next_word.c_str());
1375 wants_raw_input = cmd_obj->WantsRawCommandString ();
1376 }
Caroline Tice649116c2011-05-11 16:07:06 +00001377 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001378 {
1379 revised_command_line.Printf ("%s", next_word.c_str());
1380 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001381 }
1382 }
1383 else
1384 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001385 if (cmd_obj->IsMultiwordObject ())
1386 {
1387 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1388 if (sub_cmd_obj)
1389 {
1390 actual_cmd_name_len += next_word.length() + 1;
1391 revised_command_line.Printf (" %s", next_word.c_str());
1392 cmd_obj = sub_cmd_obj;
1393 wants_raw_input = cmd_obj->WantsRawCommandString ();
1394 }
1395 else
1396 {
1397 if (quote_char)
1398 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1399 else
1400 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1401 done = true;
1402 }
1403 }
Caroline Tice649116c2011-05-11 16:07:06 +00001404 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001405 {
1406 if (quote_char)
1407 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1408 else
1409 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1410 done = true;
1411 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001412 }
1413
1414 if (cmd_obj == NULL)
1415 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001416 uint32_t num_matches = matches.GetSize();
1417 if (matches.GetSize() > 1) {
1418 std::string error_msg;
1419 error_msg.assign ("Ambiguous command '");
1420 error_msg.append(next_word.c_str());
1421 error_msg.append ("'.");
1422
1423 error_msg.append (" Possible matches:");
1424
1425 for (uint32_t i = 0; i < num_matches; ++i) {
1426 error_msg.append ("\n\t");
1427 error_msg.append (matches.GetStringAtIndex(i));
1428 }
1429 error_msg.append ("\n");
1430 result.AppendRawError (error_msg.c_str(), error_msg.size());
1431 } else {
1432 // We didn't have only one match, otherwise we wouldn't get here.
1433 assert(num_matches == 0);
1434 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1435 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001436 result.SetStatus (eReturnStatusFailed);
1437 return false;
1438 }
1439
Greg Clayton7268b4c2011-10-28 21:38:01 +00001440 if (cmd_obj->IsMultiwordObject ())
1441 {
1442 if (!suffix.empty())
1443 {
1444
1445 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1446 next_word.c_str(),
1447 suffix.c_str());
1448 result.SetStatus (eReturnStatusFailed);
1449 return false;
1450 }
1451 }
1452 else
1453 {
1454 // If we found a normal command, we are done
1455 done = true;
1456 if (!suffix.empty())
1457 {
1458 switch (suffix[0])
1459 {
1460 case '/':
1461 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001462 {
1463 Options *command_options = cmd_obj->GetOptions();
1464 if (command_options && command_options->SupportsLongOption("gdb-format"))
1465 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001466 std::string gdb_format_option ("--gdb-format=");
1467 gdb_format_option += (suffix.c_str() + 1);
1468
1469 bool inserted = false;
1470 std::string &cmd = revised_command_line.GetString();
1471 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1472 if (arg_terminator_idx != std::string::npos)
1473 {
1474 // Insert the gdb format option before the "--" that terminates options
1475 gdb_format_option.append(1,' ');
1476 cmd.insert(arg_terminator_idx, gdb_format_option);
1477 inserted = true;
1478 }
1479
1480 if (!inserted)
1481 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1482
1483 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1484 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001485 }
1486 else
1487 {
1488 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1489 cmd_obj->GetCommandName());
1490 result.SetStatus (eReturnStatusFailed);
1491 return false;
1492 }
1493 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001494 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001495
1496 default:
1497 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1498 suffix.c_str());
1499 result.SetStatus (eReturnStatusFailed);
1500 return false;
1501
Greg Clayton7268b4c2011-10-28 21:38:01 +00001502 }
1503 }
1504 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001505 if (command_string.length() == 0)
1506 done = true;
1507
Chris Lattner24943d22010-06-08 16:52:24 +00001508 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001509
Greg Clayton7268b4c2011-10-28 21:38:01 +00001510 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001511 revised_command_line.Printf (" %s", command_string.c_str());
1512
1513 // End of Phase 1.
1514 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1515 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1516 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1517 // wants_raw_input specifies whether the Execute method expects raw input or not.
1518
1519
1520 if (log)
1521 {
1522 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1523 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1524 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1525 }
1526
1527 // Phase 2.
1528 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1529 // CommandObject, with the appropriate arguments.
1530
1531 if (cmd_obj != NULL)
1532 {
1533 if (add_to_history)
1534 {
1535 Args command_args (revised_command_line.GetData());
1536 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1537 if (repeat_command != NULL)
1538 m_repeat_command.assign(repeat_command);
1539 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001540 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001541
Jim Ingham6247dbe2011-07-12 03:12:18 +00001542 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001543 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001544 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001545 }
1546
1547 command_string = revised_command_line.GetData();
1548 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001549 std::string remainder;
1550 if (actual_cmd_name_len < command_string.length())
1551 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1552 // than cmd_obj->GetCommandName(), because name completion
1553 // allows users to enter short versions of the names,
1554 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001555
1556 // Remove any initial spaces
1557 std::string white_space (" \t\v");
1558 size_t pos = remainder.find_first_not_of (white_space);
1559 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001560 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001561
1562 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001563 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001564
1565
Greg Claytonf1252502012-02-29 04:21:24 +00001566 CommandOverrideCallback command_callback = cmd_obj->GetOverrideCallback();
1567 bool handled = false;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001568 if (wants_raw_input)
Greg Claytonf1252502012-02-29 04:21:24 +00001569 {
1570 if (command_callback)
1571 {
1572 std::string full_command (cmd_obj->GetCommandName ());
1573 full_command += ' ';
1574 full_command += remainder;
1575 const char *argv[2] = { NULL, NULL };
1576 argv[0] = full_command.c_str();
1577 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), argv);
1578 }
1579 if (!handled)
1580 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1581 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001582 else
1583 {
1584 Args cmd_args (remainder.c_str());
Greg Claytonf1252502012-02-29 04:21:24 +00001585 if (command_callback)
1586 {
1587 Args full_args (cmd_obj->GetCommandName ());
1588 full_args.AppendArguments(cmd_args);
1589 handled = command_callback (cmd_obj->GetOverrideCallbackBaton(), full_args.GetConstArgumentVector());
1590 }
1591 if (!handled)
1592 cmd_obj->ExecuteWithOptions (cmd_args, result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001593 }
1594 }
1595 else
1596 {
1597 // We didn't find the first command object, so complete the first argument.
1598 Args command_args (revised_command_line.GetData());
1599 StringList matches;
1600 int num_matches;
1601 int cursor_index = 0;
1602 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1603 bool word_complete;
1604 num_matches = HandleCompletionMatches (command_args,
1605 cursor_index,
1606 cursor_char_position,
1607 0,
1608 -1,
1609 word_complete,
1610 matches);
1611
1612 if (num_matches > 0)
1613 {
1614 std::string error_msg;
1615 error_msg.assign ("ambiguous command '");
1616 error_msg.append(command_args.GetArgumentAtIndex(0));
1617 error_msg.append ("'.");
1618
1619 error_msg.append (" Possible completions:");
1620 for (int i = 0; i < num_matches; i++)
1621 {
1622 error_msg.append ("\n\t");
1623 error_msg.append (matches.GetStringAtIndex (i));
1624 }
1625 error_msg.append ("\n");
1626 result.AppendRawError (error_msg.c_str(), error_msg.size());
1627 }
1628 else
1629 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1630
1631 result.SetStatus (eReturnStatusFailed);
1632 }
1633
Jason Molenda24c991c2011-08-25 00:20:04 +00001634 if (log)
1635 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1636
Chris Lattner24943d22010-06-08 16:52:24 +00001637 return result.Succeeded();
1638}
1639
1640int
1641CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1642 int &cursor_index,
1643 int &cursor_char_position,
1644 int match_start_point,
1645 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001646 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001647 StringList &matches)
1648{
1649 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001650 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001651
1652 // For any of the command completions a unique match will be a complete word.
1653 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001654
1655 if (cursor_index == -1)
1656 {
1657 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001658 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001659 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1660 }
1661 else if (cursor_index == 0)
1662 {
1663 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001664 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001665 num_command_matches = matches.GetSize();
1666
1667 if (num_command_matches == 1
1668 && cmd_obj && cmd_obj->IsMultiwordObject()
1669 && matches.GetStringAtIndex(0) != NULL
1670 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1671 {
1672 look_for_subcommand = true;
1673 num_command_matches = 0;
1674 matches.DeleteStringAtIndex(0);
1675 parsed_line.AppendArgument ("");
1676 cursor_index++;
1677 cursor_char_position = 0;
1678 }
1679 }
1680
1681 if (cursor_index > 0 || look_for_subcommand)
1682 {
1683 // We are completing further on into a commands arguments, so find the command and tell it
1684 // to complete the command.
1685 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001686 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001687 if (command_object == NULL)
1688 {
1689 return 0;
1690 }
1691 else
1692 {
1693 parsed_line.Shift();
1694 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001695 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001696 cursor_index,
1697 cursor_char_position,
1698 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001699 max_return_elements,
1700 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001701 matches);
1702 }
1703 }
1704
1705 return num_command_matches;
1706
1707}
1708
1709int
1710CommandInterpreter::HandleCompletion (const char *current_line,
1711 const char *cursor,
1712 const char *last_char,
1713 int match_start_point,
1714 int max_return_elements,
1715 StringList &matches)
1716{
1717 // We parse the argument up to the cursor, so the last argument in parsed_line is
1718 // the one containing the cursor, and the cursor is after the last character.
1719
1720 Args parsed_line(current_line, last_char - current_line);
1721 Args partial_parsed_line(current_line, cursor - current_line);
1722
Jim Ingham6247dbe2011-07-12 03:12:18 +00001723 // Don't complete comments, and if the line we are completing is just the history repeat character,
1724 // substitute the appropriate history line.
1725 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1726 if (first_arg)
1727 {
1728 if (first_arg[0] == m_comment_char)
1729 return 0;
1730 else if (first_arg[0] == m_repeat_char)
1731 {
1732 const char *history_string = FindHistoryString (first_arg);
1733 if (history_string != NULL)
1734 {
1735 matches.Clear();
1736 matches.InsertStringAtIndex(0, history_string);
1737 return -2;
1738 }
1739 else
1740 return 0;
1741
1742 }
1743 }
1744
1745
Chris Lattner24943d22010-06-08 16:52:24 +00001746 int num_args = partial_parsed_line.GetArgumentCount();
1747 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1748 int cursor_char_position;
1749
1750 if (cursor_index == -1)
1751 cursor_char_position = 0;
1752 else
1753 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001754
1755 if (cursor > current_line && cursor[-1] == ' ')
1756 {
1757 // We are just after a space. If we are in an argument, then we will continue
1758 // parsing, but if we are between arguments, then we have to complete whatever the next
1759 // element would be.
1760 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1761 // protected by a quote) then the space will also be in the parsed argument...
1762
1763 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1764 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1765 {
1766 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1767 cursor_index++;
1768 cursor_char_position = 0;
1769 }
1770 }
Chris Lattner24943d22010-06-08 16:52:24 +00001771
1772 int num_command_matches;
1773
1774 matches.Clear();
1775
1776 // Only max_return_elements == -1 is supported at present:
1777 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001778 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001779 num_command_matches = HandleCompletionMatches (parsed_line,
1780 cursor_index,
1781 cursor_char_position,
1782 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001783 max_return_elements,
1784 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001785 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001786
1787 if (num_command_matches <= 0)
1788 return num_command_matches;
1789
1790 if (num_args == 0)
1791 {
1792 // If we got an empty string, insert nothing.
1793 matches.InsertStringAtIndex(0, "");
1794 }
1795 else
1796 {
1797 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1798 // put an empty string in element 0.
1799 std::string command_partial_str;
1800 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001801 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1802 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001803
1804 std::string common_prefix;
1805 matches.LongestCommonPrefix (common_prefix);
1806 int partial_name_len = command_partial_str.size();
1807
1808 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001809 // Only do this if the completer told us this was a complete word, however...
1810 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001811 {
1812 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1813 if (quote_char != '\0')
1814 common_prefix.push_back(quote_char);
1815
1816 common_prefix.push_back(' ');
1817 }
1818 common_prefix.erase (0, partial_name_len);
1819 matches.InsertStringAtIndex(0, common_prefix.c_str());
1820 }
1821 return num_command_matches;
1822}
1823
Chris Lattner24943d22010-06-08 16:52:24 +00001824
1825CommandInterpreter::~CommandInterpreter ()
1826{
1827}
1828
1829const char *
1830CommandInterpreter::GetPrompt ()
1831{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001832 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001833}
1834
1835void
1836CommandInterpreter::SetPrompt (const char *new_prompt)
1837{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001838 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001839}
1840
Jim Ingham5e16ef52010-10-04 19:49:29 +00001841size_t
Greg Clayton58928562011-02-09 01:08:52 +00001842CommandInterpreter::GetConfirmationInputReaderCallback
1843(
1844 void *baton,
1845 InputReader &reader,
1846 lldb::InputReaderAction action,
1847 const char *bytes,
1848 size_t bytes_len
1849)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001850{
Greg Clayton58928562011-02-09 01:08:52 +00001851 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001852 bool *response_ptr = (bool *) baton;
1853
1854 switch (action)
1855 {
1856 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001857 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001858 {
1859 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001860 {
Greg Clayton58928562011-02-09 01:08:52 +00001861 out_file.Printf ("%s", reader.GetPrompt());
1862 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001863 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001864 }
1865 break;
1866
1867 case eInputReaderDeactivate:
1868 break;
1869
1870 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001871 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001872 {
Greg Clayton58928562011-02-09 01:08:52 +00001873 out_file.Printf ("%s", reader.GetPrompt());
1874 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001875 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001876 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001877
1878 case eInputReaderAsynchronousOutputWritten:
1879 break;
1880
Jim Ingham5e16ef52010-10-04 19:49:29 +00001881 case eInputReaderGotToken:
1882 if (bytes_len == 0)
1883 {
1884 reader.SetIsDone(true);
1885 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001886 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001887 {
1888 *response_ptr = true;
1889 reader.SetIsDone(true);
1890 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001891 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001892 {
1893 *response_ptr = false;
1894 reader.SetIsDone(true);
1895 }
1896 else
1897 {
Greg Clayton58928562011-02-09 01:08:52 +00001898 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001899 {
Jim Ingham26183802011-11-17 01:22:00 +00001900 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001901 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001902 }
1903 }
1904 break;
1905
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001906 case eInputReaderInterrupt:
1907 case eInputReaderEndOfFile:
1908 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1909 reader.SetIsDone (true);
1910 break;
1911
Jim Ingham5e16ef52010-10-04 19:49:29 +00001912 case eInputReaderDone:
1913 break;
1914 }
1915
1916 return bytes_len;
1917
1918}
1919
1920bool
1921CommandInterpreter::Confirm (const char *message, bool default_answer)
1922{
Jim Ingham93057472010-10-04 22:44:14 +00001923 // Check AutoConfirm first:
1924 if (m_debugger.GetAutoConfirm())
1925 return default_answer;
1926
Jim Ingham5e16ef52010-10-04 19:49:29 +00001927 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1928 bool response = default_answer;
1929 if (reader_sp)
1930 {
1931 std::string prompt(message);
1932 prompt.append(": [");
1933 if (default_answer)
1934 prompt.append ("Y/n] ");
1935 else
1936 prompt.append ("y/N] ");
1937
1938 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1939 &response, // baton
1940 eInputReaderGranularityLine, // token size, to pass to callback function
1941 NULL, // end token
1942 prompt.c_str(), // prompt
1943 true)); // echo input
1944 if (err.Success())
1945 {
1946 GetDebugger().PushInputReader (reader_sp);
1947 }
1948 reader_sp->WaitOnReaderIsDone();
1949 }
1950 return response;
1951}
1952
1953
Chris Lattner24943d22010-06-08 16:52:24 +00001954void
1955CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1956{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001957 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001958
1959 if (cmd_obj_sp != NULL)
1960 {
1961 CommandObject *cmd_obj = cmd_obj_sp.get();
1962 if (cmd_obj->IsCrossRefObject ())
1963 cmd_obj->AddObject (object_type);
1964 }
1965}
1966
Chris Lattner24943d22010-06-08 16:52:24 +00001967OptionArgVectorSP
1968CommandInterpreter::GetAliasOptions (const char *alias_name)
1969{
1970 OptionArgMap::iterator pos;
1971 OptionArgVectorSP ret_val;
1972
1973 std::string alias (alias_name);
1974
1975 if (HasAliasOptions())
1976 {
1977 pos = m_alias_options.find (alias);
1978 if (pos != m_alias_options.end())
1979 ret_val = pos->second;
1980 }
1981
1982 return ret_val;
1983}
1984
1985void
1986CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1987{
1988 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1989 if (pos != m_alias_options.end())
1990 {
1991 m_alias_options.erase (pos);
1992 }
1993}
1994
1995void
1996CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1997{
1998 m_alias_options[alias_name] = option_arg_vector_sp;
1999}
2000
2001bool
2002CommandInterpreter::HasCommands ()
2003{
2004 return (!m_command_dict.empty());
2005}
2006
2007bool
2008CommandInterpreter::HasAliases ()
2009{
2010 return (!m_alias_dict.empty());
2011}
2012
2013bool
2014CommandInterpreter::HasUserCommands ()
2015{
2016 return (!m_user_dict.empty());
2017}
2018
2019bool
2020CommandInterpreter::HasAliasOptions ()
2021{
2022 return (!m_alias_options.empty());
2023}
2024
Chris Lattner24943d22010-06-08 16:52:24 +00002025void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002026CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2027 const char *alias_name,
2028 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002029 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002030 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002031{
2032 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002033
2034 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002035
Caroline Tice44c841d2010-12-07 19:58:26 +00002036 // Make sure that the alias name is the 0th element in cmd_args
2037 std::string alias_name_str = alias_name;
2038 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2039 cmd_args.Unshift (alias_name);
2040
2041 Args new_args (alias_cmd_obj->GetCommandName());
2042 if (new_args.GetArgumentCount() == 2)
2043 new_args.Shift();
2044
Chris Lattner24943d22010-06-08 16:52:24 +00002045 if (option_arg_vector_sp.get())
2046 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002047 if (wants_raw_input)
2048 {
2049 // We have a command that both has command options and takes raw input. Make *sure* it has a
2050 // " -- " in the right place in the raw_input_string.
2051 size_t pos = raw_input_string.find(" -- ");
2052 if (pos == std::string::npos)
2053 {
2054 // None found; assume it goes at the beginning of the raw input string
2055 raw_input_string.insert (0, " -- ");
2056 }
2057 }
Chris Lattner24943d22010-06-08 16:52:24 +00002058
2059 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2060 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002061 std::vector<bool> used (old_size + 1, false);
2062
2063 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002064
2065 for (int i = 0; i < option_arg_vector->size(); ++i)
2066 {
2067 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002068 OptionArgValue value_pair = option_pair.second;
2069 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002070 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002071 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002072 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002073 {
2074 if (!wants_raw_input
2075 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2076 new_args.AppendArgument (value.c_str());
2077 }
Chris Lattner24943d22010-06-08 16:52:24 +00002078 else
2079 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002080 if (value_type != optional_argument)
2081 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002082 if (value.compare ("<no-argument>") != 0)
2083 {
2084 int index = GetOptionArgumentPosition (value.c_str());
2085 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002086 {
Chris Lattner24943d22010-06-08 16:52:24 +00002087 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002088 if (value_type != optional_argument)
2089 new_args.AppendArgument (value.c_str());
2090 else
2091 {
2092 char buffer[255];
2093 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2094 new_args.AppendArgument (buffer);
2095 }
2096
2097 }
Chris Lattner24943d22010-06-08 16:52:24 +00002098 else if (index >= cmd_args.GetArgumentCount())
2099 {
2100 result.AppendErrorWithFormat
2101 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2102 index);
2103 result.SetStatus (eReturnStatusFailed);
2104 return;
2105 }
2106 else
2107 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002108 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2109 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2110 if (strpos != std::string::npos)
2111 {
2112 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2113 }
2114
2115 if (value_type != optional_argument)
2116 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2117 else
2118 {
2119 char buffer[255];
2120 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2121 cmd_args.GetArgumentAtIndex (index));
2122 new_args.AppendArgument (buffer);
2123 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002124 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002125 }
2126 }
2127 }
2128 }
2129
2130 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2131 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002132 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002133 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2134 }
2135
2136 cmd_args.Clear();
2137 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2138 }
2139 else
2140 {
2141 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002142 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2143 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2144 // input string.
2145 if (wants_raw_input)
2146 {
2147 cmd_args.Clear();
2148 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2149 }
Chris Lattner24943d22010-06-08 16:52:24 +00002150 return;
2151 }
2152
2153 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2154 return;
2155}
2156
2157
2158int
2159CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2160{
2161 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2162 // of zero.
2163
2164 char *cptr = (char *) in_string;
2165
2166 // Does it start with '%'
2167 if (cptr[0] == '%')
2168 {
2169 ++cptr;
2170
2171 // Is the rest of it entirely digits?
2172 if (isdigit (cptr[0]))
2173 {
2174 const char *start = cptr;
2175 while (isdigit (cptr[0]))
2176 ++cptr;
2177
2178 // We've gotten to the end of the digits; are we at the end of the string?
2179 if (cptr[0] == '\0')
2180 position = atoi (start);
2181 }
2182 }
2183
2184 return position;
2185}
2186
2187void
2188CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2189{
Jim Ingham574c3d62011-08-12 23:34:31 +00002190 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002191 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002192 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002193 // In the current working directory we don't load any program specific
2194 // .lldbinit files, we only look for a "./.lldbinit" file.
2195 if (m_skip_lldbinit_files)
2196 return;
2197
2198 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002199 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002200 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002201 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002202 // If we aren't looking in the current working directory we are looking
2203 // in the home directory. We will first see if there is an application
2204 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2205 // "-" and the name of the program. If this file doesn't exist, we fall
2206 // back to just the "~/.lldbinit" file. We also obey any requests to not
2207 // load the init files.
2208 const char *init_file_path = "~/.lldbinit";
2209
2210 if (m_skip_app_init_files == false)
2211 {
2212 FileSpec program_file_spec (Host::GetProgramFileSpec());
2213 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002214
Greg Claytond6edcb52011-09-11 00:01:44 +00002215 if (program_name)
2216 {
2217 char program_init_file_name[PATH_MAX];
2218 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2219 init_file.SetFile (program_init_file_name, true);
2220 if (!init_file.Exists())
2221 init_file.Clear();
2222 }
2223 }
2224
2225 if (!init_file && !m_skip_lldbinit_files)
2226 init_file.SetFile (init_file_path, true);
2227 }
2228
Chris Lattner24943d22010-06-08 16:52:24 +00002229 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2230 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2231
2232 if (init_file.Exists())
2233 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002234 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2235 bool stop_on_continue = true;
2236 bool stop_on_error = false;
2237 bool echo_commands = false;
2238 bool print_results = false;
2239
Enrico Granata01bc2d42012-05-31 01:09:06 +00002240 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002241 }
2242 else
2243 {
2244 // nothing to be done if the file doesn't exist
2245 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2246 }
2247}
2248
Greg Claytonb72d0f02011-04-12 05:54:46 +00002249PlatformSP
2250CommandInterpreter::GetPlatform (bool prefer_target_platform)
2251{
2252 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002253 if (prefer_target_platform)
2254 {
2255 Target *target = m_exe_ctx.GetTargetPtr();
2256 if (target)
2257 platform_sp = target->GetPlatform();
2258 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002259
2260 if (!platform_sp)
2261 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2262 return platform_sp;
2263}
2264
Jim Ingham949d5ac2011-02-18 00:54:25 +00002265void
Jim Inghama4fede32011-03-11 01:51:49 +00002266CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002267 ExecutionContext *override_context,
2268 bool stop_on_continue,
2269 bool stop_on_error,
2270 bool echo_commands,
2271 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002272 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002273 CommandReturnObject &result)
2274{
2275 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002276
2277 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2278 // Make sure you reset this value anywhere you return from the function.
2279
2280 bool old_async_execution = m_debugger.GetAsyncExecution();
2281
2282 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2283 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2284
2285 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002286 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002287
2288 if (!stop_on_continue)
2289 {
2290 m_debugger.SetAsyncExecution (false);
2291 }
2292
2293 for (int idx = 0; idx < num_lines; idx++)
2294 {
2295 const char *cmd = commands.GetStringAtIndex(idx);
2296 if (cmd[0] == '\0')
2297 continue;
2298
Jim Ingham949d5ac2011-02-18 00:54:25 +00002299 if (echo_commands)
2300 {
2301 result.AppendMessageWithFormat ("%s %s\n",
2302 GetPrompt(),
2303 cmd);
2304 }
2305
Greg Claytonaa378b12011-02-20 02:15:07 +00002306 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002307 // If override_context is not NULL, pass no_context_switching = true for
2308 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002309 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002310 NULL, /* override_context */
2311 true, /* repeat_on_empty_command */
2312 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002313
2314 if (print_results)
2315 {
2316 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002317 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002318 }
2319
2320 if (!success || !tmp_result.Succeeded())
2321 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002322 const char *error_msg = tmp_result.GetErrorData();
2323 if (error_msg == NULL || error_msg[0] == '\0')
2324 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002325 if (stop_on_error)
2326 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002327 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2328 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002329 result.SetStatus (eReturnStatusFailed);
2330 m_debugger.SetAsyncExecution (old_async_execution);
2331 return;
2332 }
2333 else if (print_results)
2334 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002335 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002336 idx + 1,
2337 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002338 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002339 }
2340 }
2341
Caroline Tice4a348082011-05-02 20:41:46 +00002342 if (result.GetImmediateOutputStream())
2343 result.GetImmediateOutputStream()->Flush();
2344
2345 if (result.GetImmediateErrorStream())
2346 result.GetImmediateErrorStream()->Flush();
2347
Jim Ingham949d5ac2011-02-18 00:54:25 +00002348 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2349 // could be running (for instance in Breakpoint Commands.
2350 // So we check the return value to see if it is has running in it.
2351 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2352 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2353 {
2354 if (stop_on_continue)
2355 {
2356 // If we caused the target to proceed, and we're going to stop in that case, set the
2357 // status in our real result before returning. This is an error if the continue was not the
2358 // last command in the set of commands to be run.
2359 if (idx != num_lines - 1)
2360 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2361 idx + 1, cmd);
2362 else
2363 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2364
2365 result.SetStatus(tmp_result.GetStatus());
2366 m_debugger.SetAsyncExecution (old_async_execution);
2367
2368 return;
2369 }
2370 }
2371
2372 }
2373
2374 result.SetStatus (eReturnStatusSuccessFinishResult);
2375 m_debugger.SetAsyncExecution (old_async_execution);
2376
2377 return;
2378}
2379
2380void
2381CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2382 ExecutionContext *context,
2383 bool stop_on_continue,
2384 bool stop_on_error,
2385 bool echo_command,
2386 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002387 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002388 CommandReturnObject &result)
2389{
2390 if (cmd_file.Exists())
2391 {
2392 bool success;
2393 StringList commands;
2394 success = commands.ReadFileLines(cmd_file);
2395 if (!success)
2396 {
2397 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2398 result.SetStatus (eReturnStatusFailed);
2399 return;
2400 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002401 m_command_source_depth++;
2402 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2403 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002404 }
2405 else
2406 {
2407 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2408 cmd_file.GetFilename().AsCString());
2409 result.SetStatus (eReturnStatusFailed);
2410 return;
2411 }
2412}
2413
Chris Lattner24943d22010-06-08 16:52:24 +00002414ScriptInterpreter *
2415CommandInterpreter::GetScriptInterpreter ()
2416{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002417 if (m_script_interpreter_ap.get() != NULL)
2418 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002419
Caroline Tice0aa2e552011-01-14 00:29:16 +00002420 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2421 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002422 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002423 case eScriptLanguagePython:
2424#ifndef LLDB_DISABLE_PYTHON
2425 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2426 break;
2427#else
2428 // Fall through to the None case when python is disabled
2429#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002430 case eScriptLanguageNone:
2431 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2432 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002433 default:
2434 break;
2435 };
2436
2437 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002438}
2439
2440
2441
2442bool
2443CommandInterpreter::GetSynchronous ()
2444{
2445 return m_synchronous_execution;
2446}
2447
2448void
2449CommandInterpreter::SetSynchronous (bool value)
2450{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002451 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002452}
2453
2454void
2455CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2456 const char *word_text,
2457 const char *separator,
2458 const char *help_text,
2459 uint32_t max_word_len)
2460{
Greg Clayton238c0a12010-09-18 01:14:36 +00002461 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2462
Chris Lattner24943d22010-06-08 16:52:24 +00002463 int indent_size = max_word_len + strlen (separator) + 2;
2464
2465 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002466
2467 StreamString text_strm;
2468 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2469
2470 size_t len = text_strm.GetSize();
2471 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002472 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002473 {
2474 text_strm.EOL();
2475 len = text_strm.GetSize();
2476 }
Chris Lattner24943d22010-06-08 16:52:24 +00002477
2478 if (len < max_columns)
2479 {
2480 // Output it as a single line.
2481 strm.Printf ("%s", text);
2482 }
2483 else
2484 {
2485 // We need to break it up into multiple lines.
2486 bool first_line = true;
2487 int text_width;
2488 int start = 0;
2489 int end = start;
2490 int final_end = strlen (text);
2491 int sub_len;
2492
2493 while (end < final_end)
2494 {
2495 if (first_line)
2496 text_width = max_columns - 1;
2497 else
2498 text_width = max_columns - indent_size - 1;
2499
2500 // Don't start the 'text' on a space, since we're already outputting the indentation.
2501 if (!first_line)
2502 {
2503 while ((start < final_end) && (text[start] == ' '))
2504 start++;
2505 }
2506
2507 end = start + text_width;
2508 if (end > final_end)
2509 end = final_end;
2510 else
2511 {
2512 // If we're not at the end of the text, make sure we break the line on white space.
2513 while (end > start
2514 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2515 end--;
2516 }
2517
2518 sub_len = end - start;
2519 if (start != 0)
2520 strm.EOL();
2521 if (!first_line)
2522 strm.Indent();
2523 else
2524 first_line = false;
2525 assert (start <= final_end);
2526 assert (start + sub_len <= final_end);
2527 if (sub_len > 0)
2528 strm.Write (text + start, sub_len);
2529 start = end + 1;
2530 }
2531 }
2532 strm.EOL();
2533 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002534}
2535
2536void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002537CommandInterpreter::OutputHelpText (Stream &strm,
2538 const char *word_text,
2539 const char *separator,
2540 const char *help_text,
2541 uint32_t max_word_len)
2542{
2543 int indent_size = max_word_len + strlen (separator) + 2;
2544
2545 strm.IndentMore (indent_size);
2546
2547 StreamString text_strm;
2548 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2549
2550 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2551 bool first_line = true;
2552
2553 size_t len = text_strm.GetSize();
2554 const char *text = text_strm.GetData();
2555
2556 uint32_t chars_left = max_columns;
2557
2558 for (uint32_t i = 0; i < len; i++)
2559 {
2560 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2561 {
2562 first_line = false;
2563 chars_left = max_columns - indent_size;
2564 strm.EOL();
2565 strm.Indent();
2566 }
2567 else
2568 {
2569 strm.PutChar(text[i]);
2570 chars_left--;
2571 }
2572
2573 }
2574
2575 strm.EOL();
2576 strm.IndentLess(indent_size);
2577}
2578
2579void
Chris Lattner24943d22010-06-08 16:52:24 +00002580CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2581 StringList &commands_found, StringList &commands_help)
2582{
2583 CommandObject::CommandMap::const_iterator pos;
2584 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2585 CommandObject *sub_cmd_obj;
2586
2587 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2588 {
2589 const char * command_name = pos->first.c_str();
2590 sub_cmd_obj = pos->second.get();
2591 StreamString complete_command_name;
2592
2593 complete_command_name.Printf ("%s %s", prefix, command_name);
2594
Greg Clayton238c0a12010-09-18 01:14:36 +00002595 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002596 {
2597 commands_found.AppendString (complete_command_name.GetData());
2598 commands_help.AppendString (sub_cmd_obj->GetHelp());
2599 }
2600
2601 if (sub_cmd_obj->IsMultiwordObject())
2602 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2603 commands_help);
2604 }
2605
2606}
2607
2608void
2609CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2610 StringList &commands_help)
2611{
2612 CommandObject::CommandMap::const_iterator pos;
2613
2614 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2615 {
2616 const char *command_name = pos->first.c_str();
2617 CommandObject *cmd_obj = pos->second.get();
2618
Greg Clayton238c0a12010-09-18 01:14:36 +00002619 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002620 {
2621 commands_found.AppendString (command_name);
2622 commands_help.AppendString (cmd_obj->GetHelp());
2623 }
2624
2625 if (cmd_obj->IsMultiwordObject())
2626 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2627
2628 }
2629}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002630
2631
2632void
2633CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2634{
2635 m_exe_ctx.Clear();
2636
2637 if (override_context != NULL)
2638 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002639 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002640 }
2641 else
2642 {
2643 TargetSP target_sp (m_debugger.GetSelectedTarget());
2644 if (target_sp)
2645 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002646 m_exe_ctx.SetTargetSP (target_sp);
2647 ProcessSP process_sp (target_sp->GetProcessSP());
2648 m_exe_ctx.SetProcessSP (process_sp);
2649 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002650 {
Greg Clayton13d24fb2012-01-29 20:56:30 +00002651 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
Greg Clayton567e7f32011-09-22 04:58:26 +00002652 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002653 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002654 m_exe_ctx.SetThreadSP (thread_sp);
2655 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2656 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002657 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002658 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002659 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002660 if (frame_sp)
2661 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002662 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002663 if (frame_sp)
2664 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002665 }
2666 }
2667 }
2668 }
2669}
2670
Jim Ingham6247dbe2011-07-12 03:12:18 +00002671void
2672CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2673{
2674 DumpHistory (stream, 0, count - 1);
2675}
2676
2677void
2678CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2679{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002680 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2681 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002682 {
2683 if (!m_command_history[i].empty())
2684 {
2685 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002686 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002687 }
2688 }
2689}
2690
2691const char *
2692CommandInterpreter::FindHistoryString (const char *input_str) const
2693{
2694 if (input_str[0] != m_repeat_char)
2695 return NULL;
2696 if (input_str[1] == '-')
2697 {
2698 bool success;
2699 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2700 if (!success)
2701 return NULL;
2702 if (idx > m_command_history.size())
2703 return NULL;
2704 idx = m_command_history.size() - idx;
2705 return m_command_history[idx].c_str();
2706
2707 }
2708 else if (input_str[1] == m_repeat_char)
2709 {
2710 if (m_command_history.empty())
2711 return NULL;
2712 else
2713 return m_command_history.back().c_str();
2714 }
2715 else
2716 {
2717 bool success;
2718 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2719 if (!success)
2720 return NULL;
2721 if (idx >= m_command_history.size())
2722 return NULL;
2723 return m_command_history[idx].c_str();
2724 }
2725}