blob: 43bb6544ac57de69634835a8dd2becda022d727d [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
62CommandInterpreter::CommandInterpreter
63(
Greg Clayton63094e02010-06-23 01:19:29 +000064 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000065 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000066 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000067) :
Greg Clayton49ce6822010-10-31 03:01:06 +000068 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000069 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000070 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000071 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000072 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000073 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +000074 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +000075 m_repeat_char ('!'),
Enrico Granata293a7b32011-08-15 19:24:02 +000076 m_batch_command_mode (false),
77 m_truncation_warning(eNoTruncation)
Chris Lattner24943d22010-06-08 16:52:24 +000078{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000079 const char *dbg_name = debugger.GetInstanceName().AsCString();
80 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
81 StreamString var_name;
82 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000083 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000084 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000085 m_debugger.GetInstanceName().AsCString());
86 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
87 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
88 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000089}
90
91void
92CommandInterpreter::Initialize ()
93{
94 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
95
96 CommandReturnObject result;
97
98 LoadCommandDictionary ();
99
Chris Lattner24943d22010-06-08 16:52:24 +0000100 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000101 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
102 if (cmd_obj_sp)
103 {
104 AddAlias ("q", cmd_obj_sp);
105 AddAlias ("exit", cmd_obj_sp);
106 }
107
108 cmd_obj_sp = GetCommandSPExact ("process continue", false);
109 if (cmd_obj_sp)
110 {
111 AddAlias ("c", cmd_obj_sp);
112 AddAlias ("continue", cmd_obj_sp);
113 }
114
115 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
116 if (cmd_obj_sp)
117 AddAlias ("b", cmd_obj_sp);
118
119 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
120 if (cmd_obj_sp)
121 AddAlias ("bt", cmd_obj_sp);
122
123 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
124 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000125 {
126 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000127 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000128 }
129
130 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
131 if (cmd_obj_sp)
132 {
133 AddAlias ("nexti", cmd_obj_sp);
134 AddAlias ("ni", cmd_obj_sp);
135 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000136
137 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
138 if (cmd_obj_sp)
139 {
140 AddAlias ("s", cmd_obj_sp);
141 AddAlias ("step", cmd_obj_sp);
142 }
143
144 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
145 if (cmd_obj_sp)
146 {
147 AddAlias ("n", cmd_obj_sp);
148 AddAlias ("next", cmd_obj_sp);
149 }
150
151 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
152 if (cmd_obj_sp)
153 {
154 AddAlias ("f", cmd_obj_sp);
155 AddAlias ("finish", cmd_obj_sp);
156 }
157
158 cmd_obj_sp = GetCommandSPExact ("source list", false);
159 if (cmd_obj_sp)
160 {
161 AddAlias ("l", cmd_obj_sp);
162 AddAlias ("list", cmd_obj_sp);
163 }
164
165 cmd_obj_sp = GetCommandSPExact ("memory read", false);
166 if (cmd_obj_sp)
167 AddAlias ("x", cmd_obj_sp);
168
169 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
170 if (cmd_obj_sp)
171 AddAlias ("up", cmd_obj_sp);
172
173 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
174 if (cmd_obj_sp)
175 AddAlias ("down", cmd_obj_sp);
176
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000177 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000178 if (cmd_obj_sp)
179 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000180
181 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
182 if (cmd_obj_sp)
183 AddAlias ("dis", cmd_obj_sp);
184
185 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
186 if (cmd_obj_sp)
187 AddAlias ("di", cmd_obj_sp);
188
189
Jason Molenda730cae02011-10-22 01:30:52 +0000190
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000191 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000192 if (cmd_obj_sp)
193 AddAlias ("undisplay", cmd_obj_sp);
194
Caroline Tice5ddbe212011-05-06 21:37:15 +0000195 cmd_obj_sp = GetCommandSPExact ("target create", false);
196 if (cmd_obj_sp)
197 AddAlias ("file", cmd_obj_sp);
198
199 cmd_obj_sp = GetCommandSPExact ("target modules", false);
200 if (cmd_obj_sp)
201 AddAlias ("image", cmd_obj_sp);
202
203
204 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000205
Caroline Tice5ddbe212011-05-06 21:37:15 +0000206 cmd_obj_sp = GetCommandSPExact ("expression", false);
207 if (cmd_obj_sp)
208 {
209 AddAlias ("expr", cmd_obj_sp);
210
211 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
212 AddAlias ("p", cmd_obj_sp);
213 AddAlias ("print", cmd_obj_sp);
214 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
215 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
216
217 alias_arguments_vector_sp.reset (new OptionArgVector);
218 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
219 AddAlias ("po", cmd_obj_sp);
220 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
221 }
222
223 cmd_obj_sp = GetCommandSPExact ("process launch", false);
224 if (cmd_obj_sp)
225 {
226 alias_arguments_vector_sp.reset (new OptionArgVector);
227 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
228 AddAlias ("r", cmd_obj_sp);
229 AddAlias ("run", cmd_obj_sp);
230 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
231 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
232 }
Chris Lattner24943d22010-06-08 16:52:24 +0000233}
234
Chris Lattner24943d22010-06-08 16:52:24 +0000235const char *
236CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
237{
238 // This function has not yet been implemented.
239
240 // Look for any embedded script command
241 // If found,
242 // get interpreter object from the command dictionary,
243 // call execute_one_command on it,
244 // get the results as a string,
245 // substitute that string for current stuff.
246
247 return arg;
248}
249
250
251void
252CommandInterpreter::LoadCommandDictionary ()
253{
254 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
255
256 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
257 //
258 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
259 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
260 // the cross-referencing stuff) are created!!!
261 //
262 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
263
264
265 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
266 // are created. This is so that when another command is created that needs to go into a crossref object,
267 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
268 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
269
Chris Lattner24943d22010-06-08 16:52:24 +0000270 // Non-CommandObjectCrossref commands can now be created.
271
Caroline Tice5bc8c972010-09-20 20:44:43 +0000272 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000273
Greg Clayton238c0a12010-09-18 01:14:36 +0000274 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000275 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000276 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000277 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000278 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
279 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000280// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000281 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000282 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000283 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000284 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
285 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000286 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000287 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000288 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000289 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000290 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000291 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000292 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000293 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
294 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000295 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000296 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000297 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000298
299 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000300 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000301 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000302 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000303 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000304 if (break_regex_cmd_ap.get())
305 {
306 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
307 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
308 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000309 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000310 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000311 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000312 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
313 {
314 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
315 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
316 }
317 }
Jim Inghame56493f2011-03-22 02:29:32 +0000318
319 std::auto_ptr<CommandObjectRegexCommand>
320 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000321 "_regexp-down",
322 "Go down \"n\" frames in the stack (1 frame by default).",
323 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000324 if (down_regex_cmd_ap.get())
325 {
326 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
327 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
328 {
329 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
330 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
331 }
332 }
333
334 std::auto_ptr<CommandObjectRegexCommand>
335 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000336 "_regexp-up",
337 "Go up \"n\" frames in the stack (1 frame by default).",
338 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000339 if (up_regex_cmd_ap.get())
340 {
341 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
342 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
343 {
344 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
345 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
346 }
347 }
Jason Molenda730cae02011-10-22 01:30:52 +0000348
349 std::auto_ptr<CommandObjectRegexCommand>
350 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000351 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000352 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000353 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000354 if (display_regex_cmd_ap.get())
355 {
356 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
357 {
358 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
359 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
360 }
361 }
362
363 std::auto_ptr<CommandObjectRegexCommand>
364 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000365 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000366 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000367 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000368 if (undisplay_regex_cmd_ap.get())
369 {
370 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
371 {
372 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
373 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
374 }
375 }
376
Chris Lattner24943d22010-06-08 16:52:24 +0000377}
378
379int
380CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
381 StringList &matches)
382{
383 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
384
385 if (include_aliases)
386 {
387 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
388 }
389
390 return matches.GetSize();
391}
392
393CommandObjectSP
394CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
395{
396 CommandObject::CommandMap::iterator pos;
397 CommandObjectSP ret_val;
398
399 std::string cmd(cmd_cstr);
400
401 if (HasCommands())
402 {
403 pos = m_command_dict.find(cmd);
404 if (pos != m_command_dict.end())
405 ret_val = pos->second;
406 }
407
408 if (include_aliases && HasAliases())
409 {
410 pos = m_alias_dict.find(cmd);
411 if (pos != m_alias_dict.end())
412 ret_val = pos->second;
413 }
414
415 if (HasUserCommands())
416 {
417 pos = m_user_dict.find(cmd);
418 if (pos != m_user_dict.end())
419 ret_val = pos->second;
420 }
421
422 if (!exact && ret_val == NULL)
423 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000424 // We will only get into here if we didn't find any exact matches.
425
426 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
427
Chris Lattner24943d22010-06-08 16:52:24 +0000428 StringList local_matches;
429 if (matches == NULL)
430 matches = &local_matches;
431
Jim Inghamd40f8a62010-07-06 22:46:59 +0000432 unsigned int num_cmd_matches = 0;
433 unsigned int num_alias_matches = 0;
434 unsigned int num_user_matches = 0;
435
436 // Look through the command dictionaries one by one, and if we get only one match from any of
437 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
438
Chris Lattner24943d22010-06-08 16:52:24 +0000439 if (HasCommands())
440 {
441 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
442 }
443
444 if (num_cmd_matches == 1)
445 {
446 cmd.assign(matches->GetStringAtIndex(0));
447 pos = m_command_dict.find(cmd);
448 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000449 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000450 }
451
Jim Ingham9a574172010-06-24 20:28:42 +0000452 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000453 {
454 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
455
456 }
457
Jim Inghamd40f8a62010-07-06 22:46:59 +0000458 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000459 {
460 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
461 pos = m_alias_dict.find(cmd);
462 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000463 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000464 }
465
Jim Ingham9a574172010-06-24 20:28:42 +0000466 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000467 {
468 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
469 }
470
Jim Inghamd40f8a62010-07-06 22:46:59 +0000471 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000472 {
473 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
474
475 pos = m_user_dict.find (cmd);
476 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000477 user_match_sp = pos->second;
478 }
479
480 // If we got exactly one match, return that, otherwise return the match list.
481
482 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
483 {
484 if (num_cmd_matches)
485 return real_match_sp;
486 else if (num_alias_matches)
487 return alias_match_sp;
488 else
489 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000490 }
491 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000492 else if (matches && ret_val != NULL)
493 {
494 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000495 }
496
497
498 return ret_val;
499}
500
Greg Claytond12aeab2011-04-20 16:37:46 +0000501bool
502CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
503{
504 if (name && name[0])
505 {
506 std::string name_sstr(name);
507 if (!can_replace)
508 {
509 if (m_command_dict.find (name_sstr) != m_command_dict.end())
510 return false;
511 }
512 m_command_dict[name_sstr] = cmd_sp;
513 return true;
514 }
515 return false;
516}
517
Enrico Granata6b1596d2011-08-16 23:24:13 +0000518bool
519CommandInterpreter::AddUserCommand (const char *name,
520 const lldb::CommandObjectSP &cmd_sp,
521 bool can_replace)
522{
523 if (name && name[0])
524 {
525 std::string name_sstr(name);
526 if (!can_replace)
527 {
528 if (m_user_dict.find (name_sstr) != m_user_dict.end())
529 return false;
530 }
531 m_user_dict[name_sstr] = cmd_sp;
532 return true;
533 }
534 return false;
535}
Greg Claytond12aeab2011-04-20 16:37:46 +0000536
Jim Inghamd40f8a62010-07-06 22:46:59 +0000537CommandObjectSP
538CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000539{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000540 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
541 CommandObjectSP ret_val; // Possibly empty return value.
542
543 if (cmd_cstr == NULL)
544 return ret_val;
545
546 if (cmd_words.GetArgumentCount() == 1)
547 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
548 else
549 {
550 // We have a multi-word command (seemingly), so we need to do more work.
551 // First, get the cmd_obj_sp for the first word in the command.
552 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
553 if (cmd_obj_sp.get() != NULL)
554 {
555 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
556 // command name), and find the appropriate sub-command SP for each command word....
557 size_t end = cmd_words.GetArgumentCount();
558 for (size_t j= 1; j < end; ++j)
559 {
560 if (cmd_obj_sp->IsMultiwordObject())
561 {
562 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
563 (cmd_words.GetArgumentAtIndex (j));
564 if (cmd_obj_sp.get() == NULL)
565 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
566 return ret_val;
567 }
568 else
569 // We have more words in the command name, but we don't have a multiword object. Fail and return
570 // empty 'ret_val'.
571 return ret_val;
572 }
573 // We successfully looped through all the command words and got valid command objects for them. Assign the
574 // last object retrieved to 'ret_val'.
575 ret_val = cmd_obj_sp;
576 }
577 }
578 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000579}
580
581CommandObject *
582CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
583{
584 return GetCommandSPExact (cmd_cstr, include_aliases).get();
585}
586
587CommandObject *
588CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
589{
590 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
591
592 // If we didn't find an exact match to the command string in the commands, look in
593 // the aliases.
594
595 if (command_obj == NULL)
596 {
597 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
598 }
599
600 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
601 // in both the commands and the aliases.
602
603 if (command_obj == NULL)
604 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
605
606 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000607}
608
609bool
610CommandInterpreter::CommandExists (const char *cmd)
611{
612 return m_command_dict.find(cmd) != m_command_dict.end();
613}
614
615bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000616CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
617 const char *options_args,
618 OptionArgVectorSP &option_arg_vector_sp)
619{
620 bool success = true;
621 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
622
623 if (!options_args || (strlen (options_args) < 1))
624 return true;
625
626 std::string options_string (options_args);
627 Args args (options_args);
628 CommandReturnObject result;
629 // Check to see if the command being aliased can take any command options.
630 Options *options = cmd_obj_sp->GetOptions ();
631 if (options)
632 {
633 // See if any options were specified as part of the alias; if so, handle them appropriately.
634 options->NotifyOptionParsingStarting ();
635 args.Unshift ("dummy_arg");
636 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
637 args.Shift ();
638 if (result.Succeeded())
639 options->VerifyPartialOptions (result);
640 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
641 {
642 result.AppendError ("Unable to create requested alias.\n");
643 return false;
644 }
645 }
646
647 if (options_string.size() > 0)
648 {
649 if (cmd_obj_sp->WantsRawCommandString ())
650 option_arg_vector->push_back (OptionArgPair ("<argument>",
651 OptionArgValue (-1,
652 options_string)));
653 else
654 {
655 int argc = args.GetArgumentCount();
656 for (size_t i = 0; i < argc; ++i)
657 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
658 option_arg_vector->push_back
659 (OptionArgPair ("<argument>",
660 OptionArgValue (-1,
661 std::string (args.GetArgumentAtIndex (i)))));
662 }
663 }
664
665 return success;
666}
667
668bool
Chris Lattner24943d22010-06-08 16:52:24 +0000669CommandInterpreter::AliasExists (const char *cmd)
670{
671 return m_alias_dict.find(cmd) != m_alias_dict.end();
672}
673
674bool
675CommandInterpreter::UserCommandExists (const char *cmd)
676{
677 return m_user_dict.find(cmd) != m_user_dict.end();
678}
679
680void
681CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
682{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000683 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000684 m_alias_dict[alias_name] = command_obj_sp;
685}
686
687bool
688CommandInterpreter::RemoveAlias (const char *alias_name)
689{
690 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
691 if (pos != m_alias_dict.end())
692 {
693 m_alias_dict.erase(pos);
694 return true;
695 }
696 return false;
697}
698bool
699CommandInterpreter::RemoveUser (const char *alias_name)
700{
701 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
702 if (pos != m_user_dict.end())
703 {
704 m_user_dict.erase(pos);
705 return true;
706 }
707 return false;
708}
709
Chris Lattner24943d22010-06-08 16:52:24 +0000710void
711CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
712{
713 help_string.Printf ("'%s", command_name);
714 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
715
716 if (option_arg_vector_sp != NULL)
717 {
718 OptionArgVector *options = option_arg_vector_sp.get();
719 for (int i = 0; i < options->size(); ++i)
720 {
721 OptionArgPair cur_option = (*options)[i];
722 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000723 OptionArgValue value_pair = cur_option.second;
724 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000725 if (opt.compare("<argument>") == 0)
726 {
727 help_string.Printf (" %s", value.c_str());
728 }
729 else
730 {
731 help_string.Printf (" %s", opt.c_str());
732 if ((value.compare ("<no-argument>") != 0)
733 && (value.compare ("<need-argument") != 0))
734 {
735 help_string.Printf (" %s", value.c_str());
736 }
737 }
738 }
739 }
740
741 help_string.Printf ("'");
742}
743
Greg Clayton65124ea2010-08-26 22:05:43 +0000744size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000745CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
746{
747 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000748 CommandObject::CommandMap::const_iterator end = dict.end();
749 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000750
Greg Clayton65124ea2010-08-26 22:05:43 +0000751 for (pos = dict.begin(); pos != end; ++pos)
752 {
753 size_t len = pos->first.size();
754 if (max_len < len)
755 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000756 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000757 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000758}
759
760void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000761CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000762 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000763{
764 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000765 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000766
767 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000768 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000769
770 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
771 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000772
Enrico Granata6b1596d2011-08-16 23:24:13 +0000773 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
774 {
775 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
776 max_len);
777 }
778 result.AppendMessage("");
779
780 }
781
782 if (m_alias_dict.size() > 0 && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000783 {
Jim Inghame3663e82010-10-22 18:47:16 +0000784 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000785 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000786 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000787 max_len = FindLongestCommandWord (m_alias_dict);
788
Chris Lattner24943d22010-06-08 16:52:24 +0000789 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
790 {
791 StreamString sstr;
792 StreamString translation_and_help;
793 std::string entry_name = pos->first;
794 std::string second_entry = pos->second.get()->GetCommandName();
795 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
796
797 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
798 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
799 translation_and_help.GetData(), max_len);
800 }
801 result.AppendMessage("");
802 }
803
Enrico Granata6b1596d2011-08-16 23:24:13 +0000804 if (m_user_dict.size() > 0 && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000805 {
806 result.AppendMessage ("The following is a list of your current user-defined commands:");
807 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000808 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000809 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
810 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000811 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
812 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000813 }
814 result.AppendMessage("");
815 }
816
817 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
818}
819
Caroline Ticee0da7a52010-12-09 22:52:49 +0000820CommandObject *
821CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000822{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000823 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
824 // eventually be invoked by the given command line.
825
826 CommandObject *cmd_obj = NULL;
827 std::string white_space (" \t\v");
828 size_t start = command_string.find_first_not_of (white_space);
829 size_t end = 0;
830 bool done = false;
831 while (!done)
832 {
833 if (start != std::string::npos)
834 {
835 // Get the next word from command_string.
836 end = command_string.find_first_of (white_space, start);
837 if (end == std::string::npos)
838 end = command_string.size();
839 std::string cmd_word = command_string.substr (start, end - start);
840
841 if (cmd_obj == NULL)
842 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
843 // command or alias.
844 cmd_obj = GetCommandObject (cmd_word.c_str());
845 else if (cmd_obj->IsMultiwordObject ())
846 {
847 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
848 CommandObject *sub_cmd_obj =
849 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
850 if (sub_cmd_obj)
851 cmd_obj = sub_cmd_obj;
852 else // cmd_word was not a valid sub-command word, so we are donee
853 done = true;
854 }
855 else
856 // We have a cmd_obj and it is not a multi-word object, so we are done.
857 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000858
Caroline Ticee0da7a52010-12-09 22:52:49 +0000859 // If we didn't find a valid command object, or our command object is not a multi-word object, or
860 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
861 // next word.
862
863 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
864 done = true;
865 else
866 start = command_string.find_first_not_of (white_space, end);
867 }
868 else
869 // Unable to find any more words.
870 done = true;
871 }
872
873 if (end == command_string.size())
874 command_string.clear();
875 else
876 command_string = command_string.substr(end);
877
878 return cmd_obj;
879}
880
Greg Clayton9d855c62011-10-25 00:36:27 +0000881static const char *k_white_space = " \t\v";
882
883static void
884StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000885{
Greg Clayton9d855c62011-10-25 00:36:27 +0000886 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000887 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000888 size_t pos = s.find_first_not_of (k_white_space);
889 if (pos == std::string::npos)
890 s.clear();
891 else if (pos == 0)
892 return;
893 s.erase (0, pos);
894 }
895}
896
897static bool
898StripFirstWord (std::string &command_string, std::string &word, char &quote_char)
899{
900 word.clear();
901 StripLeadingSpaces (command_string);
902
903 bool result = false;
904 quote_char = '\0';
905
906 if (!command_string.empty())
907 {
908 const char first_char = command_string[0];
909 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000910 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000911 quote_char = first_char;
912 const size_t end_quote_pos = command_string.find (quote_char, 1);
913 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000914 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000915 word.swap (command_string);
916 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000917 }
918 else
919 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000920 word = command_string.substr (1, end_quote_pos - 1);
921 if (end_quote_pos + 1 < command_string.size())
922 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
923 else
924 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000925 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000926 }
927 else
928 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000929 const size_t first_space_pos = command_string.find_first_of (k_white_space);
930 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000931 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000932 word.swap (command_string);
933 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +0000934 }
935 else
936 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000937 word = command_string.substr (0, first_space_pos);
938 command_string.erase(0,command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +0000939 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000940 }
Greg Clayton9d855c62011-10-25 00:36:27 +0000941 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000942 }
Greg Clayton9d855c62011-10-25 00:36:27 +0000943
944 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000945}
946
947void
948CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
949 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
950{
951 Args cmd_args (raw_input_string.c_str());
952 alias_cmd_obj = GetCommandObject (alias_name);
953 StreamString result_str;
954
955 if (alias_cmd_obj)
956 {
957 std::string alias_name_str = alias_name;
958 if ((cmd_args.GetArgumentCount() == 0)
959 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
960 cmd_args.Unshift (alias_name);
961
962 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
963 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
964
965 if (option_arg_vector_sp.get())
966 {
967 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
968
969 for (int i = 0; i < option_arg_vector->size(); ++i)
970 {
971 OptionArgPair option_pair = (*option_arg_vector)[i];
972 OptionArgValue value_pair = option_pair.second;
973 int value_type = value_pair.first;
974 std::string option = option_pair.first;
975 std::string value = value_pair.second;
976 if (option.compare ("<argument>") == 0)
977 result_str.Printf (" %s", value.c_str());
978 else
979 {
980 result_str.Printf (" %s", option.c_str());
981 if (value_type != optional_argument)
982 result_str.Printf (" ");
983 if (value.compare ("<no_argument>") != 0)
984 {
985 int index = GetOptionArgumentPosition (value.c_str());
986 if (index == 0)
987 result_str.Printf ("%s", value.c_str());
988 else if (index >= cmd_args.GetArgumentCount())
989 {
990
991 result.AppendErrorWithFormat
992 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
993 index);
994 result.SetStatus (eReturnStatusFailed);
995 return;
996 }
997 else
998 {
999 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1000 if (strpos != std::string::npos)
1001 raw_input_string = raw_input_string.erase (strpos,
1002 strlen (cmd_args.GetArgumentAtIndex (index)));
1003 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1004 }
1005 }
1006 }
1007 }
1008 }
1009
1010 alias_result = result_str.GetData();
1011 }
1012}
1013
Greg Claytonf5c0c722011-10-14 07:41:33 +00001014Error
1015CommandInterpreter::PreprocessCommand (std::string &command)
1016{
1017 // The command preprocessor needs to do things to the command
1018 // line before any parsing of arguments or anything else is done.
1019 // The only current stuff that gets proprocessed is anyting enclosed
1020 // in backtick ('`') characters is evaluated as an expression and
1021 // the result of the expression must be a scalar that can be substituted
1022 // into the command. An example would be:
1023 // (lldb) memory read `$rsp + 20`
1024 Error error; // Error for any expressions that might not evaluate
1025 size_t start_backtick;
1026 size_t pos = 0;
1027 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1028 {
1029 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1030 {
1031 // The backtick was preceeded by a '\' character, remove the slash
1032 // and don't treat the backtick as the start of an expression
1033 command.erase(start_backtick-1, 1);
1034 // No need to add one to start_backtick since we just deleted a char
1035 pos = start_backtick;
1036 }
1037 else
1038 {
1039 const size_t expr_content_start = start_backtick + 1;
1040 const size_t end_backtick = command.find ('`', expr_content_start);
1041 if (end_backtick == std::string::npos)
1042 return error;
1043 else if (end_backtick == expr_content_start)
1044 {
1045 // Empty expression (two backticks in a row)
1046 command.erase (start_backtick, 2);
1047 }
1048 else
1049 {
1050 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1051
1052 Target *target = m_exe_ctx.GetTargetPtr();
1053 if (target)
1054 {
1055 const bool unwind_on_error = true;
1056 const bool keep_in_memory = false;
1057 ValueObjectSP expr_result_valobj_sp;
1058 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1059 m_exe_ctx.GetFramePtr(),
1060 eExecutionPolicyOnlyWhenNeeded,
1061 unwind_on_error, keep_in_memory,
1062 eNoDynamicValues,
1063 expr_result_valobj_sp);
1064 if (expr_result == eExecutionCompleted)
1065 {
1066 Scalar scalar;
1067 if (expr_result_valobj_sp->ResolveValue (scalar))
1068 {
1069 command.erase (start_backtick, end_backtick - start_backtick + 1);
1070 StreamString value_strm;
1071 const bool show_type = false;
1072 scalar.GetValue (&value_strm, show_type);
1073 size_t value_string_size = value_strm.GetSize();
1074 if (value_string_size)
1075 {
1076 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1077 pos = start_backtick + value_string_size;
1078 continue;
1079 }
1080 else
1081 {
1082 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1083 }
1084 }
1085 else
1086 {
1087 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1088 }
1089 }
1090 else
1091 {
1092 if (expr_result_valobj_sp)
1093 error = expr_result_valobj_sp->GetError();
1094 if (error.Success())
1095 {
1096
1097 switch (expr_result)
1098 {
1099 case eExecutionSetupError:
1100 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1101 break;
1102 case eExecutionCompleted:
1103 break;
1104 case eExecutionDiscarded:
1105 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1106 break;
1107 case eExecutionInterrupted:
1108 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1109 break;
1110 case eExecutionTimedOut:
1111 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1112 break;
1113 }
1114 }
1115 }
1116 }
1117 }
1118 if (error.Fail())
1119 break;
1120 }
1121 }
1122 return error;
1123}
1124
1125
Caroline Ticee0da7a52010-12-09 22:52:49 +00001126bool
1127CommandInterpreter::HandleCommand (const char *command_line,
1128 bool add_to_history,
1129 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001130 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001131 bool repeat_on_empty_command,
1132 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001133
Caroline Ticee0da7a52010-12-09 22:52:49 +00001134{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001135
Caroline Ticee0da7a52010-12-09 22:52:49 +00001136 bool done = false;
1137 CommandObject *cmd_obj = NULL;
1138 std::string next_word;
1139 bool wants_raw_input = false;
1140 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001141 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001142
1143 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001144 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1145
1146 // Make a scoped cleanup object that will clear the crash description string
1147 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001148 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001149
Caroline Ticee0da7a52010-12-09 22:52:49 +00001150 if (log)
1151 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001152
Jim Inghamabab14b2010-11-04 23:08:45 +00001153 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1154
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001155 if (!no_context_switching)
1156 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +00001157
Jim Ingham949d5ac2011-02-18 00:54:25 +00001158 bool empty_command = false;
1159 bool comment_command = false;
1160 if (command_string.empty())
1161 empty_command = true;
1162 else
Chris Lattner24943d22010-06-08 16:52:24 +00001163 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001164 const char *k_space_characters = "\t\n\v\f\r ";
1165
1166 size_t non_space = command_string.find_first_not_of (k_space_characters);
1167 // Check for empty line or comment line (lines whose first
1168 // non-space character is the comment character for this interpreter)
1169 if (non_space == std::string::npos)
1170 empty_command = true;
1171 else if (command_string[non_space] == m_comment_char)
1172 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001173 else if (command_string[non_space] == m_repeat_char)
1174 {
1175 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1176 if (history_string == NULL)
1177 {
1178 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1179 result.SetStatus(eReturnStatusFailed);
1180 return false;
1181 }
1182 add_to_history = false;
1183 command_string = history_string;
1184 original_command_string = history_string;
1185 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001186 }
1187
1188 if (empty_command)
1189 {
1190 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001191 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001192 if (m_command_history.empty())
1193 {
1194 result.AppendError ("empty command");
1195 result.SetStatus(eReturnStatusFailed);
1196 return false;
1197 }
1198 else
1199 {
1200 command_line = m_repeat_command.c_str();
1201 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001202 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001203 if (m_repeat_command.empty())
1204 {
1205 result.AppendErrorWithFormat("No auto repeat.\n");
1206 result.SetStatus (eReturnStatusFailed);
1207 return false;
1208 }
1209 }
1210 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001211 }
1212 else
1213 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001214 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1215 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001216 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001217 }
1218 else if (comment_command)
1219 {
1220 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1221 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001222 }
Caroline Tice649116c2011-05-11 16:07:06 +00001223
Greg Claytonf5c0c722011-10-14 07:41:33 +00001224
1225 Error error (PreprocessCommand (command_string));
1226
1227 if (error.Fail())
1228 {
1229 result.AppendError (error.AsCString());
1230 result.SetStatus(eReturnStatusFailed);
1231 return false;
1232 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001233 // Phase 1.
1234
1235 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1236 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1237 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1238 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1239 // 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 +00001240 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001241 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001242
Caroline Ticee0da7a52010-12-09 22:52:49 +00001243 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001244 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001245 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001246 {
Caroline Tice649116c2011-05-11 16:07:06 +00001247 char quote_char = '\0';
Greg Clayton9d855c62011-10-25 00:36:27 +00001248 StripFirstWord (command_string, next_word, quote_char);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001249 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +00001250 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001251 std::string alias_result;
1252 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
1253 revised_command_line.Printf ("%s", alias_result.c_str());
1254 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +00001255 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001256 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +00001257 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1258 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001259 }
1260 else if (!cmd_obj)
1261 {
1262 cmd_obj = GetCommandObject (next_word.c_str());
1263 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +00001264 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001265 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +00001266 revised_command_line.Printf ("%s", next_word.c_str());
1267 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +00001268 }
1269 else
1270 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001271 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001272 }
1273 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001274 else if (cmd_obj->IsMultiwordObject ())
1275 {
1276 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1277 if (sub_cmd_obj)
1278 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001279 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001280 revised_command_line.Printf (" %s", next_word.c_str());
1281 cmd_obj = sub_cmd_obj;
1282 wants_raw_input = cmd_obj->WantsRawCommandString ();
1283 }
1284 else
1285 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001286 if (quote_char)
1287 revised_command_line.Printf (" %c%s%c", quote_char, next_word.c_str(), quote_char);
Caroline Tice649116c2011-05-11 16:07:06 +00001288 else
1289 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001290 done = true;
1291 }
1292 }
1293 else
1294 {
Greg Clayton9d855c62011-10-25 00:36:27 +00001295 if (quote_char)
1296 revised_command_line.Printf (" %c%s%c", quote_char, next_word.c_str(), quote_char);
Caroline Tice649116c2011-05-11 16:07:06 +00001297 else
1298 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001299 done = true;
1300 }
1301
1302 if (cmd_obj == NULL)
1303 {
1304 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1305 result.SetStatus (eReturnStatusFailed);
1306 return false;
1307 }
1308
1309 next_word.erase ();
1310 if (command_string.length() == 0)
1311 done = true;
1312
Chris Lattner24943d22010-06-08 16:52:24 +00001313 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001314
1315 if (command_string.size() > 0)
1316 revised_command_line.Printf (" %s", command_string.c_str());
1317
1318 // End of Phase 1.
1319 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1320 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1321 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1322 // wants_raw_input specifies whether the Execute method expects raw input or not.
1323
1324
1325 if (log)
1326 {
1327 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1328 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1329 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1330 }
1331
1332 // Phase 2.
1333 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1334 // CommandObject, with the appropriate arguments.
1335
1336 if (cmd_obj != NULL)
1337 {
1338 if (add_to_history)
1339 {
1340 Args command_args (revised_command_line.GetData());
1341 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1342 if (repeat_command != NULL)
1343 m_repeat_command.assign(repeat_command);
1344 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001345 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001346
Jim Ingham6247dbe2011-07-12 03:12:18 +00001347 // Don't keep pushing the same command onto the history...
1348 if (m_command_history.size() == 0 || m_command_history.back() != original_command_string)
1349 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001350 }
1351
1352 command_string = revised_command_line.GetData();
1353 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001354 std::string remainder;
1355 if (actual_cmd_name_len < command_string.length())
1356 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1357 // than cmd_obj->GetCommandName(), because name completion
1358 // allows users to enter short versions of the names,
1359 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001360
1361 // Remove any initial spaces
1362 std::string white_space (" \t\v");
1363 size_t pos = remainder.find_first_not_of (white_space);
1364 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001365 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001366
1367 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001368 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001369
1370
1371 if (wants_raw_input)
1372 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1373 else
1374 {
1375 Args cmd_args (remainder.c_str());
1376 cmd_obj->ExecuteWithOptions (cmd_args, result);
1377 }
1378 }
1379 else
1380 {
1381 // We didn't find the first command object, so complete the first argument.
1382 Args command_args (revised_command_line.GetData());
1383 StringList matches;
1384 int num_matches;
1385 int cursor_index = 0;
1386 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1387 bool word_complete;
1388 num_matches = HandleCompletionMatches (command_args,
1389 cursor_index,
1390 cursor_char_position,
1391 0,
1392 -1,
1393 word_complete,
1394 matches);
1395
1396 if (num_matches > 0)
1397 {
1398 std::string error_msg;
1399 error_msg.assign ("ambiguous command '");
1400 error_msg.append(command_args.GetArgumentAtIndex(0));
1401 error_msg.append ("'.");
1402
1403 error_msg.append (" Possible completions:");
1404 for (int i = 0; i < num_matches; i++)
1405 {
1406 error_msg.append ("\n\t");
1407 error_msg.append (matches.GetStringAtIndex (i));
1408 }
1409 error_msg.append ("\n");
1410 result.AppendRawError (error_msg.c_str(), error_msg.size());
1411 }
1412 else
1413 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1414
1415 result.SetStatus (eReturnStatusFailed);
1416 }
1417
Jason Molenda24c991c2011-08-25 00:20:04 +00001418 if (log)
1419 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1420
Chris Lattner24943d22010-06-08 16:52:24 +00001421 return result.Succeeded();
1422}
1423
1424int
1425CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1426 int &cursor_index,
1427 int &cursor_char_position,
1428 int match_start_point,
1429 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001430 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001431 StringList &matches)
1432{
1433 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001434 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001435
1436 // For any of the command completions a unique match will be a complete word.
1437 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001438
1439 if (cursor_index == -1)
1440 {
1441 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001442 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001443 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1444 }
1445 else if (cursor_index == 0)
1446 {
1447 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001448 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001449 num_command_matches = matches.GetSize();
1450
1451 if (num_command_matches == 1
1452 && cmd_obj && cmd_obj->IsMultiwordObject()
1453 && matches.GetStringAtIndex(0) != NULL
1454 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1455 {
1456 look_for_subcommand = true;
1457 num_command_matches = 0;
1458 matches.DeleteStringAtIndex(0);
1459 parsed_line.AppendArgument ("");
1460 cursor_index++;
1461 cursor_char_position = 0;
1462 }
1463 }
1464
1465 if (cursor_index > 0 || look_for_subcommand)
1466 {
1467 // We are completing further on into a commands arguments, so find the command and tell it
1468 // to complete the command.
1469 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001470 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001471 if (command_object == NULL)
1472 {
1473 return 0;
1474 }
1475 else
1476 {
1477 parsed_line.Shift();
1478 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001479 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001480 cursor_index,
1481 cursor_char_position,
1482 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001483 max_return_elements,
1484 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001485 matches);
1486 }
1487 }
1488
1489 return num_command_matches;
1490
1491}
1492
1493int
1494CommandInterpreter::HandleCompletion (const char *current_line,
1495 const char *cursor,
1496 const char *last_char,
1497 int match_start_point,
1498 int max_return_elements,
1499 StringList &matches)
1500{
1501 // We parse the argument up to the cursor, so the last argument in parsed_line is
1502 // the one containing the cursor, and the cursor is after the last character.
1503
1504 Args parsed_line(current_line, last_char - current_line);
1505 Args partial_parsed_line(current_line, cursor - current_line);
1506
Jim Ingham6247dbe2011-07-12 03:12:18 +00001507 // Don't complete comments, and if the line we are completing is just the history repeat character,
1508 // substitute the appropriate history line.
1509 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1510 if (first_arg)
1511 {
1512 if (first_arg[0] == m_comment_char)
1513 return 0;
1514 else if (first_arg[0] == m_repeat_char)
1515 {
1516 const char *history_string = FindHistoryString (first_arg);
1517 if (history_string != NULL)
1518 {
1519 matches.Clear();
1520 matches.InsertStringAtIndex(0, history_string);
1521 return -2;
1522 }
1523 else
1524 return 0;
1525
1526 }
1527 }
1528
1529
Chris Lattner24943d22010-06-08 16:52:24 +00001530 int num_args = partial_parsed_line.GetArgumentCount();
1531 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1532 int cursor_char_position;
1533
1534 if (cursor_index == -1)
1535 cursor_char_position = 0;
1536 else
1537 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001538
1539 if (cursor > current_line && cursor[-1] == ' ')
1540 {
1541 // We are just after a space. If we are in an argument, then we will continue
1542 // parsing, but if we are between arguments, then we have to complete whatever the next
1543 // element would be.
1544 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1545 // protected by a quote) then the space will also be in the parsed argument...
1546
1547 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1548 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1549 {
1550 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1551 cursor_index++;
1552 cursor_char_position = 0;
1553 }
1554 }
Chris Lattner24943d22010-06-08 16:52:24 +00001555
1556 int num_command_matches;
1557
1558 matches.Clear();
1559
1560 // Only max_return_elements == -1 is supported at present:
1561 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001562 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001563 num_command_matches = HandleCompletionMatches (parsed_line,
1564 cursor_index,
1565 cursor_char_position,
1566 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001567 max_return_elements,
1568 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001569 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001570
1571 if (num_command_matches <= 0)
1572 return num_command_matches;
1573
1574 if (num_args == 0)
1575 {
1576 // If we got an empty string, insert nothing.
1577 matches.InsertStringAtIndex(0, "");
1578 }
1579 else
1580 {
1581 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1582 // put an empty string in element 0.
1583 std::string command_partial_str;
1584 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001585 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1586 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001587
1588 std::string common_prefix;
1589 matches.LongestCommonPrefix (common_prefix);
1590 int partial_name_len = command_partial_str.size();
1591
1592 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001593 // Only do this if the completer told us this was a complete word, however...
1594 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001595 {
1596 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1597 if (quote_char != '\0')
1598 common_prefix.push_back(quote_char);
1599
1600 common_prefix.push_back(' ');
1601 }
1602 common_prefix.erase (0, partial_name_len);
1603 matches.InsertStringAtIndex(0, common_prefix.c_str());
1604 }
1605 return num_command_matches;
1606}
1607
Chris Lattner24943d22010-06-08 16:52:24 +00001608
1609CommandInterpreter::~CommandInterpreter ()
1610{
1611}
1612
1613const char *
1614CommandInterpreter::GetPrompt ()
1615{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001616 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001617}
1618
1619void
1620CommandInterpreter::SetPrompt (const char *new_prompt)
1621{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001622 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001623}
1624
Jim Ingham5e16ef52010-10-04 19:49:29 +00001625size_t
Greg Clayton58928562011-02-09 01:08:52 +00001626CommandInterpreter::GetConfirmationInputReaderCallback
1627(
1628 void *baton,
1629 InputReader &reader,
1630 lldb::InputReaderAction action,
1631 const char *bytes,
1632 size_t bytes_len
1633)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001634{
Greg Clayton58928562011-02-09 01:08:52 +00001635 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001636 bool *response_ptr = (bool *) baton;
1637
1638 switch (action)
1639 {
1640 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001641 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001642 {
1643 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001644 {
Greg Clayton58928562011-02-09 01:08:52 +00001645 out_file.Printf ("%s", reader.GetPrompt());
1646 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001647 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001648 }
1649 break;
1650
1651 case eInputReaderDeactivate:
1652 break;
1653
1654 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001655 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001656 {
Greg Clayton58928562011-02-09 01:08:52 +00001657 out_file.Printf ("%s", reader.GetPrompt());
1658 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001659 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001660 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001661
1662 case eInputReaderAsynchronousOutputWritten:
1663 break;
1664
Jim Ingham5e16ef52010-10-04 19:49:29 +00001665 case eInputReaderGotToken:
1666 if (bytes_len == 0)
1667 {
1668 reader.SetIsDone(true);
1669 }
1670 else if (bytes[0] == 'y')
1671 {
1672 *response_ptr = true;
1673 reader.SetIsDone(true);
1674 }
1675 else if (bytes[0] == 'n')
1676 {
1677 *response_ptr = false;
1678 reader.SetIsDone(true);
1679 }
1680 else
1681 {
Greg Clayton58928562011-02-09 01:08:52 +00001682 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001683 {
Greg Clayton58928562011-02-09 01:08:52 +00001684 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1685 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001686 }
1687 }
1688 break;
1689
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001690 case eInputReaderInterrupt:
1691 case eInputReaderEndOfFile:
1692 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1693 reader.SetIsDone (true);
1694 break;
1695
Jim Ingham5e16ef52010-10-04 19:49:29 +00001696 case eInputReaderDone:
1697 break;
1698 }
1699
1700 return bytes_len;
1701
1702}
1703
1704bool
1705CommandInterpreter::Confirm (const char *message, bool default_answer)
1706{
Jim Ingham93057472010-10-04 22:44:14 +00001707 // Check AutoConfirm first:
1708 if (m_debugger.GetAutoConfirm())
1709 return default_answer;
1710
Jim Ingham5e16ef52010-10-04 19:49:29 +00001711 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1712 bool response = default_answer;
1713 if (reader_sp)
1714 {
1715 std::string prompt(message);
1716 prompt.append(": [");
1717 if (default_answer)
1718 prompt.append ("Y/n] ");
1719 else
1720 prompt.append ("y/N] ");
1721
1722 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1723 &response, // baton
1724 eInputReaderGranularityLine, // token size, to pass to callback function
1725 NULL, // end token
1726 prompt.c_str(), // prompt
1727 true)); // echo input
1728 if (err.Success())
1729 {
1730 GetDebugger().PushInputReader (reader_sp);
1731 }
1732 reader_sp->WaitOnReaderIsDone();
1733 }
1734 return response;
1735}
1736
1737
Chris Lattner24943d22010-06-08 16:52:24 +00001738void
1739CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1740{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001741 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001742
1743 if (cmd_obj_sp != NULL)
1744 {
1745 CommandObject *cmd_obj = cmd_obj_sp.get();
1746 if (cmd_obj->IsCrossRefObject ())
1747 cmd_obj->AddObject (object_type);
1748 }
1749}
1750
Chris Lattner24943d22010-06-08 16:52:24 +00001751OptionArgVectorSP
1752CommandInterpreter::GetAliasOptions (const char *alias_name)
1753{
1754 OptionArgMap::iterator pos;
1755 OptionArgVectorSP ret_val;
1756
1757 std::string alias (alias_name);
1758
1759 if (HasAliasOptions())
1760 {
1761 pos = m_alias_options.find (alias);
1762 if (pos != m_alias_options.end())
1763 ret_val = pos->second;
1764 }
1765
1766 return ret_val;
1767}
1768
1769void
1770CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1771{
1772 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1773 if (pos != m_alias_options.end())
1774 {
1775 m_alias_options.erase (pos);
1776 }
1777}
1778
1779void
1780CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1781{
1782 m_alias_options[alias_name] = option_arg_vector_sp;
1783}
1784
1785bool
1786CommandInterpreter::HasCommands ()
1787{
1788 return (!m_command_dict.empty());
1789}
1790
1791bool
1792CommandInterpreter::HasAliases ()
1793{
1794 return (!m_alias_dict.empty());
1795}
1796
1797bool
1798CommandInterpreter::HasUserCommands ()
1799{
1800 return (!m_user_dict.empty());
1801}
1802
1803bool
1804CommandInterpreter::HasAliasOptions ()
1805{
1806 return (!m_alias_options.empty());
1807}
1808
Chris Lattner24943d22010-06-08 16:52:24 +00001809void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001810CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1811 const char *alias_name,
1812 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001813 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001814 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001815{
1816 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001817
1818 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001819
Caroline Tice44c841d2010-12-07 19:58:26 +00001820 // Make sure that the alias name is the 0th element in cmd_args
1821 std::string alias_name_str = alias_name;
1822 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1823 cmd_args.Unshift (alias_name);
1824
1825 Args new_args (alias_cmd_obj->GetCommandName());
1826 if (new_args.GetArgumentCount() == 2)
1827 new_args.Shift();
1828
Chris Lattner24943d22010-06-08 16:52:24 +00001829 if (option_arg_vector_sp.get())
1830 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001831 if (wants_raw_input)
1832 {
1833 // We have a command that both has command options and takes raw input. Make *sure* it has a
1834 // " -- " in the right place in the raw_input_string.
1835 size_t pos = raw_input_string.find(" -- ");
1836 if (pos == std::string::npos)
1837 {
1838 // None found; assume it goes at the beginning of the raw input string
1839 raw_input_string.insert (0, " -- ");
1840 }
1841 }
Chris Lattner24943d22010-06-08 16:52:24 +00001842
1843 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1844 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001845 std::vector<bool> used (old_size + 1, false);
1846
1847 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001848
1849 for (int i = 0; i < option_arg_vector->size(); ++i)
1850 {
1851 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001852 OptionArgValue value_pair = option_pair.second;
1853 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001854 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001855 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001856 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001857 {
1858 if (!wants_raw_input
1859 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1860 new_args.AppendArgument (value.c_str());
1861 }
Chris Lattner24943d22010-06-08 16:52:24 +00001862 else
1863 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001864 if (value_type != optional_argument)
1865 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001866 if (value.compare ("<no-argument>") != 0)
1867 {
1868 int index = GetOptionArgumentPosition (value.c_str());
1869 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001870 {
Chris Lattner24943d22010-06-08 16:52:24 +00001871 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001872 if (value_type != optional_argument)
1873 new_args.AppendArgument (value.c_str());
1874 else
1875 {
1876 char buffer[255];
1877 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1878 new_args.AppendArgument (buffer);
1879 }
1880
1881 }
Chris Lattner24943d22010-06-08 16:52:24 +00001882 else if (index >= cmd_args.GetArgumentCount())
1883 {
1884 result.AppendErrorWithFormat
1885 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1886 index);
1887 result.SetStatus (eReturnStatusFailed);
1888 return;
1889 }
1890 else
1891 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001892 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1893 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1894 if (strpos != std::string::npos)
1895 {
1896 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1897 }
1898
1899 if (value_type != optional_argument)
1900 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1901 else
1902 {
1903 char buffer[255];
1904 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1905 cmd_args.GetArgumentAtIndex (index));
1906 new_args.AppendArgument (buffer);
1907 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001908 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001909 }
1910 }
1911 }
1912 }
1913
1914 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1915 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001916 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001917 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1918 }
1919
1920 cmd_args.Clear();
1921 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1922 }
1923 else
1924 {
1925 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001926 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1927 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1928 // input string.
1929 if (wants_raw_input)
1930 {
1931 cmd_args.Clear();
1932 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1933 }
Chris Lattner24943d22010-06-08 16:52:24 +00001934 return;
1935 }
1936
1937 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1938 return;
1939}
1940
1941
1942int
1943CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1944{
1945 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1946 // of zero.
1947
1948 char *cptr = (char *) in_string;
1949
1950 // Does it start with '%'
1951 if (cptr[0] == '%')
1952 {
1953 ++cptr;
1954
1955 // Is the rest of it entirely digits?
1956 if (isdigit (cptr[0]))
1957 {
1958 const char *start = cptr;
1959 while (isdigit (cptr[0]))
1960 ++cptr;
1961
1962 // We've gotten to the end of the digits; are we at the end of the string?
1963 if (cptr[0] == '\0')
1964 position = atoi (start);
1965 }
1966 }
1967
1968 return position;
1969}
1970
1971void
1972CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1973{
Jim Ingham574c3d62011-08-12 23:34:31 +00001974 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00001975 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00001976 {
Greg Claytond6edcb52011-09-11 00:01:44 +00001977 // In the current working directory we don't load any program specific
1978 // .lldbinit files, we only look for a "./.lldbinit" file.
1979 if (m_skip_lldbinit_files)
1980 return;
1981
1982 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00001983 }
Greg Claytond6edcb52011-09-11 00:01:44 +00001984 else
Jim Ingham574c3d62011-08-12 23:34:31 +00001985 {
Greg Claytond6edcb52011-09-11 00:01:44 +00001986 // If we aren't looking in the current working directory we are looking
1987 // in the home directory. We will first see if there is an application
1988 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
1989 // "-" and the name of the program. If this file doesn't exist, we fall
1990 // back to just the "~/.lldbinit" file. We also obey any requests to not
1991 // load the init files.
1992 const char *init_file_path = "~/.lldbinit";
1993
1994 if (m_skip_app_init_files == false)
1995 {
1996 FileSpec program_file_spec (Host::GetProgramFileSpec());
1997 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00001998
Greg Claytond6edcb52011-09-11 00:01:44 +00001999 if (program_name)
2000 {
2001 char program_init_file_name[PATH_MAX];
2002 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2003 init_file.SetFile (program_init_file_name, true);
2004 if (!init_file.Exists())
2005 init_file.Clear();
2006 }
2007 }
2008
2009 if (!init_file && !m_skip_lldbinit_files)
2010 init_file.SetFile (init_file_path, true);
2011 }
2012
Chris Lattner24943d22010-06-08 16:52:24 +00002013 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2014 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2015
2016 if (init_file.Exists())
2017 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002018 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2019 bool stop_on_continue = true;
2020 bool stop_on_error = false;
2021 bool echo_commands = false;
2022 bool print_results = false;
2023
2024 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002025 }
2026 else
2027 {
2028 // nothing to be done if the file doesn't exist
2029 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2030 }
2031}
2032
Greg Claytonb72d0f02011-04-12 05:54:46 +00002033PlatformSP
2034CommandInterpreter::GetPlatform (bool prefer_target_platform)
2035{
2036 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002037 if (prefer_target_platform)
2038 {
2039 Target *target = m_exe_ctx.GetTargetPtr();
2040 if (target)
2041 platform_sp = target->GetPlatform();
2042 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002043
2044 if (!platform_sp)
2045 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2046 return platform_sp;
2047}
2048
Jim Ingham949d5ac2011-02-18 00:54:25 +00002049void
Jim Inghama4fede32011-03-11 01:51:49 +00002050CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002051 ExecutionContext *override_context,
2052 bool stop_on_continue,
2053 bool stop_on_error,
2054 bool echo_commands,
2055 bool print_results,
2056 CommandReturnObject &result)
2057{
2058 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002059
2060 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2061 // Make sure you reset this value anywhere you return from the function.
2062
2063 bool old_async_execution = m_debugger.GetAsyncExecution();
2064
2065 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2066 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2067
2068 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002069 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002070
2071 if (!stop_on_continue)
2072 {
2073 m_debugger.SetAsyncExecution (false);
2074 }
2075
2076 for (int idx = 0; idx < num_lines; idx++)
2077 {
2078 const char *cmd = commands.GetStringAtIndex(idx);
2079 if (cmd[0] == '\0')
2080 continue;
2081
Jim Ingham949d5ac2011-02-18 00:54:25 +00002082 if (echo_commands)
2083 {
2084 result.AppendMessageWithFormat ("%s %s\n",
2085 GetPrompt(),
2086 cmd);
2087 }
2088
Greg Claytonaa378b12011-02-20 02:15:07 +00002089 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002090 // If override_context is not NULL, pass no_context_switching = true for
2091 // HandleCommand() since we updated our context already.
2092 bool success = HandleCommand(cmd, false, tmp_result,
2093 NULL, /* override_context */
2094 true, /* repeat_on_empty_command */
2095 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002096
2097 if (print_results)
2098 {
2099 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002100 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002101 }
2102
2103 if (!success || !tmp_result.Succeeded())
2104 {
2105 if (stop_on_error)
2106 {
2107 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
2108 idx, cmd);
2109 result.SetStatus (eReturnStatusFailed);
2110 m_debugger.SetAsyncExecution (old_async_execution);
2111 return;
2112 }
2113 else if (print_results)
2114 {
2115 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
2116 idx + 1,
2117 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002118 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002119 }
2120 }
2121
Caroline Tice4a348082011-05-02 20:41:46 +00002122 if (result.GetImmediateOutputStream())
2123 result.GetImmediateOutputStream()->Flush();
2124
2125 if (result.GetImmediateErrorStream())
2126 result.GetImmediateErrorStream()->Flush();
2127
Jim Ingham949d5ac2011-02-18 00:54:25 +00002128 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2129 // could be running (for instance in Breakpoint Commands.
2130 // So we check the return value to see if it is has running in it.
2131 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2132 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2133 {
2134 if (stop_on_continue)
2135 {
2136 // If we caused the target to proceed, and we're going to stop in that case, set the
2137 // status in our real result before returning. This is an error if the continue was not the
2138 // last command in the set of commands to be run.
2139 if (idx != num_lines - 1)
2140 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2141 idx + 1, cmd);
2142 else
2143 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2144
2145 result.SetStatus(tmp_result.GetStatus());
2146 m_debugger.SetAsyncExecution (old_async_execution);
2147
2148 return;
2149 }
2150 }
2151
2152 }
2153
2154 result.SetStatus (eReturnStatusSuccessFinishResult);
2155 m_debugger.SetAsyncExecution (old_async_execution);
2156
2157 return;
2158}
2159
2160void
2161CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2162 ExecutionContext *context,
2163 bool stop_on_continue,
2164 bool stop_on_error,
2165 bool echo_command,
2166 bool print_result,
2167 CommandReturnObject &result)
2168{
2169 if (cmd_file.Exists())
2170 {
2171 bool success;
2172 StringList commands;
2173 success = commands.ReadFileLines(cmd_file);
2174 if (!success)
2175 {
2176 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2177 result.SetStatus (eReturnStatusFailed);
2178 return;
2179 }
2180 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
2181 }
2182 else
2183 {
2184 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2185 cmd_file.GetFilename().AsCString());
2186 result.SetStatus (eReturnStatusFailed);
2187 return;
2188 }
2189}
2190
Chris Lattner24943d22010-06-08 16:52:24 +00002191ScriptInterpreter *
2192CommandInterpreter::GetScriptInterpreter ()
2193{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002194 if (m_script_interpreter_ap.get() != NULL)
2195 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002196
Caroline Tice0aa2e552011-01-14 00:29:16 +00002197 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2198 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002199 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00002200 case eScriptLanguageNone:
2201 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2202 break;
2203 case eScriptLanguagePython:
2204 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2205 break;
2206 default:
2207 break;
2208 };
2209
2210 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002211}
2212
2213
2214
2215bool
2216CommandInterpreter::GetSynchronous ()
2217{
2218 return m_synchronous_execution;
2219}
2220
2221void
2222CommandInterpreter::SetSynchronous (bool value)
2223{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002224 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002225}
2226
2227void
2228CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2229 const char *word_text,
2230 const char *separator,
2231 const char *help_text,
2232 uint32_t max_word_len)
2233{
Greg Clayton238c0a12010-09-18 01:14:36 +00002234 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2235
Chris Lattner24943d22010-06-08 16:52:24 +00002236 int indent_size = max_word_len + strlen (separator) + 2;
2237
2238 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002239
2240 StreamString text_strm;
2241 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2242
2243 size_t len = text_strm.GetSize();
2244 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002245 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002246 {
2247 text_strm.EOL();
2248 len = text_strm.GetSize();
2249 }
Chris Lattner24943d22010-06-08 16:52:24 +00002250
2251 if (len < max_columns)
2252 {
2253 // Output it as a single line.
2254 strm.Printf ("%s", text);
2255 }
2256 else
2257 {
2258 // We need to break it up into multiple lines.
2259 bool first_line = true;
2260 int text_width;
2261 int start = 0;
2262 int end = start;
2263 int final_end = strlen (text);
2264 int sub_len;
2265
2266 while (end < final_end)
2267 {
2268 if (first_line)
2269 text_width = max_columns - 1;
2270 else
2271 text_width = max_columns - indent_size - 1;
2272
2273 // Don't start the 'text' on a space, since we're already outputting the indentation.
2274 if (!first_line)
2275 {
2276 while ((start < final_end) && (text[start] == ' '))
2277 start++;
2278 }
2279
2280 end = start + text_width;
2281 if (end > final_end)
2282 end = final_end;
2283 else
2284 {
2285 // If we're not at the end of the text, make sure we break the line on white space.
2286 while (end > start
2287 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2288 end--;
2289 }
2290
2291 sub_len = end - start;
2292 if (start != 0)
2293 strm.EOL();
2294 if (!first_line)
2295 strm.Indent();
2296 else
2297 first_line = false;
2298 assert (start <= final_end);
2299 assert (start + sub_len <= final_end);
2300 if (sub_len > 0)
2301 strm.Write (text + start, sub_len);
2302 start = end + 1;
2303 }
2304 }
2305 strm.EOL();
2306 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002307}
2308
2309void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002310CommandInterpreter::OutputHelpText (Stream &strm,
2311 const char *word_text,
2312 const char *separator,
2313 const char *help_text,
2314 uint32_t max_word_len)
2315{
2316 int indent_size = max_word_len + strlen (separator) + 2;
2317
2318 strm.IndentMore (indent_size);
2319
2320 StreamString text_strm;
2321 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2322
2323 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2324 bool first_line = true;
2325
2326 size_t len = text_strm.GetSize();
2327 const char *text = text_strm.GetData();
2328
2329 uint32_t chars_left = max_columns;
2330
2331 for (uint32_t i = 0; i < len; i++)
2332 {
2333 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2334 {
2335 first_line = false;
2336 chars_left = max_columns - indent_size;
2337 strm.EOL();
2338 strm.Indent();
2339 }
2340 else
2341 {
2342 strm.PutChar(text[i]);
2343 chars_left--;
2344 }
2345
2346 }
2347
2348 strm.EOL();
2349 strm.IndentLess(indent_size);
2350}
2351
2352void
Chris Lattner24943d22010-06-08 16:52:24 +00002353CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2354 StringList &commands_found, StringList &commands_help)
2355{
2356 CommandObject::CommandMap::const_iterator pos;
2357 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2358 CommandObject *sub_cmd_obj;
2359
2360 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2361 {
2362 const char * command_name = pos->first.c_str();
2363 sub_cmd_obj = pos->second.get();
2364 StreamString complete_command_name;
2365
2366 complete_command_name.Printf ("%s %s", prefix, command_name);
2367
Greg Clayton238c0a12010-09-18 01:14:36 +00002368 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002369 {
2370 commands_found.AppendString (complete_command_name.GetData());
2371 commands_help.AppendString (sub_cmd_obj->GetHelp());
2372 }
2373
2374 if (sub_cmd_obj->IsMultiwordObject())
2375 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2376 commands_help);
2377 }
2378
2379}
2380
2381void
2382CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2383 StringList &commands_help)
2384{
2385 CommandObject::CommandMap::const_iterator pos;
2386
2387 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2388 {
2389 const char *command_name = pos->first.c_str();
2390 CommandObject *cmd_obj = pos->second.get();
2391
Greg Clayton238c0a12010-09-18 01:14:36 +00002392 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002393 {
2394 commands_found.AppendString (command_name);
2395 commands_help.AppendString (cmd_obj->GetHelp());
2396 }
2397
2398 if (cmd_obj->IsMultiwordObject())
2399 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2400
2401 }
2402}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002403
2404
2405void
2406CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2407{
2408 m_exe_ctx.Clear();
2409
2410 if (override_context != NULL)
2411 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002412 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002413 }
2414 else
2415 {
2416 TargetSP target_sp (m_debugger.GetSelectedTarget());
2417 if (target_sp)
2418 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002419 m_exe_ctx.SetTargetSP (target_sp);
2420 ProcessSP process_sp (target_sp->GetProcessSP());
2421 m_exe_ctx.SetProcessSP (process_sp);
2422 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002423 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002424 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread().get());
2425 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002426 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002427 m_exe_ctx.SetThreadSP (thread_sp);
2428 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2429 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002430 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002431 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002432 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002433 if (frame_sp)
2434 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002435 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002436 if (frame_sp)
2437 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002438 }
2439 }
2440 }
2441 }
2442}
2443
Jim Ingham6247dbe2011-07-12 03:12:18 +00002444void
2445CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2446{
2447 DumpHistory (stream, 0, count - 1);
2448}
2449
2450void
2451CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2452{
2453 size_t num_history_elements = m_command_history.size();
2454 if (start > num_history_elements)
2455 return;
2456 for (uint32_t i = start; i < num_history_elements && i <= end; i++)
2457 {
2458 if (!m_command_history[i].empty())
2459 {
2460 stream.Indent();
2461 stream.Printf ("%4d: %s\n", i, m_command_history[i].c_str());
2462 }
2463 }
2464}
2465
2466const char *
2467CommandInterpreter::FindHistoryString (const char *input_str) const
2468{
2469 if (input_str[0] != m_repeat_char)
2470 return NULL;
2471 if (input_str[1] == '-')
2472 {
2473 bool success;
2474 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2475 if (!success)
2476 return NULL;
2477 if (idx > m_command_history.size())
2478 return NULL;
2479 idx = m_command_history.size() - idx;
2480 return m_command_history[idx].c_str();
2481
2482 }
2483 else if (input_str[1] == m_repeat_char)
2484 {
2485 if (m_command_history.empty())
2486 return NULL;
2487 else
2488 return m_command_history.back().c_str();
2489 }
2490 else
2491 {
2492 bool success;
2493 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2494 if (!success)
2495 return NULL;
2496 if (idx >= m_command_history.size())
2497 return NULL;
2498 return m_command_history[idx].c_str();
2499 }
2500}