blob: 2879ec45f8f270b274a2d7524ef48bad6ff67384 [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);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000251#if defined (__arm__)
252 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
253#else
Greg Clayton86c50d72012-05-18 00:04:38 +0000254 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda36eb7c02012-07-06 02:46:23 +0000255#endif
Caroline Tice5ddbe212011-05-06 21:37:15 +0000256 AddAlias ("r", cmd_obj_sp);
257 AddAlias ("run", cmd_obj_sp);
258 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
259 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
260 }
Greg Claytonc84623f2012-03-29 21:47:51 +0000261
262 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
263 if (cmd_obj_sp)
264 {
265 AddAlias ("add-dsym", cmd_obj_sp);
266 }
Sean Callanan7b71b172012-05-21 18:25:19 +0000267
268 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
269 if (cmd_obj_sp)
270 {
271 alias_arguments_vector_sp.reset (new OptionArgVector);
272 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
273 AddAlias ("rb", cmd_obj_sp);
274 AddOrReplaceAliasOptions("rb", alias_arguments_vector_sp);
275 }
Chris Lattner24943d22010-06-08 16:52:24 +0000276}
277
Chris Lattner24943d22010-06-08 16:52:24 +0000278const char *
279CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
280{
281 // This function has not yet been implemented.
282
283 // Look for any embedded script command
284 // If found,
285 // get interpreter object from the command dictionary,
286 // call execute_one_command on it,
287 // get the results as a string,
288 // substitute that string for current stuff.
289
290 return arg;
291}
292
293
294void
295CommandInterpreter::LoadCommandDictionary ()
296{
297 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
298
299 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
300 //
301 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
302 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
303 // the cross-referencing stuff) are created!!!
304 //
305 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
306
307
308 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
309 // are created. This is so that when another command is created that needs to go into a crossref object,
310 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
311 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
312
Chris Lattner24943d22010-06-08 16:52:24 +0000313 // Non-CommandObjectCrossref commands can now be created.
314
Caroline Tice5bc8c972010-09-20 20:44:43 +0000315 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000316
Greg Clayton238c0a12010-09-18 01:14:36 +0000317 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000318 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000319 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000320 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000321 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
322 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000323// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000324 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000325 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000326 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000327 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
328 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000329 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000330 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000331 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000332 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000333 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000334 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000335 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000336 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
337 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000338 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000339 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000340 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000341
342 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000343 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000344 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000345 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000346 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000347 if (break_regex_cmd_ap.get())
348 {
349 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
350 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
351 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000352 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000353 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000354 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000355 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
356 {
357 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
358 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
359 }
360 }
Jim Inghame56493f2011-03-22 02:29:32 +0000361
362 std::auto_ptr<CommandObjectRegexCommand>
363 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000364 "_regexp-down",
365 "Go down \"n\" frames in the stack (1 frame by default).",
366 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000367 if (down_regex_cmd_ap.get())
368 {
369 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
370 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
371 {
372 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
373 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
374 }
375 }
376
377 std::auto_ptr<CommandObjectRegexCommand>
378 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000379 "_regexp-up",
380 "Go up \"n\" frames in the stack (1 frame by default).",
381 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000382 if (up_regex_cmd_ap.get())
383 {
384 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
385 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
386 {
387 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
388 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
389 }
390 }
Jason Molenda730cae02011-10-22 01:30:52 +0000391
392 std::auto_ptr<CommandObjectRegexCommand>
393 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000394 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000395 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000396 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000397 if (display_regex_cmd_ap.get())
398 {
399 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
400 {
401 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
402 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
403 }
404 }
405
406 std::auto_ptr<CommandObjectRegexCommand>
407 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000408 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000409 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000410 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000411 if (undisplay_regex_cmd_ap.get())
412 {
413 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
414 {
415 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
416 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
417 }
418 }
419
Chris Lattner24943d22010-06-08 16:52:24 +0000420}
421
422int
423CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
424 StringList &matches)
425{
426 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
427
428 if (include_aliases)
429 {
430 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
431 }
432
433 return matches.GetSize();
434}
435
436CommandObjectSP
437CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
438{
439 CommandObject::CommandMap::iterator pos;
440 CommandObjectSP ret_val;
441
442 std::string cmd(cmd_cstr);
443
444 if (HasCommands())
445 {
446 pos = m_command_dict.find(cmd);
447 if (pos != m_command_dict.end())
448 ret_val = pos->second;
449 }
450
451 if (include_aliases && HasAliases())
452 {
453 pos = m_alias_dict.find(cmd);
454 if (pos != m_alias_dict.end())
455 ret_val = pos->second;
456 }
457
458 if (HasUserCommands())
459 {
460 pos = m_user_dict.find(cmd);
461 if (pos != m_user_dict.end())
462 ret_val = pos->second;
463 }
464
465 if (!exact && ret_val == NULL)
466 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000467 // We will only get into here if we didn't find any exact matches.
468
469 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
470
Chris Lattner24943d22010-06-08 16:52:24 +0000471 StringList local_matches;
472 if (matches == NULL)
473 matches = &local_matches;
474
Jim Inghamd40f8a62010-07-06 22:46:59 +0000475 unsigned int num_cmd_matches = 0;
476 unsigned int num_alias_matches = 0;
477 unsigned int num_user_matches = 0;
478
479 // Look through the command dictionaries one by one, and if we get only one match from any of
480 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
481
Chris Lattner24943d22010-06-08 16:52:24 +0000482 if (HasCommands())
483 {
484 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
485 }
486
487 if (num_cmd_matches == 1)
488 {
489 cmd.assign(matches->GetStringAtIndex(0));
490 pos = m_command_dict.find(cmd);
491 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000492 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000493 }
494
Jim Ingham9a574172010-06-24 20:28:42 +0000495 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000496 {
497 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
498
499 }
500
Jim Inghamd40f8a62010-07-06 22:46:59 +0000501 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000502 {
503 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
504 pos = m_alias_dict.find(cmd);
505 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000506 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000507 }
508
Jim Ingham9a574172010-06-24 20:28:42 +0000509 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000510 {
511 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
512 }
513
Jim Inghamd40f8a62010-07-06 22:46:59 +0000514 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000515 {
516 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
517
518 pos = m_user_dict.find (cmd);
519 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000520 user_match_sp = pos->second;
521 }
522
523 // If we got exactly one match, return that, otherwise return the match list.
524
525 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
526 {
527 if (num_cmd_matches)
528 return real_match_sp;
529 else if (num_alias_matches)
530 return alias_match_sp;
531 else
532 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000533 }
534 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000535 else if (matches && ret_val != NULL)
536 {
537 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000538 }
539
540
541 return ret_val;
542}
543
Greg Claytond12aeab2011-04-20 16:37:46 +0000544bool
545CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
546{
547 if (name && name[0])
548 {
549 std::string name_sstr(name);
550 if (!can_replace)
551 {
552 if (m_command_dict.find (name_sstr) != m_command_dict.end())
553 return false;
554 }
555 m_command_dict[name_sstr] = cmd_sp;
556 return true;
557 }
558 return false;
559}
560
Enrico Granata6b1596d2011-08-16 23:24:13 +0000561bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000562CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000563 const lldb::CommandObjectSP &cmd_sp,
564 bool can_replace)
565{
Enrico Granata6010ace2011-11-07 22:57:04 +0000566 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000567 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000568
569 const char* name_cstr = name.c_str();
570
571 // do not allow replacement of internal commands
572 if (CommandExists(name_cstr))
573 return false;
574
575 if (can_replace == false && UserCommandExists(name_cstr))
576 return false;
577
578 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000579 return true;
580 }
581 return false;
582}
Greg Claytond12aeab2011-04-20 16:37:46 +0000583
Jim Inghamd40f8a62010-07-06 22:46:59 +0000584CommandObjectSP
585CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000586{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000587 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
588 CommandObjectSP ret_val; // Possibly empty return value.
589
590 if (cmd_cstr == NULL)
591 return ret_val;
592
593 if (cmd_words.GetArgumentCount() == 1)
594 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
595 else
596 {
597 // We have a multi-word command (seemingly), so we need to do more work.
598 // First, get the cmd_obj_sp for the first word in the command.
599 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
600 if (cmd_obj_sp.get() != NULL)
601 {
602 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
603 // command name), and find the appropriate sub-command SP for each command word....
604 size_t end = cmd_words.GetArgumentCount();
605 for (size_t j= 1; j < end; ++j)
606 {
607 if (cmd_obj_sp->IsMultiwordObject())
608 {
609 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
610 (cmd_words.GetArgumentAtIndex (j));
611 if (cmd_obj_sp.get() == NULL)
612 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
613 return ret_val;
614 }
615 else
616 // We have more words in the command name, but we don't have a multiword object. Fail and return
617 // empty 'ret_val'.
618 return ret_val;
619 }
620 // We successfully looped through all the command words and got valid command objects for them. Assign the
621 // last object retrieved to 'ret_val'.
622 ret_val = cmd_obj_sp;
623 }
624 }
625 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000626}
627
628CommandObject *
629CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
630{
631 return GetCommandSPExact (cmd_cstr, include_aliases).get();
632}
633
634CommandObject *
635CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
636{
637 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
638
639 // If we didn't find an exact match to the command string in the commands, look in
640 // the aliases.
641
642 if (command_obj == NULL)
643 {
644 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
645 }
646
647 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
648 // in both the commands and the aliases.
649
650 if (command_obj == NULL)
651 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
652
653 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000654}
655
656bool
657CommandInterpreter::CommandExists (const char *cmd)
658{
659 return m_command_dict.find(cmd) != m_command_dict.end();
660}
661
662bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000663CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
664 const char *options_args,
665 OptionArgVectorSP &option_arg_vector_sp)
666{
667 bool success = true;
668 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
669
670 if (!options_args || (strlen (options_args) < 1))
671 return true;
672
673 std::string options_string (options_args);
674 Args args (options_args);
675 CommandReturnObject result;
676 // Check to see if the command being aliased can take any command options.
677 Options *options = cmd_obj_sp->GetOptions ();
678 if (options)
679 {
680 // See if any options were specified as part of the alias; if so, handle them appropriately.
681 options->NotifyOptionParsingStarting ();
682 args.Unshift ("dummy_arg");
683 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
684 args.Shift ();
685 if (result.Succeeded())
686 options->VerifyPartialOptions (result);
687 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
688 {
689 result.AppendError ("Unable to create requested alias.\n");
690 return false;
691 }
692 }
693
Greg Clayton7268b4c2011-10-28 21:38:01 +0000694 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000695 {
696 if (cmd_obj_sp->WantsRawCommandString ())
697 option_arg_vector->push_back (OptionArgPair ("<argument>",
698 OptionArgValue (-1,
699 options_string)));
700 else
701 {
702 int argc = args.GetArgumentCount();
703 for (size_t i = 0; i < argc; ++i)
704 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
705 option_arg_vector->push_back
706 (OptionArgPair ("<argument>",
707 OptionArgValue (-1,
708 std::string (args.GetArgumentAtIndex (i)))));
709 }
710 }
711
712 return success;
713}
714
715bool
Chris Lattner24943d22010-06-08 16:52:24 +0000716CommandInterpreter::AliasExists (const char *cmd)
717{
718 return m_alias_dict.find(cmd) != m_alias_dict.end();
719}
720
721bool
722CommandInterpreter::UserCommandExists (const char *cmd)
723{
724 return m_user_dict.find(cmd) != m_user_dict.end();
725}
726
727void
728CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
729{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000730 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000731 m_alias_dict[alias_name] = command_obj_sp;
732}
733
734bool
735CommandInterpreter::RemoveAlias (const char *alias_name)
736{
737 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
738 if (pos != m_alias_dict.end())
739 {
740 m_alias_dict.erase(pos);
741 return true;
742 }
743 return false;
744}
745bool
746CommandInterpreter::RemoveUser (const char *alias_name)
747{
748 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
749 if (pos != m_user_dict.end())
750 {
751 m_user_dict.erase(pos);
752 return true;
753 }
754 return false;
755}
756
Chris Lattner24943d22010-06-08 16:52:24 +0000757void
758CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
759{
760 help_string.Printf ("'%s", command_name);
761 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
762
763 if (option_arg_vector_sp != NULL)
764 {
765 OptionArgVector *options = option_arg_vector_sp.get();
766 for (int i = 0; i < options->size(); ++i)
767 {
768 OptionArgPair cur_option = (*options)[i];
769 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000770 OptionArgValue value_pair = cur_option.second;
771 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000772 if (opt.compare("<argument>") == 0)
773 {
774 help_string.Printf (" %s", value.c_str());
775 }
776 else
777 {
778 help_string.Printf (" %s", opt.c_str());
779 if ((value.compare ("<no-argument>") != 0)
780 && (value.compare ("<need-argument") != 0))
781 {
782 help_string.Printf (" %s", value.c_str());
783 }
784 }
785 }
786 }
787
788 help_string.Printf ("'");
789}
790
Greg Clayton65124ea2010-08-26 22:05:43 +0000791size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000792CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
793{
794 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000795 CommandObject::CommandMap::const_iterator end = dict.end();
796 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000797
Greg Clayton65124ea2010-08-26 22:05:43 +0000798 for (pos = dict.begin(); pos != end; ++pos)
799 {
800 size_t len = pos->first.size();
801 if (max_len < len)
802 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000803 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000804 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000805}
806
807void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000808CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000809 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000810{
811 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000812 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000813
814 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000815 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000816
817 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
818 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000819
Enrico Granata6b1596d2011-08-16 23:24:13 +0000820 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
821 {
822 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
823 max_len);
824 }
825 result.AppendMessage("");
826
827 }
828
Greg Clayton7268b4c2011-10-28 21:38:01 +0000829 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000830 {
Jim Inghame3663e82010-10-22 18:47:16 +0000831 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000832 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000833 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000834 max_len = FindLongestCommandWord (m_alias_dict);
835
Chris Lattner24943d22010-06-08 16:52:24 +0000836 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
837 {
838 StreamString sstr;
839 StreamString translation_and_help;
840 std::string entry_name = pos->first;
841 std::string second_entry = pos->second.get()->GetCommandName();
842 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
843
844 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
845 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
846 translation_and_help.GetData(), max_len);
847 }
848 result.AppendMessage("");
849 }
850
Greg Clayton7268b4c2011-10-28 21:38:01 +0000851 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000852 {
853 result.AppendMessage ("The following is a list of your current user-defined commands:");
854 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000855 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000856 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
857 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000858 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
859 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000860 }
861 result.AppendMessage("");
862 }
863
864 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
865}
866
Caroline Ticee0da7a52010-12-09 22:52:49 +0000867CommandObject *
868CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000869{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000870 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
871 // eventually be invoked by the given command line.
872
873 CommandObject *cmd_obj = NULL;
874 std::string white_space (" \t\v");
875 size_t start = command_string.find_first_not_of (white_space);
876 size_t end = 0;
877 bool done = false;
878 while (!done)
879 {
880 if (start != std::string::npos)
881 {
882 // Get the next word from command_string.
883 end = command_string.find_first_of (white_space, start);
884 if (end == std::string::npos)
885 end = command_string.size();
886 std::string cmd_word = command_string.substr (start, end - start);
887
888 if (cmd_obj == NULL)
889 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
890 // command or alias.
891 cmd_obj = GetCommandObject (cmd_word.c_str());
892 else if (cmd_obj->IsMultiwordObject ())
893 {
894 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
895 CommandObject *sub_cmd_obj =
896 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
897 if (sub_cmd_obj)
898 cmd_obj = sub_cmd_obj;
899 else // cmd_word was not a valid sub-command word, so we are donee
900 done = true;
901 }
902 else
903 // We have a cmd_obj and it is not a multi-word object, so we are done.
904 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000905
Caroline Ticee0da7a52010-12-09 22:52:49 +0000906 // If we didn't find a valid command object, or our command object is not a multi-word object, or
907 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
908 // next word.
909
910 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
911 done = true;
912 else
913 start = command_string.find_first_not_of (white_space, end);
914 }
915 else
916 // Unable to find any more words.
917 done = true;
918 }
919
920 if (end == command_string.size())
921 command_string.clear();
922 else
923 command_string = command_string.substr(end);
924
925 return cmd_obj;
926}
927
Greg Clayton9d855c62011-10-25 00:36:27 +0000928static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000929static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000930static void
931StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000932{
Greg Clayton9d855c62011-10-25 00:36:27 +0000933 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000934 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000935 size_t pos = s.find_first_not_of (k_white_space);
936 if (pos == std::string::npos)
937 s.clear();
938 else if (pos == 0)
939 return;
940 s.erase (0, pos);
941 }
942}
943
Greg Clayton3840cd72011-11-09 23:25:03 +0000944static size_t
945FindArgumentTerminator (const std::string &s)
946{
Greg Clayton3840cd72011-11-09 23:25:03 +0000947 const size_t s_len = s.size();
948 size_t offset = 0;
949 while (offset < s_len)
950 {
951 size_t pos = s.find ("--", offset);
952 if (pos == std::string::npos)
953 break;
954 if (pos > 0)
955 {
956 if (isspace(s[pos-1]))
957 {
958 // Check if the string ends "\s--" (where \s is a space character)
959 // or if we have "\s--\s".
960 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
961 {
Greg Clayton3840cd72011-11-09 23:25:03 +0000962 return pos;
963 }
964 }
965 }
966 offset = pos + 2;
967 }
Greg Clayton3840cd72011-11-09 23:25:03 +0000968 return std::string::npos;
969}
970
Greg Clayton9d855c62011-10-25 00:36:27 +0000971static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000972ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000973{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000974 command.clear();
975 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000976 StripLeadingSpaces (command_string);
977
978 bool result = false;
979 quote_char = '\0';
980
981 if (!command_string.empty())
982 {
983 const char first_char = command_string[0];
984 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000985 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000986 quote_char = first_char;
987 const size_t end_quote_pos = command_string.find (quote_char, 1);
988 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000989 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000990 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000991 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000992 }
993 else
994 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000995 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +0000996 if (end_quote_pos + 1 < command_string.size())
997 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
998 else
999 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +00001000 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001001 }
1002 else
1003 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001004 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1005 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +00001006 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001007 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +00001008 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +00001009 }
1010 else
1011 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001012 command.assign (command_string, 0, first_space_pos);
1013 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +00001014 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001015 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001016 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001017 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001018
1019
1020 if (!command.empty())
1021 {
1022 // actual commands can't start with '-' or '_'
1023 if (command[0] != '-' && command[0] != '_')
1024 {
1025 size_t pos = command.find_first_not_of(k_valid_command_chars);
1026 if (pos > 0 && pos != std::string::npos)
1027 {
1028 suffix.assign (command.begin() + pos, command.end());
1029 command.erase (pos);
1030 }
1031 }
1032 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001033
1034 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001035}
1036
Greg Clayton7268b4c2011-10-28 21:38:01 +00001037CommandObject *
1038CommandInterpreter::BuildAliasResult (const char *alias_name,
1039 std::string &raw_input_string,
1040 std::string &alias_result,
1041 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001042{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001043 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001044 Args cmd_args (raw_input_string.c_str());
1045 alias_cmd_obj = GetCommandObject (alias_name);
1046 StreamString result_str;
1047
1048 if (alias_cmd_obj)
1049 {
1050 std::string alias_name_str = alias_name;
1051 if ((cmd_args.GetArgumentCount() == 0)
1052 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1053 cmd_args.Unshift (alias_name);
1054
1055 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1056 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1057
1058 if (option_arg_vector_sp.get())
1059 {
1060 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1061
1062 for (int i = 0; i < option_arg_vector->size(); ++i)
1063 {
1064 OptionArgPair option_pair = (*option_arg_vector)[i];
1065 OptionArgValue value_pair = option_pair.second;
1066 int value_type = value_pair.first;
1067 std::string option = option_pair.first;
1068 std::string value = value_pair.second;
1069 if (option.compare ("<argument>") == 0)
1070 result_str.Printf (" %s", value.c_str());
1071 else
1072 {
1073 result_str.Printf (" %s", option.c_str());
1074 if (value_type != optional_argument)
1075 result_str.Printf (" ");
1076 if (value.compare ("<no_argument>") != 0)
1077 {
1078 int index = GetOptionArgumentPosition (value.c_str());
1079 if (index == 0)
1080 result_str.Printf ("%s", value.c_str());
1081 else if (index >= cmd_args.GetArgumentCount())
1082 {
1083
1084 result.AppendErrorWithFormat
1085 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1086 index);
1087 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001088 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001089 }
1090 else
1091 {
1092 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1093 if (strpos != std::string::npos)
1094 raw_input_string = raw_input_string.erase (strpos,
1095 strlen (cmd_args.GetArgumentAtIndex (index)));
1096 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1097 }
1098 }
1099 }
1100 }
1101 }
1102
1103 alias_result = result_str.GetData();
1104 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001105 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001106}
1107
Greg Claytonf5c0c722011-10-14 07:41:33 +00001108Error
1109CommandInterpreter::PreprocessCommand (std::string &command)
1110{
1111 // The command preprocessor needs to do things to the command
1112 // line before any parsing of arguments or anything else is done.
1113 // The only current stuff that gets proprocessed is anyting enclosed
1114 // in backtick ('`') characters is evaluated as an expression and
1115 // the result of the expression must be a scalar that can be substituted
1116 // into the command. An example would be:
1117 // (lldb) memory read `$rsp + 20`
1118 Error error; // Error for any expressions that might not evaluate
1119 size_t start_backtick;
1120 size_t pos = 0;
1121 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1122 {
1123 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1124 {
1125 // The backtick was preceeded by a '\' character, remove the slash
1126 // and don't treat the backtick as the start of an expression
1127 command.erase(start_backtick-1, 1);
1128 // No need to add one to start_backtick since we just deleted a char
1129 pos = start_backtick;
1130 }
1131 else
1132 {
1133 const size_t expr_content_start = start_backtick + 1;
1134 const size_t end_backtick = command.find ('`', expr_content_start);
1135 if (end_backtick == std::string::npos)
1136 return error;
1137 else if (end_backtick == expr_content_start)
1138 {
1139 // Empty expression (two backticks in a row)
1140 command.erase (start_backtick, 2);
1141 }
1142 else
1143 {
1144 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1145
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001146 ExecutionContext exe_ctx(GetExecutionContext());
1147 Target *target = exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001148 // Get a dummy target to allow for calculator mode while processing backticks.
1149 // This also helps break the infinite loop caused when target is null.
1150 if (!target)
1151 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001152 if (target)
1153 {
Sean Callanandaa6efe2011-12-21 22:22:58 +00001154 const bool coerce_to_id = false;
Greg Claytonf5c0c722011-10-14 07:41:33 +00001155 const bool unwind_on_error = true;
1156 const bool keep_in_memory = false;
1157 ValueObjectSP expr_result_valobj_sp;
1158 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Greg Claytonbcaf99a2012-07-12 20:32:19 +00001159 exe_ctx.GetFramePtr(),
Greg Claytonf5c0c722011-10-14 07:41:33 +00001160 eExecutionPolicyOnlyWhenNeeded,
Sean Callanandaa6efe2011-12-21 22:22:58 +00001161 coerce_to_id,
1162 unwind_on_error,
1163 keep_in_memory,
Greg Claytonf5c0c722011-10-14 07:41:33 +00001164 eNoDynamicValues,
1165 expr_result_valobj_sp);
1166 if (expr_result == eExecutionCompleted)
1167 {
1168 Scalar scalar;
1169 if (expr_result_valobj_sp->ResolveValue (scalar))
1170 {
1171 command.erase (start_backtick, end_backtick - start_backtick + 1);
1172 StreamString value_strm;
1173 const bool show_type = false;
1174 scalar.GetValue (&value_strm, show_type);
1175 size_t value_string_size = value_strm.GetSize();
1176 if (value_string_size)
1177 {
1178 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1179 pos = start_backtick + value_string_size;
1180 continue;
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 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1190 }
1191 }
1192 else
1193 {
1194 if (expr_result_valobj_sp)
1195 error = expr_result_valobj_sp->GetError();
1196 if (error.Success())
1197 {
1198
1199 switch (expr_result)
1200 {
1201 case eExecutionSetupError:
1202 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1203 break;
1204 case eExecutionCompleted:
1205 break;
1206 case eExecutionDiscarded:
1207 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1208 break;
1209 case eExecutionInterrupted:
1210 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1211 break;
1212 case eExecutionTimedOut:
1213 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1214 break;
1215 }
1216 }
1217 }
1218 }
1219 }
1220 if (error.Fail())
1221 break;
1222 }
1223 }
1224 return error;
1225}
1226
1227
Caroline Ticee0da7a52010-12-09 22:52:49 +00001228bool
1229CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata01bc2d42012-05-31 01:09:06 +00001230 LazyBool lazy_add_to_history,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001231 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001232 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001233 bool repeat_on_empty_command,
1234 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001235
Caroline Ticee0da7a52010-12-09 22:52:49 +00001236{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001237
Caroline Ticee0da7a52010-12-09 22:52:49 +00001238 bool done = false;
1239 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001240 bool wants_raw_input = false;
1241 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001242 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001243
1244 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001245 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1246
1247 // Make a scoped cleanup object that will clear the crash description string
1248 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001249 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001250
Caroline Ticee0da7a52010-12-09 22:52:49 +00001251 if (log)
1252 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001253
Jim Inghamabab14b2010-11-04 23:08:45 +00001254 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1255
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001256 if (!no_context_switching)
1257 UpdateExecutionContext (override_context);
Enrico Granata01bc2d42012-05-31 01:09:06 +00001258
1259 // <rdar://problem/11328896>
1260 bool add_to_history;
1261 if (lazy_add_to_history == eLazyBoolCalculate)
1262 add_to_history = (m_command_source_depth == 0);
1263 else
1264 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1265
Jim Ingham949d5ac2011-02-18 00:54:25 +00001266 bool empty_command = false;
1267 bool comment_command = false;
1268 if (command_string.empty())
1269 empty_command = true;
1270 else
Chris Lattner24943d22010-06-08 16:52:24 +00001271 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001272 const char *k_space_characters = "\t\n\v\f\r ";
1273
1274 size_t non_space = command_string.find_first_not_of (k_space_characters);
1275 // Check for empty line or comment line (lines whose first
1276 // non-space character is the comment character for this interpreter)
1277 if (non_space == std::string::npos)
1278 empty_command = true;
1279 else if (command_string[non_space] == m_comment_char)
1280 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001281 else if (command_string[non_space] == m_repeat_char)
1282 {
1283 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1284 if (history_string == NULL)
1285 {
1286 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1287 result.SetStatus(eReturnStatusFailed);
1288 return false;
1289 }
1290 add_to_history = false;
1291 command_string = history_string;
1292 original_command_string = history_string;
1293 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001294 }
1295
1296 if (empty_command)
1297 {
1298 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001299 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001300 if (m_command_history.empty())
1301 {
1302 result.AppendError ("empty command");
1303 result.SetStatus(eReturnStatusFailed);
1304 return false;
1305 }
1306 else
1307 {
1308 command_line = m_repeat_command.c_str();
1309 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001310 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001311 if (m_repeat_command.empty())
1312 {
1313 result.AppendErrorWithFormat("No auto repeat.\n");
1314 result.SetStatus (eReturnStatusFailed);
1315 return false;
1316 }
1317 }
1318 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001319 }
1320 else
1321 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001322 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1323 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001324 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001325 }
1326 else if (comment_command)
1327 {
1328 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1329 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001330 }
Caroline Tice649116c2011-05-11 16:07:06 +00001331
Greg Claytonf5c0c722011-10-14 07:41:33 +00001332
1333 Error error (PreprocessCommand (command_string));
1334
1335 if (error.Fail())
1336 {
1337 result.AppendError (error.AsCString());
1338 result.SetStatus(eReturnStatusFailed);
1339 return false;
1340 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001341 // Phase 1.
1342
1343 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1344 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1345 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1346 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1347 // 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 +00001348 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001349 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001350
Caroline Ticee0da7a52010-12-09 22:52:49 +00001351 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001352 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001353 std::string next_word;
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001354 StringList matches;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001355 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001356 {
Caroline Tice649116c2011-05-11 16:07:06 +00001357 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001358 std::string suffix;
1359 ExtractCommand (command_string, next_word, suffix, quote_char);
1360 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001361 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001362 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001363 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001364 std::string alias_result;
1365 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1366 revised_command_line.Printf ("%s", alias_result.c_str());
1367 if (cmd_obj)
1368 {
1369 wants_raw_input = cmd_obj->WantsRawCommandString ();
1370 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1371 }
Chris Lattner24943d22010-06-08 16:52:24 +00001372 }
1373 else
1374 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001375 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001376 if (cmd_obj)
1377 {
1378 actual_cmd_name_len += next_word.length();
1379 revised_command_line.Printf ("%s", next_word.c_str());
1380 wants_raw_input = cmd_obj->WantsRawCommandString ();
1381 }
Caroline Tice649116c2011-05-11 16:07:06 +00001382 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001383 {
1384 revised_command_line.Printf ("%s", next_word.c_str());
1385 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001386 }
1387 }
1388 else
1389 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001390 if (cmd_obj->IsMultiwordObject ())
1391 {
1392 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1393 if (sub_cmd_obj)
1394 {
1395 actual_cmd_name_len += next_word.length() + 1;
1396 revised_command_line.Printf (" %s", next_word.c_str());
1397 cmd_obj = sub_cmd_obj;
1398 wants_raw_input = cmd_obj->WantsRawCommandString ();
1399 }
1400 else
1401 {
1402 if (quote_char)
1403 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1404 else
1405 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1406 done = true;
1407 }
1408 }
Caroline Tice649116c2011-05-11 16:07:06 +00001409 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001410 {
1411 if (quote_char)
1412 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1413 else
1414 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1415 done = true;
1416 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001417 }
1418
1419 if (cmd_obj == NULL)
1420 {
Filipe Cabecinhas4bc8d162012-05-16 23:25:54 +00001421 uint32_t num_matches = matches.GetSize();
1422 if (matches.GetSize() > 1) {
1423 std::string error_msg;
1424 error_msg.assign ("Ambiguous command '");
1425 error_msg.append(next_word.c_str());
1426 error_msg.append ("'.");
1427
1428 error_msg.append (" Possible matches:");
1429
1430 for (uint32_t i = 0; i < num_matches; ++i) {
1431 error_msg.append ("\n\t");
1432 error_msg.append (matches.GetStringAtIndex(i));
1433 }
1434 error_msg.append ("\n");
1435 result.AppendRawError (error_msg.c_str(), error_msg.size());
1436 } else {
1437 // We didn't have only one match, otherwise we wouldn't get here.
1438 assert(num_matches == 0);
1439 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1440 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001441 result.SetStatus (eReturnStatusFailed);
1442 return false;
1443 }
1444
Greg Clayton7268b4c2011-10-28 21:38:01 +00001445 if (cmd_obj->IsMultiwordObject ())
1446 {
1447 if (!suffix.empty())
1448 {
1449
1450 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1451 next_word.c_str(),
1452 suffix.c_str());
1453 result.SetStatus (eReturnStatusFailed);
1454 return false;
1455 }
1456 }
1457 else
1458 {
1459 // If we found a normal command, we are done
1460 done = true;
1461 if (!suffix.empty())
1462 {
1463 switch (suffix[0])
1464 {
1465 case '/':
1466 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001467 {
1468 Options *command_options = cmd_obj->GetOptions();
1469 if (command_options && command_options->SupportsLongOption("gdb-format"))
1470 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001471 std::string gdb_format_option ("--gdb-format=");
1472 gdb_format_option += (suffix.c_str() + 1);
1473
1474 bool inserted = false;
1475 std::string &cmd = revised_command_line.GetString();
1476 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1477 if (arg_terminator_idx != std::string::npos)
1478 {
1479 // Insert the gdb format option before the "--" that terminates options
1480 gdb_format_option.append(1,' ');
1481 cmd.insert(arg_terminator_idx, gdb_format_option);
1482 inserted = true;
1483 }
1484
1485 if (!inserted)
1486 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1487
1488 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1489 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001490 }
1491 else
1492 {
1493 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1494 cmd_obj->GetCommandName());
1495 result.SetStatus (eReturnStatusFailed);
1496 return false;
1497 }
1498 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001499 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001500
1501 default:
1502 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1503 suffix.c_str());
1504 result.SetStatus (eReturnStatusFailed);
1505 return false;
1506
Greg Clayton7268b4c2011-10-28 21:38:01 +00001507 }
1508 }
1509 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001510 if (command_string.length() == 0)
1511 done = true;
1512
Chris Lattner24943d22010-06-08 16:52:24 +00001513 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001514
Greg Clayton7268b4c2011-10-28 21:38:01 +00001515 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001516 revised_command_line.Printf (" %s", command_string.c_str());
1517
1518 // End of Phase 1.
1519 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1520 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1521 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1522 // wants_raw_input specifies whether the Execute method expects raw input or not.
1523
1524
1525 if (log)
1526 {
1527 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1528 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1529 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1530 }
1531
1532 // Phase 2.
1533 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1534 // CommandObject, with the appropriate arguments.
1535
1536 if (cmd_obj != NULL)
1537 {
1538 if (add_to_history)
1539 {
1540 Args command_args (revised_command_line.GetData());
1541 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1542 if (repeat_command != NULL)
1543 m_repeat_command.assign(repeat_command);
1544 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001545 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001546
Jim Ingham6247dbe2011-07-12 03:12:18 +00001547 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001548 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001549 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001550 }
1551
1552 command_string = revised_command_line.GetData();
1553 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001554 std::string remainder;
1555 if (actual_cmd_name_len < command_string.length())
1556 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1557 // than cmd_obj->GetCommandName(), because name completion
1558 // allows users to enter short versions of the names,
1559 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001560
1561 // Remove any initial spaces
1562 std::string white_space (" \t\v");
1563 size_t pos = remainder.find_first_not_of (white_space);
1564 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001565 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001566
1567 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001568 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001569
Jim Inghamda26bd22012-06-08 21:56:10 +00001570 cmd_obj->Execute (remainder.c_str(), result);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001571 }
1572 else
1573 {
1574 // We didn't find the first command object, so complete the first argument.
1575 Args command_args (revised_command_line.GetData());
1576 StringList matches;
1577 int num_matches;
1578 int cursor_index = 0;
1579 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1580 bool word_complete;
1581 num_matches = HandleCompletionMatches (command_args,
1582 cursor_index,
1583 cursor_char_position,
1584 0,
1585 -1,
1586 word_complete,
1587 matches);
1588
1589 if (num_matches > 0)
1590 {
1591 std::string error_msg;
1592 error_msg.assign ("ambiguous command '");
1593 error_msg.append(command_args.GetArgumentAtIndex(0));
1594 error_msg.append ("'.");
1595
1596 error_msg.append (" Possible completions:");
1597 for (int i = 0; i < num_matches; i++)
1598 {
1599 error_msg.append ("\n\t");
1600 error_msg.append (matches.GetStringAtIndex (i));
1601 }
1602 error_msg.append ("\n");
1603 result.AppendRawError (error_msg.c_str(), error_msg.size());
1604 }
1605 else
1606 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1607
1608 result.SetStatus (eReturnStatusFailed);
1609 }
1610
Jason Molenda24c991c2011-08-25 00:20:04 +00001611 if (log)
1612 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1613
Chris Lattner24943d22010-06-08 16:52:24 +00001614 return result.Succeeded();
1615}
1616
1617int
1618CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1619 int &cursor_index,
1620 int &cursor_char_position,
1621 int match_start_point,
1622 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001623 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001624 StringList &matches)
1625{
1626 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001627 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001628
1629 // For any of the command completions a unique match will be a complete word.
1630 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001631
1632 if (cursor_index == -1)
1633 {
1634 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001635 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001636 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1637 }
1638 else if (cursor_index == 0)
1639 {
1640 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001641 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001642 num_command_matches = matches.GetSize();
1643
1644 if (num_command_matches == 1
1645 && cmd_obj && cmd_obj->IsMultiwordObject()
1646 && matches.GetStringAtIndex(0) != NULL
1647 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1648 {
1649 look_for_subcommand = true;
1650 num_command_matches = 0;
1651 matches.DeleteStringAtIndex(0);
1652 parsed_line.AppendArgument ("");
1653 cursor_index++;
1654 cursor_char_position = 0;
1655 }
1656 }
1657
1658 if (cursor_index > 0 || look_for_subcommand)
1659 {
1660 // We are completing further on into a commands arguments, so find the command and tell it
1661 // to complete the command.
1662 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001663 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001664 if (command_object == NULL)
1665 {
1666 return 0;
1667 }
1668 else
1669 {
1670 parsed_line.Shift();
1671 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001672 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001673 cursor_index,
1674 cursor_char_position,
1675 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001676 max_return_elements,
1677 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001678 matches);
1679 }
1680 }
1681
1682 return num_command_matches;
1683
1684}
1685
1686int
1687CommandInterpreter::HandleCompletion (const char *current_line,
1688 const char *cursor,
1689 const char *last_char,
1690 int match_start_point,
1691 int max_return_elements,
1692 StringList &matches)
1693{
1694 // We parse the argument up to the cursor, so the last argument in parsed_line is
1695 // the one containing the cursor, and the cursor is after the last character.
1696
1697 Args parsed_line(current_line, last_char - current_line);
1698 Args partial_parsed_line(current_line, cursor - current_line);
1699
Jim Ingham6247dbe2011-07-12 03:12:18 +00001700 // Don't complete comments, and if the line we are completing is just the history repeat character,
1701 // substitute the appropriate history line.
1702 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1703 if (first_arg)
1704 {
1705 if (first_arg[0] == m_comment_char)
1706 return 0;
1707 else if (first_arg[0] == m_repeat_char)
1708 {
1709 const char *history_string = FindHistoryString (first_arg);
1710 if (history_string != NULL)
1711 {
1712 matches.Clear();
1713 matches.InsertStringAtIndex(0, history_string);
1714 return -2;
1715 }
1716 else
1717 return 0;
1718
1719 }
1720 }
1721
1722
Chris Lattner24943d22010-06-08 16:52:24 +00001723 int num_args = partial_parsed_line.GetArgumentCount();
1724 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1725 int cursor_char_position;
1726
1727 if (cursor_index == -1)
1728 cursor_char_position = 0;
1729 else
1730 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001731
1732 if (cursor > current_line && cursor[-1] == ' ')
1733 {
1734 // We are just after a space. If we are in an argument, then we will continue
1735 // parsing, but if we are between arguments, then we have to complete whatever the next
1736 // element would be.
1737 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1738 // protected by a quote) then the space will also be in the parsed argument...
1739
1740 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1741 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1742 {
1743 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1744 cursor_index++;
1745 cursor_char_position = 0;
1746 }
1747 }
Chris Lattner24943d22010-06-08 16:52:24 +00001748
1749 int num_command_matches;
1750
1751 matches.Clear();
1752
1753 // Only max_return_elements == -1 is supported at present:
1754 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001755 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001756 num_command_matches = HandleCompletionMatches (parsed_line,
1757 cursor_index,
1758 cursor_char_position,
1759 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001760 max_return_elements,
1761 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001762 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001763
1764 if (num_command_matches <= 0)
1765 return num_command_matches;
1766
1767 if (num_args == 0)
1768 {
1769 // If we got an empty string, insert nothing.
1770 matches.InsertStringAtIndex(0, "");
1771 }
1772 else
1773 {
1774 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1775 // put an empty string in element 0.
1776 std::string command_partial_str;
1777 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001778 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1779 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001780
1781 std::string common_prefix;
1782 matches.LongestCommonPrefix (common_prefix);
1783 int partial_name_len = command_partial_str.size();
1784
1785 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001786 // Only do this if the completer told us this was a complete word, however...
1787 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001788 {
1789 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1790 if (quote_char != '\0')
1791 common_prefix.push_back(quote_char);
1792
1793 common_prefix.push_back(' ');
1794 }
1795 common_prefix.erase (0, partial_name_len);
1796 matches.InsertStringAtIndex(0, common_prefix.c_str());
1797 }
1798 return num_command_matches;
1799}
1800
Chris Lattner24943d22010-06-08 16:52:24 +00001801
1802CommandInterpreter::~CommandInterpreter ()
1803{
1804}
1805
1806const char *
1807CommandInterpreter::GetPrompt ()
1808{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001809 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001810}
1811
1812void
1813CommandInterpreter::SetPrompt (const char *new_prompt)
1814{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001815 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001816}
1817
Jim Ingham5e16ef52010-10-04 19:49:29 +00001818size_t
Greg Clayton58928562011-02-09 01:08:52 +00001819CommandInterpreter::GetConfirmationInputReaderCallback
1820(
1821 void *baton,
1822 InputReader &reader,
1823 lldb::InputReaderAction action,
1824 const char *bytes,
1825 size_t bytes_len
1826)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001827{
Greg Clayton58928562011-02-09 01:08:52 +00001828 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001829 bool *response_ptr = (bool *) baton;
1830
1831 switch (action)
1832 {
1833 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001834 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001835 {
1836 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001837 {
Greg Clayton58928562011-02-09 01:08:52 +00001838 out_file.Printf ("%s", reader.GetPrompt());
1839 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001840 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001841 }
1842 break;
1843
1844 case eInputReaderDeactivate:
1845 break;
1846
1847 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001848 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001849 {
Greg Clayton58928562011-02-09 01:08:52 +00001850 out_file.Printf ("%s", reader.GetPrompt());
1851 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001852 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001853 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001854
1855 case eInputReaderAsynchronousOutputWritten:
1856 break;
1857
Jim Ingham5e16ef52010-10-04 19:49:29 +00001858 case eInputReaderGotToken:
1859 if (bytes_len == 0)
1860 {
1861 reader.SetIsDone(true);
1862 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001863 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001864 {
1865 *response_ptr = true;
1866 reader.SetIsDone(true);
1867 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001868 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001869 {
1870 *response_ptr = false;
1871 reader.SetIsDone(true);
1872 }
1873 else
1874 {
Greg Clayton58928562011-02-09 01:08:52 +00001875 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001876 {
Jim Ingham26183802011-11-17 01:22:00 +00001877 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001878 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001879 }
1880 }
1881 break;
1882
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001883 case eInputReaderInterrupt:
1884 case eInputReaderEndOfFile:
1885 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1886 reader.SetIsDone (true);
1887 break;
1888
Jim Ingham5e16ef52010-10-04 19:49:29 +00001889 case eInputReaderDone:
1890 break;
1891 }
1892
1893 return bytes_len;
1894
1895}
1896
1897bool
1898CommandInterpreter::Confirm (const char *message, bool default_answer)
1899{
Jim Ingham93057472010-10-04 22:44:14 +00001900 // Check AutoConfirm first:
1901 if (m_debugger.GetAutoConfirm())
1902 return default_answer;
1903
Jim Ingham5e16ef52010-10-04 19:49:29 +00001904 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1905 bool response = default_answer;
1906 if (reader_sp)
1907 {
1908 std::string prompt(message);
1909 prompt.append(": [");
1910 if (default_answer)
1911 prompt.append ("Y/n] ");
1912 else
1913 prompt.append ("y/N] ");
1914
1915 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1916 &response, // baton
1917 eInputReaderGranularityLine, // token size, to pass to callback function
1918 NULL, // end token
1919 prompt.c_str(), // prompt
1920 true)); // echo input
1921 if (err.Success())
1922 {
1923 GetDebugger().PushInputReader (reader_sp);
1924 }
1925 reader_sp->WaitOnReaderIsDone();
1926 }
1927 return response;
1928}
1929
1930
Chris Lattner24943d22010-06-08 16:52:24 +00001931void
1932CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1933{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001934 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001935
1936 if (cmd_obj_sp != NULL)
1937 {
1938 CommandObject *cmd_obj = cmd_obj_sp.get();
1939 if (cmd_obj->IsCrossRefObject ())
1940 cmd_obj->AddObject (object_type);
1941 }
1942}
1943
Chris Lattner24943d22010-06-08 16:52:24 +00001944OptionArgVectorSP
1945CommandInterpreter::GetAliasOptions (const char *alias_name)
1946{
1947 OptionArgMap::iterator pos;
1948 OptionArgVectorSP ret_val;
1949
1950 std::string alias (alias_name);
1951
1952 if (HasAliasOptions())
1953 {
1954 pos = m_alias_options.find (alias);
1955 if (pos != m_alias_options.end())
1956 ret_val = pos->second;
1957 }
1958
1959 return ret_val;
1960}
1961
1962void
1963CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1964{
1965 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1966 if (pos != m_alias_options.end())
1967 {
1968 m_alias_options.erase (pos);
1969 }
1970}
1971
1972void
1973CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1974{
1975 m_alias_options[alias_name] = option_arg_vector_sp;
1976}
1977
1978bool
1979CommandInterpreter::HasCommands ()
1980{
1981 return (!m_command_dict.empty());
1982}
1983
1984bool
1985CommandInterpreter::HasAliases ()
1986{
1987 return (!m_alias_dict.empty());
1988}
1989
1990bool
1991CommandInterpreter::HasUserCommands ()
1992{
1993 return (!m_user_dict.empty());
1994}
1995
1996bool
1997CommandInterpreter::HasAliasOptions ()
1998{
1999 return (!m_alias_options.empty());
2000}
2001
Chris Lattner24943d22010-06-08 16:52:24 +00002002void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002003CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2004 const char *alias_name,
2005 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00002006 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002007 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00002008{
2009 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00002010
2011 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00002012
Caroline Tice44c841d2010-12-07 19:58:26 +00002013 // Make sure that the alias name is the 0th element in cmd_args
2014 std::string alias_name_str = alias_name;
2015 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2016 cmd_args.Unshift (alias_name);
2017
2018 Args new_args (alias_cmd_obj->GetCommandName());
2019 if (new_args.GetArgumentCount() == 2)
2020 new_args.Shift();
2021
Chris Lattner24943d22010-06-08 16:52:24 +00002022 if (option_arg_vector_sp.get())
2023 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002024 if (wants_raw_input)
2025 {
2026 // We have a command that both has command options and takes raw input. Make *sure* it has a
2027 // " -- " in the right place in the raw_input_string.
2028 size_t pos = raw_input_string.find(" -- ");
2029 if (pos == std::string::npos)
2030 {
2031 // None found; assume it goes at the beginning of the raw input string
2032 raw_input_string.insert (0, " -- ");
2033 }
2034 }
Chris Lattner24943d22010-06-08 16:52:24 +00002035
2036 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
2037 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002038 std::vector<bool> used (old_size + 1, false);
2039
2040 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002041
2042 for (int i = 0; i < option_arg_vector->size(); ++i)
2043 {
2044 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00002045 OptionArgValue value_pair = option_pair.second;
2046 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00002047 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00002048 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00002049 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002050 {
2051 if (!wants_raw_input
2052 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2053 new_args.AppendArgument (value.c_str());
2054 }
Chris Lattner24943d22010-06-08 16:52:24 +00002055 else
2056 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002057 if (value_type != optional_argument)
2058 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002059 if (value.compare ("<no-argument>") != 0)
2060 {
2061 int index = GetOptionArgumentPosition (value.c_str());
2062 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002063 {
Chris Lattner24943d22010-06-08 16:52:24 +00002064 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002065 if (value_type != optional_argument)
2066 new_args.AppendArgument (value.c_str());
2067 else
2068 {
2069 char buffer[255];
2070 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2071 new_args.AppendArgument (buffer);
2072 }
2073
2074 }
Chris Lattner24943d22010-06-08 16:52:24 +00002075 else if (index >= cmd_args.GetArgumentCount())
2076 {
2077 result.AppendErrorWithFormat
2078 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2079 index);
2080 result.SetStatus (eReturnStatusFailed);
2081 return;
2082 }
2083 else
2084 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002085 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2086 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2087 if (strpos != std::string::npos)
2088 {
2089 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2090 }
2091
2092 if (value_type != optional_argument)
2093 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2094 else
2095 {
2096 char buffer[255];
2097 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2098 cmd_args.GetArgumentAtIndex (index));
2099 new_args.AppendArgument (buffer);
2100 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002101 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002102 }
2103 }
2104 }
2105 }
2106
2107 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2108 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002109 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002110 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2111 }
2112
2113 cmd_args.Clear();
2114 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2115 }
2116 else
2117 {
2118 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002119 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2120 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2121 // input string.
2122 if (wants_raw_input)
2123 {
2124 cmd_args.Clear();
2125 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2126 }
Chris Lattner24943d22010-06-08 16:52:24 +00002127 return;
2128 }
2129
2130 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2131 return;
2132}
2133
2134
2135int
2136CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2137{
2138 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2139 // of zero.
2140
2141 char *cptr = (char *) in_string;
2142
2143 // Does it start with '%'
2144 if (cptr[0] == '%')
2145 {
2146 ++cptr;
2147
2148 // Is the rest of it entirely digits?
2149 if (isdigit (cptr[0]))
2150 {
2151 const char *start = cptr;
2152 while (isdigit (cptr[0]))
2153 ++cptr;
2154
2155 // We've gotten to the end of the digits; are we at the end of the string?
2156 if (cptr[0] == '\0')
2157 position = atoi (start);
2158 }
2159 }
2160
2161 return position;
2162}
2163
2164void
2165CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2166{
Jim Ingham574c3d62011-08-12 23:34:31 +00002167 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002168 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002169 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002170 // In the current working directory we don't load any program specific
2171 // .lldbinit files, we only look for a "./.lldbinit" file.
2172 if (m_skip_lldbinit_files)
2173 return;
2174
2175 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002176 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002177 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002178 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002179 // If we aren't looking in the current working directory we are looking
2180 // in the home directory. We will first see if there is an application
2181 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2182 // "-" and the name of the program. If this file doesn't exist, we fall
2183 // back to just the "~/.lldbinit" file. We also obey any requests to not
2184 // load the init files.
2185 const char *init_file_path = "~/.lldbinit";
2186
2187 if (m_skip_app_init_files == false)
2188 {
2189 FileSpec program_file_spec (Host::GetProgramFileSpec());
2190 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002191
Greg Claytond6edcb52011-09-11 00:01:44 +00002192 if (program_name)
2193 {
2194 char program_init_file_name[PATH_MAX];
2195 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2196 init_file.SetFile (program_init_file_name, true);
2197 if (!init_file.Exists())
2198 init_file.Clear();
2199 }
2200 }
2201
2202 if (!init_file && !m_skip_lldbinit_files)
2203 init_file.SetFile (init_file_path, true);
2204 }
2205
Chris Lattner24943d22010-06-08 16:52:24 +00002206 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2207 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2208
2209 if (init_file.Exists())
2210 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002211 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2212 bool stop_on_continue = true;
2213 bool stop_on_error = false;
2214 bool echo_commands = false;
2215 bool print_results = false;
2216
Enrico Granata01bc2d42012-05-31 01:09:06 +00002217 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002218 }
2219 else
2220 {
2221 // nothing to be done if the file doesn't exist
2222 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2223 }
2224}
2225
Greg Claytonb72d0f02011-04-12 05:54:46 +00002226PlatformSP
2227CommandInterpreter::GetPlatform (bool prefer_target_platform)
2228{
2229 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002230 if (prefer_target_platform)
2231 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002232 ExecutionContext exe_ctx(GetExecutionContext());
2233 Target *target = exe_ctx.GetTargetPtr();
Greg Clayton567e7f32011-09-22 04:58:26 +00002234 if (target)
2235 platform_sp = target->GetPlatform();
2236 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002237
2238 if (!platform_sp)
2239 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2240 return platform_sp;
2241}
2242
Jim Ingham949d5ac2011-02-18 00:54:25 +00002243void
Jim Inghama4fede32011-03-11 01:51:49 +00002244CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002245 ExecutionContext *override_context,
2246 bool stop_on_continue,
2247 bool stop_on_error,
2248 bool echo_commands,
2249 bool print_results,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002250 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002251 CommandReturnObject &result)
2252{
2253 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002254
2255 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2256 // Make sure you reset this value anywhere you return from the function.
2257
2258 bool old_async_execution = m_debugger.GetAsyncExecution();
2259
2260 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2261 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2262
2263 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002264 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002265
2266 if (!stop_on_continue)
2267 {
2268 m_debugger.SetAsyncExecution (false);
2269 }
2270
2271 for (int idx = 0; idx < num_lines; idx++)
2272 {
2273 const char *cmd = commands.GetStringAtIndex(idx);
2274 if (cmd[0] == '\0')
2275 continue;
2276
Jim Ingham949d5ac2011-02-18 00:54:25 +00002277 if (echo_commands)
2278 {
2279 result.AppendMessageWithFormat ("%s %s\n",
2280 GetPrompt(),
2281 cmd);
2282 }
2283
Greg Claytonaa378b12011-02-20 02:15:07 +00002284 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002285 // If override_context is not NULL, pass no_context_switching = true for
2286 // HandleCommand() since we updated our context already.
Enrico Granata01bc2d42012-05-31 01:09:06 +00002287 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002288 NULL, /* override_context */
2289 true, /* repeat_on_empty_command */
2290 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002291
2292 if (print_results)
2293 {
2294 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002295 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002296 }
2297
2298 if (!success || !tmp_result.Succeeded())
2299 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002300 const char *error_msg = tmp_result.GetErrorData();
2301 if (error_msg == NULL || error_msg[0] == '\0')
2302 error_msg = "<unknown error>.\n";
Jim Ingham949d5ac2011-02-18 00:54:25 +00002303 if (stop_on_error)
2304 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002305 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2306 idx, cmd, error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002307 result.SetStatus (eReturnStatusFailed);
2308 m_debugger.SetAsyncExecution (old_async_execution);
2309 return;
2310 }
2311 else if (print_results)
2312 {
Jim Ingham862fd5c2012-04-24 02:25:07 +00002313 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Ingham949d5ac2011-02-18 00:54:25 +00002314 idx + 1,
2315 cmd,
Jim Ingham862fd5c2012-04-24 02:25:07 +00002316 error_msg);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002317 }
2318 }
2319
Caroline Tice4a348082011-05-02 20:41:46 +00002320 if (result.GetImmediateOutputStream())
2321 result.GetImmediateOutputStream()->Flush();
2322
2323 if (result.GetImmediateErrorStream())
2324 result.GetImmediateErrorStream()->Flush();
2325
Jim Ingham949d5ac2011-02-18 00:54:25 +00002326 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2327 // could be running (for instance in Breakpoint Commands.
2328 // So we check the return value to see if it is has running in it.
2329 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2330 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2331 {
2332 if (stop_on_continue)
2333 {
2334 // If we caused the target to proceed, and we're going to stop in that case, set the
2335 // status in our real result before returning. This is an error if the continue was not the
2336 // last command in the set of commands to be run.
2337 if (idx != num_lines - 1)
2338 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2339 idx + 1, cmd);
2340 else
2341 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2342
2343 result.SetStatus(tmp_result.GetStatus());
2344 m_debugger.SetAsyncExecution (old_async_execution);
2345
2346 return;
2347 }
2348 }
2349
2350 }
2351
2352 result.SetStatus (eReturnStatusSuccessFinishResult);
2353 m_debugger.SetAsyncExecution (old_async_execution);
2354
2355 return;
2356}
2357
2358void
2359CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2360 ExecutionContext *context,
2361 bool stop_on_continue,
2362 bool stop_on_error,
2363 bool echo_command,
2364 bool print_result,
Enrico Granata01bc2d42012-05-31 01:09:06 +00002365 LazyBool add_to_history,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002366 CommandReturnObject &result)
2367{
2368 if (cmd_file.Exists())
2369 {
2370 bool success;
2371 StringList commands;
2372 success = commands.ReadFileLines(cmd_file);
2373 if (!success)
2374 {
2375 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2376 result.SetStatus (eReturnStatusFailed);
2377 return;
2378 }
Enrico Granata01bc2d42012-05-31 01:09:06 +00002379 m_command_source_depth++;
2380 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2381 m_command_source_depth--;
Jim Ingham949d5ac2011-02-18 00:54:25 +00002382 }
2383 else
2384 {
2385 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2386 cmd_file.GetFilename().AsCString());
2387 result.SetStatus (eReturnStatusFailed);
2388 return;
2389 }
2390}
2391
Chris Lattner24943d22010-06-08 16:52:24 +00002392ScriptInterpreter *
2393CommandInterpreter::GetScriptInterpreter ()
2394{
Enrico Granatac5c10a42012-07-10 18:23:48 +00002395 // <rdar://problem/11751427>
2396 // we need to protect the initialization of the script interpreter
2397 // otherwise we could end up with two threads both trying to create
2398 // their instance of it, and for some languages (e.g. Python)
2399 // this is a bulletproof recipe for disaster!
2400 // this needs to be a function-level static because multiple Debugger instances living in the same process
2401 // still need to be isolated and not try to initialize Python concurrently
Enrico Granatab88c0a92012-07-10 19:04:14 +00002402 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2403 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granatac5c10a42012-07-10 18:23:48 +00002404
Caroline Tice0aa2e552011-01-14 00:29:16 +00002405 if (m_script_interpreter_ap.get() != NULL)
2406 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002407
Caroline Tice0aa2e552011-01-14 00:29:16 +00002408 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2409 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002410 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002411 case eScriptLanguagePython:
2412#ifndef LLDB_DISABLE_PYTHON
2413 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2414 break;
2415#else
2416 // Fall through to the None case when python is disabled
2417#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002418 case eScriptLanguageNone:
2419 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2420 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002421 default:
2422 break;
2423 };
2424
2425 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002426}
2427
2428
2429
2430bool
2431CommandInterpreter::GetSynchronous ()
2432{
2433 return m_synchronous_execution;
2434}
2435
2436void
2437CommandInterpreter::SetSynchronous (bool value)
2438{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002439 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002440}
2441
2442void
2443CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2444 const char *word_text,
2445 const char *separator,
2446 const char *help_text,
2447 uint32_t max_word_len)
2448{
Greg Clayton238c0a12010-09-18 01:14:36 +00002449 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2450
Chris Lattner24943d22010-06-08 16:52:24 +00002451 int indent_size = max_word_len + strlen (separator) + 2;
2452
2453 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002454
2455 StreamString text_strm;
2456 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2457
2458 size_t len = text_strm.GetSize();
2459 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002460 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002461 {
2462 text_strm.EOL();
2463 len = text_strm.GetSize();
2464 }
Chris Lattner24943d22010-06-08 16:52:24 +00002465
2466 if (len < max_columns)
2467 {
2468 // Output it as a single line.
2469 strm.Printf ("%s", text);
2470 }
2471 else
2472 {
2473 // We need to break it up into multiple lines.
2474 bool first_line = true;
2475 int text_width;
2476 int start = 0;
2477 int end = start;
2478 int final_end = strlen (text);
2479 int sub_len;
2480
2481 while (end < final_end)
2482 {
2483 if (first_line)
2484 text_width = max_columns - 1;
2485 else
2486 text_width = max_columns - indent_size - 1;
2487
2488 // Don't start the 'text' on a space, since we're already outputting the indentation.
2489 if (!first_line)
2490 {
2491 while ((start < final_end) && (text[start] == ' '))
2492 start++;
2493 }
2494
2495 end = start + text_width;
2496 if (end > final_end)
2497 end = final_end;
2498 else
2499 {
2500 // If we're not at the end of the text, make sure we break the line on white space.
2501 while (end > start
2502 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2503 end--;
2504 }
2505
2506 sub_len = end - start;
2507 if (start != 0)
2508 strm.EOL();
2509 if (!first_line)
2510 strm.Indent();
2511 else
2512 first_line = false;
2513 assert (start <= final_end);
2514 assert (start + sub_len <= final_end);
2515 if (sub_len > 0)
2516 strm.Write (text + start, sub_len);
2517 start = end + 1;
2518 }
2519 }
2520 strm.EOL();
2521 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002522}
2523
2524void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002525CommandInterpreter::OutputHelpText (Stream &strm,
2526 const char *word_text,
2527 const char *separator,
2528 const char *help_text,
2529 uint32_t max_word_len)
2530{
2531 int indent_size = max_word_len + strlen (separator) + 2;
2532
2533 strm.IndentMore (indent_size);
2534
2535 StreamString text_strm;
2536 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2537
2538 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2539 bool first_line = true;
2540
2541 size_t len = text_strm.GetSize();
2542 const char *text = text_strm.GetData();
2543
2544 uint32_t chars_left = max_columns;
2545
2546 for (uint32_t i = 0; i < len; i++)
2547 {
2548 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2549 {
2550 first_line = false;
2551 chars_left = max_columns - indent_size;
2552 strm.EOL();
2553 strm.Indent();
2554 }
2555 else
2556 {
2557 strm.PutChar(text[i]);
2558 chars_left--;
2559 }
2560
2561 }
2562
2563 strm.EOL();
2564 strm.IndentLess(indent_size);
2565}
2566
2567void
Chris Lattner24943d22010-06-08 16:52:24 +00002568CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2569 StringList &commands_found, StringList &commands_help)
2570{
2571 CommandObject::CommandMap::const_iterator pos;
2572 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2573 CommandObject *sub_cmd_obj;
2574
2575 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2576 {
2577 const char * command_name = pos->first.c_str();
2578 sub_cmd_obj = pos->second.get();
2579 StreamString complete_command_name;
2580
2581 complete_command_name.Printf ("%s %s", prefix, command_name);
2582
Greg Clayton238c0a12010-09-18 01:14:36 +00002583 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002584 {
2585 commands_found.AppendString (complete_command_name.GetData());
2586 commands_help.AppendString (sub_cmd_obj->GetHelp());
2587 }
2588
2589 if (sub_cmd_obj->IsMultiwordObject())
2590 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2591 commands_help);
2592 }
2593
2594}
2595
2596void
2597CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2598 StringList &commands_help)
2599{
2600 CommandObject::CommandMap::const_iterator pos;
2601
2602 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2603 {
2604 const char *command_name = pos->first.c_str();
2605 CommandObject *cmd_obj = pos->second.get();
2606
Greg Clayton238c0a12010-09-18 01:14:36 +00002607 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002608 {
2609 commands_found.AppendString (command_name);
2610 commands_help.AppendString (cmd_obj->GetHelp());
2611 }
2612
2613 if (cmd_obj->IsMultiwordObject())
2614 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2615
2616 }
2617}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002618
2619
2620void
2621CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2622{
Greg Claytonb72d0f02011-04-12 05:54:46 +00002623 if (override_context != NULL)
2624 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002625 m_exe_ctx_ref = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002626 }
2627 else
2628 {
Greg Claytonbcaf99a2012-07-12 20:32:19 +00002629 const bool adopt_selected = true;
2630 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002631 }
2632}
2633
Jim Ingham6247dbe2011-07-12 03:12:18 +00002634void
2635CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2636{
2637 DumpHistory (stream, 0, count - 1);
2638}
2639
2640void
2641CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2642{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002643 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2644 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002645 {
2646 if (!m_command_history[i].empty())
2647 {
2648 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002649 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002650 }
2651 }
2652}
2653
2654const char *
2655CommandInterpreter::FindHistoryString (const char *input_str) const
2656{
2657 if (input_str[0] != m_repeat_char)
2658 return NULL;
2659 if (input_str[1] == '-')
2660 {
2661 bool success;
2662 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2663 if (!success)
2664 return NULL;
2665 if (idx > m_command_history.size())
2666 return NULL;
2667 idx = m_command_history.size() - idx;
2668 return m_command_history[idx].c_str();
2669
2670 }
2671 else if (input_str[1] == m_repeat_char)
2672 {
2673 if (m_command_history.empty())
2674 return NULL;
2675 else
2676 return m_command_history.back().c_str();
2677 }
2678 else
2679 {
2680 bool success;
2681 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2682 if (!success)
2683 return NULL;
2684 if (idx >= m_command_history.size())
2685 return NULL;
2686 return m_command_history[idx].c_str();
2687 }
2688}