blob: ab50edf9526d6fff6fb4f67986a1e331cdac0f7c [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"
Chris Lattner24943d22010-06-08 16:52:24 +000040
Jim Ingham84cdc152010-06-15 19:49:27 +000041#include "lldb/Interpreter/Args.h"
Caroline Tice5ddbe212011-05-06 21:37:15 +000042#include "lldb/Interpreter/Options.h"
Chris Lattner24943d22010-06-08 16:52:24 +000043#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000044#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000045#include "lldb/Core/Stream.h"
46#include "lldb/Core/Timer.h"
Greg Claytoncd548032011-02-01 01:31:41 +000047#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000048#include "lldb/Target/Process.h"
49#include "lldb/Target/Thread.h"
50#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000051#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000052
53#include "lldb/Interpreter/CommandReturnObject.h"
54#include "lldb/Interpreter/CommandInterpreter.h"
Caroline Tice0aa2e552011-01-14 00:29:16 +000055#include "lldb/Interpreter/ScriptInterpreterNone.h"
56#include "lldb/Interpreter/ScriptInterpreterPython.h"
Chris Lattner24943d22010-06-08 16:52:24 +000057
58using namespace lldb;
59using namespace lldb_private;
60
61CommandInterpreter::CommandInterpreter
62(
Greg Clayton63094e02010-06-23 01:19:29 +000063 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000064 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000065 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000066) :
Greg Clayton49ce6822010-10-31 03:01:06 +000067 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000068 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000069 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000070 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000071 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000072 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +000073 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +000074 m_repeat_char ('!'),
Enrico Granata293a7b32011-08-15 19:24:02 +000075 m_batch_command_mode (false),
76 m_truncation_warning(eNoTruncation)
Chris Lattner24943d22010-06-08 16:52:24 +000077{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000078 const char *dbg_name = debugger.GetInstanceName().AsCString();
79 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
80 StreamString var_name;
81 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000082 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000083 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000084 m_debugger.GetInstanceName().AsCString());
85 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
86 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
87 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000088}
89
90void
91CommandInterpreter::Initialize ()
92{
93 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
94
95 CommandReturnObject result;
96
97 LoadCommandDictionary ();
98
Chris Lattner24943d22010-06-08 16:52:24 +000099 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000100 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
101 if (cmd_obj_sp)
102 {
103 AddAlias ("q", cmd_obj_sp);
104 AddAlias ("exit", cmd_obj_sp);
105 }
106
107 cmd_obj_sp = GetCommandSPExact ("process continue", false);
108 if (cmd_obj_sp)
109 {
110 AddAlias ("c", cmd_obj_sp);
111 AddAlias ("continue", cmd_obj_sp);
112 }
113
114 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
115 if (cmd_obj_sp)
116 AddAlias ("b", cmd_obj_sp);
117
118 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
119 if (cmd_obj_sp)
120 AddAlias ("bt", cmd_obj_sp);
121
122 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
123 if (cmd_obj_sp)
124 AddAlias ("si", cmd_obj_sp);
125
126 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
127 if (cmd_obj_sp)
128 {
129 AddAlias ("s", cmd_obj_sp);
130 AddAlias ("step", cmd_obj_sp);
131 }
132
133 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
134 if (cmd_obj_sp)
135 {
136 AddAlias ("n", cmd_obj_sp);
137 AddAlias ("next", cmd_obj_sp);
138 }
139
140 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
141 if (cmd_obj_sp)
142 {
143 AddAlias ("f", cmd_obj_sp);
144 AddAlias ("finish", cmd_obj_sp);
145 }
146
147 cmd_obj_sp = GetCommandSPExact ("source list", false);
148 if (cmd_obj_sp)
149 {
150 AddAlias ("l", cmd_obj_sp);
151 AddAlias ("list", cmd_obj_sp);
152 }
153
154 cmd_obj_sp = GetCommandSPExact ("memory read", false);
155 if (cmd_obj_sp)
156 AddAlias ("x", cmd_obj_sp);
157
158 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
159 if (cmd_obj_sp)
160 AddAlias ("up", cmd_obj_sp);
161
162 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
163 if (cmd_obj_sp)
164 AddAlias ("down", cmd_obj_sp);
165
166 cmd_obj_sp = GetCommandSPExact ("target create", false);
167 if (cmd_obj_sp)
168 AddAlias ("file", cmd_obj_sp);
169
170 cmd_obj_sp = GetCommandSPExact ("target modules", false);
171 if (cmd_obj_sp)
172 AddAlias ("image", cmd_obj_sp);
173
174
175 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000176
Caroline Tice5ddbe212011-05-06 21:37:15 +0000177 cmd_obj_sp = GetCommandSPExact ("expression", false);
178 if (cmd_obj_sp)
179 {
180 AddAlias ("expr", cmd_obj_sp);
181
182 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
183 AddAlias ("p", cmd_obj_sp);
184 AddAlias ("print", cmd_obj_sp);
185 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
186 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
187
188 alias_arguments_vector_sp.reset (new OptionArgVector);
189 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
190 AddAlias ("po", cmd_obj_sp);
191 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
192 }
193
194 cmd_obj_sp = GetCommandSPExact ("process launch", false);
195 if (cmd_obj_sp)
196 {
197 alias_arguments_vector_sp.reset (new OptionArgVector);
198 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
199 AddAlias ("r", cmd_obj_sp);
200 AddAlias ("run", cmd_obj_sp);
201 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
202 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
203 }
204
Chris Lattner24943d22010-06-08 16:52:24 +0000205}
206
Chris Lattner24943d22010-06-08 16:52:24 +0000207const char *
208CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
209{
210 // This function has not yet been implemented.
211
212 // Look for any embedded script command
213 // If found,
214 // get interpreter object from the command dictionary,
215 // call execute_one_command on it,
216 // get the results as a string,
217 // substitute that string for current stuff.
218
219 return arg;
220}
221
222
223void
224CommandInterpreter::LoadCommandDictionary ()
225{
226 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
227
228 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
229 //
230 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
231 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
232 // the cross-referencing stuff) are created!!!
233 //
234 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
235
236
237 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
238 // are created. This is so that when another command is created that needs to go into a crossref object,
239 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
240 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
241
Chris Lattner24943d22010-06-08 16:52:24 +0000242 // Non-CommandObjectCrossref commands can now be created.
243
Caroline Tice5bc8c972010-09-20 20:44:43 +0000244 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000245
Greg Clayton238c0a12010-09-18 01:14:36 +0000246 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000247 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000248 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000249 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000250 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
251 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000252// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000253 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000254 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000255 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000256 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
257 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000258 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000259 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000260 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000261 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000262 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000263 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000264 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000265 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
266 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Greg Clayton5c28dd12011-06-23 17:59:56 +0000267 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000268 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000269
270 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000271 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000272 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000273 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000274 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000275 if (break_regex_cmd_ap.get())
276 {
277 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
278 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
279 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000280 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000281 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000282 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000283 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
284 {
285 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
286 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
287 }
288 }
Jim Inghame56493f2011-03-22 02:29:32 +0000289
290 std::auto_ptr<CommandObjectRegexCommand>
291 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000292 "_regexp-down",
293 "Go down \"n\" frames in the stack (1 frame by default).",
294 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000295 if (down_regex_cmd_ap.get())
296 {
297 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
298 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
299 {
300 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
301 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
302 }
303 }
304
305 std::auto_ptr<CommandObjectRegexCommand>
306 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000307 "_regexp-up",
308 "Go up \"n\" frames in the stack (1 frame by default).",
309 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000310 if (up_regex_cmd_ap.get())
311 {
312 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
313 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
314 {
315 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
316 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
317 }
318 }
Chris Lattner24943d22010-06-08 16:52:24 +0000319}
320
321int
322CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
323 StringList &matches)
324{
325 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
326
327 if (include_aliases)
328 {
329 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
330 }
331
332 return matches.GetSize();
333}
334
335CommandObjectSP
336CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
337{
338 CommandObject::CommandMap::iterator pos;
339 CommandObjectSP ret_val;
340
341 std::string cmd(cmd_cstr);
342
343 if (HasCommands())
344 {
345 pos = m_command_dict.find(cmd);
346 if (pos != m_command_dict.end())
347 ret_val = pos->second;
348 }
349
350 if (include_aliases && HasAliases())
351 {
352 pos = m_alias_dict.find(cmd);
353 if (pos != m_alias_dict.end())
354 ret_val = pos->second;
355 }
356
357 if (HasUserCommands())
358 {
359 pos = m_user_dict.find(cmd);
360 if (pos != m_user_dict.end())
361 ret_val = pos->second;
362 }
363
364 if (!exact && ret_val == NULL)
365 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000366 // We will only get into here if we didn't find any exact matches.
367
368 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
369
Chris Lattner24943d22010-06-08 16:52:24 +0000370 StringList local_matches;
371 if (matches == NULL)
372 matches = &local_matches;
373
Jim Inghamd40f8a62010-07-06 22:46:59 +0000374 unsigned int num_cmd_matches = 0;
375 unsigned int num_alias_matches = 0;
376 unsigned int num_user_matches = 0;
377
378 // Look through the command dictionaries one by one, and if we get only one match from any of
379 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
380
Chris Lattner24943d22010-06-08 16:52:24 +0000381 if (HasCommands())
382 {
383 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
384 }
385
386 if (num_cmd_matches == 1)
387 {
388 cmd.assign(matches->GetStringAtIndex(0));
389 pos = m_command_dict.find(cmd);
390 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000391 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000392 }
393
Jim Ingham9a574172010-06-24 20:28:42 +0000394 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000395 {
396 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
397
398 }
399
Jim Inghamd40f8a62010-07-06 22:46:59 +0000400 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000401 {
402 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
403 pos = m_alias_dict.find(cmd);
404 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000405 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000406 }
407
Jim Ingham9a574172010-06-24 20:28:42 +0000408 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000409 {
410 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
411 }
412
Jim Inghamd40f8a62010-07-06 22:46:59 +0000413 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000414 {
415 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
416
417 pos = m_user_dict.find (cmd);
418 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000419 user_match_sp = pos->second;
420 }
421
422 // If we got exactly one match, return that, otherwise return the match list.
423
424 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
425 {
426 if (num_cmd_matches)
427 return real_match_sp;
428 else if (num_alias_matches)
429 return alias_match_sp;
430 else
431 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000432 }
433 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000434 else if (matches && ret_val != NULL)
435 {
436 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000437 }
438
439
440 return ret_val;
441}
442
Greg Claytond12aeab2011-04-20 16:37:46 +0000443bool
444CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
445{
446 if (name && name[0])
447 {
448 std::string name_sstr(name);
449 if (!can_replace)
450 {
451 if (m_command_dict.find (name_sstr) != m_command_dict.end())
452 return false;
453 }
454 m_command_dict[name_sstr] = cmd_sp;
455 return true;
456 }
457 return false;
458}
459
460
Jim Inghamd40f8a62010-07-06 22:46:59 +0000461CommandObjectSP
462CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000463{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000464 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
465 CommandObjectSP ret_val; // Possibly empty return value.
466
467 if (cmd_cstr == NULL)
468 return ret_val;
469
470 if (cmd_words.GetArgumentCount() == 1)
471 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
472 else
473 {
474 // We have a multi-word command (seemingly), so we need to do more work.
475 // First, get the cmd_obj_sp for the first word in the command.
476 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
477 if (cmd_obj_sp.get() != NULL)
478 {
479 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
480 // command name), and find the appropriate sub-command SP for each command word....
481 size_t end = cmd_words.GetArgumentCount();
482 for (size_t j= 1; j < end; ++j)
483 {
484 if (cmd_obj_sp->IsMultiwordObject())
485 {
486 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
487 (cmd_words.GetArgumentAtIndex (j));
488 if (cmd_obj_sp.get() == NULL)
489 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
490 return ret_val;
491 }
492 else
493 // We have more words in the command name, but we don't have a multiword object. Fail and return
494 // empty 'ret_val'.
495 return ret_val;
496 }
497 // We successfully looped through all the command words and got valid command objects for them. Assign the
498 // last object retrieved to 'ret_val'.
499 ret_val = cmd_obj_sp;
500 }
501 }
502 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000503}
504
505CommandObject *
506CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
507{
508 return GetCommandSPExact (cmd_cstr, include_aliases).get();
509}
510
511CommandObject *
512CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
513{
514 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
515
516 // If we didn't find an exact match to the command string in the commands, look in
517 // the aliases.
518
519 if (command_obj == NULL)
520 {
521 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
522 }
523
524 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
525 // in both the commands and the aliases.
526
527 if (command_obj == NULL)
528 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
529
530 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000531}
532
533bool
534CommandInterpreter::CommandExists (const char *cmd)
535{
536 return m_command_dict.find(cmd) != m_command_dict.end();
537}
538
539bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000540CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
541 const char *options_args,
542 OptionArgVectorSP &option_arg_vector_sp)
543{
544 bool success = true;
545 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
546
547 if (!options_args || (strlen (options_args) < 1))
548 return true;
549
550 std::string options_string (options_args);
551 Args args (options_args);
552 CommandReturnObject result;
553 // Check to see if the command being aliased can take any command options.
554 Options *options = cmd_obj_sp->GetOptions ();
555 if (options)
556 {
557 // See if any options were specified as part of the alias; if so, handle them appropriately.
558 options->NotifyOptionParsingStarting ();
559 args.Unshift ("dummy_arg");
560 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
561 args.Shift ();
562 if (result.Succeeded())
563 options->VerifyPartialOptions (result);
564 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
565 {
566 result.AppendError ("Unable to create requested alias.\n");
567 return false;
568 }
569 }
570
571 if (options_string.size() > 0)
572 {
573 if (cmd_obj_sp->WantsRawCommandString ())
574 option_arg_vector->push_back (OptionArgPair ("<argument>",
575 OptionArgValue (-1,
576 options_string)));
577 else
578 {
579 int argc = args.GetArgumentCount();
580 for (size_t i = 0; i < argc; ++i)
581 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
582 option_arg_vector->push_back
583 (OptionArgPair ("<argument>",
584 OptionArgValue (-1,
585 std::string (args.GetArgumentAtIndex (i)))));
586 }
587 }
588
589 return success;
590}
591
592bool
Chris Lattner24943d22010-06-08 16:52:24 +0000593CommandInterpreter::AliasExists (const char *cmd)
594{
595 return m_alias_dict.find(cmd) != m_alias_dict.end();
596}
597
598bool
599CommandInterpreter::UserCommandExists (const char *cmd)
600{
601 return m_user_dict.find(cmd) != m_user_dict.end();
602}
603
604void
605CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
606{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000607 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000608 m_alias_dict[alias_name] = command_obj_sp;
609}
610
611bool
612CommandInterpreter::RemoveAlias (const char *alias_name)
613{
614 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
615 if (pos != m_alias_dict.end())
616 {
617 m_alias_dict.erase(pos);
618 return true;
619 }
620 return false;
621}
622bool
623CommandInterpreter::RemoveUser (const char *alias_name)
624{
625 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
626 if (pos != m_user_dict.end())
627 {
628 m_user_dict.erase(pos);
629 return true;
630 }
631 return false;
632}
633
Chris Lattner24943d22010-06-08 16:52:24 +0000634void
635CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
636{
637 help_string.Printf ("'%s", command_name);
638 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
639
640 if (option_arg_vector_sp != NULL)
641 {
642 OptionArgVector *options = option_arg_vector_sp.get();
643 for (int i = 0; i < options->size(); ++i)
644 {
645 OptionArgPair cur_option = (*options)[i];
646 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000647 OptionArgValue value_pair = cur_option.second;
648 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000649 if (opt.compare("<argument>") == 0)
650 {
651 help_string.Printf (" %s", value.c_str());
652 }
653 else
654 {
655 help_string.Printf (" %s", opt.c_str());
656 if ((value.compare ("<no-argument>") != 0)
657 && (value.compare ("<need-argument") != 0))
658 {
659 help_string.Printf (" %s", value.c_str());
660 }
661 }
662 }
663 }
664
665 help_string.Printf ("'");
666}
667
Greg Clayton65124ea2010-08-26 22:05:43 +0000668size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000669CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
670{
671 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000672 CommandObject::CommandMap::const_iterator end = dict.end();
673 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000674
Greg Clayton65124ea2010-08-26 22:05:43 +0000675 for (pos = dict.begin(); pos != end; ++pos)
676 {
677 size_t len = pos->first.size();
678 if (max_len < len)
679 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000680 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000681 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000682}
683
684void
685CommandInterpreter::GetHelp (CommandReturnObject &result)
686{
687 CommandObject::CommandMap::const_iterator pos;
688 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
689 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000690 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000691
692 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
693 {
694 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
695 max_len);
696 }
697 result.AppendMessage("");
698
699 if (m_alias_dict.size() > 0)
700 {
Jim Inghame3663e82010-10-22 18:47:16 +0000701 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000702 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000703 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000704 max_len = FindLongestCommandWord (m_alias_dict);
705
Chris Lattner24943d22010-06-08 16:52:24 +0000706 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
707 {
708 StreamString sstr;
709 StreamString translation_and_help;
710 std::string entry_name = pos->first;
711 std::string second_entry = pos->second.get()->GetCommandName();
712 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
713
714 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
715 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
716 translation_and_help.GetData(), max_len);
717 }
718 result.AppendMessage("");
719 }
720
721 if (m_user_dict.size() > 0)
722 {
723 result.AppendMessage ("The following is a list of your current user-defined commands:");
724 result.AppendMessage("");
725 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
726 {
727 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
728 }
729 result.AppendMessage("");
730 }
731
732 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
733}
734
Caroline Ticee0da7a52010-12-09 22:52:49 +0000735CommandObject *
736CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000737{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000738 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
739 // eventually be invoked by the given command line.
740
741 CommandObject *cmd_obj = NULL;
742 std::string white_space (" \t\v");
743 size_t start = command_string.find_first_not_of (white_space);
744 size_t end = 0;
745 bool done = false;
746 while (!done)
747 {
748 if (start != std::string::npos)
749 {
750 // Get the next word from command_string.
751 end = command_string.find_first_of (white_space, start);
752 if (end == std::string::npos)
753 end = command_string.size();
754 std::string cmd_word = command_string.substr (start, end - start);
755
756 if (cmd_obj == NULL)
757 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
758 // command or alias.
759 cmd_obj = GetCommandObject (cmd_word.c_str());
760 else if (cmd_obj->IsMultiwordObject ())
761 {
762 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
763 CommandObject *sub_cmd_obj =
764 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
765 if (sub_cmd_obj)
766 cmd_obj = sub_cmd_obj;
767 else // cmd_word was not a valid sub-command word, so we are donee
768 done = true;
769 }
770 else
771 // We have a cmd_obj and it is not a multi-word object, so we are done.
772 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000773
Caroline Ticee0da7a52010-12-09 22:52:49 +0000774 // If we didn't find a valid command object, or our command object is not a multi-word object, or
775 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
776 // next word.
777
778 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
779 done = true;
780 else
781 start = command_string.find_first_not_of (white_space, end);
782 }
783 else
784 // Unable to find any more words.
785 done = true;
786 }
787
788 if (end == command_string.size())
789 command_string.clear();
790 else
791 command_string = command_string.substr(end);
792
793 return cmd_obj;
794}
795
796bool
Caroline Tice649116c2011-05-11 16:07:06 +0000797CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word, bool &was_quoted, char &quote_char)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000798{
799 std::string white_space (" \t\v");
800 size_t start;
801 size_t end;
802
803 start = command_string.find_first_not_of (white_space);
804 if (start != std::string::npos)
805 {
Caroline Tice649116c2011-05-11 16:07:06 +0000806 size_t len = command_string.size() - start;
807 if (len >= 2
808 && ((command_string[start] == '\'') || (command_string[start] == '"')))
Caroline Ticee0da7a52010-12-09 22:52:49 +0000809 {
Caroline Tice649116c2011-05-11 16:07:06 +0000810 was_quoted = true;
811 quote_char = command_string[start];
812 std::string quote_string = command_string.substr (start, 1);
813 start = start + 1;
814 end = command_string.find (quote_string, start);
815 if (end != std::string::npos)
816 {
817 word = command_string.substr (start, end - start);
818 if (end + 1 < len)
819 command_string = command_string.substr (end+1);
820 else
821 command_string.erase ();
822 size_t pos = command_string.find_first_not_of (white_space);
823 if ((pos != 0) && (pos != std::string::npos))
824 command_string = command_string.substr (pos);
825 }
826 else
827 {
828 word = command_string.substr (start - 1);
829 command_string.erase ();
830 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000831 }
832 else
833 {
Caroline Tice649116c2011-05-11 16:07:06 +0000834 end = command_string.find_first_of (white_space, start);
835 if (end != std::string::npos)
836 {
837 word = command_string.substr (start, end - start);
838 command_string = command_string.substr (end);
839 size_t pos = command_string.find_first_not_of (white_space);
840 if ((pos != 0) && (pos != std::string::npos))
841 command_string = command_string.substr (pos);
842 }
843 else
844 {
845 word = command_string.substr (start);
846 command_string.erase();
847 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000848 }
849
850 }
851 return true;
852}
853
854void
855CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
856 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
857{
858 Args cmd_args (raw_input_string.c_str());
859 alias_cmd_obj = GetCommandObject (alias_name);
860 StreamString result_str;
861
862 if (alias_cmd_obj)
863 {
864 std::string alias_name_str = alias_name;
865 if ((cmd_args.GetArgumentCount() == 0)
866 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
867 cmd_args.Unshift (alias_name);
868
869 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
870 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
871
872 if (option_arg_vector_sp.get())
873 {
874 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
875
876 for (int i = 0; i < option_arg_vector->size(); ++i)
877 {
878 OptionArgPair option_pair = (*option_arg_vector)[i];
879 OptionArgValue value_pair = option_pair.second;
880 int value_type = value_pair.first;
881 std::string option = option_pair.first;
882 std::string value = value_pair.second;
883 if (option.compare ("<argument>") == 0)
884 result_str.Printf (" %s", value.c_str());
885 else
886 {
887 result_str.Printf (" %s", option.c_str());
888 if (value_type != optional_argument)
889 result_str.Printf (" ");
890 if (value.compare ("<no_argument>") != 0)
891 {
892 int index = GetOptionArgumentPosition (value.c_str());
893 if (index == 0)
894 result_str.Printf ("%s", value.c_str());
895 else if (index >= cmd_args.GetArgumentCount())
896 {
897
898 result.AppendErrorWithFormat
899 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
900 index);
901 result.SetStatus (eReturnStatusFailed);
902 return;
903 }
904 else
905 {
906 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
907 if (strpos != std::string::npos)
908 raw_input_string = raw_input_string.erase (strpos,
909 strlen (cmd_args.GetArgumentAtIndex (index)));
910 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
911 }
912 }
913 }
914 }
915 }
916
917 alias_result = result_str.GetData();
918 }
919}
920
921bool
922CommandInterpreter::HandleCommand (const char *command_line,
923 bool add_to_history,
924 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +0000925 ExecutionContext *override_context,
926 bool repeat_on_empty_command)
927
Caroline Ticee0da7a52010-12-09 22:52:49 +0000928{
Jim Ingham949d5ac2011-02-18 00:54:25 +0000929
Caroline Ticee0da7a52010-12-09 22:52:49 +0000930 bool done = false;
931 CommandObject *cmd_obj = NULL;
932 std::string next_word;
933 bool wants_raw_input = false;
934 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +0000935 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +0000936
937 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000938 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
939
940 // Make a scoped cleanup object that will clear the crash description string
941 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +0000942 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +0000943
Caroline Ticee0da7a52010-12-09 22:52:49 +0000944 if (log)
945 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000946
Jim Inghamabab14b2010-11-04 23:08:45 +0000947 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
948
Greg Claytonb72d0f02011-04-12 05:54:46 +0000949 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000950
Jim Ingham949d5ac2011-02-18 00:54:25 +0000951 bool empty_command = false;
952 bool comment_command = false;
953 if (command_string.empty())
954 empty_command = true;
955 else
Chris Lattner24943d22010-06-08 16:52:24 +0000956 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000957 const char *k_space_characters = "\t\n\v\f\r ";
958
959 size_t non_space = command_string.find_first_not_of (k_space_characters);
960 // Check for empty line or comment line (lines whose first
961 // non-space character is the comment character for this interpreter)
962 if (non_space == std::string::npos)
963 empty_command = true;
964 else if (command_string[non_space] == m_comment_char)
965 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +0000966 else if (command_string[non_space] == m_repeat_char)
967 {
968 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
969 if (history_string == NULL)
970 {
971 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
972 result.SetStatus(eReturnStatusFailed);
973 return false;
974 }
975 add_to_history = false;
976 command_string = history_string;
977 original_command_string = history_string;
978 }
Jim Ingham949d5ac2011-02-18 00:54:25 +0000979 }
980
981 if (empty_command)
982 {
983 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +0000984 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000985 if (m_command_history.empty())
986 {
987 result.AppendError ("empty command");
988 result.SetStatus(eReturnStatusFailed);
989 return false;
990 }
991 else
992 {
993 command_line = m_repeat_command.c_str();
994 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +0000995 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +0000996 if (m_repeat_command.empty())
997 {
998 result.AppendErrorWithFormat("No auto repeat.\n");
999 result.SetStatus (eReturnStatusFailed);
1000 return false;
1001 }
1002 }
1003 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001004 }
1005 else
1006 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001007 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1008 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001009 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001010 }
1011 else if (comment_command)
1012 {
1013 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1014 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001015 }
Caroline Tice649116c2011-05-11 16:07:06 +00001016
Caroline Ticee0da7a52010-12-09 22:52:49 +00001017 // Phase 1.
1018
1019 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1020 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1021 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1022 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1023 // 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 +00001024 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001025 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001026
Caroline Ticee0da7a52010-12-09 22:52:49 +00001027 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001028 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001029 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001030 {
Caroline Tice649116c2011-05-11 16:07:06 +00001031 bool was_quoted = false;
1032 char quote_char = '\0';
1033 StripFirstWord (command_string, next_word, was_quoted, quote_char);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001034 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +00001035 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001036 std::string alias_result;
1037 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
1038 revised_command_line.Printf ("%s", alias_result.c_str());
1039 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +00001040 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001041 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +00001042 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1043 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001044 }
1045 else if (!cmd_obj)
1046 {
1047 cmd_obj = GetCommandObject (next_word.c_str());
1048 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +00001049 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001050 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +00001051 revised_command_line.Printf ("%s", next_word.c_str());
1052 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +00001053 }
1054 else
1055 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001056 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001057 }
1058 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001059 else if (cmd_obj->IsMultiwordObject ())
1060 {
1061 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1062 if (sub_cmd_obj)
1063 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001064 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001065 revised_command_line.Printf (" %s", next_word.c_str());
1066 cmd_obj = sub_cmd_obj;
1067 wants_raw_input = cmd_obj->WantsRawCommandString ();
1068 }
1069 else
1070 {
Caroline Tice649116c2011-05-11 16:07:06 +00001071 if (was_quoted)
1072 {
1073 if (quote_char == '"')
1074 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1075 else
1076 revised_command_line.Printf (" '%s'", next_word.c_str());
1077 }
1078 else
1079 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001080 done = true;
1081 }
1082 }
1083 else
1084 {
Caroline Tice649116c2011-05-11 16:07:06 +00001085 if (was_quoted)
1086 {
1087 if (quote_char == '"')
1088 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1089 else
1090 revised_command_line.Printf (" '%s'", next_word.c_str());
1091 }
1092 else
1093 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001094 done = true;
1095 }
1096
1097 if (cmd_obj == NULL)
1098 {
1099 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1100 result.SetStatus (eReturnStatusFailed);
1101 return false;
1102 }
1103
1104 next_word.erase ();
1105 if (command_string.length() == 0)
1106 done = true;
1107
Chris Lattner24943d22010-06-08 16:52:24 +00001108 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001109
1110 if (command_string.size() > 0)
1111 revised_command_line.Printf (" %s", command_string.c_str());
1112
1113 // End of Phase 1.
1114 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1115 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1116 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1117 // wants_raw_input specifies whether the Execute method expects raw input or not.
1118
1119
1120 if (log)
1121 {
1122 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1123 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1124 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1125 }
1126
1127 // Phase 2.
1128 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1129 // CommandObject, with the appropriate arguments.
1130
1131 if (cmd_obj != NULL)
1132 {
1133 if (add_to_history)
1134 {
1135 Args command_args (revised_command_line.GetData());
1136 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1137 if (repeat_command != NULL)
1138 m_repeat_command.assign(repeat_command);
1139 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001140 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001141
Jim Ingham6247dbe2011-07-12 03:12:18 +00001142 // Don't keep pushing the same command onto the history...
1143 if (m_command_history.size() == 0 || m_command_history.back() != original_command_string)
1144 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001145 }
1146
1147 command_string = revised_command_line.GetData();
1148 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001149 std::string remainder;
1150 if (actual_cmd_name_len < command_string.length())
1151 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1152 // than cmd_obj->GetCommandName(), because name completion
1153 // allows users to enter short versions of the names,
1154 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001155
1156 // Remove any initial spaces
1157 std::string white_space (" \t\v");
1158 size_t pos = remainder.find_first_not_of (white_space);
1159 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001160 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001161
1162 if (log)
1163 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
1164
1165
1166 if (wants_raw_input)
1167 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1168 else
1169 {
1170 Args cmd_args (remainder.c_str());
1171 cmd_obj->ExecuteWithOptions (cmd_args, result);
1172 }
1173 }
1174 else
1175 {
1176 // We didn't find the first command object, so complete the first argument.
1177 Args command_args (revised_command_line.GetData());
1178 StringList matches;
1179 int num_matches;
1180 int cursor_index = 0;
1181 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1182 bool word_complete;
1183 num_matches = HandleCompletionMatches (command_args,
1184 cursor_index,
1185 cursor_char_position,
1186 0,
1187 -1,
1188 word_complete,
1189 matches);
1190
1191 if (num_matches > 0)
1192 {
1193 std::string error_msg;
1194 error_msg.assign ("ambiguous command '");
1195 error_msg.append(command_args.GetArgumentAtIndex(0));
1196 error_msg.append ("'.");
1197
1198 error_msg.append (" Possible completions:");
1199 for (int i = 0; i < num_matches; i++)
1200 {
1201 error_msg.append ("\n\t");
1202 error_msg.append (matches.GetStringAtIndex (i));
1203 }
1204 error_msg.append ("\n");
1205 result.AppendRawError (error_msg.c_str(), error_msg.size());
1206 }
1207 else
1208 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1209
1210 result.SetStatus (eReturnStatusFailed);
1211 }
1212
Chris Lattner24943d22010-06-08 16:52:24 +00001213 return result.Succeeded();
1214}
1215
1216int
1217CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1218 int &cursor_index,
1219 int &cursor_char_position,
1220 int match_start_point,
1221 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001222 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001223 StringList &matches)
1224{
1225 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001226 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001227
1228 // For any of the command completions a unique match will be a complete word.
1229 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001230
1231 if (cursor_index == -1)
1232 {
1233 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001234 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001235 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1236 }
1237 else if (cursor_index == 0)
1238 {
1239 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001240 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001241 num_command_matches = matches.GetSize();
1242
1243 if (num_command_matches == 1
1244 && cmd_obj && cmd_obj->IsMultiwordObject()
1245 && matches.GetStringAtIndex(0) != NULL
1246 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1247 {
1248 look_for_subcommand = true;
1249 num_command_matches = 0;
1250 matches.DeleteStringAtIndex(0);
1251 parsed_line.AppendArgument ("");
1252 cursor_index++;
1253 cursor_char_position = 0;
1254 }
1255 }
1256
1257 if (cursor_index > 0 || look_for_subcommand)
1258 {
1259 // We are completing further on into a commands arguments, so find the command and tell it
1260 // to complete the command.
1261 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001262 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001263 if (command_object == NULL)
1264 {
1265 return 0;
1266 }
1267 else
1268 {
1269 parsed_line.Shift();
1270 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001271 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001272 cursor_index,
1273 cursor_char_position,
1274 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001275 max_return_elements,
1276 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001277 matches);
1278 }
1279 }
1280
1281 return num_command_matches;
1282
1283}
1284
1285int
1286CommandInterpreter::HandleCompletion (const char *current_line,
1287 const char *cursor,
1288 const char *last_char,
1289 int match_start_point,
1290 int max_return_elements,
1291 StringList &matches)
1292{
1293 // We parse the argument up to the cursor, so the last argument in parsed_line is
1294 // the one containing the cursor, and the cursor is after the last character.
1295
1296 Args parsed_line(current_line, last_char - current_line);
1297 Args partial_parsed_line(current_line, cursor - current_line);
1298
Jim Ingham6247dbe2011-07-12 03:12:18 +00001299 // Don't complete comments, and if the line we are completing is just the history repeat character,
1300 // substitute the appropriate history line.
1301 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1302 if (first_arg)
1303 {
1304 if (first_arg[0] == m_comment_char)
1305 return 0;
1306 else if (first_arg[0] == m_repeat_char)
1307 {
1308 const char *history_string = FindHistoryString (first_arg);
1309 if (history_string != NULL)
1310 {
1311 matches.Clear();
1312 matches.InsertStringAtIndex(0, history_string);
1313 return -2;
1314 }
1315 else
1316 return 0;
1317
1318 }
1319 }
1320
1321
Chris Lattner24943d22010-06-08 16:52:24 +00001322 int num_args = partial_parsed_line.GetArgumentCount();
1323 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1324 int cursor_char_position;
1325
1326 if (cursor_index == -1)
1327 cursor_char_position = 0;
1328 else
1329 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001330
1331 if (cursor > current_line && cursor[-1] == ' ')
1332 {
1333 // We are just after a space. If we are in an argument, then we will continue
1334 // parsing, but if we are between arguments, then we have to complete whatever the next
1335 // element would be.
1336 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1337 // protected by a quote) then the space will also be in the parsed argument...
1338
1339 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1340 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1341 {
1342 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1343 cursor_index++;
1344 cursor_char_position = 0;
1345 }
1346 }
Chris Lattner24943d22010-06-08 16:52:24 +00001347
1348 int num_command_matches;
1349
1350 matches.Clear();
1351
1352 // Only max_return_elements == -1 is supported at present:
1353 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001354 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001355 num_command_matches = HandleCompletionMatches (parsed_line,
1356 cursor_index,
1357 cursor_char_position,
1358 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001359 max_return_elements,
1360 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001361 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001362
1363 if (num_command_matches <= 0)
1364 return num_command_matches;
1365
1366 if (num_args == 0)
1367 {
1368 // If we got an empty string, insert nothing.
1369 matches.InsertStringAtIndex(0, "");
1370 }
1371 else
1372 {
1373 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1374 // put an empty string in element 0.
1375 std::string command_partial_str;
1376 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001377 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1378 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001379
1380 std::string common_prefix;
1381 matches.LongestCommonPrefix (common_prefix);
1382 int partial_name_len = command_partial_str.size();
1383
1384 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001385 // Only do this if the completer told us this was a complete word, however...
1386 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001387 {
1388 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1389 if (quote_char != '\0')
1390 common_prefix.push_back(quote_char);
1391
1392 common_prefix.push_back(' ');
1393 }
1394 common_prefix.erase (0, partial_name_len);
1395 matches.InsertStringAtIndex(0, common_prefix.c_str());
1396 }
1397 return num_command_matches;
1398}
1399
Chris Lattner24943d22010-06-08 16:52:24 +00001400
1401CommandInterpreter::~CommandInterpreter ()
1402{
1403}
1404
1405const char *
1406CommandInterpreter::GetPrompt ()
1407{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001408 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001409}
1410
1411void
1412CommandInterpreter::SetPrompt (const char *new_prompt)
1413{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001414 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001415}
1416
Jim Ingham5e16ef52010-10-04 19:49:29 +00001417size_t
Greg Clayton58928562011-02-09 01:08:52 +00001418CommandInterpreter::GetConfirmationInputReaderCallback
1419(
1420 void *baton,
1421 InputReader &reader,
1422 lldb::InputReaderAction action,
1423 const char *bytes,
1424 size_t bytes_len
1425)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001426{
Greg Clayton58928562011-02-09 01:08:52 +00001427 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001428 bool *response_ptr = (bool *) baton;
1429
1430 switch (action)
1431 {
1432 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001433 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001434 {
1435 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001436 {
Greg Clayton58928562011-02-09 01:08:52 +00001437 out_file.Printf ("%s", reader.GetPrompt());
1438 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001439 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001440 }
1441 break;
1442
1443 case eInputReaderDeactivate:
1444 break;
1445
1446 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001447 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001448 {
Greg Clayton58928562011-02-09 01:08:52 +00001449 out_file.Printf ("%s", reader.GetPrompt());
1450 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001451 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001452 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001453
1454 case eInputReaderAsynchronousOutputWritten:
1455 break;
1456
Jim Ingham5e16ef52010-10-04 19:49:29 +00001457 case eInputReaderGotToken:
1458 if (bytes_len == 0)
1459 {
1460 reader.SetIsDone(true);
1461 }
1462 else if (bytes[0] == 'y')
1463 {
1464 *response_ptr = true;
1465 reader.SetIsDone(true);
1466 }
1467 else if (bytes[0] == 'n')
1468 {
1469 *response_ptr = false;
1470 reader.SetIsDone(true);
1471 }
1472 else
1473 {
Greg Clayton58928562011-02-09 01:08:52 +00001474 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001475 {
Greg Clayton58928562011-02-09 01:08:52 +00001476 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1477 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001478 }
1479 }
1480 break;
1481
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001482 case eInputReaderInterrupt:
1483 case eInputReaderEndOfFile:
1484 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1485 reader.SetIsDone (true);
1486 break;
1487
Jim Ingham5e16ef52010-10-04 19:49:29 +00001488 case eInputReaderDone:
1489 break;
1490 }
1491
1492 return bytes_len;
1493
1494}
1495
1496bool
1497CommandInterpreter::Confirm (const char *message, bool default_answer)
1498{
Jim Ingham93057472010-10-04 22:44:14 +00001499 // Check AutoConfirm first:
1500 if (m_debugger.GetAutoConfirm())
1501 return default_answer;
1502
Jim Ingham5e16ef52010-10-04 19:49:29 +00001503 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1504 bool response = default_answer;
1505 if (reader_sp)
1506 {
1507 std::string prompt(message);
1508 prompt.append(": [");
1509 if (default_answer)
1510 prompt.append ("Y/n] ");
1511 else
1512 prompt.append ("y/N] ");
1513
1514 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1515 &response, // baton
1516 eInputReaderGranularityLine, // token size, to pass to callback function
1517 NULL, // end token
1518 prompt.c_str(), // prompt
1519 true)); // echo input
1520 if (err.Success())
1521 {
1522 GetDebugger().PushInputReader (reader_sp);
1523 }
1524 reader_sp->WaitOnReaderIsDone();
1525 }
1526 return response;
1527}
1528
1529
Chris Lattner24943d22010-06-08 16:52:24 +00001530void
1531CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1532{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001533 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001534
1535 if (cmd_obj_sp != NULL)
1536 {
1537 CommandObject *cmd_obj = cmd_obj_sp.get();
1538 if (cmd_obj->IsCrossRefObject ())
1539 cmd_obj->AddObject (object_type);
1540 }
1541}
1542
Chris Lattner24943d22010-06-08 16:52:24 +00001543OptionArgVectorSP
1544CommandInterpreter::GetAliasOptions (const char *alias_name)
1545{
1546 OptionArgMap::iterator pos;
1547 OptionArgVectorSP ret_val;
1548
1549 std::string alias (alias_name);
1550
1551 if (HasAliasOptions())
1552 {
1553 pos = m_alias_options.find (alias);
1554 if (pos != m_alias_options.end())
1555 ret_val = pos->second;
1556 }
1557
1558 return ret_val;
1559}
1560
1561void
1562CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1563{
1564 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1565 if (pos != m_alias_options.end())
1566 {
1567 m_alias_options.erase (pos);
1568 }
1569}
1570
1571void
1572CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1573{
1574 m_alias_options[alias_name] = option_arg_vector_sp;
1575}
1576
1577bool
1578CommandInterpreter::HasCommands ()
1579{
1580 return (!m_command_dict.empty());
1581}
1582
1583bool
1584CommandInterpreter::HasAliases ()
1585{
1586 return (!m_alias_dict.empty());
1587}
1588
1589bool
1590CommandInterpreter::HasUserCommands ()
1591{
1592 return (!m_user_dict.empty());
1593}
1594
1595bool
1596CommandInterpreter::HasAliasOptions ()
1597{
1598 return (!m_alias_options.empty());
1599}
1600
Chris Lattner24943d22010-06-08 16:52:24 +00001601void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001602CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1603 const char *alias_name,
1604 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001605 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001606 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001607{
1608 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001609
1610 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001611
Caroline Tice44c841d2010-12-07 19:58:26 +00001612 // Make sure that the alias name is the 0th element in cmd_args
1613 std::string alias_name_str = alias_name;
1614 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1615 cmd_args.Unshift (alias_name);
1616
1617 Args new_args (alias_cmd_obj->GetCommandName());
1618 if (new_args.GetArgumentCount() == 2)
1619 new_args.Shift();
1620
Chris Lattner24943d22010-06-08 16:52:24 +00001621 if (option_arg_vector_sp.get())
1622 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001623 if (wants_raw_input)
1624 {
1625 // We have a command that both has command options and takes raw input. Make *sure* it has a
1626 // " -- " in the right place in the raw_input_string.
1627 size_t pos = raw_input_string.find(" -- ");
1628 if (pos == std::string::npos)
1629 {
1630 // None found; assume it goes at the beginning of the raw input string
1631 raw_input_string.insert (0, " -- ");
1632 }
1633 }
Chris Lattner24943d22010-06-08 16:52:24 +00001634
1635 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1636 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001637 std::vector<bool> used (old_size + 1, false);
1638
1639 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001640
1641 for (int i = 0; i < option_arg_vector->size(); ++i)
1642 {
1643 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001644 OptionArgValue value_pair = option_pair.second;
1645 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001646 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001647 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001648 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001649 {
1650 if (!wants_raw_input
1651 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1652 new_args.AppendArgument (value.c_str());
1653 }
Chris Lattner24943d22010-06-08 16:52:24 +00001654 else
1655 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001656 if (value_type != optional_argument)
1657 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001658 if (value.compare ("<no-argument>") != 0)
1659 {
1660 int index = GetOptionArgumentPosition (value.c_str());
1661 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001662 {
Chris Lattner24943d22010-06-08 16:52:24 +00001663 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001664 if (value_type != optional_argument)
1665 new_args.AppendArgument (value.c_str());
1666 else
1667 {
1668 char buffer[255];
1669 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1670 new_args.AppendArgument (buffer);
1671 }
1672
1673 }
Chris Lattner24943d22010-06-08 16:52:24 +00001674 else if (index >= cmd_args.GetArgumentCount())
1675 {
1676 result.AppendErrorWithFormat
1677 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1678 index);
1679 result.SetStatus (eReturnStatusFailed);
1680 return;
1681 }
1682 else
1683 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001684 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1685 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1686 if (strpos != std::string::npos)
1687 {
1688 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1689 }
1690
1691 if (value_type != optional_argument)
1692 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1693 else
1694 {
1695 char buffer[255];
1696 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1697 cmd_args.GetArgumentAtIndex (index));
1698 new_args.AppendArgument (buffer);
1699 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001700 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001701 }
1702 }
1703 }
1704 }
1705
1706 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1707 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001708 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001709 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1710 }
1711
1712 cmd_args.Clear();
1713 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1714 }
1715 else
1716 {
1717 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001718 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1719 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1720 // input string.
1721 if (wants_raw_input)
1722 {
1723 cmd_args.Clear();
1724 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1725 }
Chris Lattner24943d22010-06-08 16:52:24 +00001726 return;
1727 }
1728
1729 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1730 return;
1731}
1732
1733
1734int
1735CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1736{
1737 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1738 // of zero.
1739
1740 char *cptr = (char *) in_string;
1741
1742 // Does it start with '%'
1743 if (cptr[0] == '%')
1744 {
1745 ++cptr;
1746
1747 // Is the rest of it entirely digits?
1748 if (isdigit (cptr[0]))
1749 {
1750 const char *start = cptr;
1751 while (isdigit (cptr[0]))
1752 ++cptr;
1753
1754 // We've gotten to the end of the digits; are we at the end of the string?
1755 if (cptr[0] == '\0')
1756 position = atoi (start);
1757 }
1758 }
1759
1760 return position;
1761}
1762
1763void
1764CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1765{
Greg Clayton887aa282010-10-11 01:05:37 +00001766 // Don't parse any .lldbinit files if we were asked not to
Jim Ingham574c3d62011-08-12 23:34:31 +00001767 if (m_skip_lldbinit_files && m_skip_app_init_files)
Greg Clayton887aa282010-10-11 01:05:37 +00001768 return;
1769
Chris Lattner24943d22010-06-08 16:52:24 +00001770 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Jim Ingham574c3d62011-08-12 23:34:31 +00001771
1772 std::string app_specific_init;
1773
1774 if (!m_skip_app_init_files)
1775 {
1776 FileSpec host_spec = Host::GetProgramFileSpec();
1777 const char *host_name = host_spec.GetFilename().AsCString();
1778
1779 if (host_name != NULL && strcmp (host_name, "lldb") != 0)
1780 {
1781 app_specific_init += init_file_path;
1782 app_specific_init += "-";
1783 app_specific_init += host_name;
1784 }
1785 }
1786
1787 FileSpec init_file;
1788 if (!app_specific_init.empty())
1789 {
1790 init_file.SetFile (app_specific_init.c_str(), true);
1791 }
1792
1793 if (!m_skip_lldbinit_files && !init_file.Exists())
1794 {
1795 init_file.SetFile (init_file_path, true);
1796 }
1797
Chris Lattner24943d22010-06-08 16:52:24 +00001798 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1799 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1800
1801 if (init_file.Exists())
1802 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001803 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1804 bool stop_on_continue = true;
1805 bool stop_on_error = false;
1806 bool echo_commands = false;
1807 bool print_results = false;
1808
1809 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001810 }
1811 else
1812 {
1813 // nothing to be done if the file doesn't exist
1814 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1815 }
1816}
1817
Greg Claytonb72d0f02011-04-12 05:54:46 +00001818PlatformSP
1819CommandInterpreter::GetPlatform (bool prefer_target_platform)
1820{
1821 PlatformSP platform_sp;
1822 if (prefer_target_platform && m_exe_ctx.target)
1823 platform_sp = m_exe_ctx.target->GetPlatform();
1824
1825 if (!platform_sp)
1826 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
1827 return platform_sp;
1828}
1829
Jim Ingham949d5ac2011-02-18 00:54:25 +00001830void
Jim Inghama4fede32011-03-11 01:51:49 +00001831CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001832 ExecutionContext *override_context,
1833 bool stop_on_continue,
1834 bool stop_on_error,
1835 bool echo_commands,
1836 bool print_results,
1837 CommandReturnObject &result)
1838{
1839 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00001840
1841 // If we are going to continue past a "continue" then we need to run the commands synchronously.
1842 // Make sure you reset this value anywhere you return from the function.
1843
1844 bool old_async_execution = m_debugger.GetAsyncExecution();
1845
1846 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1847 // cause series of commands that change the context, then do an operation that relies on that context to fail.
1848
1849 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001850 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00001851
1852 if (!stop_on_continue)
1853 {
1854 m_debugger.SetAsyncExecution (false);
1855 }
1856
1857 for (int idx = 0; idx < num_lines; idx++)
1858 {
1859 const char *cmd = commands.GetStringAtIndex(idx);
1860 if (cmd[0] == '\0')
1861 continue;
1862
Jim Ingham949d5ac2011-02-18 00:54:25 +00001863 if (echo_commands)
1864 {
1865 result.AppendMessageWithFormat ("%s %s\n",
1866 GetPrompt(),
1867 cmd);
1868 }
1869
Greg Claytonaa378b12011-02-20 02:15:07 +00001870 CommandReturnObject tmp_result;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001871 bool success = HandleCommand(cmd, false, tmp_result, NULL);
1872
1873 if (print_results)
1874 {
1875 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001876 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001877 }
1878
1879 if (!success || !tmp_result.Succeeded())
1880 {
1881 if (stop_on_error)
1882 {
1883 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1884 idx, cmd);
1885 result.SetStatus (eReturnStatusFailed);
1886 m_debugger.SetAsyncExecution (old_async_execution);
1887 return;
1888 }
1889 else if (print_results)
1890 {
1891 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1892 idx + 1,
1893 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001894 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001895 }
1896 }
1897
Caroline Tice4a348082011-05-02 20:41:46 +00001898 if (result.GetImmediateOutputStream())
1899 result.GetImmediateOutputStream()->Flush();
1900
1901 if (result.GetImmediateErrorStream())
1902 result.GetImmediateErrorStream()->Flush();
1903
Jim Ingham949d5ac2011-02-18 00:54:25 +00001904 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1905 // could be running (for instance in Breakpoint Commands.
1906 // So we check the return value to see if it is has running in it.
1907 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1908 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1909 {
1910 if (stop_on_continue)
1911 {
1912 // If we caused the target to proceed, and we're going to stop in that case, set the
1913 // status in our real result before returning. This is an error if the continue was not the
1914 // last command in the set of commands to be run.
1915 if (idx != num_lines - 1)
1916 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1917 idx + 1, cmd);
1918 else
1919 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1920
1921 result.SetStatus(tmp_result.GetStatus());
1922 m_debugger.SetAsyncExecution (old_async_execution);
1923
1924 return;
1925 }
1926 }
1927
1928 }
1929
1930 result.SetStatus (eReturnStatusSuccessFinishResult);
1931 m_debugger.SetAsyncExecution (old_async_execution);
1932
1933 return;
1934}
1935
1936void
1937CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1938 ExecutionContext *context,
1939 bool stop_on_continue,
1940 bool stop_on_error,
1941 bool echo_command,
1942 bool print_result,
1943 CommandReturnObject &result)
1944{
1945 if (cmd_file.Exists())
1946 {
1947 bool success;
1948 StringList commands;
1949 success = commands.ReadFileLines(cmd_file);
1950 if (!success)
1951 {
1952 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1953 result.SetStatus (eReturnStatusFailed);
1954 return;
1955 }
1956 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1957 }
1958 else
1959 {
1960 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1961 cmd_file.GetFilename().AsCString());
1962 result.SetStatus (eReturnStatusFailed);
1963 return;
1964 }
1965}
1966
Chris Lattner24943d22010-06-08 16:52:24 +00001967ScriptInterpreter *
1968CommandInterpreter::GetScriptInterpreter ()
1969{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001970 if (m_script_interpreter_ap.get() != NULL)
1971 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00001972
Caroline Tice0aa2e552011-01-14 00:29:16 +00001973 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
1974 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00001975 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001976 case eScriptLanguageNone:
1977 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
1978 break;
1979 case eScriptLanguagePython:
1980 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
1981 break;
1982 default:
1983 break;
1984 };
1985
1986 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00001987}
1988
1989
1990
1991bool
1992CommandInterpreter::GetSynchronous ()
1993{
1994 return m_synchronous_execution;
1995}
1996
1997void
1998CommandInterpreter::SetSynchronous (bool value)
1999{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002000 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002001}
2002
2003void
2004CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2005 const char *word_text,
2006 const char *separator,
2007 const char *help_text,
2008 uint32_t max_word_len)
2009{
Greg Clayton238c0a12010-09-18 01:14:36 +00002010 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2011
Chris Lattner24943d22010-06-08 16:52:24 +00002012 int indent_size = max_word_len + strlen (separator) + 2;
2013
2014 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002015
2016 StreamString text_strm;
2017 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2018
2019 size_t len = text_strm.GetSize();
2020 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002021 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002022 {
2023 text_strm.EOL();
2024 len = text_strm.GetSize();
2025 }
Chris Lattner24943d22010-06-08 16:52:24 +00002026
2027 if (len < max_columns)
2028 {
2029 // Output it as a single line.
2030 strm.Printf ("%s", text);
2031 }
2032 else
2033 {
2034 // We need to break it up into multiple lines.
2035 bool first_line = true;
2036 int text_width;
2037 int start = 0;
2038 int end = start;
2039 int final_end = strlen (text);
2040 int sub_len;
2041
2042 while (end < final_end)
2043 {
2044 if (first_line)
2045 text_width = max_columns - 1;
2046 else
2047 text_width = max_columns - indent_size - 1;
2048
2049 // Don't start the 'text' on a space, since we're already outputting the indentation.
2050 if (!first_line)
2051 {
2052 while ((start < final_end) && (text[start] == ' '))
2053 start++;
2054 }
2055
2056 end = start + text_width;
2057 if (end > final_end)
2058 end = final_end;
2059 else
2060 {
2061 // If we're not at the end of the text, make sure we break the line on white space.
2062 while (end > start
2063 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2064 end--;
2065 }
2066
2067 sub_len = end - start;
2068 if (start != 0)
2069 strm.EOL();
2070 if (!first_line)
2071 strm.Indent();
2072 else
2073 first_line = false;
2074 assert (start <= final_end);
2075 assert (start + sub_len <= final_end);
2076 if (sub_len > 0)
2077 strm.Write (text + start, sub_len);
2078 start = end + 1;
2079 }
2080 }
2081 strm.EOL();
2082 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002083}
2084
2085void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002086CommandInterpreter::OutputHelpText (Stream &strm,
2087 const char *word_text,
2088 const char *separator,
2089 const char *help_text,
2090 uint32_t max_word_len)
2091{
2092 int indent_size = max_word_len + strlen (separator) + 2;
2093
2094 strm.IndentMore (indent_size);
2095
2096 StreamString text_strm;
2097 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2098
2099 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2100 bool first_line = true;
2101
2102 size_t len = text_strm.GetSize();
2103 const char *text = text_strm.GetData();
2104
2105 uint32_t chars_left = max_columns;
2106
2107 for (uint32_t i = 0; i < len; i++)
2108 {
2109 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2110 {
2111 first_line = false;
2112 chars_left = max_columns - indent_size;
2113 strm.EOL();
2114 strm.Indent();
2115 }
2116 else
2117 {
2118 strm.PutChar(text[i]);
2119 chars_left--;
2120 }
2121
2122 }
2123
2124 strm.EOL();
2125 strm.IndentLess(indent_size);
2126}
2127
2128void
Chris Lattner24943d22010-06-08 16:52:24 +00002129CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2130 StringList &commands_found, StringList &commands_help)
2131{
2132 CommandObject::CommandMap::const_iterator pos;
2133 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2134 CommandObject *sub_cmd_obj;
2135
2136 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2137 {
2138 const char * command_name = pos->first.c_str();
2139 sub_cmd_obj = pos->second.get();
2140 StreamString complete_command_name;
2141
2142 complete_command_name.Printf ("%s %s", prefix, command_name);
2143
Greg Clayton238c0a12010-09-18 01:14:36 +00002144 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002145 {
2146 commands_found.AppendString (complete_command_name.GetData());
2147 commands_help.AppendString (sub_cmd_obj->GetHelp());
2148 }
2149
2150 if (sub_cmd_obj->IsMultiwordObject())
2151 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2152 commands_help);
2153 }
2154
2155}
2156
2157void
2158CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2159 StringList &commands_help)
2160{
2161 CommandObject::CommandMap::const_iterator pos;
2162
2163 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2164 {
2165 const char *command_name = pos->first.c_str();
2166 CommandObject *cmd_obj = pos->second.get();
2167
Greg Clayton238c0a12010-09-18 01:14:36 +00002168 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002169 {
2170 commands_found.AppendString (command_name);
2171 commands_help.AppendString (cmd_obj->GetHelp());
2172 }
2173
2174 if (cmd_obj->IsMultiwordObject())
2175 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2176
2177 }
2178}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002179
2180
2181void
2182CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2183{
2184 m_exe_ctx.Clear();
2185
2186 if (override_context != NULL)
2187 {
2188 m_exe_ctx.target = override_context->target;
2189 m_exe_ctx.process = override_context->process;
2190 m_exe_ctx.thread = override_context->thread;
2191 m_exe_ctx.frame = override_context->frame;
2192 }
2193 else
2194 {
2195 TargetSP target_sp (m_debugger.GetSelectedTarget());
2196 if (target_sp)
2197 {
2198 m_exe_ctx.target = target_sp.get();
2199 m_exe_ctx.process = target_sp->GetProcessSP().get();
2200 if (m_exe_ctx.process && m_exe_ctx.process->IsAlive() && !m_exe_ctx.process->IsRunning())
2201 {
2202 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetSelectedThread().get();
2203 if (m_exe_ctx.thread == NULL)
2204 {
2205 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetThreadAtIndex(0).get();
2206 // If we didn't have a selected thread, select one here.
2207 if (m_exe_ctx.thread != NULL)
2208 m_exe_ctx.process->GetThreadList().SetSelectedThreadByID(m_exe_ctx.thread->GetID());
2209 }
2210 if (m_exe_ctx.thread)
2211 {
2212 m_exe_ctx.frame = m_exe_ctx.thread->GetSelectedFrame().get();
2213 if (m_exe_ctx.frame == NULL)
2214 {
2215 m_exe_ctx.frame = m_exe_ctx.thread->GetStackFrameAtIndex (0).get();
2216 // If we didn't have a selected frame select one here.
2217 if (m_exe_ctx.frame != NULL)
2218 m_exe_ctx.thread->SetSelectedFrame(m_exe_ctx.frame);
2219 }
2220 }
2221 }
2222 }
2223 }
2224}
2225
Jim Ingham6247dbe2011-07-12 03:12:18 +00002226void
2227CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2228{
2229 DumpHistory (stream, 0, count - 1);
2230}
2231
2232void
2233CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2234{
2235 size_t num_history_elements = m_command_history.size();
2236 if (start > num_history_elements)
2237 return;
2238 for (uint32_t i = start; i < num_history_elements && i <= end; i++)
2239 {
2240 if (!m_command_history[i].empty())
2241 {
2242 stream.Indent();
2243 stream.Printf ("%4d: %s\n", i, m_command_history[i].c_str());
2244 }
2245 }
2246}
2247
2248const char *
2249CommandInterpreter::FindHistoryString (const char *input_str) const
2250{
2251 if (input_str[0] != m_repeat_char)
2252 return NULL;
2253 if (input_str[1] == '-')
2254 {
2255 bool success;
2256 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2257 if (!success)
2258 return NULL;
2259 if (idx > m_command_history.size())
2260 return NULL;
2261 idx = m_command_history.size() - idx;
2262 return m_command_history[idx].c_str();
2263
2264 }
2265 else if (input_str[1] == m_repeat_char)
2266 {
2267 if (m_command_history.empty())
2268 return NULL;
2269 else
2270 return m_command_history.back().c_str();
2271 }
2272 else
2273 {
2274 bool success;
2275 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2276 if (!success)
2277 return NULL;
2278 if (idx >= m_command_history.size())
2279 return NULL;
2280 return m_command_history[idx].c_str();
2281 }
2282}