blob: 0b77607906e3c69f8c50844ce7d2b4c2a1562406 [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 ('!'),
Caroline Tice892fadd2011-06-16 16:27:19 +000075 m_batch_command_mode (false)
Chris Lattner24943d22010-06-08 16:52:24 +000076{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000077 const char *dbg_name = debugger.GetInstanceName().AsCString();
78 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
79 StreamString var_name;
80 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000081 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000082 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000083 m_debugger.GetInstanceName().AsCString());
84 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
85 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
86 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000087}
88
89void
90CommandInterpreter::Initialize ()
91{
92 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
93
94 CommandReturnObject result;
95
96 LoadCommandDictionary ();
97
Chris Lattner24943d22010-06-08 16:52:24 +000098 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +000099 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
100 if (cmd_obj_sp)
101 {
102 AddAlias ("q", cmd_obj_sp);
103 AddAlias ("exit", cmd_obj_sp);
104 }
105
106 cmd_obj_sp = GetCommandSPExact ("process continue", false);
107 if (cmd_obj_sp)
108 {
109 AddAlias ("c", cmd_obj_sp);
110 AddAlias ("continue", cmd_obj_sp);
111 }
112
113 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
114 if (cmd_obj_sp)
115 AddAlias ("b", cmd_obj_sp);
116
117 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
118 if (cmd_obj_sp)
119 AddAlias ("bt", cmd_obj_sp);
120
121 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
122 if (cmd_obj_sp)
123 AddAlias ("si", cmd_obj_sp);
124
125 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
126 if (cmd_obj_sp)
127 {
128 AddAlias ("s", cmd_obj_sp);
129 AddAlias ("step", cmd_obj_sp);
130 }
131
132 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
133 if (cmd_obj_sp)
134 {
135 AddAlias ("n", cmd_obj_sp);
136 AddAlias ("next", cmd_obj_sp);
137 }
138
139 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
140 if (cmd_obj_sp)
141 {
142 AddAlias ("f", cmd_obj_sp);
143 AddAlias ("finish", cmd_obj_sp);
144 }
145
146 cmd_obj_sp = GetCommandSPExact ("source list", false);
147 if (cmd_obj_sp)
148 {
149 AddAlias ("l", cmd_obj_sp);
150 AddAlias ("list", cmd_obj_sp);
151 }
152
153 cmd_obj_sp = GetCommandSPExact ("memory read", false);
154 if (cmd_obj_sp)
155 AddAlias ("x", cmd_obj_sp);
156
157 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
158 if (cmd_obj_sp)
159 AddAlias ("up", cmd_obj_sp);
160
161 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
162 if (cmd_obj_sp)
163 AddAlias ("down", cmd_obj_sp);
164
165 cmd_obj_sp = GetCommandSPExact ("target create", false);
166 if (cmd_obj_sp)
167 AddAlias ("file", cmd_obj_sp);
168
169 cmd_obj_sp = GetCommandSPExact ("target modules", false);
170 if (cmd_obj_sp)
171 AddAlias ("image", cmd_obj_sp);
172
173
174 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000175
Caroline Tice5ddbe212011-05-06 21:37:15 +0000176 cmd_obj_sp = GetCommandSPExact ("expression", false);
177 if (cmd_obj_sp)
178 {
179 AddAlias ("expr", cmd_obj_sp);
180
181 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
182 AddAlias ("p", cmd_obj_sp);
183 AddAlias ("print", cmd_obj_sp);
184 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
185 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
186
187 alias_arguments_vector_sp.reset (new OptionArgVector);
188 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
189 AddAlias ("po", cmd_obj_sp);
190 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
191 }
192
193 cmd_obj_sp = GetCommandSPExact ("process launch", false);
194 if (cmd_obj_sp)
195 {
196 alias_arguments_vector_sp.reset (new OptionArgVector);
197 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
198 AddAlias ("r", cmd_obj_sp);
199 AddAlias ("run", cmd_obj_sp);
200 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
201 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
202 }
203
Chris Lattner24943d22010-06-08 16:52:24 +0000204}
205
Chris Lattner24943d22010-06-08 16:52:24 +0000206const char *
207CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
208{
209 // This function has not yet been implemented.
210
211 // Look for any embedded script command
212 // If found,
213 // get interpreter object from the command dictionary,
214 // call execute_one_command on it,
215 // get the results as a string,
216 // substitute that string for current stuff.
217
218 return arg;
219}
220
221
222void
223CommandInterpreter::LoadCommandDictionary ()
224{
225 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
226
227 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
228 //
229 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
230 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
231 // the cross-referencing stuff) are created!!!
232 //
233 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
234
235
236 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
237 // are created. This is so that when another command is created that needs to go into a crossref object,
238 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
239 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
240
Chris Lattner24943d22010-06-08 16:52:24 +0000241 // Non-CommandObjectCrossref commands can now be created.
242
Caroline Tice5bc8c972010-09-20 20:44:43 +0000243 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000244
Greg Clayton238c0a12010-09-18 01:14:36 +0000245 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000246 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000247 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000248 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000249 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
250 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000251// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000252 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000253 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000254 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000255 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
256 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000257 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000258 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000259 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000260 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000261 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000262 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000263 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000264 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
265 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Greg Clayton5c28dd12011-06-23 17:59:56 +0000266 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000267 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000268
269 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000270 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000271 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000272 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000273 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000274 if (break_regex_cmd_ap.get())
275 {
276 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
277 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
278 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000279 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000280 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000281 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000282 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
283 {
284 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
285 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
286 }
287 }
Jim Inghame56493f2011-03-22 02:29:32 +0000288
289 std::auto_ptr<CommandObjectRegexCommand>
290 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000291 "_regexp-down",
292 "Go down \"n\" frames in the stack (1 frame by default).",
293 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000294 if (down_regex_cmd_ap.get())
295 {
296 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
297 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
298 {
299 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
300 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
301 }
302 }
303
304 std::auto_ptr<CommandObjectRegexCommand>
305 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000306 "_regexp-up",
307 "Go up \"n\" frames in the stack (1 frame by default).",
308 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000309 if (up_regex_cmd_ap.get())
310 {
311 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
312 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
313 {
314 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
315 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
316 }
317 }
Chris Lattner24943d22010-06-08 16:52:24 +0000318}
319
320int
321CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
322 StringList &matches)
323{
324 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
325
326 if (include_aliases)
327 {
328 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
329 }
330
331 return matches.GetSize();
332}
333
334CommandObjectSP
335CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
336{
337 CommandObject::CommandMap::iterator pos;
338 CommandObjectSP ret_val;
339
340 std::string cmd(cmd_cstr);
341
342 if (HasCommands())
343 {
344 pos = m_command_dict.find(cmd);
345 if (pos != m_command_dict.end())
346 ret_val = pos->second;
347 }
348
349 if (include_aliases && HasAliases())
350 {
351 pos = m_alias_dict.find(cmd);
352 if (pos != m_alias_dict.end())
353 ret_val = pos->second;
354 }
355
356 if (HasUserCommands())
357 {
358 pos = m_user_dict.find(cmd);
359 if (pos != m_user_dict.end())
360 ret_val = pos->second;
361 }
362
363 if (!exact && ret_val == NULL)
364 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000365 // We will only get into here if we didn't find any exact matches.
366
367 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
368
Chris Lattner24943d22010-06-08 16:52:24 +0000369 StringList local_matches;
370 if (matches == NULL)
371 matches = &local_matches;
372
Jim Inghamd40f8a62010-07-06 22:46:59 +0000373 unsigned int num_cmd_matches = 0;
374 unsigned int num_alias_matches = 0;
375 unsigned int num_user_matches = 0;
376
377 // Look through the command dictionaries one by one, and if we get only one match from any of
378 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
379
Chris Lattner24943d22010-06-08 16:52:24 +0000380 if (HasCommands())
381 {
382 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
383 }
384
385 if (num_cmd_matches == 1)
386 {
387 cmd.assign(matches->GetStringAtIndex(0));
388 pos = m_command_dict.find(cmd);
389 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000390 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000391 }
392
Jim Ingham9a574172010-06-24 20:28:42 +0000393 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000394 {
395 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
396
397 }
398
Jim Inghamd40f8a62010-07-06 22:46:59 +0000399 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000400 {
401 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
402 pos = m_alias_dict.find(cmd);
403 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000404 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000405 }
406
Jim Ingham9a574172010-06-24 20:28:42 +0000407 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000408 {
409 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
410 }
411
Jim Inghamd40f8a62010-07-06 22:46:59 +0000412 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000413 {
414 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
415
416 pos = m_user_dict.find (cmd);
417 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000418 user_match_sp = pos->second;
419 }
420
421 // If we got exactly one match, return that, otherwise return the match list.
422
423 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
424 {
425 if (num_cmd_matches)
426 return real_match_sp;
427 else if (num_alias_matches)
428 return alias_match_sp;
429 else
430 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000431 }
432 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000433 else if (matches && ret_val != NULL)
434 {
435 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000436 }
437
438
439 return ret_val;
440}
441
Greg Claytond12aeab2011-04-20 16:37:46 +0000442bool
443CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
444{
445 if (name && name[0])
446 {
447 std::string name_sstr(name);
448 if (!can_replace)
449 {
450 if (m_command_dict.find (name_sstr) != m_command_dict.end())
451 return false;
452 }
453 m_command_dict[name_sstr] = cmd_sp;
454 return true;
455 }
456 return false;
457}
458
459
Jim Inghamd40f8a62010-07-06 22:46:59 +0000460CommandObjectSP
461CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000462{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000463 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
464 CommandObjectSP ret_val; // Possibly empty return value.
465
466 if (cmd_cstr == NULL)
467 return ret_val;
468
469 if (cmd_words.GetArgumentCount() == 1)
470 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
471 else
472 {
473 // We have a multi-word command (seemingly), so we need to do more work.
474 // First, get the cmd_obj_sp for the first word in the command.
475 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
476 if (cmd_obj_sp.get() != NULL)
477 {
478 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
479 // command name), and find the appropriate sub-command SP for each command word....
480 size_t end = cmd_words.GetArgumentCount();
481 for (size_t j= 1; j < end; ++j)
482 {
483 if (cmd_obj_sp->IsMultiwordObject())
484 {
485 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
486 (cmd_words.GetArgumentAtIndex (j));
487 if (cmd_obj_sp.get() == NULL)
488 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
489 return ret_val;
490 }
491 else
492 // We have more words in the command name, but we don't have a multiword object. Fail and return
493 // empty 'ret_val'.
494 return ret_val;
495 }
496 // We successfully looped through all the command words and got valid command objects for them. Assign the
497 // last object retrieved to 'ret_val'.
498 ret_val = cmd_obj_sp;
499 }
500 }
501 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000502}
503
504CommandObject *
505CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
506{
507 return GetCommandSPExact (cmd_cstr, include_aliases).get();
508}
509
510CommandObject *
511CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
512{
513 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
514
515 // If we didn't find an exact match to the command string in the commands, look in
516 // the aliases.
517
518 if (command_obj == NULL)
519 {
520 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
521 }
522
523 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
524 // in both the commands and the aliases.
525
526 if (command_obj == NULL)
527 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
528
529 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000530}
531
532bool
533CommandInterpreter::CommandExists (const char *cmd)
534{
535 return m_command_dict.find(cmd) != m_command_dict.end();
536}
537
538bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000539CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
540 const char *options_args,
541 OptionArgVectorSP &option_arg_vector_sp)
542{
543 bool success = true;
544 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
545
546 if (!options_args || (strlen (options_args) < 1))
547 return true;
548
549 std::string options_string (options_args);
550 Args args (options_args);
551 CommandReturnObject result;
552 // Check to see if the command being aliased can take any command options.
553 Options *options = cmd_obj_sp->GetOptions ();
554 if (options)
555 {
556 // See if any options were specified as part of the alias; if so, handle them appropriately.
557 options->NotifyOptionParsingStarting ();
558 args.Unshift ("dummy_arg");
559 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
560 args.Shift ();
561 if (result.Succeeded())
562 options->VerifyPartialOptions (result);
563 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
564 {
565 result.AppendError ("Unable to create requested alias.\n");
566 return false;
567 }
568 }
569
570 if (options_string.size() > 0)
571 {
572 if (cmd_obj_sp->WantsRawCommandString ())
573 option_arg_vector->push_back (OptionArgPair ("<argument>",
574 OptionArgValue (-1,
575 options_string)));
576 else
577 {
578 int argc = args.GetArgumentCount();
579 for (size_t i = 0; i < argc; ++i)
580 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
581 option_arg_vector->push_back
582 (OptionArgPair ("<argument>",
583 OptionArgValue (-1,
584 std::string (args.GetArgumentAtIndex (i)))));
585 }
586 }
587
588 return success;
589}
590
591bool
Chris Lattner24943d22010-06-08 16:52:24 +0000592CommandInterpreter::AliasExists (const char *cmd)
593{
594 return m_alias_dict.find(cmd) != m_alias_dict.end();
595}
596
597bool
598CommandInterpreter::UserCommandExists (const char *cmd)
599{
600 return m_user_dict.find(cmd) != m_user_dict.end();
601}
602
603void
604CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
605{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000606 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000607 m_alias_dict[alias_name] = command_obj_sp;
608}
609
610bool
611CommandInterpreter::RemoveAlias (const char *alias_name)
612{
613 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
614 if (pos != m_alias_dict.end())
615 {
616 m_alias_dict.erase(pos);
617 return true;
618 }
619 return false;
620}
621bool
622CommandInterpreter::RemoveUser (const char *alias_name)
623{
624 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
625 if (pos != m_user_dict.end())
626 {
627 m_user_dict.erase(pos);
628 return true;
629 }
630 return false;
631}
632
Chris Lattner24943d22010-06-08 16:52:24 +0000633void
634CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
635{
636 help_string.Printf ("'%s", command_name);
637 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
638
639 if (option_arg_vector_sp != NULL)
640 {
641 OptionArgVector *options = option_arg_vector_sp.get();
642 for (int i = 0; i < options->size(); ++i)
643 {
644 OptionArgPair cur_option = (*options)[i];
645 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000646 OptionArgValue value_pair = cur_option.second;
647 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000648 if (opt.compare("<argument>") == 0)
649 {
650 help_string.Printf (" %s", value.c_str());
651 }
652 else
653 {
654 help_string.Printf (" %s", opt.c_str());
655 if ((value.compare ("<no-argument>") != 0)
656 && (value.compare ("<need-argument") != 0))
657 {
658 help_string.Printf (" %s", value.c_str());
659 }
660 }
661 }
662 }
663
664 help_string.Printf ("'");
665}
666
Greg Clayton65124ea2010-08-26 22:05:43 +0000667size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000668CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
669{
670 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000671 CommandObject::CommandMap::const_iterator end = dict.end();
672 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000673
Greg Clayton65124ea2010-08-26 22:05:43 +0000674 for (pos = dict.begin(); pos != end; ++pos)
675 {
676 size_t len = pos->first.size();
677 if (max_len < len)
678 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000679 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000680 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000681}
682
683void
684CommandInterpreter::GetHelp (CommandReturnObject &result)
685{
686 CommandObject::CommandMap::const_iterator pos;
687 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
688 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000689 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000690
691 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
692 {
693 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
694 max_len);
695 }
696 result.AppendMessage("");
697
698 if (m_alias_dict.size() > 0)
699 {
Jim Inghame3663e82010-10-22 18:47:16 +0000700 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000701 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000702 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000703 max_len = FindLongestCommandWord (m_alias_dict);
704
Chris Lattner24943d22010-06-08 16:52:24 +0000705 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
706 {
707 StreamString sstr;
708 StreamString translation_and_help;
709 std::string entry_name = pos->first;
710 std::string second_entry = pos->second.get()->GetCommandName();
711 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
712
713 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
714 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
715 translation_and_help.GetData(), max_len);
716 }
717 result.AppendMessage("");
718 }
719
720 if (m_user_dict.size() > 0)
721 {
722 result.AppendMessage ("The following is a list of your current user-defined commands:");
723 result.AppendMessage("");
724 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
725 {
726 result.AppendMessageWithFormat ("%s -- %s\n", pos->first.c_str(), pos->second->GetHelp());
727 }
728 result.AppendMessage("");
729 }
730
731 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
732}
733
Caroline Ticee0da7a52010-12-09 22:52:49 +0000734CommandObject *
735CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000736{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000737 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
738 // eventually be invoked by the given command line.
739
740 CommandObject *cmd_obj = NULL;
741 std::string white_space (" \t\v");
742 size_t start = command_string.find_first_not_of (white_space);
743 size_t end = 0;
744 bool done = false;
745 while (!done)
746 {
747 if (start != std::string::npos)
748 {
749 // Get the next word from command_string.
750 end = command_string.find_first_of (white_space, start);
751 if (end == std::string::npos)
752 end = command_string.size();
753 std::string cmd_word = command_string.substr (start, end - start);
754
755 if (cmd_obj == NULL)
756 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
757 // command or alias.
758 cmd_obj = GetCommandObject (cmd_word.c_str());
759 else if (cmd_obj->IsMultiwordObject ())
760 {
761 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
762 CommandObject *sub_cmd_obj =
763 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
764 if (sub_cmd_obj)
765 cmd_obj = sub_cmd_obj;
766 else // cmd_word was not a valid sub-command word, so we are donee
767 done = true;
768 }
769 else
770 // We have a cmd_obj and it is not a multi-word object, so we are done.
771 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000772
Caroline Ticee0da7a52010-12-09 22:52:49 +0000773 // If we didn't find a valid command object, or our command object is not a multi-word object, or
774 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
775 // next word.
776
777 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
778 done = true;
779 else
780 start = command_string.find_first_not_of (white_space, end);
781 }
782 else
783 // Unable to find any more words.
784 done = true;
785 }
786
787 if (end == command_string.size())
788 command_string.clear();
789 else
790 command_string = command_string.substr(end);
791
792 return cmd_obj;
793}
794
795bool
Caroline Tice649116c2011-05-11 16:07:06 +0000796CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word, bool &was_quoted, char &quote_char)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000797{
798 std::string white_space (" \t\v");
799 size_t start;
800 size_t end;
801
802 start = command_string.find_first_not_of (white_space);
803 if (start != std::string::npos)
804 {
Caroline Tice649116c2011-05-11 16:07:06 +0000805 size_t len = command_string.size() - start;
806 if (len >= 2
807 && ((command_string[start] == '\'') || (command_string[start] == '"')))
Caroline Ticee0da7a52010-12-09 22:52:49 +0000808 {
Caroline Tice649116c2011-05-11 16:07:06 +0000809 was_quoted = true;
810 quote_char = command_string[start];
811 std::string quote_string = command_string.substr (start, 1);
812 start = start + 1;
813 end = command_string.find (quote_string, start);
814 if (end != std::string::npos)
815 {
816 word = command_string.substr (start, end - start);
817 if (end + 1 < len)
818 command_string = command_string.substr (end+1);
819 else
820 command_string.erase ();
821 size_t pos = command_string.find_first_not_of (white_space);
822 if ((pos != 0) && (pos != std::string::npos))
823 command_string = command_string.substr (pos);
824 }
825 else
826 {
827 word = command_string.substr (start - 1);
828 command_string.erase ();
829 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000830 }
831 else
832 {
Caroline Tice649116c2011-05-11 16:07:06 +0000833 end = command_string.find_first_of (white_space, start);
834 if (end != std::string::npos)
835 {
836 word = command_string.substr (start, end - start);
837 command_string = command_string.substr (end);
838 size_t pos = command_string.find_first_not_of (white_space);
839 if ((pos != 0) && (pos != std::string::npos))
840 command_string = command_string.substr (pos);
841 }
842 else
843 {
844 word = command_string.substr (start);
845 command_string.erase();
846 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000847 }
848
849 }
850 return true;
851}
852
853void
854CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
855 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
856{
857 Args cmd_args (raw_input_string.c_str());
858 alias_cmd_obj = GetCommandObject (alias_name);
859 StreamString result_str;
860
861 if (alias_cmd_obj)
862 {
863 std::string alias_name_str = alias_name;
864 if ((cmd_args.GetArgumentCount() == 0)
865 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
866 cmd_args.Unshift (alias_name);
867
868 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
869 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
870
871 if (option_arg_vector_sp.get())
872 {
873 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
874
875 for (int i = 0; i < option_arg_vector->size(); ++i)
876 {
877 OptionArgPair option_pair = (*option_arg_vector)[i];
878 OptionArgValue value_pair = option_pair.second;
879 int value_type = value_pair.first;
880 std::string option = option_pair.first;
881 std::string value = value_pair.second;
882 if (option.compare ("<argument>") == 0)
883 result_str.Printf (" %s", value.c_str());
884 else
885 {
886 result_str.Printf (" %s", option.c_str());
887 if (value_type != optional_argument)
888 result_str.Printf (" ");
889 if (value.compare ("<no_argument>") != 0)
890 {
891 int index = GetOptionArgumentPosition (value.c_str());
892 if (index == 0)
893 result_str.Printf ("%s", value.c_str());
894 else if (index >= cmd_args.GetArgumentCount())
895 {
896
897 result.AppendErrorWithFormat
898 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
899 index);
900 result.SetStatus (eReturnStatusFailed);
901 return;
902 }
903 else
904 {
905 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
906 if (strpos != std::string::npos)
907 raw_input_string = raw_input_string.erase (strpos,
908 strlen (cmd_args.GetArgumentAtIndex (index)));
909 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
910 }
911 }
912 }
913 }
914 }
915
916 alias_result = result_str.GetData();
917 }
918}
919
920bool
921CommandInterpreter::HandleCommand (const char *command_line,
922 bool add_to_history,
923 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +0000924 ExecutionContext *override_context,
925 bool repeat_on_empty_command)
926
Caroline Ticee0da7a52010-12-09 22:52:49 +0000927{
Jim Ingham949d5ac2011-02-18 00:54:25 +0000928
Caroline Ticee0da7a52010-12-09 22:52:49 +0000929 bool done = false;
930 CommandObject *cmd_obj = NULL;
931 std::string next_word;
932 bool wants_raw_input = false;
933 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +0000934 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +0000935
936 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000937 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
938
939 // Make a scoped cleanup object that will clear the crash description string
940 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +0000941 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +0000942
Caroline Ticee0da7a52010-12-09 22:52:49 +0000943 if (log)
944 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000945
Jim Inghamabab14b2010-11-04 23:08:45 +0000946 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
947
Greg Claytonb72d0f02011-04-12 05:54:46 +0000948 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000949
Jim Ingham949d5ac2011-02-18 00:54:25 +0000950 bool empty_command = false;
951 bool comment_command = false;
952 if (command_string.empty())
953 empty_command = true;
954 else
Chris Lattner24943d22010-06-08 16:52:24 +0000955 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000956 const char *k_space_characters = "\t\n\v\f\r ";
957
958 size_t non_space = command_string.find_first_not_of (k_space_characters);
959 // Check for empty line or comment line (lines whose first
960 // non-space character is the comment character for this interpreter)
961 if (non_space == std::string::npos)
962 empty_command = true;
963 else if (command_string[non_space] == m_comment_char)
964 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +0000965 else if (command_string[non_space] == m_repeat_char)
966 {
967 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
968 if (history_string == NULL)
969 {
970 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
971 result.SetStatus(eReturnStatusFailed);
972 return false;
973 }
974 add_to_history = false;
975 command_string = history_string;
976 original_command_string = history_string;
977 }
Jim Ingham949d5ac2011-02-18 00:54:25 +0000978 }
979
980 if (empty_command)
981 {
982 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +0000983 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000984 if (m_command_history.empty())
985 {
986 result.AppendError ("empty command");
987 result.SetStatus(eReturnStatusFailed);
988 return false;
989 }
990 else
991 {
992 command_line = m_repeat_command.c_str();
993 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +0000994 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +0000995 if (m_repeat_command.empty())
996 {
997 result.AppendErrorWithFormat("No auto repeat.\n");
998 result.SetStatus (eReturnStatusFailed);
999 return false;
1000 }
1001 }
1002 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001003 }
1004 else
1005 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001006 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1007 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001008 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001009 }
1010 else if (comment_command)
1011 {
1012 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1013 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001014 }
Caroline Tice649116c2011-05-11 16:07:06 +00001015
Caroline Ticee0da7a52010-12-09 22:52:49 +00001016 // Phase 1.
1017
1018 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1019 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1020 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1021 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1022 // 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 +00001023 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001024 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001025
Caroline Ticee0da7a52010-12-09 22:52:49 +00001026 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001027 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001028 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001029 {
Caroline Tice649116c2011-05-11 16:07:06 +00001030 bool was_quoted = false;
1031 char quote_char = '\0';
1032 StripFirstWord (command_string, next_word, was_quoted, quote_char);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001033 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +00001034 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001035 std::string alias_result;
1036 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
1037 revised_command_line.Printf ("%s", alias_result.c_str());
1038 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +00001039 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001040 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +00001041 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1042 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001043 }
1044 else if (!cmd_obj)
1045 {
1046 cmd_obj = GetCommandObject (next_word.c_str());
1047 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +00001048 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001049 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +00001050 revised_command_line.Printf ("%s", next_word.c_str());
1051 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +00001052 }
1053 else
1054 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001055 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001056 }
1057 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001058 else if (cmd_obj->IsMultiwordObject ())
1059 {
1060 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1061 if (sub_cmd_obj)
1062 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001063 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001064 revised_command_line.Printf (" %s", next_word.c_str());
1065 cmd_obj = sub_cmd_obj;
1066 wants_raw_input = cmd_obj->WantsRawCommandString ();
1067 }
1068 else
1069 {
Caroline Tice649116c2011-05-11 16:07:06 +00001070 if (was_quoted)
1071 {
1072 if (quote_char == '"')
1073 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1074 else
1075 revised_command_line.Printf (" '%s'", next_word.c_str());
1076 }
1077 else
1078 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001079 done = true;
1080 }
1081 }
1082 else
1083 {
Caroline Tice649116c2011-05-11 16:07:06 +00001084 if (was_quoted)
1085 {
1086 if (quote_char == '"')
1087 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1088 else
1089 revised_command_line.Printf (" '%s'", next_word.c_str());
1090 }
1091 else
1092 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001093 done = true;
1094 }
1095
1096 if (cmd_obj == NULL)
1097 {
1098 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1099 result.SetStatus (eReturnStatusFailed);
1100 return false;
1101 }
1102
1103 next_word.erase ();
1104 if (command_string.length() == 0)
1105 done = true;
1106
Chris Lattner24943d22010-06-08 16:52:24 +00001107 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001108
1109 if (command_string.size() > 0)
1110 revised_command_line.Printf (" %s", command_string.c_str());
1111
1112 // End of Phase 1.
1113 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1114 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1115 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1116 // wants_raw_input specifies whether the Execute method expects raw input or not.
1117
1118
1119 if (log)
1120 {
1121 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1122 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1123 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1124 }
1125
1126 // Phase 2.
1127 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1128 // CommandObject, with the appropriate arguments.
1129
1130 if (cmd_obj != NULL)
1131 {
1132 if (add_to_history)
1133 {
1134 Args command_args (revised_command_line.GetData());
1135 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1136 if (repeat_command != NULL)
1137 m_repeat_command.assign(repeat_command);
1138 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001139 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001140
Jim Ingham6247dbe2011-07-12 03:12:18 +00001141 // Don't keep pushing the same command onto the history...
1142 if (m_command_history.size() == 0 || m_command_history.back() != original_command_string)
1143 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001144 }
1145
1146 command_string = revised_command_line.GetData();
1147 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001148 std::string remainder;
1149 if (actual_cmd_name_len < command_string.length())
1150 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1151 // than cmd_obj->GetCommandName(), because name completion
1152 // allows users to enter short versions of the names,
1153 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001154
1155 // Remove any initial spaces
1156 std::string white_space (" \t\v");
1157 size_t pos = remainder.find_first_not_of (white_space);
1158 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001159 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001160
1161 if (log)
1162 log->Printf ("HandleCommand, command line after removing command name(s): '%s'\n", remainder.c_str());
1163
1164
1165 if (wants_raw_input)
1166 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1167 else
1168 {
1169 Args cmd_args (remainder.c_str());
1170 cmd_obj->ExecuteWithOptions (cmd_args, result);
1171 }
1172 }
1173 else
1174 {
1175 // We didn't find the first command object, so complete the first argument.
1176 Args command_args (revised_command_line.GetData());
1177 StringList matches;
1178 int num_matches;
1179 int cursor_index = 0;
1180 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1181 bool word_complete;
1182 num_matches = HandleCompletionMatches (command_args,
1183 cursor_index,
1184 cursor_char_position,
1185 0,
1186 -1,
1187 word_complete,
1188 matches);
1189
1190 if (num_matches > 0)
1191 {
1192 std::string error_msg;
1193 error_msg.assign ("ambiguous command '");
1194 error_msg.append(command_args.GetArgumentAtIndex(0));
1195 error_msg.append ("'.");
1196
1197 error_msg.append (" Possible completions:");
1198 for (int i = 0; i < num_matches; i++)
1199 {
1200 error_msg.append ("\n\t");
1201 error_msg.append (matches.GetStringAtIndex (i));
1202 }
1203 error_msg.append ("\n");
1204 result.AppendRawError (error_msg.c_str(), error_msg.size());
1205 }
1206 else
1207 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1208
1209 result.SetStatus (eReturnStatusFailed);
1210 }
1211
Chris Lattner24943d22010-06-08 16:52:24 +00001212 return result.Succeeded();
1213}
1214
1215int
1216CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1217 int &cursor_index,
1218 int &cursor_char_position,
1219 int match_start_point,
1220 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001221 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001222 StringList &matches)
1223{
1224 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001225 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001226
1227 // For any of the command completions a unique match will be a complete word.
1228 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001229
1230 if (cursor_index == -1)
1231 {
1232 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001233 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001234 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1235 }
1236 else if (cursor_index == 0)
1237 {
1238 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001239 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001240 num_command_matches = matches.GetSize();
1241
1242 if (num_command_matches == 1
1243 && cmd_obj && cmd_obj->IsMultiwordObject()
1244 && matches.GetStringAtIndex(0) != NULL
1245 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1246 {
1247 look_for_subcommand = true;
1248 num_command_matches = 0;
1249 matches.DeleteStringAtIndex(0);
1250 parsed_line.AppendArgument ("");
1251 cursor_index++;
1252 cursor_char_position = 0;
1253 }
1254 }
1255
1256 if (cursor_index > 0 || look_for_subcommand)
1257 {
1258 // We are completing further on into a commands arguments, so find the command and tell it
1259 // to complete the command.
1260 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001261 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001262 if (command_object == NULL)
1263 {
1264 return 0;
1265 }
1266 else
1267 {
1268 parsed_line.Shift();
1269 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001270 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001271 cursor_index,
1272 cursor_char_position,
1273 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001274 max_return_elements,
1275 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001276 matches);
1277 }
1278 }
1279
1280 return num_command_matches;
1281
1282}
1283
1284int
1285CommandInterpreter::HandleCompletion (const char *current_line,
1286 const char *cursor,
1287 const char *last_char,
1288 int match_start_point,
1289 int max_return_elements,
1290 StringList &matches)
1291{
1292 // We parse the argument up to the cursor, so the last argument in parsed_line is
1293 // the one containing the cursor, and the cursor is after the last character.
1294
1295 Args parsed_line(current_line, last_char - current_line);
1296 Args partial_parsed_line(current_line, cursor - current_line);
1297
Jim Ingham6247dbe2011-07-12 03:12:18 +00001298 // Don't complete comments, and if the line we are completing is just the history repeat character,
1299 // substitute the appropriate history line.
1300 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1301 if (first_arg)
1302 {
1303 if (first_arg[0] == m_comment_char)
1304 return 0;
1305 else if (first_arg[0] == m_repeat_char)
1306 {
1307 const char *history_string = FindHistoryString (first_arg);
1308 if (history_string != NULL)
1309 {
1310 matches.Clear();
1311 matches.InsertStringAtIndex(0, history_string);
1312 return -2;
1313 }
1314 else
1315 return 0;
1316
1317 }
1318 }
1319
1320
Chris Lattner24943d22010-06-08 16:52:24 +00001321 int num_args = partial_parsed_line.GetArgumentCount();
1322 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1323 int cursor_char_position;
1324
1325 if (cursor_index == -1)
1326 cursor_char_position = 0;
1327 else
1328 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001329
1330 if (cursor > current_line && cursor[-1] == ' ')
1331 {
1332 // We are just after a space. If we are in an argument, then we will continue
1333 // parsing, but if we are between arguments, then we have to complete whatever the next
1334 // element would be.
1335 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1336 // protected by a quote) then the space will also be in the parsed argument...
1337
1338 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1339 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1340 {
1341 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1342 cursor_index++;
1343 cursor_char_position = 0;
1344 }
1345 }
Chris Lattner24943d22010-06-08 16:52:24 +00001346
1347 int num_command_matches;
1348
1349 matches.Clear();
1350
1351 // Only max_return_elements == -1 is supported at present:
1352 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001353 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001354 num_command_matches = HandleCompletionMatches (parsed_line,
1355 cursor_index,
1356 cursor_char_position,
1357 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001358 max_return_elements,
1359 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001360 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001361
1362 if (num_command_matches <= 0)
1363 return num_command_matches;
1364
1365 if (num_args == 0)
1366 {
1367 // If we got an empty string, insert nothing.
1368 matches.InsertStringAtIndex(0, "");
1369 }
1370 else
1371 {
1372 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1373 // put an empty string in element 0.
1374 std::string command_partial_str;
1375 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001376 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1377 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001378
1379 std::string common_prefix;
1380 matches.LongestCommonPrefix (common_prefix);
1381 int partial_name_len = command_partial_str.size();
1382
1383 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001384 // Only do this if the completer told us this was a complete word, however...
1385 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001386 {
1387 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1388 if (quote_char != '\0')
1389 common_prefix.push_back(quote_char);
1390
1391 common_prefix.push_back(' ');
1392 }
1393 common_prefix.erase (0, partial_name_len);
1394 matches.InsertStringAtIndex(0, common_prefix.c_str());
1395 }
1396 return num_command_matches;
1397}
1398
Chris Lattner24943d22010-06-08 16:52:24 +00001399
1400CommandInterpreter::~CommandInterpreter ()
1401{
1402}
1403
1404const char *
1405CommandInterpreter::GetPrompt ()
1406{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001407 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001408}
1409
1410void
1411CommandInterpreter::SetPrompt (const char *new_prompt)
1412{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001413 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001414}
1415
Jim Ingham5e16ef52010-10-04 19:49:29 +00001416size_t
Greg Clayton58928562011-02-09 01:08:52 +00001417CommandInterpreter::GetConfirmationInputReaderCallback
1418(
1419 void *baton,
1420 InputReader &reader,
1421 lldb::InputReaderAction action,
1422 const char *bytes,
1423 size_t bytes_len
1424)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001425{
Greg Clayton58928562011-02-09 01:08:52 +00001426 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001427 bool *response_ptr = (bool *) baton;
1428
1429 switch (action)
1430 {
1431 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001432 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001433 {
1434 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001435 {
Greg Clayton58928562011-02-09 01:08:52 +00001436 out_file.Printf ("%s", reader.GetPrompt());
1437 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001438 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001439 }
1440 break;
1441
1442 case eInputReaderDeactivate:
1443 break;
1444
1445 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001446 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001447 {
Greg Clayton58928562011-02-09 01:08:52 +00001448 out_file.Printf ("%s", reader.GetPrompt());
1449 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001450 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001451 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001452
1453 case eInputReaderAsynchronousOutputWritten:
1454 break;
1455
Jim Ingham5e16ef52010-10-04 19:49:29 +00001456 case eInputReaderGotToken:
1457 if (bytes_len == 0)
1458 {
1459 reader.SetIsDone(true);
1460 }
1461 else if (bytes[0] == 'y')
1462 {
1463 *response_ptr = true;
1464 reader.SetIsDone(true);
1465 }
1466 else if (bytes[0] == 'n')
1467 {
1468 *response_ptr = false;
1469 reader.SetIsDone(true);
1470 }
1471 else
1472 {
Greg Clayton58928562011-02-09 01:08:52 +00001473 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001474 {
Greg Clayton58928562011-02-09 01:08:52 +00001475 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1476 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001477 }
1478 }
1479 break;
1480
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001481 case eInputReaderInterrupt:
1482 case eInputReaderEndOfFile:
1483 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1484 reader.SetIsDone (true);
1485 break;
1486
Jim Ingham5e16ef52010-10-04 19:49:29 +00001487 case eInputReaderDone:
1488 break;
1489 }
1490
1491 return bytes_len;
1492
1493}
1494
1495bool
1496CommandInterpreter::Confirm (const char *message, bool default_answer)
1497{
Jim Ingham93057472010-10-04 22:44:14 +00001498 // Check AutoConfirm first:
1499 if (m_debugger.GetAutoConfirm())
1500 return default_answer;
1501
Jim Ingham5e16ef52010-10-04 19:49:29 +00001502 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1503 bool response = default_answer;
1504 if (reader_sp)
1505 {
1506 std::string prompt(message);
1507 prompt.append(": [");
1508 if (default_answer)
1509 prompt.append ("Y/n] ");
1510 else
1511 prompt.append ("y/N] ");
1512
1513 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1514 &response, // baton
1515 eInputReaderGranularityLine, // token size, to pass to callback function
1516 NULL, // end token
1517 prompt.c_str(), // prompt
1518 true)); // echo input
1519 if (err.Success())
1520 {
1521 GetDebugger().PushInputReader (reader_sp);
1522 }
1523 reader_sp->WaitOnReaderIsDone();
1524 }
1525 return response;
1526}
1527
1528
Chris Lattner24943d22010-06-08 16:52:24 +00001529void
1530CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1531{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001532 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001533
1534 if (cmd_obj_sp != NULL)
1535 {
1536 CommandObject *cmd_obj = cmd_obj_sp.get();
1537 if (cmd_obj->IsCrossRefObject ())
1538 cmd_obj->AddObject (object_type);
1539 }
1540}
1541
Chris Lattner24943d22010-06-08 16:52:24 +00001542OptionArgVectorSP
1543CommandInterpreter::GetAliasOptions (const char *alias_name)
1544{
1545 OptionArgMap::iterator pos;
1546 OptionArgVectorSP ret_val;
1547
1548 std::string alias (alias_name);
1549
1550 if (HasAliasOptions())
1551 {
1552 pos = m_alias_options.find (alias);
1553 if (pos != m_alias_options.end())
1554 ret_val = pos->second;
1555 }
1556
1557 return ret_val;
1558}
1559
1560void
1561CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1562{
1563 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1564 if (pos != m_alias_options.end())
1565 {
1566 m_alias_options.erase (pos);
1567 }
1568}
1569
1570void
1571CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1572{
1573 m_alias_options[alias_name] = option_arg_vector_sp;
1574}
1575
1576bool
1577CommandInterpreter::HasCommands ()
1578{
1579 return (!m_command_dict.empty());
1580}
1581
1582bool
1583CommandInterpreter::HasAliases ()
1584{
1585 return (!m_alias_dict.empty());
1586}
1587
1588bool
1589CommandInterpreter::HasUserCommands ()
1590{
1591 return (!m_user_dict.empty());
1592}
1593
1594bool
1595CommandInterpreter::HasAliasOptions ()
1596{
1597 return (!m_alias_options.empty());
1598}
1599
Chris Lattner24943d22010-06-08 16:52:24 +00001600void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001601CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1602 const char *alias_name,
1603 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001604 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001605 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001606{
1607 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001608
1609 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001610
Caroline Tice44c841d2010-12-07 19:58:26 +00001611 // Make sure that the alias name is the 0th element in cmd_args
1612 std::string alias_name_str = alias_name;
1613 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1614 cmd_args.Unshift (alias_name);
1615
1616 Args new_args (alias_cmd_obj->GetCommandName());
1617 if (new_args.GetArgumentCount() == 2)
1618 new_args.Shift();
1619
Chris Lattner24943d22010-06-08 16:52:24 +00001620 if (option_arg_vector_sp.get())
1621 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001622 if (wants_raw_input)
1623 {
1624 // We have a command that both has command options and takes raw input. Make *sure* it has a
1625 // " -- " in the right place in the raw_input_string.
1626 size_t pos = raw_input_string.find(" -- ");
1627 if (pos == std::string::npos)
1628 {
1629 // None found; assume it goes at the beginning of the raw input string
1630 raw_input_string.insert (0, " -- ");
1631 }
1632 }
Chris Lattner24943d22010-06-08 16:52:24 +00001633
1634 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1635 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001636 std::vector<bool> used (old_size + 1, false);
1637
1638 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001639
1640 for (int i = 0; i < option_arg_vector->size(); ++i)
1641 {
1642 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001643 OptionArgValue value_pair = option_pair.second;
1644 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001645 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001646 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001647 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001648 {
1649 if (!wants_raw_input
1650 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1651 new_args.AppendArgument (value.c_str());
1652 }
Chris Lattner24943d22010-06-08 16:52:24 +00001653 else
1654 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001655 if (value_type != optional_argument)
1656 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001657 if (value.compare ("<no-argument>") != 0)
1658 {
1659 int index = GetOptionArgumentPosition (value.c_str());
1660 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001661 {
Chris Lattner24943d22010-06-08 16:52:24 +00001662 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001663 if (value_type != optional_argument)
1664 new_args.AppendArgument (value.c_str());
1665 else
1666 {
1667 char buffer[255];
1668 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1669 new_args.AppendArgument (buffer);
1670 }
1671
1672 }
Chris Lattner24943d22010-06-08 16:52:24 +00001673 else if (index >= cmd_args.GetArgumentCount())
1674 {
1675 result.AppendErrorWithFormat
1676 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1677 index);
1678 result.SetStatus (eReturnStatusFailed);
1679 return;
1680 }
1681 else
1682 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001683 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1684 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1685 if (strpos != std::string::npos)
1686 {
1687 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1688 }
1689
1690 if (value_type != optional_argument)
1691 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1692 else
1693 {
1694 char buffer[255];
1695 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1696 cmd_args.GetArgumentAtIndex (index));
1697 new_args.AppendArgument (buffer);
1698 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001699 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001700 }
1701 }
1702 }
1703 }
1704
1705 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1706 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001707 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001708 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1709 }
1710
1711 cmd_args.Clear();
1712 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1713 }
1714 else
1715 {
1716 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001717 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1718 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1719 // input string.
1720 if (wants_raw_input)
1721 {
1722 cmd_args.Clear();
1723 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1724 }
Chris Lattner24943d22010-06-08 16:52:24 +00001725 return;
1726 }
1727
1728 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1729 return;
1730}
1731
1732
1733int
1734CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1735{
1736 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1737 // of zero.
1738
1739 char *cptr = (char *) in_string;
1740
1741 // Does it start with '%'
1742 if (cptr[0] == '%')
1743 {
1744 ++cptr;
1745
1746 // Is the rest of it entirely digits?
1747 if (isdigit (cptr[0]))
1748 {
1749 const char *start = cptr;
1750 while (isdigit (cptr[0]))
1751 ++cptr;
1752
1753 // We've gotten to the end of the digits; are we at the end of the string?
1754 if (cptr[0] == '\0')
1755 position = atoi (start);
1756 }
1757 }
1758
1759 return position;
1760}
1761
1762void
1763CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1764{
Greg Clayton887aa282010-10-11 01:05:37 +00001765 // Don't parse any .lldbinit files if we were asked not to
Jim Ingham574c3d62011-08-12 23:34:31 +00001766 if (m_skip_lldbinit_files && m_skip_app_init_files)
Greg Clayton887aa282010-10-11 01:05:37 +00001767 return;
1768
Chris Lattner24943d22010-06-08 16:52:24 +00001769 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Jim Ingham574c3d62011-08-12 23:34:31 +00001770
1771 std::string app_specific_init;
1772
1773 if (!m_skip_app_init_files)
1774 {
1775 FileSpec host_spec = Host::GetProgramFileSpec();
1776 const char *host_name = host_spec.GetFilename().AsCString();
1777
1778 if (host_name != NULL && strcmp (host_name, "lldb") != 0)
1779 {
1780 app_specific_init += init_file_path;
1781 app_specific_init += "-";
1782 app_specific_init += host_name;
1783 }
1784 }
1785
1786 FileSpec init_file;
1787 if (!app_specific_init.empty())
1788 {
1789 init_file.SetFile (app_specific_init.c_str(), true);
1790 }
1791
1792 if (!m_skip_lldbinit_files && !init_file.Exists())
1793 {
1794 init_file.SetFile (init_file_path, true);
1795 }
1796
Chris Lattner24943d22010-06-08 16:52:24 +00001797 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1798 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1799
1800 if (init_file.Exists())
1801 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001802 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1803 bool stop_on_continue = true;
1804 bool stop_on_error = false;
1805 bool echo_commands = false;
1806 bool print_results = false;
1807
1808 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001809 }
1810 else
1811 {
1812 // nothing to be done if the file doesn't exist
1813 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1814 }
1815}
1816
Greg Claytonb72d0f02011-04-12 05:54:46 +00001817PlatformSP
1818CommandInterpreter::GetPlatform (bool prefer_target_platform)
1819{
1820 PlatformSP platform_sp;
1821 if (prefer_target_platform && m_exe_ctx.target)
1822 platform_sp = m_exe_ctx.target->GetPlatform();
1823
1824 if (!platform_sp)
1825 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
1826 return platform_sp;
1827}
1828
Jim Ingham949d5ac2011-02-18 00:54:25 +00001829void
Jim Inghama4fede32011-03-11 01:51:49 +00001830CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001831 ExecutionContext *override_context,
1832 bool stop_on_continue,
1833 bool stop_on_error,
1834 bool echo_commands,
1835 bool print_results,
1836 CommandReturnObject &result)
1837{
1838 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00001839
1840 // If we are going to continue past a "continue" then we need to run the commands synchronously.
1841 // Make sure you reset this value anywhere you return from the function.
1842
1843 bool old_async_execution = m_debugger.GetAsyncExecution();
1844
1845 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1846 // cause series of commands that change the context, then do an operation that relies on that context to fail.
1847
1848 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001849 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00001850
1851 if (!stop_on_continue)
1852 {
1853 m_debugger.SetAsyncExecution (false);
1854 }
1855
1856 for (int idx = 0; idx < num_lines; idx++)
1857 {
1858 const char *cmd = commands.GetStringAtIndex(idx);
1859 if (cmd[0] == '\0')
1860 continue;
1861
Jim Ingham949d5ac2011-02-18 00:54:25 +00001862 if (echo_commands)
1863 {
1864 result.AppendMessageWithFormat ("%s %s\n",
1865 GetPrompt(),
1866 cmd);
1867 }
1868
Greg Claytonaa378b12011-02-20 02:15:07 +00001869 CommandReturnObject tmp_result;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001870 bool success = HandleCommand(cmd, false, tmp_result, NULL);
1871
1872 if (print_results)
1873 {
1874 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001875 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001876 }
1877
1878 if (!success || !tmp_result.Succeeded())
1879 {
1880 if (stop_on_error)
1881 {
1882 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1883 idx, cmd);
1884 result.SetStatus (eReturnStatusFailed);
1885 m_debugger.SetAsyncExecution (old_async_execution);
1886 return;
1887 }
1888 else if (print_results)
1889 {
1890 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1891 idx + 1,
1892 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001893 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001894 }
1895 }
1896
Caroline Tice4a348082011-05-02 20:41:46 +00001897 if (result.GetImmediateOutputStream())
1898 result.GetImmediateOutputStream()->Flush();
1899
1900 if (result.GetImmediateErrorStream())
1901 result.GetImmediateErrorStream()->Flush();
1902
Jim Ingham949d5ac2011-02-18 00:54:25 +00001903 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1904 // could be running (for instance in Breakpoint Commands.
1905 // So we check the return value to see if it is has running in it.
1906 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1907 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1908 {
1909 if (stop_on_continue)
1910 {
1911 // If we caused the target to proceed, and we're going to stop in that case, set the
1912 // status in our real result before returning. This is an error if the continue was not the
1913 // last command in the set of commands to be run.
1914 if (idx != num_lines - 1)
1915 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1916 idx + 1, cmd);
1917 else
1918 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1919
1920 result.SetStatus(tmp_result.GetStatus());
1921 m_debugger.SetAsyncExecution (old_async_execution);
1922
1923 return;
1924 }
1925 }
1926
1927 }
1928
1929 result.SetStatus (eReturnStatusSuccessFinishResult);
1930 m_debugger.SetAsyncExecution (old_async_execution);
1931
1932 return;
1933}
1934
1935void
1936CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1937 ExecutionContext *context,
1938 bool stop_on_continue,
1939 bool stop_on_error,
1940 bool echo_command,
1941 bool print_result,
1942 CommandReturnObject &result)
1943{
1944 if (cmd_file.Exists())
1945 {
1946 bool success;
1947 StringList commands;
1948 success = commands.ReadFileLines(cmd_file);
1949 if (!success)
1950 {
1951 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1952 result.SetStatus (eReturnStatusFailed);
1953 return;
1954 }
1955 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1956 }
1957 else
1958 {
1959 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1960 cmd_file.GetFilename().AsCString());
1961 result.SetStatus (eReturnStatusFailed);
1962 return;
1963 }
1964}
1965
Chris Lattner24943d22010-06-08 16:52:24 +00001966ScriptInterpreter *
1967CommandInterpreter::GetScriptInterpreter ()
1968{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001969 if (m_script_interpreter_ap.get() != NULL)
1970 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00001971
Caroline Tice0aa2e552011-01-14 00:29:16 +00001972 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
1973 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00001974 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001975 case eScriptLanguageNone:
1976 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
1977 break;
1978 case eScriptLanguagePython:
1979 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
1980 break;
1981 default:
1982 break;
1983 };
1984
1985 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00001986}
1987
1988
1989
1990bool
1991CommandInterpreter::GetSynchronous ()
1992{
1993 return m_synchronous_execution;
1994}
1995
1996void
1997CommandInterpreter::SetSynchronous (bool value)
1998{
Johnny Chend7a4eb02010-10-14 01:22:03 +00001999 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002000}
2001
2002void
2003CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2004 const char *word_text,
2005 const char *separator,
2006 const char *help_text,
2007 uint32_t max_word_len)
2008{
Greg Clayton238c0a12010-09-18 01:14:36 +00002009 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2010
Chris Lattner24943d22010-06-08 16:52:24 +00002011 int indent_size = max_word_len + strlen (separator) + 2;
2012
2013 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002014
2015 StreamString text_strm;
2016 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2017
2018 size_t len = text_strm.GetSize();
2019 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002020 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002021 {
2022 text_strm.EOL();
2023 len = text_strm.GetSize();
2024 }
Chris Lattner24943d22010-06-08 16:52:24 +00002025
2026 if (len < max_columns)
2027 {
2028 // Output it as a single line.
2029 strm.Printf ("%s", text);
2030 }
2031 else
2032 {
2033 // We need to break it up into multiple lines.
2034 bool first_line = true;
2035 int text_width;
2036 int start = 0;
2037 int end = start;
2038 int final_end = strlen (text);
2039 int sub_len;
2040
2041 while (end < final_end)
2042 {
2043 if (first_line)
2044 text_width = max_columns - 1;
2045 else
2046 text_width = max_columns - indent_size - 1;
2047
2048 // Don't start the 'text' on a space, since we're already outputting the indentation.
2049 if (!first_line)
2050 {
2051 while ((start < final_end) && (text[start] == ' '))
2052 start++;
2053 }
2054
2055 end = start + text_width;
2056 if (end > final_end)
2057 end = final_end;
2058 else
2059 {
2060 // If we're not at the end of the text, make sure we break the line on white space.
2061 while (end > start
2062 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2063 end--;
2064 }
2065
2066 sub_len = end - start;
2067 if (start != 0)
2068 strm.EOL();
2069 if (!first_line)
2070 strm.Indent();
2071 else
2072 first_line = false;
2073 assert (start <= final_end);
2074 assert (start + sub_len <= final_end);
2075 if (sub_len > 0)
2076 strm.Write (text + start, sub_len);
2077 start = end + 1;
2078 }
2079 }
2080 strm.EOL();
2081 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002082}
2083
2084void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002085CommandInterpreter::OutputHelpText (Stream &strm,
2086 const char *word_text,
2087 const char *separator,
2088 const char *help_text,
2089 uint32_t max_word_len)
2090{
2091 int indent_size = max_word_len + strlen (separator) + 2;
2092
2093 strm.IndentMore (indent_size);
2094
2095 StreamString text_strm;
2096 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2097
2098 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2099 bool first_line = true;
2100
2101 size_t len = text_strm.GetSize();
2102 const char *text = text_strm.GetData();
2103
2104 uint32_t chars_left = max_columns;
2105
2106 for (uint32_t i = 0; i < len; i++)
2107 {
2108 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2109 {
2110 first_line = false;
2111 chars_left = max_columns - indent_size;
2112 strm.EOL();
2113 strm.Indent();
2114 }
2115 else
2116 {
2117 strm.PutChar(text[i]);
2118 chars_left--;
2119 }
2120
2121 }
2122
2123 strm.EOL();
2124 strm.IndentLess(indent_size);
2125}
2126
2127void
Chris Lattner24943d22010-06-08 16:52:24 +00002128CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2129 StringList &commands_found, StringList &commands_help)
2130{
2131 CommandObject::CommandMap::const_iterator pos;
2132 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2133 CommandObject *sub_cmd_obj;
2134
2135 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2136 {
2137 const char * command_name = pos->first.c_str();
2138 sub_cmd_obj = pos->second.get();
2139 StreamString complete_command_name;
2140
2141 complete_command_name.Printf ("%s %s", prefix, command_name);
2142
Greg Clayton238c0a12010-09-18 01:14:36 +00002143 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002144 {
2145 commands_found.AppendString (complete_command_name.GetData());
2146 commands_help.AppendString (sub_cmd_obj->GetHelp());
2147 }
2148
2149 if (sub_cmd_obj->IsMultiwordObject())
2150 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2151 commands_help);
2152 }
2153
2154}
2155
2156void
2157CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2158 StringList &commands_help)
2159{
2160 CommandObject::CommandMap::const_iterator pos;
2161
2162 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2163 {
2164 const char *command_name = pos->first.c_str();
2165 CommandObject *cmd_obj = pos->second.get();
2166
Greg Clayton238c0a12010-09-18 01:14:36 +00002167 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002168 {
2169 commands_found.AppendString (command_name);
2170 commands_help.AppendString (cmd_obj->GetHelp());
2171 }
2172
2173 if (cmd_obj->IsMultiwordObject())
2174 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2175
2176 }
2177}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002178
2179
2180void
2181CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2182{
2183 m_exe_ctx.Clear();
2184
2185 if (override_context != NULL)
2186 {
2187 m_exe_ctx.target = override_context->target;
2188 m_exe_ctx.process = override_context->process;
2189 m_exe_ctx.thread = override_context->thread;
2190 m_exe_ctx.frame = override_context->frame;
2191 }
2192 else
2193 {
2194 TargetSP target_sp (m_debugger.GetSelectedTarget());
2195 if (target_sp)
2196 {
2197 m_exe_ctx.target = target_sp.get();
2198 m_exe_ctx.process = target_sp->GetProcessSP().get();
2199 if (m_exe_ctx.process && m_exe_ctx.process->IsAlive() && !m_exe_ctx.process->IsRunning())
2200 {
2201 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetSelectedThread().get();
2202 if (m_exe_ctx.thread == NULL)
2203 {
2204 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetThreadAtIndex(0).get();
2205 // If we didn't have a selected thread, select one here.
2206 if (m_exe_ctx.thread != NULL)
2207 m_exe_ctx.process->GetThreadList().SetSelectedThreadByID(m_exe_ctx.thread->GetID());
2208 }
2209 if (m_exe_ctx.thread)
2210 {
2211 m_exe_ctx.frame = m_exe_ctx.thread->GetSelectedFrame().get();
2212 if (m_exe_ctx.frame == NULL)
2213 {
2214 m_exe_ctx.frame = m_exe_ctx.thread->GetStackFrameAtIndex (0).get();
2215 // If we didn't have a selected frame select one here.
2216 if (m_exe_ctx.frame != NULL)
2217 m_exe_ctx.thread->SetSelectedFrame(m_exe_ctx.frame);
2218 }
2219 }
2220 }
2221 }
2222 }
2223}
2224
Jim Ingham6247dbe2011-07-12 03:12:18 +00002225void
2226CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2227{
2228 DumpHistory (stream, 0, count - 1);
2229}
2230
2231void
2232CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2233{
2234 size_t num_history_elements = m_command_history.size();
2235 if (start > num_history_elements)
2236 return;
2237 for (uint32_t i = start; i < num_history_elements && i <= end; i++)
2238 {
2239 if (!m_command_history[i].empty())
2240 {
2241 stream.Indent();
2242 stream.Printf ("%4d: %s\n", i, m_command_history[i].c_str());
2243 }
2244 }
2245}
2246
2247const char *
2248CommandInterpreter::FindHistoryString (const char *input_str) const
2249{
2250 if (input_str[0] != m_repeat_char)
2251 return NULL;
2252 if (input_str[1] == '-')
2253 {
2254 bool success;
2255 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2256 if (!success)
2257 return NULL;
2258 if (idx > m_command_history.size())
2259 return NULL;
2260 idx = m_command_history.size() - idx;
2261 return m_command_history[idx].c_str();
2262
2263 }
2264 else if (input_str[1] == m_repeat_char)
2265 {
2266 if (m_command_history.empty())
2267 return NULL;
2268 else
2269 return m_command_history.back().c_str();
2270 }
2271 else
2272 {
2273 bool success;
2274 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2275 if (!success)
2276 return NULL;
2277 if (idx >= m_command_history.size())
2278 return NULL;
2279 return m_command_history[idx].c_str();
2280 }
2281}