blob: 23c77548eae136aeeb983977554cd60dd7d41f07 [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 Molenda730cae02011-10-22 01:30:52 +0000177 cmd_obj_sp = GetCommandSPExact ("_display", false);
178 if (cmd_obj_sp)
179 AddAlias ("display", cmd_obj_sp);
180
181 cmd_obj_sp = GetCommandSPExact ("_undisplay", false);
182 if (cmd_obj_sp)
183 AddAlias ("undisplay", cmd_obj_sp);
184
Caroline Tice5ddbe212011-05-06 21:37:15 +0000185 cmd_obj_sp = GetCommandSPExact ("target create", false);
186 if (cmd_obj_sp)
187 AddAlias ("file", cmd_obj_sp);
188
189 cmd_obj_sp = GetCommandSPExact ("target modules", false);
190 if (cmd_obj_sp)
191 AddAlias ("image", cmd_obj_sp);
192
193
194 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000195
Caroline Tice5ddbe212011-05-06 21:37:15 +0000196 cmd_obj_sp = GetCommandSPExact ("expression", false);
197 if (cmd_obj_sp)
198 {
199 AddAlias ("expr", cmd_obj_sp);
200
201 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
202 AddAlias ("p", cmd_obj_sp);
203 AddAlias ("print", cmd_obj_sp);
204 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
205 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
206
207 alias_arguments_vector_sp.reset (new OptionArgVector);
208 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
209 AddAlias ("po", cmd_obj_sp);
210 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
211 }
212
213 cmd_obj_sp = GetCommandSPExact ("process launch", false);
214 if (cmd_obj_sp)
215 {
216 alias_arguments_vector_sp.reset (new OptionArgVector);
217 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
218 AddAlias ("r", cmd_obj_sp);
219 AddAlias ("run", cmd_obj_sp);
220 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
221 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
222 }
Chris Lattner24943d22010-06-08 16:52:24 +0000223}
224
Chris Lattner24943d22010-06-08 16:52:24 +0000225const char *
226CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
227{
228 // This function has not yet been implemented.
229
230 // Look for any embedded script command
231 // If found,
232 // get interpreter object from the command dictionary,
233 // call execute_one_command on it,
234 // get the results as a string,
235 // substitute that string for current stuff.
236
237 return arg;
238}
239
240
241void
242CommandInterpreter::LoadCommandDictionary ()
243{
244 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
245
246 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
247 //
248 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
249 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
250 // the cross-referencing stuff) are created!!!
251 //
252 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
253
254
255 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
256 // are created. This is so that when another command is created that needs to go into a crossref object,
257 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
258 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
259
Chris Lattner24943d22010-06-08 16:52:24 +0000260 // Non-CommandObjectCrossref commands can now be created.
261
Caroline Tice5bc8c972010-09-20 20:44:43 +0000262 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000263
Greg Clayton238c0a12010-09-18 01:14:36 +0000264 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000265 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000266 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000267 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000268 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
269 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000270// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000271 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000272 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000273 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000274 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
275 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000276 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000277 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000278 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000279 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000280 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000281 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000282 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000283 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
284 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000285 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000286 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000287 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000288
289 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000290 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000291 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000292 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000293 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000294 if (break_regex_cmd_ap.get())
295 {
296 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
297 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
298 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000299 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000300 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000301 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000302 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
303 {
304 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
305 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
306 }
307 }
Jim Inghame56493f2011-03-22 02:29:32 +0000308
309 std::auto_ptr<CommandObjectRegexCommand>
310 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000311 "_regexp-down",
312 "Go down \"n\" frames in the stack (1 frame by default).",
313 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000314 if (down_regex_cmd_ap.get())
315 {
316 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
317 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
318 {
319 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
320 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
321 }
322 }
323
324 std::auto_ptr<CommandObjectRegexCommand>
325 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000326 "_regexp-up",
327 "Go up \"n\" frames in the stack (1 frame by default).",
328 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000329 if (up_regex_cmd_ap.get())
330 {
331 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
332 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
333 {
334 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
335 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
336 }
337 }
Jason Molenda730cae02011-10-22 01:30:52 +0000338
339 std::auto_ptr<CommandObjectRegexCommand>
340 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
341 "_display",
342 "Add an expression evaluation stop-hook.",
343 "_display expression", 2));
344 if (display_regex_cmd_ap.get())
345 {
346 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
347 {
348 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
349 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
350 }
351 }
352
353 std::auto_ptr<CommandObjectRegexCommand>
354 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
355 "_undisplay",
356 "Remove an expression evaluation stop-hook.",
357 "_undisplay stop-hook-number", 2));
358 if (undisplay_regex_cmd_ap.get())
359 {
360 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
361 {
362 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
363 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
364 }
365 }
366
Chris Lattner24943d22010-06-08 16:52:24 +0000367}
368
369int
370CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
371 StringList &matches)
372{
373 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
374
375 if (include_aliases)
376 {
377 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
378 }
379
380 return matches.GetSize();
381}
382
383CommandObjectSP
384CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
385{
386 CommandObject::CommandMap::iterator pos;
387 CommandObjectSP ret_val;
388
389 std::string cmd(cmd_cstr);
390
391 if (HasCommands())
392 {
393 pos = m_command_dict.find(cmd);
394 if (pos != m_command_dict.end())
395 ret_val = pos->second;
396 }
397
398 if (include_aliases && HasAliases())
399 {
400 pos = m_alias_dict.find(cmd);
401 if (pos != m_alias_dict.end())
402 ret_val = pos->second;
403 }
404
405 if (HasUserCommands())
406 {
407 pos = m_user_dict.find(cmd);
408 if (pos != m_user_dict.end())
409 ret_val = pos->second;
410 }
411
412 if (!exact && ret_val == NULL)
413 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000414 // We will only get into here if we didn't find any exact matches.
415
416 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
417
Chris Lattner24943d22010-06-08 16:52:24 +0000418 StringList local_matches;
419 if (matches == NULL)
420 matches = &local_matches;
421
Jim Inghamd40f8a62010-07-06 22:46:59 +0000422 unsigned int num_cmd_matches = 0;
423 unsigned int num_alias_matches = 0;
424 unsigned int num_user_matches = 0;
425
426 // Look through the command dictionaries one by one, and if we get only one match from any of
427 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
428
Chris Lattner24943d22010-06-08 16:52:24 +0000429 if (HasCommands())
430 {
431 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
432 }
433
434 if (num_cmd_matches == 1)
435 {
436 cmd.assign(matches->GetStringAtIndex(0));
437 pos = m_command_dict.find(cmd);
438 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000439 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000440 }
441
Jim Ingham9a574172010-06-24 20:28:42 +0000442 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000443 {
444 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
445
446 }
447
Jim Inghamd40f8a62010-07-06 22:46:59 +0000448 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000449 {
450 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
451 pos = m_alias_dict.find(cmd);
452 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000453 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000454 }
455
Jim Ingham9a574172010-06-24 20:28:42 +0000456 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000457 {
458 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
459 }
460
Jim Inghamd40f8a62010-07-06 22:46:59 +0000461 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000462 {
463 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
464
465 pos = m_user_dict.find (cmd);
466 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000467 user_match_sp = pos->second;
468 }
469
470 // If we got exactly one match, return that, otherwise return the match list.
471
472 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
473 {
474 if (num_cmd_matches)
475 return real_match_sp;
476 else if (num_alias_matches)
477 return alias_match_sp;
478 else
479 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000480 }
481 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000482 else if (matches && ret_val != NULL)
483 {
484 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000485 }
486
487
488 return ret_val;
489}
490
Greg Claytond12aeab2011-04-20 16:37:46 +0000491bool
492CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
493{
494 if (name && name[0])
495 {
496 std::string name_sstr(name);
497 if (!can_replace)
498 {
499 if (m_command_dict.find (name_sstr) != m_command_dict.end())
500 return false;
501 }
502 m_command_dict[name_sstr] = cmd_sp;
503 return true;
504 }
505 return false;
506}
507
Enrico Granata6b1596d2011-08-16 23:24:13 +0000508bool
509CommandInterpreter::AddUserCommand (const char *name,
510 const lldb::CommandObjectSP &cmd_sp,
511 bool can_replace)
512{
513 if (name && name[0])
514 {
515 std::string name_sstr(name);
516 if (!can_replace)
517 {
518 if (m_user_dict.find (name_sstr) != m_user_dict.end())
519 return false;
520 }
521 m_user_dict[name_sstr] = cmd_sp;
522 return true;
523 }
524 return false;
525}
Greg Claytond12aeab2011-04-20 16:37:46 +0000526
Jim Inghamd40f8a62010-07-06 22:46:59 +0000527CommandObjectSP
528CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000529{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000530 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
531 CommandObjectSP ret_val; // Possibly empty return value.
532
533 if (cmd_cstr == NULL)
534 return ret_val;
535
536 if (cmd_words.GetArgumentCount() == 1)
537 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
538 else
539 {
540 // We have a multi-word command (seemingly), so we need to do more work.
541 // First, get the cmd_obj_sp for the first word in the command.
542 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
543 if (cmd_obj_sp.get() != NULL)
544 {
545 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
546 // command name), and find the appropriate sub-command SP for each command word....
547 size_t end = cmd_words.GetArgumentCount();
548 for (size_t j= 1; j < end; ++j)
549 {
550 if (cmd_obj_sp->IsMultiwordObject())
551 {
552 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
553 (cmd_words.GetArgumentAtIndex (j));
554 if (cmd_obj_sp.get() == NULL)
555 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
556 return ret_val;
557 }
558 else
559 // We have more words in the command name, but we don't have a multiword object. Fail and return
560 // empty 'ret_val'.
561 return ret_val;
562 }
563 // We successfully looped through all the command words and got valid command objects for them. Assign the
564 // last object retrieved to 'ret_val'.
565 ret_val = cmd_obj_sp;
566 }
567 }
568 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000569}
570
571CommandObject *
572CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
573{
574 return GetCommandSPExact (cmd_cstr, include_aliases).get();
575}
576
577CommandObject *
578CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
579{
580 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
581
582 // If we didn't find an exact match to the command string in the commands, look in
583 // the aliases.
584
585 if (command_obj == NULL)
586 {
587 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
588 }
589
590 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
591 // in both the commands and the aliases.
592
593 if (command_obj == NULL)
594 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
595
596 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000597}
598
599bool
600CommandInterpreter::CommandExists (const char *cmd)
601{
602 return m_command_dict.find(cmd) != m_command_dict.end();
603}
604
605bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000606CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
607 const char *options_args,
608 OptionArgVectorSP &option_arg_vector_sp)
609{
610 bool success = true;
611 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
612
613 if (!options_args || (strlen (options_args) < 1))
614 return true;
615
616 std::string options_string (options_args);
617 Args args (options_args);
618 CommandReturnObject result;
619 // Check to see if the command being aliased can take any command options.
620 Options *options = cmd_obj_sp->GetOptions ();
621 if (options)
622 {
623 // See if any options were specified as part of the alias; if so, handle them appropriately.
624 options->NotifyOptionParsingStarting ();
625 args.Unshift ("dummy_arg");
626 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
627 args.Shift ();
628 if (result.Succeeded())
629 options->VerifyPartialOptions (result);
630 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
631 {
632 result.AppendError ("Unable to create requested alias.\n");
633 return false;
634 }
635 }
636
637 if (options_string.size() > 0)
638 {
639 if (cmd_obj_sp->WantsRawCommandString ())
640 option_arg_vector->push_back (OptionArgPair ("<argument>",
641 OptionArgValue (-1,
642 options_string)));
643 else
644 {
645 int argc = args.GetArgumentCount();
646 for (size_t i = 0; i < argc; ++i)
647 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
648 option_arg_vector->push_back
649 (OptionArgPair ("<argument>",
650 OptionArgValue (-1,
651 std::string (args.GetArgumentAtIndex (i)))));
652 }
653 }
654
655 return success;
656}
657
658bool
Chris Lattner24943d22010-06-08 16:52:24 +0000659CommandInterpreter::AliasExists (const char *cmd)
660{
661 return m_alias_dict.find(cmd) != m_alias_dict.end();
662}
663
664bool
665CommandInterpreter::UserCommandExists (const char *cmd)
666{
667 return m_user_dict.find(cmd) != m_user_dict.end();
668}
669
670void
671CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
672{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000673 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000674 m_alias_dict[alias_name] = command_obj_sp;
675}
676
677bool
678CommandInterpreter::RemoveAlias (const char *alias_name)
679{
680 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
681 if (pos != m_alias_dict.end())
682 {
683 m_alias_dict.erase(pos);
684 return true;
685 }
686 return false;
687}
688bool
689CommandInterpreter::RemoveUser (const char *alias_name)
690{
691 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
692 if (pos != m_user_dict.end())
693 {
694 m_user_dict.erase(pos);
695 return true;
696 }
697 return false;
698}
699
Chris Lattner24943d22010-06-08 16:52:24 +0000700void
701CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
702{
703 help_string.Printf ("'%s", command_name);
704 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
705
706 if (option_arg_vector_sp != NULL)
707 {
708 OptionArgVector *options = option_arg_vector_sp.get();
709 for (int i = 0; i < options->size(); ++i)
710 {
711 OptionArgPair cur_option = (*options)[i];
712 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000713 OptionArgValue value_pair = cur_option.second;
714 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000715 if (opt.compare("<argument>") == 0)
716 {
717 help_string.Printf (" %s", value.c_str());
718 }
719 else
720 {
721 help_string.Printf (" %s", opt.c_str());
722 if ((value.compare ("<no-argument>") != 0)
723 && (value.compare ("<need-argument") != 0))
724 {
725 help_string.Printf (" %s", value.c_str());
726 }
727 }
728 }
729 }
730
731 help_string.Printf ("'");
732}
733
Greg Clayton65124ea2010-08-26 22:05:43 +0000734size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000735CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
736{
737 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000738 CommandObject::CommandMap::const_iterator end = dict.end();
739 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000740
Greg Clayton65124ea2010-08-26 22:05:43 +0000741 for (pos = dict.begin(); pos != end; ++pos)
742 {
743 size_t len = pos->first.size();
744 if (max_len < len)
745 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000746 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000747 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000748}
749
750void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000751CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000752 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000753{
754 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000755 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000756
757 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000758 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000759
760 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
761 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000762
Enrico Granata6b1596d2011-08-16 23:24:13 +0000763 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
764 {
765 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
766 max_len);
767 }
768 result.AppendMessage("");
769
770 }
771
772 if (m_alias_dict.size() > 0 && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000773 {
Jim Inghame3663e82010-10-22 18:47:16 +0000774 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000775 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000776 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000777 max_len = FindLongestCommandWord (m_alias_dict);
778
Chris Lattner24943d22010-06-08 16:52:24 +0000779 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
780 {
781 StreamString sstr;
782 StreamString translation_and_help;
783 std::string entry_name = pos->first;
784 std::string second_entry = pos->second.get()->GetCommandName();
785 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
786
787 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
788 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
789 translation_and_help.GetData(), max_len);
790 }
791 result.AppendMessage("");
792 }
793
Enrico Granata6b1596d2011-08-16 23:24:13 +0000794 if (m_user_dict.size() > 0 && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000795 {
796 result.AppendMessage ("The following is a list of your current user-defined commands:");
797 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000798 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000799 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
800 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000801 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
802 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000803 }
804 result.AppendMessage("");
805 }
806
807 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
808}
809
Caroline Ticee0da7a52010-12-09 22:52:49 +0000810CommandObject *
811CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000812{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000813 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
814 // eventually be invoked by the given command line.
815
816 CommandObject *cmd_obj = NULL;
817 std::string white_space (" \t\v");
818 size_t start = command_string.find_first_not_of (white_space);
819 size_t end = 0;
820 bool done = false;
821 while (!done)
822 {
823 if (start != std::string::npos)
824 {
825 // Get the next word from command_string.
826 end = command_string.find_first_of (white_space, start);
827 if (end == std::string::npos)
828 end = command_string.size();
829 std::string cmd_word = command_string.substr (start, end - start);
830
831 if (cmd_obj == NULL)
832 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
833 // command or alias.
834 cmd_obj = GetCommandObject (cmd_word.c_str());
835 else if (cmd_obj->IsMultiwordObject ())
836 {
837 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
838 CommandObject *sub_cmd_obj =
839 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
840 if (sub_cmd_obj)
841 cmd_obj = sub_cmd_obj;
842 else // cmd_word was not a valid sub-command word, so we are donee
843 done = true;
844 }
845 else
846 // We have a cmd_obj and it is not a multi-word object, so we are done.
847 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000848
Caroline Ticee0da7a52010-12-09 22:52:49 +0000849 // If we didn't find a valid command object, or our command object is not a multi-word object, or
850 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
851 // next word.
852
853 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
854 done = true;
855 else
856 start = command_string.find_first_not_of (white_space, end);
857 }
858 else
859 // Unable to find any more words.
860 done = true;
861 }
862
863 if (end == command_string.size())
864 command_string.clear();
865 else
866 command_string = command_string.substr(end);
867
868 return cmd_obj;
869}
870
871bool
Caroline Tice649116c2011-05-11 16:07:06 +0000872CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word, bool &was_quoted, char &quote_char)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000873{
874 std::string white_space (" \t\v");
875 size_t start;
876 size_t end;
877
878 start = command_string.find_first_not_of (white_space);
879 if (start != std::string::npos)
880 {
Caroline Tice649116c2011-05-11 16:07:06 +0000881 size_t len = command_string.size() - start;
882 if (len >= 2
883 && ((command_string[start] == '\'') || (command_string[start] == '"')))
Caroline Ticee0da7a52010-12-09 22:52:49 +0000884 {
Caroline Tice649116c2011-05-11 16:07:06 +0000885 was_quoted = true;
886 quote_char = command_string[start];
887 std::string quote_string = command_string.substr (start, 1);
888 start = start + 1;
889 end = command_string.find (quote_string, start);
890 if (end != std::string::npos)
891 {
892 word = command_string.substr (start, end - start);
893 if (end + 1 < len)
894 command_string = command_string.substr (end+1);
895 else
896 command_string.erase ();
897 size_t pos = command_string.find_first_not_of (white_space);
898 if ((pos != 0) && (pos != std::string::npos))
899 command_string = command_string.substr (pos);
900 }
901 else
902 {
903 word = command_string.substr (start - 1);
904 command_string.erase ();
905 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000906 }
907 else
908 {
Caroline Tice649116c2011-05-11 16:07:06 +0000909 end = command_string.find_first_of (white_space, start);
910 if (end != std::string::npos)
911 {
912 word = command_string.substr (start, end - start);
913 command_string = command_string.substr (end);
914 size_t pos = command_string.find_first_not_of (white_space);
915 if ((pos != 0) && (pos != std::string::npos))
916 command_string = command_string.substr (pos);
917 }
918 else
919 {
920 word = command_string.substr (start);
921 command_string.erase();
922 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000923 }
924
925 }
926 return true;
927}
928
929void
930CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
931 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
932{
933 Args cmd_args (raw_input_string.c_str());
934 alias_cmd_obj = GetCommandObject (alias_name);
935 StreamString result_str;
936
937 if (alias_cmd_obj)
938 {
939 std::string alias_name_str = alias_name;
940 if ((cmd_args.GetArgumentCount() == 0)
941 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
942 cmd_args.Unshift (alias_name);
943
944 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
945 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
946
947 if (option_arg_vector_sp.get())
948 {
949 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
950
951 for (int i = 0; i < option_arg_vector->size(); ++i)
952 {
953 OptionArgPair option_pair = (*option_arg_vector)[i];
954 OptionArgValue value_pair = option_pair.second;
955 int value_type = value_pair.first;
956 std::string option = option_pair.first;
957 std::string value = value_pair.second;
958 if (option.compare ("<argument>") == 0)
959 result_str.Printf (" %s", value.c_str());
960 else
961 {
962 result_str.Printf (" %s", option.c_str());
963 if (value_type != optional_argument)
964 result_str.Printf (" ");
965 if (value.compare ("<no_argument>") != 0)
966 {
967 int index = GetOptionArgumentPosition (value.c_str());
968 if (index == 0)
969 result_str.Printf ("%s", value.c_str());
970 else if (index >= cmd_args.GetArgumentCount())
971 {
972
973 result.AppendErrorWithFormat
974 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
975 index);
976 result.SetStatus (eReturnStatusFailed);
977 return;
978 }
979 else
980 {
981 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
982 if (strpos != std::string::npos)
983 raw_input_string = raw_input_string.erase (strpos,
984 strlen (cmd_args.GetArgumentAtIndex (index)));
985 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
986 }
987 }
988 }
989 }
990 }
991
992 alias_result = result_str.GetData();
993 }
994}
995
Greg Claytonf5c0c722011-10-14 07:41:33 +0000996Error
997CommandInterpreter::PreprocessCommand (std::string &command)
998{
999 // The command preprocessor needs to do things to the command
1000 // line before any parsing of arguments or anything else is done.
1001 // The only current stuff that gets proprocessed is anyting enclosed
1002 // in backtick ('`') characters is evaluated as an expression and
1003 // the result of the expression must be a scalar that can be substituted
1004 // into the command. An example would be:
1005 // (lldb) memory read `$rsp + 20`
1006 Error error; // Error for any expressions that might not evaluate
1007 size_t start_backtick;
1008 size_t pos = 0;
1009 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1010 {
1011 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1012 {
1013 // The backtick was preceeded by a '\' character, remove the slash
1014 // and don't treat the backtick as the start of an expression
1015 command.erase(start_backtick-1, 1);
1016 // No need to add one to start_backtick since we just deleted a char
1017 pos = start_backtick;
1018 }
1019 else
1020 {
1021 const size_t expr_content_start = start_backtick + 1;
1022 const size_t end_backtick = command.find ('`', expr_content_start);
1023 if (end_backtick == std::string::npos)
1024 return error;
1025 else if (end_backtick == expr_content_start)
1026 {
1027 // Empty expression (two backticks in a row)
1028 command.erase (start_backtick, 2);
1029 }
1030 else
1031 {
1032 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1033
1034 Target *target = m_exe_ctx.GetTargetPtr();
1035 if (target)
1036 {
1037 const bool unwind_on_error = true;
1038 const bool keep_in_memory = false;
1039 ValueObjectSP expr_result_valobj_sp;
1040 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1041 m_exe_ctx.GetFramePtr(),
1042 eExecutionPolicyOnlyWhenNeeded,
1043 unwind_on_error, keep_in_memory,
1044 eNoDynamicValues,
1045 expr_result_valobj_sp);
1046 if (expr_result == eExecutionCompleted)
1047 {
1048 Scalar scalar;
1049 if (expr_result_valobj_sp->ResolveValue (scalar))
1050 {
1051 command.erase (start_backtick, end_backtick - start_backtick + 1);
1052 StreamString value_strm;
1053 const bool show_type = false;
1054 scalar.GetValue (&value_strm, show_type);
1055 size_t value_string_size = value_strm.GetSize();
1056 if (value_string_size)
1057 {
1058 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1059 pos = start_backtick + value_string_size;
1060 continue;
1061 }
1062 else
1063 {
1064 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1065 }
1066 }
1067 else
1068 {
1069 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1070 }
1071 }
1072 else
1073 {
1074 if (expr_result_valobj_sp)
1075 error = expr_result_valobj_sp->GetError();
1076 if (error.Success())
1077 {
1078
1079 switch (expr_result)
1080 {
1081 case eExecutionSetupError:
1082 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1083 break;
1084 case eExecutionCompleted:
1085 break;
1086 case eExecutionDiscarded:
1087 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1088 break;
1089 case eExecutionInterrupted:
1090 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1091 break;
1092 case eExecutionTimedOut:
1093 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1094 break;
1095 }
1096 }
1097 }
1098 }
1099 }
1100 if (error.Fail())
1101 break;
1102 }
1103 }
1104 return error;
1105}
1106
1107
Caroline Ticee0da7a52010-12-09 22:52:49 +00001108bool
1109CommandInterpreter::HandleCommand (const char *command_line,
1110 bool add_to_history,
1111 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001112 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001113 bool repeat_on_empty_command,
1114 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001115
Caroline Ticee0da7a52010-12-09 22:52:49 +00001116{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001117
Caroline Ticee0da7a52010-12-09 22:52:49 +00001118 bool done = false;
1119 CommandObject *cmd_obj = NULL;
1120 std::string next_word;
1121 bool wants_raw_input = false;
1122 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001123 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001124
1125 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001126 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1127
1128 // Make a scoped cleanup object that will clear the crash description string
1129 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001130 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001131
Caroline Ticee0da7a52010-12-09 22:52:49 +00001132 if (log)
1133 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001134
Jim Inghamabab14b2010-11-04 23:08:45 +00001135 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1136
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001137 if (!no_context_switching)
1138 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +00001139
Jim Ingham949d5ac2011-02-18 00:54:25 +00001140 bool empty_command = false;
1141 bool comment_command = false;
1142 if (command_string.empty())
1143 empty_command = true;
1144 else
Chris Lattner24943d22010-06-08 16:52:24 +00001145 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001146 const char *k_space_characters = "\t\n\v\f\r ";
1147
1148 size_t non_space = command_string.find_first_not_of (k_space_characters);
1149 // Check for empty line or comment line (lines whose first
1150 // non-space character is the comment character for this interpreter)
1151 if (non_space == std::string::npos)
1152 empty_command = true;
1153 else if (command_string[non_space] == m_comment_char)
1154 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001155 else if (command_string[non_space] == m_repeat_char)
1156 {
1157 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1158 if (history_string == NULL)
1159 {
1160 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1161 result.SetStatus(eReturnStatusFailed);
1162 return false;
1163 }
1164 add_to_history = false;
1165 command_string = history_string;
1166 original_command_string = history_string;
1167 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001168 }
1169
1170 if (empty_command)
1171 {
1172 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001173 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001174 if (m_command_history.empty())
1175 {
1176 result.AppendError ("empty command");
1177 result.SetStatus(eReturnStatusFailed);
1178 return false;
1179 }
1180 else
1181 {
1182 command_line = m_repeat_command.c_str();
1183 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001184 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001185 if (m_repeat_command.empty())
1186 {
1187 result.AppendErrorWithFormat("No auto repeat.\n");
1188 result.SetStatus (eReturnStatusFailed);
1189 return false;
1190 }
1191 }
1192 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001193 }
1194 else
1195 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001196 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1197 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001198 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001199 }
1200 else if (comment_command)
1201 {
1202 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1203 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001204 }
Caroline Tice649116c2011-05-11 16:07:06 +00001205
Greg Claytonf5c0c722011-10-14 07:41:33 +00001206
1207 Error error (PreprocessCommand (command_string));
1208
1209 if (error.Fail())
1210 {
1211 result.AppendError (error.AsCString());
1212 result.SetStatus(eReturnStatusFailed);
1213 return false;
1214 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001215 // Phase 1.
1216
1217 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1218 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1219 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1220 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1221 // 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 +00001222 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001223 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001224
Caroline Ticee0da7a52010-12-09 22:52:49 +00001225 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001226 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001227 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001228 {
Caroline Tice649116c2011-05-11 16:07:06 +00001229 bool was_quoted = false;
1230 char quote_char = '\0';
1231 StripFirstWord (command_string, next_word, was_quoted, quote_char);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001232 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +00001233 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001234 std::string alias_result;
1235 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
1236 revised_command_line.Printf ("%s", alias_result.c_str());
1237 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +00001238 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001239 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +00001240 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1241 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001242 }
1243 else if (!cmd_obj)
1244 {
1245 cmd_obj = GetCommandObject (next_word.c_str());
1246 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +00001247 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001248 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +00001249 revised_command_line.Printf ("%s", next_word.c_str());
1250 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +00001251 }
1252 else
1253 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001254 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001255 }
1256 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001257 else if (cmd_obj->IsMultiwordObject ())
1258 {
1259 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1260 if (sub_cmd_obj)
1261 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001262 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001263 revised_command_line.Printf (" %s", next_word.c_str());
1264 cmd_obj = sub_cmd_obj;
1265 wants_raw_input = cmd_obj->WantsRawCommandString ();
1266 }
1267 else
1268 {
Caroline Tice649116c2011-05-11 16:07:06 +00001269 if (was_quoted)
1270 {
1271 if (quote_char == '"')
1272 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1273 else
1274 revised_command_line.Printf (" '%s'", next_word.c_str());
1275 }
1276 else
1277 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001278 done = true;
1279 }
1280 }
1281 else
1282 {
Caroline Tice649116c2011-05-11 16:07:06 +00001283 if (was_quoted)
1284 {
1285 if (quote_char == '"')
1286 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1287 else
1288 revised_command_line.Printf (" '%s'", next_word.c_str());
1289 }
1290 else
1291 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001292 done = true;
1293 }
1294
1295 if (cmd_obj == NULL)
1296 {
1297 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1298 result.SetStatus (eReturnStatusFailed);
1299 return false;
1300 }
1301
1302 next_word.erase ();
1303 if (command_string.length() == 0)
1304 done = true;
1305
Chris Lattner24943d22010-06-08 16:52:24 +00001306 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001307
1308 if (command_string.size() > 0)
1309 revised_command_line.Printf (" %s", command_string.c_str());
1310
1311 // End of Phase 1.
1312 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1313 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1314 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1315 // wants_raw_input specifies whether the Execute method expects raw input or not.
1316
1317
1318 if (log)
1319 {
1320 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1321 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1322 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1323 }
1324
1325 // Phase 2.
1326 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1327 // CommandObject, with the appropriate arguments.
1328
1329 if (cmd_obj != NULL)
1330 {
1331 if (add_to_history)
1332 {
1333 Args command_args (revised_command_line.GetData());
1334 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1335 if (repeat_command != NULL)
1336 m_repeat_command.assign(repeat_command);
1337 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001338 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001339
Jim Ingham6247dbe2011-07-12 03:12:18 +00001340 // Don't keep pushing the same command onto the history...
1341 if (m_command_history.size() == 0 || m_command_history.back() != original_command_string)
1342 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001343 }
1344
1345 command_string = revised_command_line.GetData();
1346 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001347 std::string remainder;
1348 if (actual_cmd_name_len < command_string.length())
1349 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1350 // than cmd_obj->GetCommandName(), because name completion
1351 // allows users to enter short versions of the names,
1352 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001353
1354 // Remove any initial spaces
1355 std::string white_space (" \t\v");
1356 size_t pos = remainder.find_first_not_of (white_space);
1357 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001358 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001359
1360 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001361 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001362
1363
1364 if (wants_raw_input)
1365 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1366 else
1367 {
1368 Args cmd_args (remainder.c_str());
1369 cmd_obj->ExecuteWithOptions (cmd_args, result);
1370 }
1371 }
1372 else
1373 {
1374 // We didn't find the first command object, so complete the first argument.
1375 Args command_args (revised_command_line.GetData());
1376 StringList matches;
1377 int num_matches;
1378 int cursor_index = 0;
1379 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1380 bool word_complete;
1381 num_matches = HandleCompletionMatches (command_args,
1382 cursor_index,
1383 cursor_char_position,
1384 0,
1385 -1,
1386 word_complete,
1387 matches);
1388
1389 if (num_matches > 0)
1390 {
1391 std::string error_msg;
1392 error_msg.assign ("ambiguous command '");
1393 error_msg.append(command_args.GetArgumentAtIndex(0));
1394 error_msg.append ("'.");
1395
1396 error_msg.append (" Possible completions:");
1397 for (int i = 0; i < num_matches; i++)
1398 {
1399 error_msg.append ("\n\t");
1400 error_msg.append (matches.GetStringAtIndex (i));
1401 }
1402 error_msg.append ("\n");
1403 result.AppendRawError (error_msg.c_str(), error_msg.size());
1404 }
1405 else
1406 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1407
1408 result.SetStatus (eReturnStatusFailed);
1409 }
1410
Jason Molenda24c991c2011-08-25 00:20:04 +00001411 if (log)
1412 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1413
Chris Lattner24943d22010-06-08 16:52:24 +00001414 return result.Succeeded();
1415}
1416
1417int
1418CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1419 int &cursor_index,
1420 int &cursor_char_position,
1421 int match_start_point,
1422 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001423 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001424 StringList &matches)
1425{
1426 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001427 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001428
1429 // For any of the command completions a unique match will be a complete word.
1430 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001431
1432 if (cursor_index == -1)
1433 {
1434 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001435 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001436 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1437 }
1438 else if (cursor_index == 0)
1439 {
1440 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001441 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001442 num_command_matches = matches.GetSize();
1443
1444 if (num_command_matches == 1
1445 && cmd_obj && cmd_obj->IsMultiwordObject()
1446 && matches.GetStringAtIndex(0) != NULL
1447 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1448 {
1449 look_for_subcommand = true;
1450 num_command_matches = 0;
1451 matches.DeleteStringAtIndex(0);
1452 parsed_line.AppendArgument ("");
1453 cursor_index++;
1454 cursor_char_position = 0;
1455 }
1456 }
1457
1458 if (cursor_index > 0 || look_for_subcommand)
1459 {
1460 // We are completing further on into a commands arguments, so find the command and tell it
1461 // to complete the command.
1462 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001463 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001464 if (command_object == NULL)
1465 {
1466 return 0;
1467 }
1468 else
1469 {
1470 parsed_line.Shift();
1471 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001472 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001473 cursor_index,
1474 cursor_char_position,
1475 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001476 max_return_elements,
1477 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001478 matches);
1479 }
1480 }
1481
1482 return num_command_matches;
1483
1484}
1485
1486int
1487CommandInterpreter::HandleCompletion (const char *current_line,
1488 const char *cursor,
1489 const char *last_char,
1490 int match_start_point,
1491 int max_return_elements,
1492 StringList &matches)
1493{
1494 // We parse the argument up to the cursor, so the last argument in parsed_line is
1495 // the one containing the cursor, and the cursor is after the last character.
1496
1497 Args parsed_line(current_line, last_char - current_line);
1498 Args partial_parsed_line(current_line, cursor - current_line);
1499
Jim Ingham6247dbe2011-07-12 03:12:18 +00001500 // Don't complete comments, and if the line we are completing is just the history repeat character,
1501 // substitute the appropriate history line.
1502 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1503 if (first_arg)
1504 {
1505 if (first_arg[0] == m_comment_char)
1506 return 0;
1507 else if (first_arg[0] == m_repeat_char)
1508 {
1509 const char *history_string = FindHistoryString (first_arg);
1510 if (history_string != NULL)
1511 {
1512 matches.Clear();
1513 matches.InsertStringAtIndex(0, history_string);
1514 return -2;
1515 }
1516 else
1517 return 0;
1518
1519 }
1520 }
1521
1522
Chris Lattner24943d22010-06-08 16:52:24 +00001523 int num_args = partial_parsed_line.GetArgumentCount();
1524 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1525 int cursor_char_position;
1526
1527 if (cursor_index == -1)
1528 cursor_char_position = 0;
1529 else
1530 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001531
1532 if (cursor > current_line && cursor[-1] == ' ')
1533 {
1534 // We are just after a space. If we are in an argument, then we will continue
1535 // parsing, but if we are between arguments, then we have to complete whatever the next
1536 // element would be.
1537 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1538 // protected by a quote) then the space will also be in the parsed argument...
1539
1540 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1541 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1542 {
1543 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1544 cursor_index++;
1545 cursor_char_position = 0;
1546 }
1547 }
Chris Lattner24943d22010-06-08 16:52:24 +00001548
1549 int num_command_matches;
1550
1551 matches.Clear();
1552
1553 // Only max_return_elements == -1 is supported at present:
1554 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001555 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001556 num_command_matches = HandleCompletionMatches (parsed_line,
1557 cursor_index,
1558 cursor_char_position,
1559 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001560 max_return_elements,
1561 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001562 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001563
1564 if (num_command_matches <= 0)
1565 return num_command_matches;
1566
1567 if (num_args == 0)
1568 {
1569 // If we got an empty string, insert nothing.
1570 matches.InsertStringAtIndex(0, "");
1571 }
1572 else
1573 {
1574 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1575 // put an empty string in element 0.
1576 std::string command_partial_str;
1577 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001578 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1579 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001580
1581 std::string common_prefix;
1582 matches.LongestCommonPrefix (common_prefix);
1583 int partial_name_len = command_partial_str.size();
1584
1585 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001586 // Only do this if the completer told us this was a complete word, however...
1587 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001588 {
1589 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1590 if (quote_char != '\0')
1591 common_prefix.push_back(quote_char);
1592
1593 common_prefix.push_back(' ');
1594 }
1595 common_prefix.erase (0, partial_name_len);
1596 matches.InsertStringAtIndex(0, common_prefix.c_str());
1597 }
1598 return num_command_matches;
1599}
1600
Chris Lattner24943d22010-06-08 16:52:24 +00001601
1602CommandInterpreter::~CommandInterpreter ()
1603{
1604}
1605
1606const char *
1607CommandInterpreter::GetPrompt ()
1608{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001609 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001610}
1611
1612void
1613CommandInterpreter::SetPrompt (const char *new_prompt)
1614{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001615 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001616}
1617
Jim Ingham5e16ef52010-10-04 19:49:29 +00001618size_t
Greg Clayton58928562011-02-09 01:08:52 +00001619CommandInterpreter::GetConfirmationInputReaderCallback
1620(
1621 void *baton,
1622 InputReader &reader,
1623 lldb::InputReaderAction action,
1624 const char *bytes,
1625 size_t bytes_len
1626)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001627{
Greg Clayton58928562011-02-09 01:08:52 +00001628 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001629 bool *response_ptr = (bool *) baton;
1630
1631 switch (action)
1632 {
1633 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001634 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001635 {
1636 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001637 {
Greg Clayton58928562011-02-09 01:08:52 +00001638 out_file.Printf ("%s", reader.GetPrompt());
1639 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001640 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001641 }
1642 break;
1643
1644 case eInputReaderDeactivate:
1645 break;
1646
1647 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001648 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001649 {
Greg Clayton58928562011-02-09 01:08:52 +00001650 out_file.Printf ("%s", reader.GetPrompt());
1651 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001652 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001653 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001654
1655 case eInputReaderAsynchronousOutputWritten:
1656 break;
1657
Jim Ingham5e16ef52010-10-04 19:49:29 +00001658 case eInputReaderGotToken:
1659 if (bytes_len == 0)
1660 {
1661 reader.SetIsDone(true);
1662 }
1663 else if (bytes[0] == 'y')
1664 {
1665 *response_ptr = true;
1666 reader.SetIsDone(true);
1667 }
1668 else if (bytes[0] == 'n')
1669 {
1670 *response_ptr = false;
1671 reader.SetIsDone(true);
1672 }
1673 else
1674 {
Greg Clayton58928562011-02-09 01:08:52 +00001675 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001676 {
Greg Clayton58928562011-02-09 01:08:52 +00001677 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1678 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001679 }
1680 }
1681 break;
1682
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001683 case eInputReaderInterrupt:
1684 case eInputReaderEndOfFile:
1685 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1686 reader.SetIsDone (true);
1687 break;
1688
Jim Ingham5e16ef52010-10-04 19:49:29 +00001689 case eInputReaderDone:
1690 break;
1691 }
1692
1693 return bytes_len;
1694
1695}
1696
1697bool
1698CommandInterpreter::Confirm (const char *message, bool default_answer)
1699{
Jim Ingham93057472010-10-04 22:44:14 +00001700 // Check AutoConfirm first:
1701 if (m_debugger.GetAutoConfirm())
1702 return default_answer;
1703
Jim Ingham5e16ef52010-10-04 19:49:29 +00001704 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1705 bool response = default_answer;
1706 if (reader_sp)
1707 {
1708 std::string prompt(message);
1709 prompt.append(": [");
1710 if (default_answer)
1711 prompt.append ("Y/n] ");
1712 else
1713 prompt.append ("y/N] ");
1714
1715 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1716 &response, // baton
1717 eInputReaderGranularityLine, // token size, to pass to callback function
1718 NULL, // end token
1719 prompt.c_str(), // prompt
1720 true)); // echo input
1721 if (err.Success())
1722 {
1723 GetDebugger().PushInputReader (reader_sp);
1724 }
1725 reader_sp->WaitOnReaderIsDone();
1726 }
1727 return response;
1728}
1729
1730
Chris Lattner24943d22010-06-08 16:52:24 +00001731void
1732CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1733{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001734 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001735
1736 if (cmd_obj_sp != NULL)
1737 {
1738 CommandObject *cmd_obj = cmd_obj_sp.get();
1739 if (cmd_obj->IsCrossRefObject ())
1740 cmd_obj->AddObject (object_type);
1741 }
1742}
1743
Chris Lattner24943d22010-06-08 16:52:24 +00001744OptionArgVectorSP
1745CommandInterpreter::GetAliasOptions (const char *alias_name)
1746{
1747 OptionArgMap::iterator pos;
1748 OptionArgVectorSP ret_val;
1749
1750 std::string alias (alias_name);
1751
1752 if (HasAliasOptions())
1753 {
1754 pos = m_alias_options.find (alias);
1755 if (pos != m_alias_options.end())
1756 ret_val = pos->second;
1757 }
1758
1759 return ret_val;
1760}
1761
1762void
1763CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1764{
1765 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1766 if (pos != m_alias_options.end())
1767 {
1768 m_alias_options.erase (pos);
1769 }
1770}
1771
1772void
1773CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1774{
1775 m_alias_options[alias_name] = option_arg_vector_sp;
1776}
1777
1778bool
1779CommandInterpreter::HasCommands ()
1780{
1781 return (!m_command_dict.empty());
1782}
1783
1784bool
1785CommandInterpreter::HasAliases ()
1786{
1787 return (!m_alias_dict.empty());
1788}
1789
1790bool
1791CommandInterpreter::HasUserCommands ()
1792{
1793 return (!m_user_dict.empty());
1794}
1795
1796bool
1797CommandInterpreter::HasAliasOptions ()
1798{
1799 return (!m_alias_options.empty());
1800}
1801
Chris Lattner24943d22010-06-08 16:52:24 +00001802void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001803CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1804 const char *alias_name,
1805 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001806 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001807 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001808{
1809 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001810
1811 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001812
Caroline Tice44c841d2010-12-07 19:58:26 +00001813 // Make sure that the alias name is the 0th element in cmd_args
1814 std::string alias_name_str = alias_name;
1815 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1816 cmd_args.Unshift (alias_name);
1817
1818 Args new_args (alias_cmd_obj->GetCommandName());
1819 if (new_args.GetArgumentCount() == 2)
1820 new_args.Shift();
1821
Chris Lattner24943d22010-06-08 16:52:24 +00001822 if (option_arg_vector_sp.get())
1823 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001824 if (wants_raw_input)
1825 {
1826 // We have a command that both has command options and takes raw input. Make *sure* it has a
1827 // " -- " in the right place in the raw_input_string.
1828 size_t pos = raw_input_string.find(" -- ");
1829 if (pos == std::string::npos)
1830 {
1831 // None found; assume it goes at the beginning of the raw input string
1832 raw_input_string.insert (0, " -- ");
1833 }
1834 }
Chris Lattner24943d22010-06-08 16:52:24 +00001835
1836 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1837 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001838 std::vector<bool> used (old_size + 1, false);
1839
1840 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001841
1842 for (int i = 0; i < option_arg_vector->size(); ++i)
1843 {
1844 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001845 OptionArgValue value_pair = option_pair.second;
1846 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001847 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001848 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001849 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001850 {
1851 if (!wants_raw_input
1852 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1853 new_args.AppendArgument (value.c_str());
1854 }
Chris Lattner24943d22010-06-08 16:52:24 +00001855 else
1856 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001857 if (value_type != optional_argument)
1858 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001859 if (value.compare ("<no-argument>") != 0)
1860 {
1861 int index = GetOptionArgumentPosition (value.c_str());
1862 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001863 {
Chris Lattner24943d22010-06-08 16:52:24 +00001864 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001865 if (value_type != optional_argument)
1866 new_args.AppendArgument (value.c_str());
1867 else
1868 {
1869 char buffer[255];
1870 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1871 new_args.AppendArgument (buffer);
1872 }
1873
1874 }
Chris Lattner24943d22010-06-08 16:52:24 +00001875 else if (index >= cmd_args.GetArgumentCount())
1876 {
1877 result.AppendErrorWithFormat
1878 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1879 index);
1880 result.SetStatus (eReturnStatusFailed);
1881 return;
1882 }
1883 else
1884 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001885 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1886 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1887 if (strpos != std::string::npos)
1888 {
1889 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1890 }
1891
1892 if (value_type != optional_argument)
1893 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1894 else
1895 {
1896 char buffer[255];
1897 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1898 cmd_args.GetArgumentAtIndex (index));
1899 new_args.AppendArgument (buffer);
1900 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001901 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001902 }
1903 }
1904 }
1905 }
1906
1907 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1908 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001909 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001910 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1911 }
1912
1913 cmd_args.Clear();
1914 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1915 }
1916 else
1917 {
1918 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001919 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1920 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1921 // input string.
1922 if (wants_raw_input)
1923 {
1924 cmd_args.Clear();
1925 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1926 }
Chris Lattner24943d22010-06-08 16:52:24 +00001927 return;
1928 }
1929
1930 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1931 return;
1932}
1933
1934
1935int
1936CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1937{
1938 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1939 // of zero.
1940
1941 char *cptr = (char *) in_string;
1942
1943 // Does it start with '%'
1944 if (cptr[0] == '%')
1945 {
1946 ++cptr;
1947
1948 // Is the rest of it entirely digits?
1949 if (isdigit (cptr[0]))
1950 {
1951 const char *start = cptr;
1952 while (isdigit (cptr[0]))
1953 ++cptr;
1954
1955 // We've gotten to the end of the digits; are we at the end of the string?
1956 if (cptr[0] == '\0')
1957 position = atoi (start);
1958 }
1959 }
1960
1961 return position;
1962}
1963
1964void
1965CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1966{
Jim Ingham574c3d62011-08-12 23:34:31 +00001967 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00001968 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00001969 {
Greg Claytond6edcb52011-09-11 00:01:44 +00001970 // In the current working directory we don't load any program specific
1971 // .lldbinit files, we only look for a "./.lldbinit" file.
1972 if (m_skip_lldbinit_files)
1973 return;
1974
1975 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00001976 }
Greg Claytond6edcb52011-09-11 00:01:44 +00001977 else
Jim Ingham574c3d62011-08-12 23:34:31 +00001978 {
Greg Claytond6edcb52011-09-11 00:01:44 +00001979 // If we aren't looking in the current working directory we are looking
1980 // in the home directory. We will first see if there is an application
1981 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
1982 // "-" and the name of the program. If this file doesn't exist, we fall
1983 // back to just the "~/.lldbinit" file. We also obey any requests to not
1984 // load the init files.
1985 const char *init_file_path = "~/.lldbinit";
1986
1987 if (m_skip_app_init_files == false)
1988 {
1989 FileSpec program_file_spec (Host::GetProgramFileSpec());
1990 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00001991
Greg Claytond6edcb52011-09-11 00:01:44 +00001992 if (program_name)
1993 {
1994 char program_init_file_name[PATH_MAX];
1995 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
1996 init_file.SetFile (program_init_file_name, true);
1997 if (!init_file.Exists())
1998 init_file.Clear();
1999 }
2000 }
2001
2002 if (!init_file && !m_skip_lldbinit_files)
2003 init_file.SetFile (init_file_path, true);
2004 }
2005
Chris Lattner24943d22010-06-08 16:52:24 +00002006 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2007 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2008
2009 if (init_file.Exists())
2010 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002011 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2012 bool stop_on_continue = true;
2013 bool stop_on_error = false;
2014 bool echo_commands = false;
2015 bool print_results = false;
2016
2017 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002018 }
2019 else
2020 {
2021 // nothing to be done if the file doesn't exist
2022 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2023 }
2024}
2025
Greg Claytonb72d0f02011-04-12 05:54:46 +00002026PlatformSP
2027CommandInterpreter::GetPlatform (bool prefer_target_platform)
2028{
2029 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002030 if (prefer_target_platform)
2031 {
2032 Target *target = m_exe_ctx.GetTargetPtr();
2033 if (target)
2034 platform_sp = target->GetPlatform();
2035 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002036
2037 if (!platform_sp)
2038 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2039 return platform_sp;
2040}
2041
Jim Ingham949d5ac2011-02-18 00:54:25 +00002042void
Jim Inghama4fede32011-03-11 01:51:49 +00002043CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002044 ExecutionContext *override_context,
2045 bool stop_on_continue,
2046 bool stop_on_error,
2047 bool echo_commands,
2048 bool print_results,
2049 CommandReturnObject &result)
2050{
2051 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002052
2053 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2054 // Make sure you reset this value anywhere you return from the function.
2055
2056 bool old_async_execution = m_debugger.GetAsyncExecution();
2057
2058 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2059 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2060
2061 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002062 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002063
2064 if (!stop_on_continue)
2065 {
2066 m_debugger.SetAsyncExecution (false);
2067 }
2068
2069 for (int idx = 0; idx < num_lines; idx++)
2070 {
2071 const char *cmd = commands.GetStringAtIndex(idx);
2072 if (cmd[0] == '\0')
2073 continue;
2074
Jim Ingham949d5ac2011-02-18 00:54:25 +00002075 if (echo_commands)
2076 {
2077 result.AppendMessageWithFormat ("%s %s\n",
2078 GetPrompt(),
2079 cmd);
2080 }
2081
Greg Claytonaa378b12011-02-20 02:15:07 +00002082 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002083 // If override_context is not NULL, pass no_context_switching = true for
2084 // HandleCommand() since we updated our context already.
2085 bool success = HandleCommand(cmd, false, tmp_result,
2086 NULL, /* override_context */
2087 true, /* repeat_on_empty_command */
2088 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002089
2090 if (print_results)
2091 {
2092 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002093 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002094 }
2095
2096 if (!success || !tmp_result.Succeeded())
2097 {
2098 if (stop_on_error)
2099 {
2100 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
2101 idx, cmd);
2102 result.SetStatus (eReturnStatusFailed);
2103 m_debugger.SetAsyncExecution (old_async_execution);
2104 return;
2105 }
2106 else if (print_results)
2107 {
2108 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
2109 idx + 1,
2110 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002111 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002112 }
2113 }
2114
Caroline Tice4a348082011-05-02 20:41:46 +00002115 if (result.GetImmediateOutputStream())
2116 result.GetImmediateOutputStream()->Flush();
2117
2118 if (result.GetImmediateErrorStream())
2119 result.GetImmediateErrorStream()->Flush();
2120
Jim Ingham949d5ac2011-02-18 00:54:25 +00002121 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2122 // could be running (for instance in Breakpoint Commands.
2123 // So we check the return value to see if it is has running in it.
2124 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2125 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2126 {
2127 if (stop_on_continue)
2128 {
2129 // If we caused the target to proceed, and we're going to stop in that case, set the
2130 // status in our real result before returning. This is an error if the continue was not the
2131 // last command in the set of commands to be run.
2132 if (idx != num_lines - 1)
2133 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2134 idx + 1, cmd);
2135 else
2136 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2137
2138 result.SetStatus(tmp_result.GetStatus());
2139 m_debugger.SetAsyncExecution (old_async_execution);
2140
2141 return;
2142 }
2143 }
2144
2145 }
2146
2147 result.SetStatus (eReturnStatusSuccessFinishResult);
2148 m_debugger.SetAsyncExecution (old_async_execution);
2149
2150 return;
2151}
2152
2153void
2154CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2155 ExecutionContext *context,
2156 bool stop_on_continue,
2157 bool stop_on_error,
2158 bool echo_command,
2159 bool print_result,
2160 CommandReturnObject &result)
2161{
2162 if (cmd_file.Exists())
2163 {
2164 bool success;
2165 StringList commands;
2166 success = commands.ReadFileLines(cmd_file);
2167 if (!success)
2168 {
2169 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2170 result.SetStatus (eReturnStatusFailed);
2171 return;
2172 }
2173 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
2174 }
2175 else
2176 {
2177 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2178 cmd_file.GetFilename().AsCString());
2179 result.SetStatus (eReturnStatusFailed);
2180 return;
2181 }
2182}
2183
Chris Lattner24943d22010-06-08 16:52:24 +00002184ScriptInterpreter *
2185CommandInterpreter::GetScriptInterpreter ()
2186{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002187 if (m_script_interpreter_ap.get() != NULL)
2188 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002189
Caroline Tice0aa2e552011-01-14 00:29:16 +00002190 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2191 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002192 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00002193 case eScriptLanguageNone:
2194 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2195 break;
2196 case eScriptLanguagePython:
2197 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2198 break;
2199 default:
2200 break;
2201 };
2202
2203 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002204}
2205
2206
2207
2208bool
2209CommandInterpreter::GetSynchronous ()
2210{
2211 return m_synchronous_execution;
2212}
2213
2214void
2215CommandInterpreter::SetSynchronous (bool value)
2216{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002217 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002218}
2219
2220void
2221CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2222 const char *word_text,
2223 const char *separator,
2224 const char *help_text,
2225 uint32_t max_word_len)
2226{
Greg Clayton238c0a12010-09-18 01:14:36 +00002227 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2228
Chris Lattner24943d22010-06-08 16:52:24 +00002229 int indent_size = max_word_len + strlen (separator) + 2;
2230
2231 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002232
2233 StreamString text_strm;
2234 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2235
2236 size_t len = text_strm.GetSize();
2237 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002238 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002239 {
2240 text_strm.EOL();
2241 len = text_strm.GetSize();
2242 }
Chris Lattner24943d22010-06-08 16:52:24 +00002243
2244 if (len < max_columns)
2245 {
2246 // Output it as a single line.
2247 strm.Printf ("%s", text);
2248 }
2249 else
2250 {
2251 // We need to break it up into multiple lines.
2252 bool first_line = true;
2253 int text_width;
2254 int start = 0;
2255 int end = start;
2256 int final_end = strlen (text);
2257 int sub_len;
2258
2259 while (end < final_end)
2260 {
2261 if (first_line)
2262 text_width = max_columns - 1;
2263 else
2264 text_width = max_columns - indent_size - 1;
2265
2266 // Don't start the 'text' on a space, since we're already outputting the indentation.
2267 if (!first_line)
2268 {
2269 while ((start < final_end) && (text[start] == ' '))
2270 start++;
2271 }
2272
2273 end = start + text_width;
2274 if (end > final_end)
2275 end = final_end;
2276 else
2277 {
2278 // If we're not at the end of the text, make sure we break the line on white space.
2279 while (end > start
2280 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2281 end--;
2282 }
2283
2284 sub_len = end - start;
2285 if (start != 0)
2286 strm.EOL();
2287 if (!first_line)
2288 strm.Indent();
2289 else
2290 first_line = false;
2291 assert (start <= final_end);
2292 assert (start + sub_len <= final_end);
2293 if (sub_len > 0)
2294 strm.Write (text + start, sub_len);
2295 start = end + 1;
2296 }
2297 }
2298 strm.EOL();
2299 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002300}
2301
2302void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002303CommandInterpreter::OutputHelpText (Stream &strm,
2304 const char *word_text,
2305 const char *separator,
2306 const char *help_text,
2307 uint32_t max_word_len)
2308{
2309 int indent_size = max_word_len + strlen (separator) + 2;
2310
2311 strm.IndentMore (indent_size);
2312
2313 StreamString text_strm;
2314 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2315
2316 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2317 bool first_line = true;
2318
2319 size_t len = text_strm.GetSize();
2320 const char *text = text_strm.GetData();
2321
2322 uint32_t chars_left = max_columns;
2323
2324 for (uint32_t i = 0; i < len; i++)
2325 {
2326 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2327 {
2328 first_line = false;
2329 chars_left = max_columns - indent_size;
2330 strm.EOL();
2331 strm.Indent();
2332 }
2333 else
2334 {
2335 strm.PutChar(text[i]);
2336 chars_left--;
2337 }
2338
2339 }
2340
2341 strm.EOL();
2342 strm.IndentLess(indent_size);
2343}
2344
2345void
Chris Lattner24943d22010-06-08 16:52:24 +00002346CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2347 StringList &commands_found, StringList &commands_help)
2348{
2349 CommandObject::CommandMap::const_iterator pos;
2350 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2351 CommandObject *sub_cmd_obj;
2352
2353 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2354 {
2355 const char * command_name = pos->first.c_str();
2356 sub_cmd_obj = pos->second.get();
2357 StreamString complete_command_name;
2358
2359 complete_command_name.Printf ("%s %s", prefix, command_name);
2360
Greg Clayton238c0a12010-09-18 01:14:36 +00002361 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002362 {
2363 commands_found.AppendString (complete_command_name.GetData());
2364 commands_help.AppendString (sub_cmd_obj->GetHelp());
2365 }
2366
2367 if (sub_cmd_obj->IsMultiwordObject())
2368 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2369 commands_help);
2370 }
2371
2372}
2373
2374void
2375CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2376 StringList &commands_help)
2377{
2378 CommandObject::CommandMap::const_iterator pos;
2379
2380 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2381 {
2382 const char *command_name = pos->first.c_str();
2383 CommandObject *cmd_obj = pos->second.get();
2384
Greg Clayton238c0a12010-09-18 01:14:36 +00002385 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002386 {
2387 commands_found.AppendString (command_name);
2388 commands_help.AppendString (cmd_obj->GetHelp());
2389 }
2390
2391 if (cmd_obj->IsMultiwordObject())
2392 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2393
2394 }
2395}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002396
2397
2398void
2399CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2400{
2401 m_exe_ctx.Clear();
2402
2403 if (override_context != NULL)
2404 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002405 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002406 }
2407 else
2408 {
2409 TargetSP target_sp (m_debugger.GetSelectedTarget());
2410 if (target_sp)
2411 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002412 m_exe_ctx.SetTargetSP (target_sp);
2413 ProcessSP process_sp (target_sp->GetProcessSP());
2414 m_exe_ctx.SetProcessSP (process_sp);
2415 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002416 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002417 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread().get());
2418 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002419 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002420 m_exe_ctx.SetThreadSP (thread_sp);
2421 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2422 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002423 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002424 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002425 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002426 if (frame_sp)
2427 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002428 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002429 if (frame_sp)
2430 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002431 }
2432 }
2433 }
2434 }
2435}
2436
Jim Ingham6247dbe2011-07-12 03:12:18 +00002437void
2438CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2439{
2440 DumpHistory (stream, 0, count - 1);
2441}
2442
2443void
2444CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2445{
2446 size_t num_history_elements = m_command_history.size();
2447 if (start > num_history_elements)
2448 return;
2449 for (uint32_t i = start; i < num_history_elements && i <= end; i++)
2450 {
2451 if (!m_command_history[i].empty())
2452 {
2453 stream.Indent();
2454 stream.Printf ("%4d: %s\n", i, m_command_history[i].c_str());
2455 }
2456 }
2457}
2458
2459const char *
2460CommandInterpreter::FindHistoryString (const char *input_str) const
2461{
2462 if (input_str[0] != m_repeat_char)
2463 return NULL;
2464 if (input_str[1] == '-')
2465 {
2466 bool success;
2467 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2468 if (!success)
2469 return NULL;
2470 if (idx > m_command_history.size())
2471 return NULL;
2472 idx = m_command_history.size() - idx;
2473 return m_command_history[idx].c_str();
2474
2475 }
2476 else if (input_str[1] == m_repeat_char)
2477 {
2478 if (m_command_history.empty())
2479 return NULL;
2480 else
2481 return m_command_history.back().c_str();
2482 }
2483 else
2484 {
2485 bool success;
2486 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2487 if (!success)
2488 return NULL;
2489 if (idx >= m_command_history.size())
2490 return NULL;
2491 return m_command_history[idx].c_str();
2492 }
2493}