blob: 923c3a8ffc4d9e1248ad631e605671464270baf3 [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));
Enrico Granata6b1596d2011-08-16 23:24:13 +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
Enrico Granata6b1596d2011-08-16 23:24:13 +0000460bool
461CommandInterpreter::AddUserCommand (const char *name,
462 const lldb::CommandObjectSP &cmd_sp,
463 bool can_replace)
464{
465 if (name && name[0])
466 {
467 std::string name_sstr(name);
468 if (!can_replace)
469 {
470 if (m_user_dict.find (name_sstr) != m_user_dict.end())
471 return false;
472 }
473 m_user_dict[name_sstr] = cmd_sp;
474 return true;
475 }
476 return false;
477}
Greg Claytond12aeab2011-04-20 16:37:46 +0000478
Jim Inghamd40f8a62010-07-06 22:46:59 +0000479CommandObjectSP
480CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000481{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000482 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
483 CommandObjectSP ret_val; // Possibly empty return value.
484
485 if (cmd_cstr == NULL)
486 return ret_val;
487
488 if (cmd_words.GetArgumentCount() == 1)
489 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
490 else
491 {
492 // We have a multi-word command (seemingly), so we need to do more work.
493 // First, get the cmd_obj_sp for the first word in the command.
494 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
495 if (cmd_obj_sp.get() != NULL)
496 {
497 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
498 // command name), and find the appropriate sub-command SP for each command word....
499 size_t end = cmd_words.GetArgumentCount();
500 for (size_t j= 1; j < end; ++j)
501 {
502 if (cmd_obj_sp->IsMultiwordObject())
503 {
504 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
505 (cmd_words.GetArgumentAtIndex (j));
506 if (cmd_obj_sp.get() == NULL)
507 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
508 return ret_val;
509 }
510 else
511 // We have more words in the command name, but we don't have a multiword object. Fail and return
512 // empty 'ret_val'.
513 return ret_val;
514 }
515 // We successfully looped through all the command words and got valid command objects for them. Assign the
516 // last object retrieved to 'ret_val'.
517 ret_val = cmd_obj_sp;
518 }
519 }
520 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000521}
522
523CommandObject *
524CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
525{
526 return GetCommandSPExact (cmd_cstr, include_aliases).get();
527}
528
529CommandObject *
530CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
531{
532 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
533
534 // If we didn't find an exact match to the command string in the commands, look in
535 // the aliases.
536
537 if (command_obj == NULL)
538 {
539 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
540 }
541
542 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
543 // in both the commands and the aliases.
544
545 if (command_obj == NULL)
546 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
547
548 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000549}
550
551bool
552CommandInterpreter::CommandExists (const char *cmd)
553{
554 return m_command_dict.find(cmd) != m_command_dict.end();
555}
556
557bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000558CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
559 const char *options_args,
560 OptionArgVectorSP &option_arg_vector_sp)
561{
562 bool success = true;
563 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
564
565 if (!options_args || (strlen (options_args) < 1))
566 return true;
567
568 std::string options_string (options_args);
569 Args args (options_args);
570 CommandReturnObject result;
571 // Check to see if the command being aliased can take any command options.
572 Options *options = cmd_obj_sp->GetOptions ();
573 if (options)
574 {
575 // See if any options were specified as part of the alias; if so, handle them appropriately.
576 options->NotifyOptionParsingStarting ();
577 args.Unshift ("dummy_arg");
578 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
579 args.Shift ();
580 if (result.Succeeded())
581 options->VerifyPartialOptions (result);
582 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
583 {
584 result.AppendError ("Unable to create requested alias.\n");
585 return false;
586 }
587 }
588
589 if (options_string.size() > 0)
590 {
591 if (cmd_obj_sp->WantsRawCommandString ())
592 option_arg_vector->push_back (OptionArgPair ("<argument>",
593 OptionArgValue (-1,
594 options_string)));
595 else
596 {
597 int argc = args.GetArgumentCount();
598 for (size_t i = 0; i < argc; ++i)
599 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
600 option_arg_vector->push_back
601 (OptionArgPair ("<argument>",
602 OptionArgValue (-1,
603 std::string (args.GetArgumentAtIndex (i)))));
604 }
605 }
606
607 return success;
608}
609
610bool
Chris Lattner24943d22010-06-08 16:52:24 +0000611CommandInterpreter::AliasExists (const char *cmd)
612{
613 return m_alias_dict.find(cmd) != m_alias_dict.end();
614}
615
616bool
617CommandInterpreter::UserCommandExists (const char *cmd)
618{
619 return m_user_dict.find(cmd) != m_user_dict.end();
620}
621
622void
623CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
624{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000625 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000626 m_alias_dict[alias_name] = command_obj_sp;
627}
628
629bool
630CommandInterpreter::RemoveAlias (const char *alias_name)
631{
632 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
633 if (pos != m_alias_dict.end())
634 {
635 m_alias_dict.erase(pos);
636 return true;
637 }
638 return false;
639}
640bool
641CommandInterpreter::RemoveUser (const char *alias_name)
642{
643 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
644 if (pos != m_user_dict.end())
645 {
646 m_user_dict.erase(pos);
647 return true;
648 }
649 return false;
650}
651
Chris Lattner24943d22010-06-08 16:52:24 +0000652void
653CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
654{
655 help_string.Printf ("'%s", command_name);
656 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
657
658 if (option_arg_vector_sp != NULL)
659 {
660 OptionArgVector *options = option_arg_vector_sp.get();
661 for (int i = 0; i < options->size(); ++i)
662 {
663 OptionArgPair cur_option = (*options)[i];
664 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000665 OptionArgValue value_pair = cur_option.second;
666 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000667 if (opt.compare("<argument>") == 0)
668 {
669 help_string.Printf (" %s", value.c_str());
670 }
671 else
672 {
673 help_string.Printf (" %s", opt.c_str());
674 if ((value.compare ("<no-argument>") != 0)
675 && (value.compare ("<need-argument") != 0))
676 {
677 help_string.Printf (" %s", value.c_str());
678 }
679 }
680 }
681 }
682
683 help_string.Printf ("'");
684}
685
Greg Clayton65124ea2010-08-26 22:05:43 +0000686size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000687CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
688{
689 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000690 CommandObject::CommandMap::const_iterator end = dict.end();
691 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000692
Greg Clayton65124ea2010-08-26 22:05:43 +0000693 for (pos = dict.begin(); pos != end; ++pos)
694 {
695 size_t len = pos->first.size();
696 if (max_len < len)
697 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000698 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000699 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000700}
701
702void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000703CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000704 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000705{
706 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000707 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000708
709 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000710 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000711
712 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
713 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000714
Enrico Granata6b1596d2011-08-16 23:24:13 +0000715 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
716 {
717 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
718 max_len);
719 }
720 result.AppendMessage("");
721
722 }
723
724 if (m_alias_dict.size() > 0 && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000725 {
Jim Inghame3663e82010-10-22 18:47:16 +0000726 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000727 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000728 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000729 max_len = FindLongestCommandWord (m_alias_dict);
730
Chris Lattner24943d22010-06-08 16:52:24 +0000731 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
732 {
733 StreamString sstr;
734 StreamString translation_and_help;
735 std::string entry_name = pos->first;
736 std::string second_entry = pos->second.get()->GetCommandName();
737 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
738
739 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
740 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
741 translation_and_help.GetData(), max_len);
742 }
743 result.AppendMessage("");
744 }
745
Enrico Granata6b1596d2011-08-16 23:24:13 +0000746 if (m_user_dict.size() > 0 && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000747 {
748 result.AppendMessage ("The following is a list of your current user-defined commands:");
749 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000750 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000751 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
752 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000753 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
754 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000755 }
756 result.AppendMessage("");
757 }
758
759 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
760}
761
Caroline Ticee0da7a52010-12-09 22:52:49 +0000762CommandObject *
763CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000764{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000765 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
766 // eventually be invoked by the given command line.
767
768 CommandObject *cmd_obj = NULL;
769 std::string white_space (" \t\v");
770 size_t start = command_string.find_first_not_of (white_space);
771 size_t end = 0;
772 bool done = false;
773 while (!done)
774 {
775 if (start != std::string::npos)
776 {
777 // Get the next word from command_string.
778 end = command_string.find_first_of (white_space, start);
779 if (end == std::string::npos)
780 end = command_string.size();
781 std::string cmd_word = command_string.substr (start, end - start);
782
783 if (cmd_obj == NULL)
784 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
785 // command or alias.
786 cmd_obj = GetCommandObject (cmd_word.c_str());
787 else if (cmd_obj->IsMultiwordObject ())
788 {
789 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
790 CommandObject *sub_cmd_obj =
791 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
792 if (sub_cmd_obj)
793 cmd_obj = sub_cmd_obj;
794 else // cmd_word was not a valid sub-command word, so we are donee
795 done = true;
796 }
797 else
798 // We have a cmd_obj and it is not a multi-word object, so we are done.
799 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000800
Caroline Ticee0da7a52010-12-09 22:52:49 +0000801 // If we didn't find a valid command object, or our command object is not a multi-word object, or
802 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
803 // next word.
804
805 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
806 done = true;
807 else
808 start = command_string.find_first_not_of (white_space, end);
809 }
810 else
811 // Unable to find any more words.
812 done = true;
813 }
814
815 if (end == command_string.size())
816 command_string.clear();
817 else
818 command_string = command_string.substr(end);
819
820 return cmd_obj;
821}
822
823bool
Caroline Tice649116c2011-05-11 16:07:06 +0000824CommandInterpreter::StripFirstWord (std::string &command_string, std::string &word, bool &was_quoted, char &quote_char)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000825{
826 std::string white_space (" \t\v");
827 size_t start;
828 size_t end;
829
830 start = command_string.find_first_not_of (white_space);
831 if (start != std::string::npos)
832 {
Caroline Tice649116c2011-05-11 16:07:06 +0000833 size_t len = command_string.size() - start;
834 if (len >= 2
835 && ((command_string[start] == '\'') || (command_string[start] == '"')))
Caroline Ticee0da7a52010-12-09 22:52:49 +0000836 {
Caroline Tice649116c2011-05-11 16:07:06 +0000837 was_quoted = true;
838 quote_char = command_string[start];
839 std::string quote_string = command_string.substr (start, 1);
840 start = start + 1;
841 end = command_string.find (quote_string, start);
842 if (end != std::string::npos)
843 {
844 word = command_string.substr (start, end - start);
845 if (end + 1 < len)
846 command_string = command_string.substr (end+1);
847 else
848 command_string.erase ();
849 size_t pos = command_string.find_first_not_of (white_space);
850 if ((pos != 0) && (pos != std::string::npos))
851 command_string = command_string.substr (pos);
852 }
853 else
854 {
855 word = command_string.substr (start - 1);
856 command_string.erase ();
857 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000858 }
859 else
860 {
Caroline Tice649116c2011-05-11 16:07:06 +0000861 end = command_string.find_first_of (white_space, start);
862 if (end != std::string::npos)
863 {
864 word = command_string.substr (start, end - start);
865 command_string = command_string.substr (end);
866 size_t pos = command_string.find_first_not_of (white_space);
867 if ((pos != 0) && (pos != std::string::npos))
868 command_string = command_string.substr (pos);
869 }
870 else
871 {
872 word = command_string.substr (start);
873 command_string.erase();
874 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000875 }
876
877 }
878 return true;
879}
880
881void
882CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result,
883 CommandObject *&alias_cmd_obj, CommandReturnObject &result)
884{
885 Args cmd_args (raw_input_string.c_str());
886 alias_cmd_obj = GetCommandObject (alias_name);
887 StreamString result_str;
888
889 if (alias_cmd_obj)
890 {
891 std::string alias_name_str = alias_name;
892 if ((cmd_args.GetArgumentCount() == 0)
893 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
894 cmd_args.Unshift (alias_name);
895
896 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
897 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
898
899 if (option_arg_vector_sp.get())
900 {
901 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
902
903 for (int i = 0; i < option_arg_vector->size(); ++i)
904 {
905 OptionArgPair option_pair = (*option_arg_vector)[i];
906 OptionArgValue value_pair = option_pair.second;
907 int value_type = value_pair.first;
908 std::string option = option_pair.first;
909 std::string value = value_pair.second;
910 if (option.compare ("<argument>") == 0)
911 result_str.Printf (" %s", value.c_str());
912 else
913 {
914 result_str.Printf (" %s", option.c_str());
915 if (value_type != optional_argument)
916 result_str.Printf (" ");
917 if (value.compare ("<no_argument>") != 0)
918 {
919 int index = GetOptionArgumentPosition (value.c_str());
920 if (index == 0)
921 result_str.Printf ("%s", value.c_str());
922 else if (index >= cmd_args.GetArgumentCount())
923 {
924
925 result.AppendErrorWithFormat
926 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
927 index);
928 result.SetStatus (eReturnStatusFailed);
929 return;
930 }
931 else
932 {
933 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
934 if (strpos != std::string::npos)
935 raw_input_string = raw_input_string.erase (strpos,
936 strlen (cmd_args.GetArgumentAtIndex (index)));
937 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
938 }
939 }
940 }
941 }
942 }
943
944 alias_result = result_str.GetData();
945 }
946}
947
948bool
949CommandInterpreter::HandleCommand (const char *command_line,
950 bool add_to_history,
951 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +0000952 ExecutionContext *override_context,
953 bool repeat_on_empty_command)
954
Caroline Ticee0da7a52010-12-09 22:52:49 +0000955{
Jim Ingham949d5ac2011-02-18 00:54:25 +0000956
Caroline Ticee0da7a52010-12-09 22:52:49 +0000957 bool done = false;
958 CommandObject *cmd_obj = NULL;
959 std::string next_word;
960 bool wants_raw_input = false;
961 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +0000962 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +0000963
964 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +0000965 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
966
967 // Make a scoped cleanup object that will clear the crash description string
968 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +0000969 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +0000970
Caroline Ticee0da7a52010-12-09 22:52:49 +0000971 if (log)
972 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +0000973
Jim Inghamabab14b2010-11-04 23:08:45 +0000974 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
975
Greg Claytonb72d0f02011-04-12 05:54:46 +0000976 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +0000977
Jim Ingham949d5ac2011-02-18 00:54:25 +0000978 bool empty_command = false;
979 bool comment_command = false;
980 if (command_string.empty())
981 empty_command = true;
982 else
Chris Lattner24943d22010-06-08 16:52:24 +0000983 {
Jim Ingham949d5ac2011-02-18 00:54:25 +0000984 const char *k_space_characters = "\t\n\v\f\r ";
985
986 size_t non_space = command_string.find_first_not_of (k_space_characters);
987 // Check for empty line or comment line (lines whose first
988 // non-space character is the comment character for this interpreter)
989 if (non_space == std::string::npos)
990 empty_command = true;
991 else if (command_string[non_space] == m_comment_char)
992 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +0000993 else if (command_string[non_space] == m_repeat_char)
994 {
995 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
996 if (history_string == NULL)
997 {
998 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
999 result.SetStatus(eReturnStatusFailed);
1000 return false;
1001 }
1002 add_to_history = false;
1003 command_string = history_string;
1004 original_command_string = history_string;
1005 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001006 }
1007
1008 if (empty_command)
1009 {
1010 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001011 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001012 if (m_command_history.empty())
1013 {
1014 result.AppendError ("empty command");
1015 result.SetStatus(eReturnStatusFailed);
1016 return false;
1017 }
1018 else
1019 {
1020 command_line = m_repeat_command.c_str();
1021 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001022 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001023 if (m_repeat_command.empty())
1024 {
1025 result.AppendErrorWithFormat("No auto repeat.\n");
1026 result.SetStatus (eReturnStatusFailed);
1027 return false;
1028 }
1029 }
1030 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001031 }
1032 else
1033 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001034 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1035 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001036 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001037 }
1038 else if (comment_command)
1039 {
1040 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1041 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001042 }
Caroline Tice649116c2011-05-11 16:07:06 +00001043
Caroline Ticee0da7a52010-12-09 22:52:49 +00001044 // Phase 1.
1045
1046 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1047 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1048 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1049 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1050 // 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 +00001051 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001052 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001053
Caroline Ticee0da7a52010-12-09 22:52:49 +00001054 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001055 size_t actual_cmd_name_len = 0;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001056 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001057 {
Caroline Tice649116c2011-05-11 16:07:06 +00001058 bool was_quoted = false;
1059 char quote_char = '\0';
1060 StripFirstWord (command_string, next_word, was_quoted, quote_char);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001061 if (!cmd_obj && AliasExists (next_word.c_str()))
Chris Lattner24943d22010-06-08 16:52:24 +00001062 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001063 std::string alias_result;
1064 BuildAliasResult (next_word.c_str(), command_string, alias_result, cmd_obj, result);
1065 revised_command_line.Printf ("%s", alias_result.c_str());
1066 if (cmd_obj)
Caroline Tice56d2fc42010-12-14 18:51:39 +00001067 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001068 wants_raw_input = cmd_obj->WantsRawCommandString ();
Caroline Tice56d2fc42010-12-14 18:51:39 +00001069 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1070 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001071 }
1072 else if (!cmd_obj)
1073 {
1074 cmd_obj = GetCommandObject (next_word.c_str());
1075 if (cmd_obj)
Chris Lattner24943d22010-06-08 16:52:24 +00001076 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001077 actual_cmd_name_len += next_word.length();
Caroline Ticee0da7a52010-12-09 22:52:49 +00001078 revised_command_line.Printf ("%s", next_word.c_str());
1079 wants_raw_input = cmd_obj->WantsRawCommandString ();
Chris Lattner24943d22010-06-08 16:52:24 +00001080 }
1081 else
1082 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001083 revised_command_line.Printf ("%s", next_word.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001084 }
1085 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001086 else if (cmd_obj->IsMultiwordObject ())
1087 {
1088 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1089 if (sub_cmd_obj)
1090 {
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001091 actual_cmd_name_len += next_word.length() + 1;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001092 revised_command_line.Printf (" %s", next_word.c_str());
1093 cmd_obj = sub_cmd_obj;
1094 wants_raw_input = cmd_obj->WantsRawCommandString ();
1095 }
1096 else
1097 {
Caroline Tice649116c2011-05-11 16:07:06 +00001098 if (was_quoted)
1099 {
1100 if (quote_char == '"')
1101 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1102 else
1103 revised_command_line.Printf (" '%s'", next_word.c_str());
1104 }
1105 else
1106 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001107 done = true;
1108 }
1109 }
1110 else
1111 {
Caroline Tice649116c2011-05-11 16:07:06 +00001112 if (was_quoted)
1113 {
1114 if (quote_char == '"')
1115 revised_command_line.Printf (" \"%s\"", next_word.c_str());
1116 else
1117 revised_command_line.Printf (" '%s'", next_word.c_str());
1118 }
1119 else
1120 revised_command_line.Printf (" %s", next_word.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001121 done = true;
1122 }
1123
1124 if (cmd_obj == NULL)
1125 {
1126 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1127 result.SetStatus (eReturnStatusFailed);
1128 return false;
1129 }
1130
1131 next_word.erase ();
1132 if (command_string.length() == 0)
1133 done = true;
1134
Chris Lattner24943d22010-06-08 16:52:24 +00001135 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001136
1137 if (command_string.size() > 0)
1138 revised_command_line.Printf (" %s", command_string.c_str());
1139
1140 // End of Phase 1.
1141 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1142 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1143 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1144 // wants_raw_input specifies whether the Execute method expects raw input or not.
1145
1146
1147 if (log)
1148 {
1149 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1150 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1151 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1152 }
1153
1154 // Phase 2.
1155 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1156 // CommandObject, with the appropriate arguments.
1157
1158 if (cmd_obj != NULL)
1159 {
1160 if (add_to_history)
1161 {
1162 Args command_args (revised_command_line.GetData());
1163 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1164 if (repeat_command != NULL)
1165 m_repeat_command.assign(repeat_command);
1166 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001167 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001168
Jim Ingham6247dbe2011-07-12 03:12:18 +00001169 // Don't keep pushing the same command onto the history...
1170 if (m_command_history.size() == 0 || m_command_history.back() != original_command_string)
1171 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001172 }
1173
1174 command_string = revised_command_line.GetData();
1175 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001176 std::string remainder;
1177 if (actual_cmd_name_len < command_string.length())
1178 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1179 // than cmd_obj->GetCommandName(), because name completion
1180 // allows users to enter short versions of the names,
1181 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001182
1183 // Remove any initial spaces
1184 std::string white_space (" \t\v");
1185 size_t pos = remainder.find_first_not_of (white_space);
1186 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001187 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001188
1189 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001190 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001191
1192
1193 if (wants_raw_input)
1194 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1195 else
1196 {
1197 Args cmd_args (remainder.c_str());
1198 cmd_obj->ExecuteWithOptions (cmd_args, result);
1199 }
1200 }
1201 else
1202 {
1203 // We didn't find the first command object, so complete the first argument.
1204 Args command_args (revised_command_line.GetData());
1205 StringList matches;
1206 int num_matches;
1207 int cursor_index = 0;
1208 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1209 bool word_complete;
1210 num_matches = HandleCompletionMatches (command_args,
1211 cursor_index,
1212 cursor_char_position,
1213 0,
1214 -1,
1215 word_complete,
1216 matches);
1217
1218 if (num_matches > 0)
1219 {
1220 std::string error_msg;
1221 error_msg.assign ("ambiguous command '");
1222 error_msg.append(command_args.GetArgumentAtIndex(0));
1223 error_msg.append ("'.");
1224
1225 error_msg.append (" Possible completions:");
1226 for (int i = 0; i < num_matches; i++)
1227 {
1228 error_msg.append ("\n\t");
1229 error_msg.append (matches.GetStringAtIndex (i));
1230 }
1231 error_msg.append ("\n");
1232 result.AppendRawError (error_msg.c_str(), error_msg.size());
1233 }
1234 else
1235 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1236
1237 result.SetStatus (eReturnStatusFailed);
1238 }
1239
Jason Molenda24c991c2011-08-25 00:20:04 +00001240 if (log)
1241 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1242
Chris Lattner24943d22010-06-08 16:52:24 +00001243 return result.Succeeded();
1244}
1245
1246int
1247CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1248 int &cursor_index,
1249 int &cursor_char_position,
1250 int match_start_point,
1251 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001252 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001253 StringList &matches)
1254{
1255 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001256 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001257
1258 // For any of the command completions a unique match will be a complete word.
1259 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001260
1261 if (cursor_index == -1)
1262 {
1263 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001264 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001265 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1266 }
1267 else if (cursor_index == 0)
1268 {
1269 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001270 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001271 num_command_matches = matches.GetSize();
1272
1273 if (num_command_matches == 1
1274 && cmd_obj && cmd_obj->IsMultiwordObject()
1275 && matches.GetStringAtIndex(0) != NULL
1276 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1277 {
1278 look_for_subcommand = true;
1279 num_command_matches = 0;
1280 matches.DeleteStringAtIndex(0);
1281 parsed_line.AppendArgument ("");
1282 cursor_index++;
1283 cursor_char_position = 0;
1284 }
1285 }
1286
1287 if (cursor_index > 0 || look_for_subcommand)
1288 {
1289 // We are completing further on into a commands arguments, so find the command and tell it
1290 // to complete the command.
1291 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001292 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001293 if (command_object == NULL)
1294 {
1295 return 0;
1296 }
1297 else
1298 {
1299 parsed_line.Shift();
1300 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001301 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001302 cursor_index,
1303 cursor_char_position,
1304 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001305 max_return_elements,
1306 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001307 matches);
1308 }
1309 }
1310
1311 return num_command_matches;
1312
1313}
1314
1315int
1316CommandInterpreter::HandleCompletion (const char *current_line,
1317 const char *cursor,
1318 const char *last_char,
1319 int match_start_point,
1320 int max_return_elements,
1321 StringList &matches)
1322{
1323 // We parse the argument up to the cursor, so the last argument in parsed_line is
1324 // the one containing the cursor, and the cursor is after the last character.
1325
1326 Args parsed_line(current_line, last_char - current_line);
1327 Args partial_parsed_line(current_line, cursor - current_line);
1328
Jim Ingham6247dbe2011-07-12 03:12:18 +00001329 // Don't complete comments, and if the line we are completing is just the history repeat character,
1330 // substitute the appropriate history line.
1331 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1332 if (first_arg)
1333 {
1334 if (first_arg[0] == m_comment_char)
1335 return 0;
1336 else if (first_arg[0] == m_repeat_char)
1337 {
1338 const char *history_string = FindHistoryString (first_arg);
1339 if (history_string != NULL)
1340 {
1341 matches.Clear();
1342 matches.InsertStringAtIndex(0, history_string);
1343 return -2;
1344 }
1345 else
1346 return 0;
1347
1348 }
1349 }
1350
1351
Chris Lattner24943d22010-06-08 16:52:24 +00001352 int num_args = partial_parsed_line.GetArgumentCount();
1353 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1354 int cursor_char_position;
1355
1356 if (cursor_index == -1)
1357 cursor_char_position = 0;
1358 else
1359 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001360
1361 if (cursor > current_line && cursor[-1] == ' ')
1362 {
1363 // We are just after a space. If we are in an argument, then we will continue
1364 // parsing, but if we are between arguments, then we have to complete whatever the next
1365 // element would be.
1366 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1367 // protected by a quote) then the space will also be in the parsed argument...
1368
1369 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1370 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1371 {
1372 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1373 cursor_index++;
1374 cursor_char_position = 0;
1375 }
1376 }
Chris Lattner24943d22010-06-08 16:52:24 +00001377
1378 int num_command_matches;
1379
1380 matches.Clear();
1381
1382 // Only max_return_elements == -1 is supported at present:
1383 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001384 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001385 num_command_matches = HandleCompletionMatches (parsed_line,
1386 cursor_index,
1387 cursor_char_position,
1388 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001389 max_return_elements,
1390 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001391 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001392
1393 if (num_command_matches <= 0)
1394 return num_command_matches;
1395
1396 if (num_args == 0)
1397 {
1398 // If we got an empty string, insert nothing.
1399 matches.InsertStringAtIndex(0, "");
1400 }
1401 else
1402 {
1403 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1404 // put an empty string in element 0.
1405 std::string command_partial_str;
1406 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001407 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1408 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001409
1410 std::string common_prefix;
1411 matches.LongestCommonPrefix (common_prefix);
1412 int partial_name_len = command_partial_str.size();
1413
1414 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001415 // Only do this if the completer told us this was a complete word, however...
1416 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001417 {
1418 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1419 if (quote_char != '\0')
1420 common_prefix.push_back(quote_char);
1421
1422 common_prefix.push_back(' ');
1423 }
1424 common_prefix.erase (0, partial_name_len);
1425 matches.InsertStringAtIndex(0, common_prefix.c_str());
1426 }
1427 return num_command_matches;
1428}
1429
Chris Lattner24943d22010-06-08 16:52:24 +00001430
1431CommandInterpreter::~CommandInterpreter ()
1432{
1433}
1434
1435const char *
1436CommandInterpreter::GetPrompt ()
1437{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001438 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001439}
1440
1441void
1442CommandInterpreter::SetPrompt (const char *new_prompt)
1443{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001444 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001445}
1446
Jim Ingham5e16ef52010-10-04 19:49:29 +00001447size_t
Greg Clayton58928562011-02-09 01:08:52 +00001448CommandInterpreter::GetConfirmationInputReaderCallback
1449(
1450 void *baton,
1451 InputReader &reader,
1452 lldb::InputReaderAction action,
1453 const char *bytes,
1454 size_t bytes_len
1455)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001456{
Greg Clayton58928562011-02-09 01:08:52 +00001457 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001458 bool *response_ptr = (bool *) baton;
1459
1460 switch (action)
1461 {
1462 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001463 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001464 {
1465 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001466 {
Greg Clayton58928562011-02-09 01:08:52 +00001467 out_file.Printf ("%s", reader.GetPrompt());
1468 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001469 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001470 }
1471 break;
1472
1473 case eInputReaderDeactivate:
1474 break;
1475
1476 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001477 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001478 {
Greg Clayton58928562011-02-09 01:08:52 +00001479 out_file.Printf ("%s", reader.GetPrompt());
1480 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001481 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001482 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001483
1484 case eInputReaderAsynchronousOutputWritten:
1485 break;
1486
Jim Ingham5e16ef52010-10-04 19:49:29 +00001487 case eInputReaderGotToken:
1488 if (bytes_len == 0)
1489 {
1490 reader.SetIsDone(true);
1491 }
1492 else if (bytes[0] == 'y')
1493 {
1494 *response_ptr = true;
1495 reader.SetIsDone(true);
1496 }
1497 else if (bytes[0] == 'n')
1498 {
1499 *response_ptr = false;
1500 reader.SetIsDone(true);
1501 }
1502 else
1503 {
Greg Clayton58928562011-02-09 01:08:52 +00001504 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001505 {
Greg Clayton58928562011-02-09 01:08:52 +00001506 out_file.Printf ("Please answer \"y\" or \"n\"\n%s", reader.GetPrompt());
1507 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001508 }
1509 }
1510 break;
1511
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001512 case eInputReaderInterrupt:
1513 case eInputReaderEndOfFile:
1514 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1515 reader.SetIsDone (true);
1516 break;
1517
Jim Ingham5e16ef52010-10-04 19:49:29 +00001518 case eInputReaderDone:
1519 break;
1520 }
1521
1522 return bytes_len;
1523
1524}
1525
1526bool
1527CommandInterpreter::Confirm (const char *message, bool default_answer)
1528{
Jim Ingham93057472010-10-04 22:44:14 +00001529 // Check AutoConfirm first:
1530 if (m_debugger.GetAutoConfirm())
1531 return default_answer;
1532
Jim Ingham5e16ef52010-10-04 19:49:29 +00001533 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1534 bool response = default_answer;
1535 if (reader_sp)
1536 {
1537 std::string prompt(message);
1538 prompt.append(": [");
1539 if (default_answer)
1540 prompt.append ("Y/n] ");
1541 else
1542 prompt.append ("y/N] ");
1543
1544 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1545 &response, // baton
1546 eInputReaderGranularityLine, // token size, to pass to callback function
1547 NULL, // end token
1548 prompt.c_str(), // prompt
1549 true)); // echo input
1550 if (err.Success())
1551 {
1552 GetDebugger().PushInputReader (reader_sp);
1553 }
1554 reader_sp->WaitOnReaderIsDone();
1555 }
1556 return response;
1557}
1558
1559
Chris Lattner24943d22010-06-08 16:52:24 +00001560void
1561CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1562{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001563 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001564
1565 if (cmd_obj_sp != NULL)
1566 {
1567 CommandObject *cmd_obj = cmd_obj_sp.get();
1568 if (cmd_obj->IsCrossRefObject ())
1569 cmd_obj->AddObject (object_type);
1570 }
1571}
1572
Chris Lattner24943d22010-06-08 16:52:24 +00001573OptionArgVectorSP
1574CommandInterpreter::GetAliasOptions (const char *alias_name)
1575{
1576 OptionArgMap::iterator pos;
1577 OptionArgVectorSP ret_val;
1578
1579 std::string alias (alias_name);
1580
1581 if (HasAliasOptions())
1582 {
1583 pos = m_alias_options.find (alias);
1584 if (pos != m_alias_options.end())
1585 ret_val = pos->second;
1586 }
1587
1588 return ret_val;
1589}
1590
1591void
1592CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1593{
1594 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1595 if (pos != m_alias_options.end())
1596 {
1597 m_alias_options.erase (pos);
1598 }
1599}
1600
1601void
1602CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1603{
1604 m_alias_options[alias_name] = option_arg_vector_sp;
1605}
1606
1607bool
1608CommandInterpreter::HasCommands ()
1609{
1610 return (!m_command_dict.empty());
1611}
1612
1613bool
1614CommandInterpreter::HasAliases ()
1615{
1616 return (!m_alias_dict.empty());
1617}
1618
1619bool
1620CommandInterpreter::HasUserCommands ()
1621{
1622 return (!m_user_dict.empty());
1623}
1624
1625bool
1626CommandInterpreter::HasAliasOptions ()
1627{
1628 return (!m_alias_options.empty());
1629}
1630
Chris Lattner24943d22010-06-08 16:52:24 +00001631void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001632CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1633 const char *alias_name,
1634 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001635 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001636 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001637{
1638 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001639
1640 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001641
Caroline Tice44c841d2010-12-07 19:58:26 +00001642 // Make sure that the alias name is the 0th element in cmd_args
1643 std::string alias_name_str = alias_name;
1644 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1645 cmd_args.Unshift (alias_name);
1646
1647 Args new_args (alias_cmd_obj->GetCommandName());
1648 if (new_args.GetArgumentCount() == 2)
1649 new_args.Shift();
1650
Chris Lattner24943d22010-06-08 16:52:24 +00001651 if (option_arg_vector_sp.get())
1652 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001653 if (wants_raw_input)
1654 {
1655 // We have a command that both has command options and takes raw input. Make *sure* it has a
1656 // " -- " in the right place in the raw_input_string.
1657 size_t pos = raw_input_string.find(" -- ");
1658 if (pos == std::string::npos)
1659 {
1660 // None found; assume it goes at the beginning of the raw input string
1661 raw_input_string.insert (0, " -- ");
1662 }
1663 }
Chris Lattner24943d22010-06-08 16:52:24 +00001664
1665 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1666 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001667 std::vector<bool> used (old_size + 1, false);
1668
1669 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001670
1671 for (int i = 0; i < option_arg_vector->size(); ++i)
1672 {
1673 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001674 OptionArgValue value_pair = option_pair.second;
1675 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001676 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001677 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001678 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001679 {
1680 if (!wants_raw_input
1681 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1682 new_args.AppendArgument (value.c_str());
1683 }
Chris Lattner24943d22010-06-08 16:52:24 +00001684 else
1685 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001686 if (value_type != optional_argument)
1687 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001688 if (value.compare ("<no-argument>") != 0)
1689 {
1690 int index = GetOptionArgumentPosition (value.c_str());
1691 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001692 {
Chris Lattner24943d22010-06-08 16:52:24 +00001693 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00001694 if (value_type != optional_argument)
1695 new_args.AppendArgument (value.c_str());
1696 else
1697 {
1698 char buffer[255];
1699 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
1700 new_args.AppendArgument (buffer);
1701 }
1702
1703 }
Chris Lattner24943d22010-06-08 16:52:24 +00001704 else if (index >= cmd_args.GetArgumentCount())
1705 {
1706 result.AppendErrorWithFormat
1707 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1708 index);
1709 result.SetStatus (eReturnStatusFailed);
1710 return;
1711 }
1712 else
1713 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001714 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
1715 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1716 if (strpos != std::string::npos)
1717 {
1718 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
1719 }
1720
1721 if (value_type != optional_argument)
1722 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
1723 else
1724 {
1725 char buffer[255];
1726 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
1727 cmd_args.GetArgumentAtIndex (index));
1728 new_args.AppendArgument (buffer);
1729 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001730 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001731 }
1732 }
1733 }
1734 }
1735
1736 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
1737 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001738 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00001739 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
1740 }
1741
1742 cmd_args.Clear();
1743 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1744 }
1745 else
1746 {
1747 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00001748 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
1749 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
1750 // input string.
1751 if (wants_raw_input)
1752 {
1753 cmd_args.Clear();
1754 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
1755 }
Chris Lattner24943d22010-06-08 16:52:24 +00001756 return;
1757 }
1758
1759 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1760 return;
1761}
1762
1763
1764int
1765CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
1766{
1767 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
1768 // of zero.
1769
1770 char *cptr = (char *) in_string;
1771
1772 // Does it start with '%'
1773 if (cptr[0] == '%')
1774 {
1775 ++cptr;
1776
1777 // Is the rest of it entirely digits?
1778 if (isdigit (cptr[0]))
1779 {
1780 const char *start = cptr;
1781 while (isdigit (cptr[0]))
1782 ++cptr;
1783
1784 // We've gotten to the end of the digits; are we at the end of the string?
1785 if (cptr[0] == '\0')
1786 position = atoi (start);
1787 }
1788 }
1789
1790 return position;
1791}
1792
1793void
1794CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
1795{
Greg Clayton887aa282010-10-11 01:05:37 +00001796 // Don't parse any .lldbinit files if we were asked not to
Jim Ingham574c3d62011-08-12 23:34:31 +00001797 if (m_skip_lldbinit_files && m_skip_app_init_files)
Greg Clayton887aa282010-10-11 01:05:37 +00001798 return;
1799
Chris Lattner24943d22010-06-08 16:52:24 +00001800 const char *init_file_path = in_cwd ? "./.lldbinit" : "~/.lldbinit";
Jim Ingham574c3d62011-08-12 23:34:31 +00001801
1802 std::string app_specific_init;
1803
1804 if (!m_skip_app_init_files)
1805 {
1806 FileSpec host_spec = Host::GetProgramFileSpec();
1807 const char *host_name = host_spec.GetFilename().AsCString();
1808
1809 if (host_name != NULL && strcmp (host_name, "lldb") != 0)
1810 {
1811 app_specific_init += init_file_path;
1812 app_specific_init += "-";
1813 app_specific_init += host_name;
1814 }
1815 }
1816
1817 FileSpec init_file;
1818 if (!app_specific_init.empty())
1819 {
1820 init_file.SetFile (app_specific_init.c_str(), true);
1821 }
1822
1823 if (!m_skip_lldbinit_files && !init_file.Exists())
1824 {
1825 init_file.SetFile (init_file_path, true);
1826 }
1827
Chris Lattner24943d22010-06-08 16:52:24 +00001828 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
1829 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
1830
1831 if (init_file.Exists())
1832 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001833 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
1834 bool stop_on_continue = true;
1835 bool stop_on_error = false;
1836 bool echo_commands = false;
1837 bool print_results = false;
1838
1839 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00001840 }
1841 else
1842 {
1843 // nothing to be done if the file doesn't exist
1844 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1845 }
1846}
1847
Greg Claytonb72d0f02011-04-12 05:54:46 +00001848PlatformSP
1849CommandInterpreter::GetPlatform (bool prefer_target_platform)
1850{
1851 PlatformSP platform_sp;
1852 if (prefer_target_platform && m_exe_ctx.target)
1853 platform_sp = m_exe_ctx.target->GetPlatform();
1854
1855 if (!platform_sp)
1856 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
1857 return platform_sp;
1858}
1859
Jim Ingham949d5ac2011-02-18 00:54:25 +00001860void
Jim Inghama4fede32011-03-11 01:51:49 +00001861CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001862 ExecutionContext *override_context,
1863 bool stop_on_continue,
1864 bool stop_on_error,
1865 bool echo_commands,
1866 bool print_results,
1867 CommandReturnObject &result)
1868{
1869 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00001870
1871 // If we are going to continue past a "continue" then we need to run the commands synchronously.
1872 // Make sure you reset this value anywhere you return from the function.
1873
1874 bool old_async_execution = m_debugger.GetAsyncExecution();
1875
1876 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
1877 // cause series of commands that change the context, then do an operation that relies on that context to fail.
1878
1879 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00001880 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00001881
1882 if (!stop_on_continue)
1883 {
1884 m_debugger.SetAsyncExecution (false);
1885 }
1886
1887 for (int idx = 0; idx < num_lines; idx++)
1888 {
1889 const char *cmd = commands.GetStringAtIndex(idx);
1890 if (cmd[0] == '\0')
1891 continue;
1892
Jim Ingham949d5ac2011-02-18 00:54:25 +00001893 if (echo_commands)
1894 {
1895 result.AppendMessageWithFormat ("%s %s\n",
1896 GetPrompt(),
1897 cmd);
1898 }
1899
Greg Claytonaa378b12011-02-20 02:15:07 +00001900 CommandReturnObject tmp_result;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001901 bool success = HandleCommand(cmd, false, tmp_result, NULL);
1902
1903 if (print_results)
1904 {
1905 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001906 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001907 }
1908
1909 if (!success || !tmp_result.Succeeded())
1910 {
1911 if (stop_on_error)
1912 {
1913 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
1914 idx, cmd);
1915 result.SetStatus (eReturnStatusFailed);
1916 m_debugger.SetAsyncExecution (old_async_execution);
1917 return;
1918 }
1919 else if (print_results)
1920 {
1921 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
1922 idx + 1,
1923 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00001924 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00001925 }
1926 }
1927
Caroline Tice4a348082011-05-02 20:41:46 +00001928 if (result.GetImmediateOutputStream())
1929 result.GetImmediateOutputStream()->Flush();
1930
1931 if (result.GetImmediateErrorStream())
1932 result.GetImmediateErrorStream()->Flush();
1933
Jim Ingham949d5ac2011-02-18 00:54:25 +00001934 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
1935 // could be running (for instance in Breakpoint Commands.
1936 // So we check the return value to see if it is has running in it.
1937 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
1938 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
1939 {
1940 if (stop_on_continue)
1941 {
1942 // If we caused the target to proceed, and we're going to stop in that case, set the
1943 // status in our real result before returning. This is an error if the continue was not the
1944 // last command in the set of commands to be run.
1945 if (idx != num_lines - 1)
1946 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
1947 idx + 1, cmd);
1948 else
1949 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
1950
1951 result.SetStatus(tmp_result.GetStatus());
1952 m_debugger.SetAsyncExecution (old_async_execution);
1953
1954 return;
1955 }
1956 }
1957
1958 }
1959
1960 result.SetStatus (eReturnStatusSuccessFinishResult);
1961 m_debugger.SetAsyncExecution (old_async_execution);
1962
1963 return;
1964}
1965
1966void
1967CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
1968 ExecutionContext *context,
1969 bool stop_on_continue,
1970 bool stop_on_error,
1971 bool echo_command,
1972 bool print_result,
1973 CommandReturnObject &result)
1974{
1975 if (cmd_file.Exists())
1976 {
1977 bool success;
1978 StringList commands;
1979 success = commands.ReadFileLines(cmd_file);
1980 if (!success)
1981 {
1982 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
1983 result.SetStatus (eReturnStatusFailed);
1984 return;
1985 }
1986 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
1987 }
1988 else
1989 {
1990 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
1991 cmd_file.GetFilename().AsCString());
1992 result.SetStatus (eReturnStatusFailed);
1993 return;
1994 }
1995}
1996
Chris Lattner24943d22010-06-08 16:52:24 +00001997ScriptInterpreter *
1998CommandInterpreter::GetScriptInterpreter ()
1999{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002000 if (m_script_interpreter_ap.get() != NULL)
2001 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002002
Caroline Tice0aa2e552011-01-14 00:29:16 +00002003 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2004 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002005 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00002006 case eScriptLanguageNone:
2007 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2008 break;
2009 case eScriptLanguagePython:
2010 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2011 break;
2012 default:
2013 break;
2014 };
2015
2016 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002017}
2018
2019
2020
2021bool
2022CommandInterpreter::GetSynchronous ()
2023{
2024 return m_synchronous_execution;
2025}
2026
2027void
2028CommandInterpreter::SetSynchronous (bool value)
2029{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002030 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002031}
2032
2033void
2034CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2035 const char *word_text,
2036 const char *separator,
2037 const char *help_text,
2038 uint32_t max_word_len)
2039{
Greg Clayton238c0a12010-09-18 01:14:36 +00002040 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2041
Chris Lattner24943d22010-06-08 16:52:24 +00002042 int indent_size = max_word_len + strlen (separator) + 2;
2043
2044 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002045
2046 StreamString text_strm;
2047 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2048
2049 size_t len = text_strm.GetSize();
2050 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002051 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002052 {
2053 text_strm.EOL();
2054 len = text_strm.GetSize();
2055 }
Chris Lattner24943d22010-06-08 16:52:24 +00002056
2057 if (len < max_columns)
2058 {
2059 // Output it as a single line.
2060 strm.Printf ("%s", text);
2061 }
2062 else
2063 {
2064 // We need to break it up into multiple lines.
2065 bool first_line = true;
2066 int text_width;
2067 int start = 0;
2068 int end = start;
2069 int final_end = strlen (text);
2070 int sub_len;
2071
2072 while (end < final_end)
2073 {
2074 if (first_line)
2075 text_width = max_columns - 1;
2076 else
2077 text_width = max_columns - indent_size - 1;
2078
2079 // Don't start the 'text' on a space, since we're already outputting the indentation.
2080 if (!first_line)
2081 {
2082 while ((start < final_end) && (text[start] == ' '))
2083 start++;
2084 }
2085
2086 end = start + text_width;
2087 if (end > final_end)
2088 end = final_end;
2089 else
2090 {
2091 // If we're not at the end of the text, make sure we break the line on white space.
2092 while (end > start
2093 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2094 end--;
2095 }
2096
2097 sub_len = end - start;
2098 if (start != 0)
2099 strm.EOL();
2100 if (!first_line)
2101 strm.Indent();
2102 else
2103 first_line = false;
2104 assert (start <= final_end);
2105 assert (start + sub_len <= final_end);
2106 if (sub_len > 0)
2107 strm.Write (text + start, sub_len);
2108 start = end + 1;
2109 }
2110 }
2111 strm.EOL();
2112 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002113}
2114
2115void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002116CommandInterpreter::OutputHelpText (Stream &strm,
2117 const char *word_text,
2118 const char *separator,
2119 const char *help_text,
2120 uint32_t max_word_len)
2121{
2122 int indent_size = max_word_len + strlen (separator) + 2;
2123
2124 strm.IndentMore (indent_size);
2125
2126 StreamString text_strm;
2127 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2128
2129 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2130 bool first_line = true;
2131
2132 size_t len = text_strm.GetSize();
2133 const char *text = text_strm.GetData();
2134
2135 uint32_t chars_left = max_columns;
2136
2137 for (uint32_t i = 0; i < len; i++)
2138 {
2139 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2140 {
2141 first_line = false;
2142 chars_left = max_columns - indent_size;
2143 strm.EOL();
2144 strm.Indent();
2145 }
2146 else
2147 {
2148 strm.PutChar(text[i]);
2149 chars_left--;
2150 }
2151
2152 }
2153
2154 strm.EOL();
2155 strm.IndentLess(indent_size);
2156}
2157
2158void
Chris Lattner24943d22010-06-08 16:52:24 +00002159CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2160 StringList &commands_found, StringList &commands_help)
2161{
2162 CommandObject::CommandMap::const_iterator pos;
2163 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2164 CommandObject *sub_cmd_obj;
2165
2166 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2167 {
2168 const char * command_name = pos->first.c_str();
2169 sub_cmd_obj = pos->second.get();
2170 StreamString complete_command_name;
2171
2172 complete_command_name.Printf ("%s %s", prefix, command_name);
2173
Greg Clayton238c0a12010-09-18 01:14:36 +00002174 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002175 {
2176 commands_found.AppendString (complete_command_name.GetData());
2177 commands_help.AppendString (sub_cmd_obj->GetHelp());
2178 }
2179
2180 if (sub_cmd_obj->IsMultiwordObject())
2181 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2182 commands_help);
2183 }
2184
2185}
2186
2187void
2188CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2189 StringList &commands_help)
2190{
2191 CommandObject::CommandMap::const_iterator pos;
2192
2193 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2194 {
2195 const char *command_name = pos->first.c_str();
2196 CommandObject *cmd_obj = pos->second.get();
2197
Greg Clayton238c0a12010-09-18 01:14:36 +00002198 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002199 {
2200 commands_found.AppendString (command_name);
2201 commands_help.AppendString (cmd_obj->GetHelp());
2202 }
2203
2204 if (cmd_obj->IsMultiwordObject())
2205 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2206
2207 }
2208}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002209
2210
2211void
2212CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2213{
2214 m_exe_ctx.Clear();
2215
2216 if (override_context != NULL)
2217 {
2218 m_exe_ctx.target = override_context->target;
2219 m_exe_ctx.process = override_context->process;
2220 m_exe_ctx.thread = override_context->thread;
2221 m_exe_ctx.frame = override_context->frame;
2222 }
2223 else
2224 {
2225 TargetSP target_sp (m_debugger.GetSelectedTarget());
2226 if (target_sp)
2227 {
2228 m_exe_ctx.target = target_sp.get();
2229 m_exe_ctx.process = target_sp->GetProcessSP().get();
2230 if (m_exe_ctx.process && m_exe_ctx.process->IsAlive() && !m_exe_ctx.process->IsRunning())
2231 {
2232 m_exe_ctx.thread = m_exe_ctx.process->GetThreadList().GetSelectedThread().get();
Greg Claytonb72d0f02011-04-12 05:54:46 +00002233 if (m_exe_ctx.thread)
2234 {
2235 m_exe_ctx.frame = m_exe_ctx.thread->GetSelectedFrame().get();
2236 if (m_exe_ctx.frame == NULL)
2237 {
2238 m_exe_ctx.frame = m_exe_ctx.thread->GetStackFrameAtIndex (0).get();
2239 // If we didn't have a selected frame select one here.
2240 if (m_exe_ctx.frame != NULL)
2241 m_exe_ctx.thread->SetSelectedFrame(m_exe_ctx.frame);
2242 }
2243 }
2244 }
2245 }
2246 }
2247}
2248
Jim Ingham6247dbe2011-07-12 03:12:18 +00002249void
2250CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2251{
2252 DumpHistory (stream, 0, count - 1);
2253}
2254
2255void
2256CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2257{
2258 size_t num_history_elements = m_command_history.size();
2259 if (start > num_history_elements)
2260 return;
2261 for (uint32_t i = start; i < num_history_elements && i <= end; i++)
2262 {
2263 if (!m_command_history[i].empty())
2264 {
2265 stream.Indent();
2266 stream.Printf ("%4d: %s\n", i, m_command_history[i].c_str());
2267 }
2268 }
2269}
2270
2271const char *
2272CommandInterpreter::FindHistoryString (const char *input_str) const
2273{
2274 if (input_str[0] != m_repeat_char)
2275 return NULL;
2276 if (input_str[1] == '-')
2277 {
2278 bool success;
2279 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2280 if (!success)
2281 return NULL;
2282 if (idx > m_command_history.size())
2283 return NULL;
2284 idx = m_command_history.size() - idx;
2285 return m_command_history[idx].c_str();
2286
2287 }
2288 else if (input_str[1] == m_repeat_char)
2289 {
2290 if (m_command_history.empty())
2291 return NULL;
2292 else
2293 return m_command_history.back().c_str();
2294 }
2295 else
2296 {
2297 bool success;
2298 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2299 if (!success)
2300 return NULL;
2301 if (idx >= m_command_history.size())
2302 return NULL;
2303 return m_command_history[idx].c_str();
2304 }
2305}