blob: bce32beb6f1383881375571144bb7ceccaa9fb8e [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include <string>
Caroline Ticebd5c63e2010-10-12 21:57:09 +000011#include <vector>
Chris Lattner24943d22010-06-08 16:52:24 +000012
13#include <getopt.h>
14#include <stdlib.h>
15
Greg Clayton5c28dd12011-06-23 17:59:56 +000016#include "CommandObjectScript.h"
Peter Collingbourne921fac02011-06-23 20:37:26 +000017#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000018
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectApropos.h"
20#include "../Commands/CommandObjectArgs.h"
21#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
25#include "../Commands/CommandObjectHelp.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectLog.h"
27#include "../Commands/CommandObjectMemory.h"
Greg Claytonb1888f22011-03-19 01:12:21 +000028#include "../Commands/CommandObjectPlatform.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000029#include "../Commands/CommandObjectProcess.h"
30#include "../Commands/CommandObjectQuit.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectRegister.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectSettings.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSource.h"
Jim Ingham767af882010-07-07 03:36:20 +000034#include "../Commands/CommandObjectCommands.h"
Eli Friedmanccdb9ec2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSyntax.h"
36#include "../Commands/CommandObjectTarget.h"
37#include "../Commands/CommandObjectThread.h"
Greg Clayton5c28dd12011-06-23 17:59:56 +000038#include "../Commands/CommandObjectType.h"
Johnny Chen902e0182010-12-23 20:21:44 +000039#include "../Commands/CommandObjectVersion.h"
Johnny Chen01acfa72011-09-22 18:04:58 +000040#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
Jim Ingham84cdc152010-06-15 19:49:27 +000042#include "lldb/Interpreter/Args.h"
Caroline Tice5ddbe212011-05-06 21:37:15 +000043#include "lldb/Interpreter/Options.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Core/Debugger.h"
Jim Ingham5e16ef52010-10-04 19:49:29 +000045#include "lldb/Core/InputReader.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046#include "lldb/Core/Stream.h"
47#include "lldb/Core/Timer.h"
Greg Claytoncd548032011-02-01 01:31:41 +000048#include "lldb/Host/Host.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049#include "lldb/Target/Process.h"
50#include "lldb/Target/Thread.h"
51#include "lldb/Target/TargetList.h"
Greg Claytone98ac252010-11-10 04:57:04 +000052#include "lldb/Utility/CleanUp.h"
Chris Lattner24943d22010-06-08 16:52:24 +000053
54#include "lldb/Interpreter/CommandReturnObject.h"
55#include "lldb/Interpreter/CommandInterpreter.h"
Caroline Tice0aa2e552011-01-14 00:29:16 +000056#include "lldb/Interpreter/ScriptInterpreterNone.h"
57#include "lldb/Interpreter/ScriptInterpreterPython.h"
Chris Lattner24943d22010-06-08 16:52:24 +000058
59using namespace lldb;
60using namespace lldb_private;
61
62CommandInterpreter::CommandInterpreter
63(
Greg Clayton63094e02010-06-23 01:19:29 +000064 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000065 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000066 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000067) :
Greg Clayton49ce6822010-10-31 03:01:06 +000068 Broadcaster ("lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000069 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000070 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000071 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000072 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000073 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +000074 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +000075 m_repeat_char ('!'),
Enrico Granata293a7b32011-08-15 19:24:02 +000076 m_batch_command_mode (false),
77 m_truncation_warning(eNoTruncation)
Chris Lattner24943d22010-06-08 16:52:24 +000078{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000079 const char *dbg_name = debugger.GetInstanceName().AsCString();
80 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
81 StreamString var_name;
82 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000083 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000084 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000085 m_debugger.GetInstanceName().AsCString());
86 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
87 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
88 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Chris Lattner24943d22010-06-08 16:52:24 +000089}
90
91void
92CommandInterpreter::Initialize ()
93{
94 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
95
96 CommandReturnObject result;
97
98 LoadCommandDictionary ();
99
Chris Lattner24943d22010-06-08 16:52:24 +0000100 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000101 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
102 if (cmd_obj_sp)
103 {
104 AddAlias ("q", cmd_obj_sp);
105 AddAlias ("exit", cmd_obj_sp);
106 }
107
108 cmd_obj_sp = GetCommandSPExact ("process continue", false);
109 if (cmd_obj_sp)
110 {
111 AddAlias ("c", cmd_obj_sp);
112 AddAlias ("continue", cmd_obj_sp);
113 }
114
115 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
116 if (cmd_obj_sp)
117 AddAlias ("b", cmd_obj_sp);
118
119 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
120 if (cmd_obj_sp)
121 AddAlias ("bt", cmd_obj_sp);
122
123 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
124 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000125 {
126 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000127 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000128 }
129
130 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
131 if (cmd_obj_sp)
132 {
133 AddAlias ("nexti", cmd_obj_sp);
134 AddAlias ("ni", cmd_obj_sp);
135 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000136
137 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
138 if (cmd_obj_sp)
139 {
140 AddAlias ("s", cmd_obj_sp);
141 AddAlias ("step", cmd_obj_sp);
142 }
143
144 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
145 if (cmd_obj_sp)
146 {
147 AddAlias ("n", cmd_obj_sp);
148 AddAlias ("next", cmd_obj_sp);
149 }
150
151 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
152 if (cmd_obj_sp)
153 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000154 AddAlias ("finish", cmd_obj_sp);
155 }
156
Jim Ingham59355252011-12-02 01:12:59 +0000157 cmd_obj_sp = GetCommandSPExact ("frame select", false);
158 if (cmd_obj_sp)
159 {
160 AddAlias ("f", cmd_obj_sp);
161 }
162
Caroline Tice5ddbe212011-05-06 21:37:15 +0000163 cmd_obj_sp = GetCommandSPExact ("source list", false);
164 if (cmd_obj_sp)
165 {
166 AddAlias ("l", cmd_obj_sp);
167 AddAlias ("list", cmd_obj_sp);
168 }
169
170 cmd_obj_sp = GetCommandSPExact ("memory read", false);
171 if (cmd_obj_sp)
172 AddAlias ("x", cmd_obj_sp);
173
174 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
175 if (cmd_obj_sp)
176 AddAlias ("up", cmd_obj_sp);
177
178 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
179 if (cmd_obj_sp)
180 AddAlias ("down", cmd_obj_sp);
181
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000182 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000183 if (cmd_obj_sp)
184 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000185
186 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
187 if (cmd_obj_sp)
188 AddAlias ("dis", cmd_obj_sp);
189
190 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
191 if (cmd_obj_sp)
192 AddAlias ("di", cmd_obj_sp);
193
194
Jason Molenda730cae02011-10-22 01:30:52 +0000195
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000196 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000197 if (cmd_obj_sp)
198 AddAlias ("undisplay", cmd_obj_sp);
199
Caroline Tice5ddbe212011-05-06 21:37:15 +0000200 cmd_obj_sp = GetCommandSPExact ("target create", false);
201 if (cmd_obj_sp)
202 AddAlias ("file", cmd_obj_sp);
203
204 cmd_obj_sp = GetCommandSPExact ("target modules", false);
205 if (cmd_obj_sp)
206 AddAlias ("image", cmd_obj_sp);
207
208
209 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000210
Caroline Tice5ddbe212011-05-06 21:37:15 +0000211 cmd_obj_sp = GetCommandSPExact ("expression", false);
212 if (cmd_obj_sp)
213 {
214 AddAlias ("expr", cmd_obj_sp);
215
216 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
217 AddAlias ("p", cmd_obj_sp);
218 AddAlias ("print", cmd_obj_sp);
219 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
220 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
221
222 alias_arguments_vector_sp.reset (new OptionArgVector);
223 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
224 AddAlias ("po", cmd_obj_sp);
225 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
226 }
227
228 cmd_obj_sp = GetCommandSPExact ("process launch", false);
229 if (cmd_obj_sp)
230 {
231 alias_arguments_vector_sp.reset (new OptionArgVector);
232 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
233 AddAlias ("r", cmd_obj_sp);
234 AddAlias ("run", cmd_obj_sp);
235 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
236 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
237 }
Chris Lattner24943d22010-06-08 16:52:24 +0000238}
239
Chris Lattner24943d22010-06-08 16:52:24 +0000240const char *
241CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
242{
243 // This function has not yet been implemented.
244
245 // Look for any embedded script command
246 // If found,
247 // get interpreter object from the command dictionary,
248 // call execute_one_command on it,
249 // get the results as a string,
250 // substitute that string for current stuff.
251
252 return arg;
253}
254
255
256void
257CommandInterpreter::LoadCommandDictionary ()
258{
259 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
260
261 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
262 //
263 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
264 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
265 // the cross-referencing stuff) are created!!!
266 //
267 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
268
269
270 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
271 // are created. This is so that when another command is created that needs to go into a crossref object,
272 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
273 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
274
Chris Lattner24943d22010-06-08 16:52:24 +0000275 // Non-CommandObjectCrossref commands can now be created.
276
Caroline Tice5bc8c972010-09-20 20:44:43 +0000277 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000278
Greg Clayton238c0a12010-09-18 01:14:36 +0000279 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000280 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000281 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000282 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000283 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
284 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000285// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000286 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000287 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000288 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000289 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
290 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000291 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000292 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000293 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000294 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000295 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000296 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000297 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000298 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
299 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000300 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000301 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000302 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000303
304 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000305 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000306 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000307 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000308 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000309 if (break_regex_cmd_ap.get())
310 {
311 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
312 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
313 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000314 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000315 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000316 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000317 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
318 {
319 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
320 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
321 }
322 }
Jim Inghame56493f2011-03-22 02:29:32 +0000323
324 std::auto_ptr<CommandObjectRegexCommand>
325 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000326 "_regexp-down",
327 "Go down \"n\" frames in the stack (1 frame by default).",
328 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000329 if (down_regex_cmd_ap.get())
330 {
331 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
332 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
333 {
334 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
335 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
336 }
337 }
338
339 std::auto_ptr<CommandObjectRegexCommand>
340 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000341 "_regexp-up",
342 "Go up \"n\" frames in the stack (1 frame by default).",
343 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000344 if (up_regex_cmd_ap.get())
345 {
346 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
347 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
348 {
349 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
350 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
351 }
352 }
Jason Molenda730cae02011-10-22 01:30:52 +0000353
354 std::auto_ptr<CommandObjectRegexCommand>
355 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000356 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000357 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000358 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000359 if (display_regex_cmd_ap.get())
360 {
361 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
362 {
363 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
364 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
365 }
366 }
367
368 std::auto_ptr<CommandObjectRegexCommand>
369 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000370 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000371 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000372 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000373 if (undisplay_regex_cmd_ap.get())
374 {
375 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
376 {
377 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
378 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
379 }
380 }
381
Chris Lattner24943d22010-06-08 16:52:24 +0000382}
383
384int
385CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
386 StringList &matches)
387{
388 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
389
390 if (include_aliases)
391 {
392 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
393 }
394
395 return matches.GetSize();
396}
397
398CommandObjectSP
399CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
400{
401 CommandObject::CommandMap::iterator pos;
402 CommandObjectSP ret_val;
403
404 std::string cmd(cmd_cstr);
405
406 if (HasCommands())
407 {
408 pos = m_command_dict.find(cmd);
409 if (pos != m_command_dict.end())
410 ret_val = pos->second;
411 }
412
413 if (include_aliases && HasAliases())
414 {
415 pos = m_alias_dict.find(cmd);
416 if (pos != m_alias_dict.end())
417 ret_val = pos->second;
418 }
419
420 if (HasUserCommands())
421 {
422 pos = m_user_dict.find(cmd);
423 if (pos != m_user_dict.end())
424 ret_val = pos->second;
425 }
426
427 if (!exact && ret_val == NULL)
428 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000429 // We will only get into here if we didn't find any exact matches.
430
431 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
432
Chris Lattner24943d22010-06-08 16:52:24 +0000433 StringList local_matches;
434 if (matches == NULL)
435 matches = &local_matches;
436
Jim Inghamd40f8a62010-07-06 22:46:59 +0000437 unsigned int num_cmd_matches = 0;
438 unsigned int num_alias_matches = 0;
439 unsigned int num_user_matches = 0;
440
441 // Look through the command dictionaries one by one, and if we get only one match from any of
442 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
443
Chris Lattner24943d22010-06-08 16:52:24 +0000444 if (HasCommands())
445 {
446 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
447 }
448
449 if (num_cmd_matches == 1)
450 {
451 cmd.assign(matches->GetStringAtIndex(0));
452 pos = m_command_dict.find(cmd);
453 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000454 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000455 }
456
Jim Ingham9a574172010-06-24 20:28:42 +0000457 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000458 {
459 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
460
461 }
462
Jim Inghamd40f8a62010-07-06 22:46:59 +0000463 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000464 {
465 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
466 pos = m_alias_dict.find(cmd);
467 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000468 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000469 }
470
Jim Ingham9a574172010-06-24 20:28:42 +0000471 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000472 {
473 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
474 }
475
Jim Inghamd40f8a62010-07-06 22:46:59 +0000476 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000477 {
478 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
479
480 pos = m_user_dict.find (cmd);
481 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000482 user_match_sp = pos->second;
483 }
484
485 // If we got exactly one match, return that, otherwise return the match list.
486
487 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
488 {
489 if (num_cmd_matches)
490 return real_match_sp;
491 else if (num_alias_matches)
492 return alias_match_sp;
493 else
494 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000495 }
496 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000497 else if (matches && ret_val != NULL)
498 {
499 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000500 }
501
502
503 return ret_val;
504}
505
Greg Claytond12aeab2011-04-20 16:37:46 +0000506bool
507CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
508{
509 if (name && name[0])
510 {
511 std::string name_sstr(name);
512 if (!can_replace)
513 {
514 if (m_command_dict.find (name_sstr) != m_command_dict.end())
515 return false;
516 }
517 m_command_dict[name_sstr] = cmd_sp;
518 return true;
519 }
520 return false;
521}
522
Enrico Granata6b1596d2011-08-16 23:24:13 +0000523bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000524CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000525 const lldb::CommandObjectSP &cmd_sp,
526 bool can_replace)
527{
Enrico Granata6010ace2011-11-07 22:57:04 +0000528 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000529 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000530
531 const char* name_cstr = name.c_str();
532
533 // do not allow replacement of internal commands
534 if (CommandExists(name_cstr))
535 return false;
536
537 if (can_replace == false && UserCommandExists(name_cstr))
538 return false;
539
540 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000541 return true;
542 }
543 return false;
544}
Greg Claytond12aeab2011-04-20 16:37:46 +0000545
Jim Inghamd40f8a62010-07-06 22:46:59 +0000546CommandObjectSP
547CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000548{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000549 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
550 CommandObjectSP ret_val; // Possibly empty return value.
551
552 if (cmd_cstr == NULL)
553 return ret_val;
554
555 if (cmd_words.GetArgumentCount() == 1)
556 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
557 else
558 {
559 // We have a multi-word command (seemingly), so we need to do more work.
560 // First, get the cmd_obj_sp for the first word in the command.
561 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
562 if (cmd_obj_sp.get() != NULL)
563 {
564 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
565 // command name), and find the appropriate sub-command SP for each command word....
566 size_t end = cmd_words.GetArgumentCount();
567 for (size_t j= 1; j < end; ++j)
568 {
569 if (cmd_obj_sp->IsMultiwordObject())
570 {
571 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
572 (cmd_words.GetArgumentAtIndex (j));
573 if (cmd_obj_sp.get() == NULL)
574 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
575 return ret_val;
576 }
577 else
578 // We have more words in the command name, but we don't have a multiword object. Fail and return
579 // empty 'ret_val'.
580 return ret_val;
581 }
582 // We successfully looped through all the command words and got valid command objects for them. Assign the
583 // last object retrieved to 'ret_val'.
584 ret_val = cmd_obj_sp;
585 }
586 }
587 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000588}
589
590CommandObject *
591CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
592{
593 return GetCommandSPExact (cmd_cstr, include_aliases).get();
594}
595
596CommandObject *
597CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
598{
599 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
600
601 // If we didn't find an exact match to the command string in the commands, look in
602 // the aliases.
603
604 if (command_obj == NULL)
605 {
606 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
607 }
608
609 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
610 // in both the commands and the aliases.
611
612 if (command_obj == NULL)
613 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
614
615 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000616}
617
618bool
619CommandInterpreter::CommandExists (const char *cmd)
620{
621 return m_command_dict.find(cmd) != m_command_dict.end();
622}
623
624bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000625CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
626 const char *options_args,
627 OptionArgVectorSP &option_arg_vector_sp)
628{
629 bool success = true;
630 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
631
632 if (!options_args || (strlen (options_args) < 1))
633 return true;
634
635 std::string options_string (options_args);
636 Args args (options_args);
637 CommandReturnObject result;
638 // Check to see if the command being aliased can take any command options.
639 Options *options = cmd_obj_sp->GetOptions ();
640 if (options)
641 {
642 // See if any options were specified as part of the alias; if so, handle them appropriately.
643 options->NotifyOptionParsingStarting ();
644 args.Unshift ("dummy_arg");
645 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
646 args.Shift ();
647 if (result.Succeeded())
648 options->VerifyPartialOptions (result);
649 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
650 {
651 result.AppendError ("Unable to create requested alias.\n");
652 return false;
653 }
654 }
655
Greg Clayton7268b4c2011-10-28 21:38:01 +0000656 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000657 {
658 if (cmd_obj_sp->WantsRawCommandString ())
659 option_arg_vector->push_back (OptionArgPair ("<argument>",
660 OptionArgValue (-1,
661 options_string)));
662 else
663 {
664 int argc = args.GetArgumentCount();
665 for (size_t i = 0; i < argc; ++i)
666 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
667 option_arg_vector->push_back
668 (OptionArgPair ("<argument>",
669 OptionArgValue (-1,
670 std::string (args.GetArgumentAtIndex (i)))));
671 }
672 }
673
674 return success;
675}
676
677bool
Chris Lattner24943d22010-06-08 16:52:24 +0000678CommandInterpreter::AliasExists (const char *cmd)
679{
680 return m_alias_dict.find(cmd) != m_alias_dict.end();
681}
682
683bool
684CommandInterpreter::UserCommandExists (const char *cmd)
685{
686 return m_user_dict.find(cmd) != m_user_dict.end();
687}
688
689void
690CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
691{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000692 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000693 m_alias_dict[alias_name] = command_obj_sp;
694}
695
696bool
697CommandInterpreter::RemoveAlias (const char *alias_name)
698{
699 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
700 if (pos != m_alias_dict.end())
701 {
702 m_alias_dict.erase(pos);
703 return true;
704 }
705 return false;
706}
707bool
708CommandInterpreter::RemoveUser (const char *alias_name)
709{
710 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
711 if (pos != m_user_dict.end())
712 {
713 m_user_dict.erase(pos);
714 return true;
715 }
716 return false;
717}
718
Chris Lattner24943d22010-06-08 16:52:24 +0000719void
720CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
721{
722 help_string.Printf ("'%s", command_name);
723 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
724
725 if (option_arg_vector_sp != NULL)
726 {
727 OptionArgVector *options = option_arg_vector_sp.get();
728 for (int i = 0; i < options->size(); ++i)
729 {
730 OptionArgPair cur_option = (*options)[i];
731 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000732 OptionArgValue value_pair = cur_option.second;
733 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000734 if (opt.compare("<argument>") == 0)
735 {
736 help_string.Printf (" %s", value.c_str());
737 }
738 else
739 {
740 help_string.Printf (" %s", opt.c_str());
741 if ((value.compare ("<no-argument>") != 0)
742 && (value.compare ("<need-argument") != 0))
743 {
744 help_string.Printf (" %s", value.c_str());
745 }
746 }
747 }
748 }
749
750 help_string.Printf ("'");
751}
752
Greg Clayton65124ea2010-08-26 22:05:43 +0000753size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000754CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
755{
756 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000757 CommandObject::CommandMap::const_iterator end = dict.end();
758 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000759
Greg Clayton65124ea2010-08-26 22:05:43 +0000760 for (pos = dict.begin(); pos != end; ++pos)
761 {
762 size_t len = pos->first.size();
763 if (max_len < len)
764 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000765 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000766 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000767}
768
769void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000770CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000771 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000772{
773 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000774 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000775
776 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000777 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000778
779 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
780 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000781
Enrico Granata6b1596d2011-08-16 23:24:13 +0000782 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
783 {
784 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
785 max_len);
786 }
787 result.AppendMessage("");
788
789 }
790
Greg Clayton7268b4c2011-10-28 21:38:01 +0000791 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000792 {
Jim Inghame3663e82010-10-22 18:47:16 +0000793 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000794 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000795 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000796 max_len = FindLongestCommandWord (m_alias_dict);
797
Chris Lattner24943d22010-06-08 16:52:24 +0000798 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
799 {
800 StreamString sstr;
801 StreamString translation_and_help;
802 std::string entry_name = pos->first;
803 std::string second_entry = pos->second.get()->GetCommandName();
804 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
805
806 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
807 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
808 translation_and_help.GetData(), max_len);
809 }
810 result.AppendMessage("");
811 }
812
Greg Clayton7268b4c2011-10-28 21:38:01 +0000813 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000814 {
815 result.AppendMessage ("The following is a list of your current user-defined commands:");
816 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000817 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000818 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
819 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000820 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
821 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000822 }
823 result.AppendMessage("");
824 }
825
826 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
827}
828
Caroline Ticee0da7a52010-12-09 22:52:49 +0000829CommandObject *
830CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000831{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000832 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
833 // eventually be invoked by the given command line.
834
835 CommandObject *cmd_obj = NULL;
836 std::string white_space (" \t\v");
837 size_t start = command_string.find_first_not_of (white_space);
838 size_t end = 0;
839 bool done = false;
840 while (!done)
841 {
842 if (start != std::string::npos)
843 {
844 // Get the next word from command_string.
845 end = command_string.find_first_of (white_space, start);
846 if (end == std::string::npos)
847 end = command_string.size();
848 std::string cmd_word = command_string.substr (start, end - start);
849
850 if (cmd_obj == NULL)
851 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
852 // command or alias.
853 cmd_obj = GetCommandObject (cmd_word.c_str());
854 else if (cmd_obj->IsMultiwordObject ())
855 {
856 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
857 CommandObject *sub_cmd_obj =
858 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
859 if (sub_cmd_obj)
860 cmd_obj = sub_cmd_obj;
861 else // cmd_word was not a valid sub-command word, so we are donee
862 done = true;
863 }
864 else
865 // We have a cmd_obj and it is not a multi-word object, so we are done.
866 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000867
Caroline Ticee0da7a52010-12-09 22:52:49 +0000868 // If we didn't find a valid command object, or our command object is not a multi-word object, or
869 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
870 // next word.
871
872 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
873 done = true;
874 else
875 start = command_string.find_first_not_of (white_space, end);
876 }
877 else
878 // Unable to find any more words.
879 done = true;
880 }
881
882 if (end == command_string.size())
883 command_string.clear();
884 else
885 command_string = command_string.substr(end);
886
887 return cmd_obj;
888}
889
Greg Clayton9d855c62011-10-25 00:36:27 +0000890static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000891static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000892static void
893StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000894{
Greg Clayton9d855c62011-10-25 00:36:27 +0000895 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000896 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000897 size_t pos = s.find_first_not_of (k_white_space);
898 if (pos == std::string::npos)
899 s.clear();
900 else if (pos == 0)
901 return;
902 s.erase (0, pos);
903 }
904}
905
Greg Clayton3840cd72011-11-09 23:25:03 +0000906static size_t
907FindArgumentTerminator (const std::string &s)
908{
Greg Clayton3840cd72011-11-09 23:25:03 +0000909 const size_t s_len = s.size();
910 size_t offset = 0;
911 while (offset < s_len)
912 {
913 size_t pos = s.find ("--", offset);
914 if (pos == std::string::npos)
915 break;
916 if (pos > 0)
917 {
918 if (isspace(s[pos-1]))
919 {
920 // Check if the string ends "\s--" (where \s is a space character)
921 // or if we have "\s--\s".
922 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
923 {
Greg Clayton3840cd72011-11-09 23:25:03 +0000924 return pos;
925 }
926 }
927 }
928 offset = pos + 2;
929 }
Greg Clayton3840cd72011-11-09 23:25:03 +0000930 return std::string::npos;
931}
932
Greg Clayton9d855c62011-10-25 00:36:27 +0000933static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000934ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000935{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000936 command.clear();
937 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000938 StripLeadingSpaces (command_string);
939
940 bool result = false;
941 quote_char = '\0';
942
943 if (!command_string.empty())
944 {
945 const char first_char = command_string[0];
946 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000947 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000948 quote_char = first_char;
949 const size_t end_quote_pos = command_string.find (quote_char, 1);
950 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000951 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000952 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000953 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000954 }
955 else
956 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000957 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +0000958 if (end_quote_pos + 1 < command_string.size())
959 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
960 else
961 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000962 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000963 }
964 else
965 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000966 const size_t first_space_pos = command_string.find_first_of (k_white_space);
967 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000968 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000969 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000970 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +0000971 }
972 else
973 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000974 command.assign (command_string, 0, first_space_pos);
975 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +0000976 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000977 }
Greg Clayton9d855c62011-10-25 00:36:27 +0000978 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000979 }
Greg Clayton7268b4c2011-10-28 21:38:01 +0000980
981
982 if (!command.empty())
983 {
984 // actual commands can't start with '-' or '_'
985 if (command[0] != '-' && command[0] != '_')
986 {
987 size_t pos = command.find_first_not_of(k_valid_command_chars);
988 if (pos > 0 && pos != std::string::npos)
989 {
990 suffix.assign (command.begin() + pos, command.end());
991 command.erase (pos);
992 }
993 }
994 }
Greg Clayton9d855c62011-10-25 00:36:27 +0000995
996 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000997}
998
Greg Clayton7268b4c2011-10-28 21:38:01 +0000999CommandObject *
1000CommandInterpreter::BuildAliasResult (const char *alias_name,
1001 std::string &raw_input_string,
1002 std::string &alias_result,
1003 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001004{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001005 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001006 Args cmd_args (raw_input_string.c_str());
1007 alias_cmd_obj = GetCommandObject (alias_name);
1008 StreamString result_str;
1009
1010 if (alias_cmd_obj)
1011 {
1012 std::string alias_name_str = alias_name;
1013 if ((cmd_args.GetArgumentCount() == 0)
1014 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1015 cmd_args.Unshift (alias_name);
1016
1017 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1018 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1019
1020 if (option_arg_vector_sp.get())
1021 {
1022 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1023
1024 for (int i = 0; i < option_arg_vector->size(); ++i)
1025 {
1026 OptionArgPair option_pair = (*option_arg_vector)[i];
1027 OptionArgValue value_pair = option_pair.second;
1028 int value_type = value_pair.first;
1029 std::string option = option_pair.first;
1030 std::string value = value_pair.second;
1031 if (option.compare ("<argument>") == 0)
1032 result_str.Printf (" %s", value.c_str());
1033 else
1034 {
1035 result_str.Printf (" %s", option.c_str());
1036 if (value_type != optional_argument)
1037 result_str.Printf (" ");
1038 if (value.compare ("<no_argument>") != 0)
1039 {
1040 int index = GetOptionArgumentPosition (value.c_str());
1041 if (index == 0)
1042 result_str.Printf ("%s", value.c_str());
1043 else if (index >= cmd_args.GetArgumentCount())
1044 {
1045
1046 result.AppendErrorWithFormat
1047 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1048 index);
1049 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001050 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001051 }
1052 else
1053 {
1054 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1055 if (strpos != std::string::npos)
1056 raw_input_string = raw_input_string.erase (strpos,
1057 strlen (cmd_args.GetArgumentAtIndex (index)));
1058 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1059 }
1060 }
1061 }
1062 }
1063 }
1064
1065 alias_result = result_str.GetData();
1066 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001067 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001068}
1069
Greg Claytonf5c0c722011-10-14 07:41:33 +00001070Error
1071CommandInterpreter::PreprocessCommand (std::string &command)
1072{
1073 // The command preprocessor needs to do things to the command
1074 // line before any parsing of arguments or anything else is done.
1075 // The only current stuff that gets proprocessed is anyting enclosed
1076 // in backtick ('`') characters is evaluated as an expression and
1077 // the result of the expression must be a scalar that can be substituted
1078 // into the command. An example would be:
1079 // (lldb) memory read `$rsp + 20`
1080 Error error; // Error for any expressions that might not evaluate
1081 size_t start_backtick;
1082 size_t pos = 0;
1083 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1084 {
1085 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1086 {
1087 // The backtick was preceeded by a '\' character, remove the slash
1088 // and don't treat the backtick as the start of an expression
1089 command.erase(start_backtick-1, 1);
1090 // No need to add one to start_backtick since we just deleted a char
1091 pos = start_backtick;
1092 }
1093 else
1094 {
1095 const size_t expr_content_start = start_backtick + 1;
1096 const size_t end_backtick = command.find ('`', expr_content_start);
1097 if (end_backtick == std::string::npos)
1098 return error;
1099 else if (end_backtick == expr_content_start)
1100 {
1101 // Empty expression (two backticks in a row)
1102 command.erase (start_backtick, 2);
1103 }
1104 else
1105 {
1106 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1107
1108 Target *target = m_exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001109 // Get a dummy target to allow for calculator mode while processing backticks.
1110 // This also helps break the infinite loop caused when target is null.
1111 if (!target)
1112 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001113 if (target)
1114 {
1115 const bool unwind_on_error = true;
1116 const bool keep_in_memory = false;
1117 ValueObjectSP expr_result_valobj_sp;
1118 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1119 m_exe_ctx.GetFramePtr(),
1120 eExecutionPolicyOnlyWhenNeeded,
1121 unwind_on_error, keep_in_memory,
1122 eNoDynamicValues,
1123 expr_result_valobj_sp);
1124 if (expr_result == eExecutionCompleted)
1125 {
1126 Scalar scalar;
1127 if (expr_result_valobj_sp->ResolveValue (scalar))
1128 {
1129 command.erase (start_backtick, end_backtick - start_backtick + 1);
1130 StreamString value_strm;
1131 const bool show_type = false;
1132 scalar.GetValue (&value_strm, show_type);
1133 size_t value_string_size = value_strm.GetSize();
1134 if (value_string_size)
1135 {
1136 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1137 pos = start_backtick + value_string_size;
1138 continue;
1139 }
1140 else
1141 {
1142 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1143 }
1144 }
1145 else
1146 {
1147 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1148 }
1149 }
1150 else
1151 {
1152 if (expr_result_valobj_sp)
1153 error = expr_result_valobj_sp->GetError();
1154 if (error.Success())
1155 {
1156
1157 switch (expr_result)
1158 {
1159 case eExecutionSetupError:
1160 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1161 break;
1162 case eExecutionCompleted:
1163 break;
1164 case eExecutionDiscarded:
1165 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1166 break;
1167 case eExecutionInterrupted:
1168 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1169 break;
1170 case eExecutionTimedOut:
1171 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1172 break;
1173 }
1174 }
1175 }
1176 }
1177 }
1178 if (error.Fail())
1179 break;
1180 }
1181 }
1182 return error;
1183}
1184
1185
Caroline Ticee0da7a52010-12-09 22:52:49 +00001186bool
1187CommandInterpreter::HandleCommand (const char *command_line,
1188 bool add_to_history,
1189 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001190 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001191 bool repeat_on_empty_command,
1192 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001193
Caroline Ticee0da7a52010-12-09 22:52:49 +00001194{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001195
Caroline Ticee0da7a52010-12-09 22:52:49 +00001196 bool done = false;
1197 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001198 bool wants_raw_input = false;
1199 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001200 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001201
1202 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001203 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1204
1205 // Make a scoped cleanup object that will clear the crash description string
1206 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001207 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001208
Caroline Ticee0da7a52010-12-09 22:52:49 +00001209 if (log)
1210 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001211
Jim Inghamabab14b2010-11-04 23:08:45 +00001212 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1213
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001214 if (!no_context_switching)
1215 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +00001216
Jim Ingham949d5ac2011-02-18 00:54:25 +00001217 bool empty_command = false;
1218 bool comment_command = false;
1219 if (command_string.empty())
1220 empty_command = true;
1221 else
Chris Lattner24943d22010-06-08 16:52:24 +00001222 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001223 const char *k_space_characters = "\t\n\v\f\r ";
1224
1225 size_t non_space = command_string.find_first_not_of (k_space_characters);
1226 // Check for empty line or comment line (lines whose first
1227 // non-space character is the comment character for this interpreter)
1228 if (non_space == std::string::npos)
1229 empty_command = true;
1230 else if (command_string[non_space] == m_comment_char)
1231 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001232 else if (command_string[non_space] == m_repeat_char)
1233 {
1234 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1235 if (history_string == NULL)
1236 {
1237 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1238 result.SetStatus(eReturnStatusFailed);
1239 return false;
1240 }
1241 add_to_history = false;
1242 command_string = history_string;
1243 original_command_string = history_string;
1244 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001245 }
1246
1247 if (empty_command)
1248 {
1249 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001250 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001251 if (m_command_history.empty())
1252 {
1253 result.AppendError ("empty command");
1254 result.SetStatus(eReturnStatusFailed);
1255 return false;
1256 }
1257 else
1258 {
1259 command_line = m_repeat_command.c_str();
1260 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001261 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001262 if (m_repeat_command.empty())
1263 {
1264 result.AppendErrorWithFormat("No auto repeat.\n");
1265 result.SetStatus (eReturnStatusFailed);
1266 return false;
1267 }
1268 }
1269 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001270 }
1271 else
1272 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001273 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1274 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001275 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001276 }
1277 else if (comment_command)
1278 {
1279 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1280 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001281 }
Caroline Tice649116c2011-05-11 16:07:06 +00001282
Greg Claytonf5c0c722011-10-14 07:41:33 +00001283
1284 Error error (PreprocessCommand (command_string));
1285
1286 if (error.Fail())
1287 {
1288 result.AppendError (error.AsCString());
1289 result.SetStatus(eReturnStatusFailed);
1290 return false;
1291 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001292 // Phase 1.
1293
1294 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1295 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1296 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1297 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1298 // 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 +00001299 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001300 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001301
Caroline Ticee0da7a52010-12-09 22:52:49 +00001302 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001303 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001304 std::string next_word;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001305 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001306 {
Caroline Tice649116c2011-05-11 16:07:06 +00001307 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001308 std::string suffix;
1309 ExtractCommand (command_string, next_word, suffix, quote_char);
1310 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001311 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001312 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001313 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001314 std::string alias_result;
1315 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1316 revised_command_line.Printf ("%s", alias_result.c_str());
1317 if (cmd_obj)
1318 {
1319 wants_raw_input = cmd_obj->WantsRawCommandString ();
1320 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1321 }
Chris Lattner24943d22010-06-08 16:52:24 +00001322 }
1323 else
1324 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001325 cmd_obj = GetCommandObject (next_word.c_str());
1326 if (cmd_obj)
1327 {
1328 actual_cmd_name_len += next_word.length();
1329 revised_command_line.Printf ("%s", next_word.c_str());
1330 wants_raw_input = cmd_obj->WantsRawCommandString ();
1331 }
Caroline Tice649116c2011-05-11 16:07:06 +00001332 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001333 {
1334 revised_command_line.Printf ("%s", next_word.c_str());
1335 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001336 }
1337 }
1338 else
1339 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001340 if (cmd_obj->IsMultiwordObject ())
1341 {
1342 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1343 if (sub_cmd_obj)
1344 {
1345 actual_cmd_name_len += next_word.length() + 1;
1346 revised_command_line.Printf (" %s", next_word.c_str());
1347 cmd_obj = sub_cmd_obj;
1348 wants_raw_input = cmd_obj->WantsRawCommandString ();
1349 }
1350 else
1351 {
1352 if (quote_char)
1353 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1354 else
1355 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1356 done = true;
1357 }
1358 }
Caroline Tice649116c2011-05-11 16:07:06 +00001359 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001360 {
1361 if (quote_char)
1362 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1363 else
1364 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1365 done = true;
1366 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001367 }
1368
1369 if (cmd_obj == NULL)
1370 {
1371 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1372 result.SetStatus (eReturnStatusFailed);
1373 return false;
1374 }
1375
Greg Clayton7268b4c2011-10-28 21:38:01 +00001376 if (cmd_obj->IsMultiwordObject ())
1377 {
1378 if (!suffix.empty())
1379 {
1380
1381 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1382 next_word.c_str(),
1383 suffix.c_str());
1384 result.SetStatus (eReturnStatusFailed);
1385 return false;
1386 }
1387 }
1388 else
1389 {
1390 // If we found a normal command, we are done
1391 done = true;
1392 if (!suffix.empty())
1393 {
1394 switch (suffix[0])
1395 {
1396 case '/':
1397 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001398 {
1399 Options *command_options = cmd_obj->GetOptions();
1400 if (command_options && command_options->SupportsLongOption("gdb-format"))
1401 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001402 std::string gdb_format_option ("--gdb-format=");
1403 gdb_format_option += (suffix.c_str() + 1);
1404
1405 bool inserted = false;
1406 std::string &cmd = revised_command_line.GetString();
1407 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1408 if (arg_terminator_idx != std::string::npos)
1409 {
1410 // Insert the gdb format option before the "--" that terminates options
1411 gdb_format_option.append(1,' ');
1412 cmd.insert(arg_terminator_idx, gdb_format_option);
1413 inserted = true;
1414 }
1415
1416 if (!inserted)
1417 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1418
1419 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1420 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001421 }
1422 else
1423 {
1424 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1425 cmd_obj->GetCommandName());
1426 result.SetStatus (eReturnStatusFailed);
1427 return false;
1428 }
1429 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001430 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001431
1432 default:
1433 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1434 suffix.c_str());
1435 result.SetStatus (eReturnStatusFailed);
1436 return false;
1437
Greg Clayton7268b4c2011-10-28 21:38:01 +00001438 }
1439 }
1440 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001441 if (command_string.length() == 0)
1442 done = true;
1443
Chris Lattner24943d22010-06-08 16:52:24 +00001444 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001445
Greg Clayton7268b4c2011-10-28 21:38:01 +00001446 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001447 revised_command_line.Printf (" %s", command_string.c_str());
1448
1449 // End of Phase 1.
1450 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1451 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1452 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1453 // wants_raw_input specifies whether the Execute method expects raw input or not.
1454
1455
1456 if (log)
1457 {
1458 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1459 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1460 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1461 }
1462
1463 // Phase 2.
1464 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1465 // CommandObject, with the appropriate arguments.
1466
1467 if (cmd_obj != NULL)
1468 {
1469 if (add_to_history)
1470 {
1471 Args command_args (revised_command_line.GetData());
1472 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1473 if (repeat_command != NULL)
1474 m_repeat_command.assign(repeat_command);
1475 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001476 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001477
Jim Ingham6247dbe2011-07-12 03:12:18 +00001478 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001479 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001480 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001481 }
1482
1483 command_string = revised_command_line.GetData();
1484 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001485 std::string remainder;
1486 if (actual_cmd_name_len < command_string.length())
1487 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1488 // than cmd_obj->GetCommandName(), because name completion
1489 // allows users to enter short versions of the names,
1490 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001491
1492 // Remove any initial spaces
1493 std::string white_space (" \t\v");
1494 size_t pos = remainder.find_first_not_of (white_space);
1495 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001496 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001497
1498 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001499 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001500
1501
1502 if (wants_raw_input)
1503 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1504 else
1505 {
1506 Args cmd_args (remainder.c_str());
1507 cmd_obj->ExecuteWithOptions (cmd_args, result);
1508 }
1509 }
1510 else
1511 {
1512 // We didn't find the first command object, so complete the first argument.
1513 Args command_args (revised_command_line.GetData());
1514 StringList matches;
1515 int num_matches;
1516 int cursor_index = 0;
1517 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1518 bool word_complete;
1519 num_matches = HandleCompletionMatches (command_args,
1520 cursor_index,
1521 cursor_char_position,
1522 0,
1523 -1,
1524 word_complete,
1525 matches);
1526
1527 if (num_matches > 0)
1528 {
1529 std::string error_msg;
1530 error_msg.assign ("ambiguous command '");
1531 error_msg.append(command_args.GetArgumentAtIndex(0));
1532 error_msg.append ("'.");
1533
1534 error_msg.append (" Possible completions:");
1535 for (int i = 0; i < num_matches; i++)
1536 {
1537 error_msg.append ("\n\t");
1538 error_msg.append (matches.GetStringAtIndex (i));
1539 }
1540 error_msg.append ("\n");
1541 result.AppendRawError (error_msg.c_str(), error_msg.size());
1542 }
1543 else
1544 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1545
1546 result.SetStatus (eReturnStatusFailed);
1547 }
1548
Jason Molenda24c991c2011-08-25 00:20:04 +00001549 if (log)
1550 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1551
Chris Lattner24943d22010-06-08 16:52:24 +00001552 return result.Succeeded();
1553}
1554
1555int
1556CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1557 int &cursor_index,
1558 int &cursor_char_position,
1559 int match_start_point,
1560 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001561 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001562 StringList &matches)
1563{
1564 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001565 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001566
1567 // For any of the command completions a unique match will be a complete word.
1568 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001569
1570 if (cursor_index == -1)
1571 {
1572 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001573 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001574 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1575 }
1576 else if (cursor_index == 0)
1577 {
1578 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001579 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001580 num_command_matches = matches.GetSize();
1581
1582 if (num_command_matches == 1
1583 && cmd_obj && cmd_obj->IsMultiwordObject()
1584 && matches.GetStringAtIndex(0) != NULL
1585 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1586 {
1587 look_for_subcommand = true;
1588 num_command_matches = 0;
1589 matches.DeleteStringAtIndex(0);
1590 parsed_line.AppendArgument ("");
1591 cursor_index++;
1592 cursor_char_position = 0;
1593 }
1594 }
1595
1596 if (cursor_index > 0 || look_for_subcommand)
1597 {
1598 // We are completing further on into a commands arguments, so find the command and tell it
1599 // to complete the command.
1600 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001601 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001602 if (command_object == NULL)
1603 {
1604 return 0;
1605 }
1606 else
1607 {
1608 parsed_line.Shift();
1609 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001610 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001611 cursor_index,
1612 cursor_char_position,
1613 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001614 max_return_elements,
1615 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001616 matches);
1617 }
1618 }
1619
1620 return num_command_matches;
1621
1622}
1623
1624int
1625CommandInterpreter::HandleCompletion (const char *current_line,
1626 const char *cursor,
1627 const char *last_char,
1628 int match_start_point,
1629 int max_return_elements,
1630 StringList &matches)
1631{
1632 // We parse the argument up to the cursor, so the last argument in parsed_line is
1633 // the one containing the cursor, and the cursor is after the last character.
1634
1635 Args parsed_line(current_line, last_char - current_line);
1636 Args partial_parsed_line(current_line, cursor - current_line);
1637
Jim Ingham6247dbe2011-07-12 03:12:18 +00001638 // Don't complete comments, and if the line we are completing is just the history repeat character,
1639 // substitute the appropriate history line.
1640 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1641 if (first_arg)
1642 {
1643 if (first_arg[0] == m_comment_char)
1644 return 0;
1645 else if (first_arg[0] == m_repeat_char)
1646 {
1647 const char *history_string = FindHistoryString (first_arg);
1648 if (history_string != NULL)
1649 {
1650 matches.Clear();
1651 matches.InsertStringAtIndex(0, history_string);
1652 return -2;
1653 }
1654 else
1655 return 0;
1656
1657 }
1658 }
1659
1660
Chris Lattner24943d22010-06-08 16:52:24 +00001661 int num_args = partial_parsed_line.GetArgumentCount();
1662 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1663 int cursor_char_position;
1664
1665 if (cursor_index == -1)
1666 cursor_char_position = 0;
1667 else
1668 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001669
1670 if (cursor > current_line && cursor[-1] == ' ')
1671 {
1672 // We are just after a space. If we are in an argument, then we will continue
1673 // parsing, but if we are between arguments, then we have to complete whatever the next
1674 // element would be.
1675 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1676 // protected by a quote) then the space will also be in the parsed argument...
1677
1678 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1679 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1680 {
1681 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1682 cursor_index++;
1683 cursor_char_position = 0;
1684 }
1685 }
Chris Lattner24943d22010-06-08 16:52:24 +00001686
1687 int num_command_matches;
1688
1689 matches.Clear();
1690
1691 // Only max_return_elements == -1 is supported at present:
1692 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001693 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001694 num_command_matches = HandleCompletionMatches (parsed_line,
1695 cursor_index,
1696 cursor_char_position,
1697 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001698 max_return_elements,
1699 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001700 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001701
1702 if (num_command_matches <= 0)
1703 return num_command_matches;
1704
1705 if (num_args == 0)
1706 {
1707 // If we got an empty string, insert nothing.
1708 matches.InsertStringAtIndex(0, "");
1709 }
1710 else
1711 {
1712 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1713 // put an empty string in element 0.
1714 std::string command_partial_str;
1715 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001716 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1717 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001718
1719 std::string common_prefix;
1720 matches.LongestCommonPrefix (common_prefix);
1721 int partial_name_len = command_partial_str.size();
1722
1723 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001724 // Only do this if the completer told us this was a complete word, however...
1725 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001726 {
1727 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1728 if (quote_char != '\0')
1729 common_prefix.push_back(quote_char);
1730
1731 common_prefix.push_back(' ');
1732 }
1733 common_prefix.erase (0, partial_name_len);
1734 matches.InsertStringAtIndex(0, common_prefix.c_str());
1735 }
1736 return num_command_matches;
1737}
1738
Chris Lattner24943d22010-06-08 16:52:24 +00001739
1740CommandInterpreter::~CommandInterpreter ()
1741{
1742}
1743
1744const char *
1745CommandInterpreter::GetPrompt ()
1746{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001747 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001748}
1749
1750void
1751CommandInterpreter::SetPrompt (const char *new_prompt)
1752{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001753 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001754}
1755
Jim Ingham5e16ef52010-10-04 19:49:29 +00001756size_t
Greg Clayton58928562011-02-09 01:08:52 +00001757CommandInterpreter::GetConfirmationInputReaderCallback
1758(
1759 void *baton,
1760 InputReader &reader,
1761 lldb::InputReaderAction action,
1762 const char *bytes,
1763 size_t bytes_len
1764)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001765{
Greg Clayton58928562011-02-09 01:08:52 +00001766 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001767 bool *response_ptr = (bool *) baton;
1768
1769 switch (action)
1770 {
1771 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001772 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001773 {
1774 if (reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001775 {
Greg Clayton58928562011-02-09 01:08:52 +00001776 out_file.Printf ("%s", reader.GetPrompt());
1777 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001778 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001779 }
1780 break;
1781
1782 case eInputReaderDeactivate:
1783 break;
1784
1785 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001786 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001787 {
Greg Clayton58928562011-02-09 01:08:52 +00001788 out_file.Printf ("%s", reader.GetPrompt());
1789 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001790 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001791 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001792
1793 case eInputReaderAsynchronousOutputWritten:
1794 break;
1795
Jim Ingham5e16ef52010-10-04 19:49:29 +00001796 case eInputReaderGotToken:
1797 if (bytes_len == 0)
1798 {
1799 reader.SetIsDone(true);
1800 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001801 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001802 {
1803 *response_ptr = true;
1804 reader.SetIsDone(true);
1805 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001806 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001807 {
1808 *response_ptr = false;
1809 reader.SetIsDone(true);
1810 }
1811 else
1812 {
Greg Clayton58928562011-02-09 01:08:52 +00001813 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001814 {
Jim Ingham26183802011-11-17 01:22:00 +00001815 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001816 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001817 }
1818 }
1819 break;
1820
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001821 case eInputReaderInterrupt:
1822 case eInputReaderEndOfFile:
1823 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1824 reader.SetIsDone (true);
1825 break;
1826
Jim Ingham5e16ef52010-10-04 19:49:29 +00001827 case eInputReaderDone:
1828 break;
1829 }
1830
1831 return bytes_len;
1832
1833}
1834
1835bool
1836CommandInterpreter::Confirm (const char *message, bool default_answer)
1837{
Jim Ingham93057472010-10-04 22:44:14 +00001838 // Check AutoConfirm first:
1839 if (m_debugger.GetAutoConfirm())
1840 return default_answer;
1841
Jim Ingham5e16ef52010-10-04 19:49:29 +00001842 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1843 bool response = default_answer;
1844 if (reader_sp)
1845 {
1846 std::string prompt(message);
1847 prompt.append(": [");
1848 if (default_answer)
1849 prompt.append ("Y/n] ");
1850 else
1851 prompt.append ("y/N] ");
1852
1853 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1854 &response, // baton
1855 eInputReaderGranularityLine, // token size, to pass to callback function
1856 NULL, // end token
1857 prompt.c_str(), // prompt
1858 true)); // echo input
1859 if (err.Success())
1860 {
1861 GetDebugger().PushInputReader (reader_sp);
1862 }
1863 reader_sp->WaitOnReaderIsDone();
1864 }
1865 return response;
1866}
1867
1868
Chris Lattner24943d22010-06-08 16:52:24 +00001869void
1870CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1871{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001872 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001873
1874 if (cmd_obj_sp != NULL)
1875 {
1876 CommandObject *cmd_obj = cmd_obj_sp.get();
1877 if (cmd_obj->IsCrossRefObject ())
1878 cmd_obj->AddObject (object_type);
1879 }
1880}
1881
Chris Lattner24943d22010-06-08 16:52:24 +00001882OptionArgVectorSP
1883CommandInterpreter::GetAliasOptions (const char *alias_name)
1884{
1885 OptionArgMap::iterator pos;
1886 OptionArgVectorSP ret_val;
1887
1888 std::string alias (alias_name);
1889
1890 if (HasAliasOptions())
1891 {
1892 pos = m_alias_options.find (alias);
1893 if (pos != m_alias_options.end())
1894 ret_val = pos->second;
1895 }
1896
1897 return ret_val;
1898}
1899
1900void
1901CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1902{
1903 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1904 if (pos != m_alias_options.end())
1905 {
1906 m_alias_options.erase (pos);
1907 }
1908}
1909
1910void
1911CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1912{
1913 m_alias_options[alias_name] = option_arg_vector_sp;
1914}
1915
1916bool
1917CommandInterpreter::HasCommands ()
1918{
1919 return (!m_command_dict.empty());
1920}
1921
1922bool
1923CommandInterpreter::HasAliases ()
1924{
1925 return (!m_alias_dict.empty());
1926}
1927
1928bool
1929CommandInterpreter::HasUserCommands ()
1930{
1931 return (!m_user_dict.empty());
1932}
1933
1934bool
1935CommandInterpreter::HasAliasOptions ()
1936{
1937 return (!m_alias_options.empty());
1938}
1939
Chris Lattner24943d22010-06-08 16:52:24 +00001940void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001941CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1942 const char *alias_name,
1943 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001944 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001945 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001946{
1947 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001948
1949 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001950
Caroline Tice44c841d2010-12-07 19:58:26 +00001951 // Make sure that the alias name is the 0th element in cmd_args
1952 std::string alias_name_str = alias_name;
1953 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1954 cmd_args.Unshift (alias_name);
1955
1956 Args new_args (alias_cmd_obj->GetCommandName());
1957 if (new_args.GetArgumentCount() == 2)
1958 new_args.Shift();
1959
Chris Lattner24943d22010-06-08 16:52:24 +00001960 if (option_arg_vector_sp.get())
1961 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001962 if (wants_raw_input)
1963 {
1964 // We have a command that both has command options and takes raw input. Make *sure* it has a
1965 // " -- " in the right place in the raw_input_string.
1966 size_t pos = raw_input_string.find(" -- ");
1967 if (pos == std::string::npos)
1968 {
1969 // None found; assume it goes at the beginning of the raw input string
1970 raw_input_string.insert (0, " -- ");
1971 }
1972 }
Chris Lattner24943d22010-06-08 16:52:24 +00001973
1974 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1975 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001976 std::vector<bool> used (old_size + 1, false);
1977
1978 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001979
1980 for (int i = 0; i < option_arg_vector->size(); ++i)
1981 {
1982 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001983 OptionArgValue value_pair = option_pair.second;
1984 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001985 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001986 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001987 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00001988 {
1989 if (!wants_raw_input
1990 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
1991 new_args.AppendArgument (value.c_str());
1992 }
Chris Lattner24943d22010-06-08 16:52:24 +00001993 else
1994 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001995 if (value_type != optional_argument)
1996 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00001997 if (value.compare ("<no-argument>") != 0)
1998 {
1999 int index = GetOptionArgumentPosition (value.c_str());
2000 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002001 {
Chris Lattner24943d22010-06-08 16:52:24 +00002002 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002003 if (value_type != optional_argument)
2004 new_args.AppendArgument (value.c_str());
2005 else
2006 {
2007 char buffer[255];
2008 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2009 new_args.AppendArgument (buffer);
2010 }
2011
2012 }
Chris Lattner24943d22010-06-08 16:52:24 +00002013 else if (index >= cmd_args.GetArgumentCount())
2014 {
2015 result.AppendErrorWithFormat
2016 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2017 index);
2018 result.SetStatus (eReturnStatusFailed);
2019 return;
2020 }
2021 else
2022 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002023 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2024 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2025 if (strpos != std::string::npos)
2026 {
2027 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2028 }
2029
2030 if (value_type != optional_argument)
2031 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2032 else
2033 {
2034 char buffer[255];
2035 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2036 cmd_args.GetArgumentAtIndex (index));
2037 new_args.AppendArgument (buffer);
2038 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002039 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002040 }
2041 }
2042 }
2043 }
2044
2045 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2046 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002047 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002048 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2049 }
2050
2051 cmd_args.Clear();
2052 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2053 }
2054 else
2055 {
2056 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002057 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2058 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2059 // input string.
2060 if (wants_raw_input)
2061 {
2062 cmd_args.Clear();
2063 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2064 }
Chris Lattner24943d22010-06-08 16:52:24 +00002065 return;
2066 }
2067
2068 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2069 return;
2070}
2071
2072
2073int
2074CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2075{
2076 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2077 // of zero.
2078
2079 char *cptr = (char *) in_string;
2080
2081 // Does it start with '%'
2082 if (cptr[0] == '%')
2083 {
2084 ++cptr;
2085
2086 // Is the rest of it entirely digits?
2087 if (isdigit (cptr[0]))
2088 {
2089 const char *start = cptr;
2090 while (isdigit (cptr[0]))
2091 ++cptr;
2092
2093 // We've gotten to the end of the digits; are we at the end of the string?
2094 if (cptr[0] == '\0')
2095 position = atoi (start);
2096 }
2097 }
2098
2099 return position;
2100}
2101
2102void
2103CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2104{
Jim Ingham574c3d62011-08-12 23:34:31 +00002105 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002106 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002107 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002108 // In the current working directory we don't load any program specific
2109 // .lldbinit files, we only look for a "./.lldbinit" file.
2110 if (m_skip_lldbinit_files)
2111 return;
2112
2113 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002114 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002115 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002116 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002117 // If we aren't looking in the current working directory we are looking
2118 // in the home directory. We will first see if there is an application
2119 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2120 // "-" and the name of the program. If this file doesn't exist, we fall
2121 // back to just the "~/.lldbinit" file. We also obey any requests to not
2122 // load the init files.
2123 const char *init_file_path = "~/.lldbinit";
2124
2125 if (m_skip_app_init_files == false)
2126 {
2127 FileSpec program_file_spec (Host::GetProgramFileSpec());
2128 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002129
Greg Claytond6edcb52011-09-11 00:01:44 +00002130 if (program_name)
2131 {
2132 char program_init_file_name[PATH_MAX];
2133 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2134 init_file.SetFile (program_init_file_name, true);
2135 if (!init_file.Exists())
2136 init_file.Clear();
2137 }
2138 }
2139
2140 if (!init_file && !m_skip_lldbinit_files)
2141 init_file.SetFile (init_file_path, true);
2142 }
2143
Chris Lattner24943d22010-06-08 16:52:24 +00002144 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2145 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2146
2147 if (init_file.Exists())
2148 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002149 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2150 bool stop_on_continue = true;
2151 bool stop_on_error = false;
2152 bool echo_commands = false;
2153 bool print_results = false;
2154
2155 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002156 }
2157 else
2158 {
2159 // nothing to be done if the file doesn't exist
2160 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2161 }
2162}
2163
Greg Claytonb72d0f02011-04-12 05:54:46 +00002164PlatformSP
2165CommandInterpreter::GetPlatform (bool prefer_target_platform)
2166{
2167 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002168 if (prefer_target_platform)
2169 {
2170 Target *target = m_exe_ctx.GetTargetPtr();
2171 if (target)
2172 platform_sp = target->GetPlatform();
2173 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002174
2175 if (!platform_sp)
2176 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2177 return platform_sp;
2178}
2179
Jim Ingham949d5ac2011-02-18 00:54:25 +00002180void
Jim Inghama4fede32011-03-11 01:51:49 +00002181CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002182 ExecutionContext *override_context,
2183 bool stop_on_continue,
2184 bool stop_on_error,
2185 bool echo_commands,
2186 bool print_results,
2187 CommandReturnObject &result)
2188{
2189 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002190
2191 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2192 // Make sure you reset this value anywhere you return from the function.
2193
2194 bool old_async_execution = m_debugger.GetAsyncExecution();
2195
2196 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2197 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2198
2199 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002200 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002201
2202 if (!stop_on_continue)
2203 {
2204 m_debugger.SetAsyncExecution (false);
2205 }
2206
2207 for (int idx = 0; idx < num_lines; idx++)
2208 {
2209 const char *cmd = commands.GetStringAtIndex(idx);
2210 if (cmd[0] == '\0')
2211 continue;
2212
Jim Ingham949d5ac2011-02-18 00:54:25 +00002213 if (echo_commands)
2214 {
2215 result.AppendMessageWithFormat ("%s %s\n",
2216 GetPrompt(),
2217 cmd);
2218 }
2219
Greg Claytonaa378b12011-02-20 02:15:07 +00002220 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002221 // If override_context is not NULL, pass no_context_switching = true for
2222 // HandleCommand() since we updated our context already.
2223 bool success = HandleCommand(cmd, false, tmp_result,
2224 NULL, /* override_context */
2225 true, /* repeat_on_empty_command */
2226 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002227
2228 if (print_results)
2229 {
2230 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002231 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002232 }
2233
2234 if (!success || !tmp_result.Succeeded())
2235 {
2236 if (stop_on_error)
2237 {
2238 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
2239 idx, cmd);
2240 result.SetStatus (eReturnStatusFailed);
2241 m_debugger.SetAsyncExecution (old_async_execution);
2242 return;
2243 }
2244 else if (print_results)
2245 {
2246 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
2247 idx + 1,
2248 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002249 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002250 }
2251 }
2252
Caroline Tice4a348082011-05-02 20:41:46 +00002253 if (result.GetImmediateOutputStream())
2254 result.GetImmediateOutputStream()->Flush();
2255
2256 if (result.GetImmediateErrorStream())
2257 result.GetImmediateErrorStream()->Flush();
2258
Jim Ingham949d5ac2011-02-18 00:54:25 +00002259 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2260 // could be running (for instance in Breakpoint Commands.
2261 // So we check the return value to see if it is has running in it.
2262 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2263 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2264 {
2265 if (stop_on_continue)
2266 {
2267 // If we caused the target to proceed, and we're going to stop in that case, set the
2268 // status in our real result before returning. This is an error if the continue was not the
2269 // last command in the set of commands to be run.
2270 if (idx != num_lines - 1)
2271 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2272 idx + 1, cmd);
2273 else
2274 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2275
2276 result.SetStatus(tmp_result.GetStatus());
2277 m_debugger.SetAsyncExecution (old_async_execution);
2278
2279 return;
2280 }
2281 }
2282
2283 }
2284
2285 result.SetStatus (eReturnStatusSuccessFinishResult);
2286 m_debugger.SetAsyncExecution (old_async_execution);
2287
2288 return;
2289}
2290
2291void
2292CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2293 ExecutionContext *context,
2294 bool stop_on_continue,
2295 bool stop_on_error,
2296 bool echo_command,
2297 bool print_result,
2298 CommandReturnObject &result)
2299{
2300 if (cmd_file.Exists())
2301 {
2302 bool success;
2303 StringList commands;
2304 success = commands.ReadFileLines(cmd_file);
2305 if (!success)
2306 {
2307 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2308 result.SetStatus (eReturnStatusFailed);
2309 return;
2310 }
2311 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
2312 }
2313 else
2314 {
2315 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2316 cmd_file.GetFilename().AsCString());
2317 result.SetStatus (eReturnStatusFailed);
2318 return;
2319 }
2320}
2321
Chris Lattner24943d22010-06-08 16:52:24 +00002322ScriptInterpreter *
2323CommandInterpreter::GetScriptInterpreter ()
2324{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002325 if (m_script_interpreter_ap.get() != NULL)
2326 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002327
Caroline Tice0aa2e552011-01-14 00:29:16 +00002328 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2329 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002330 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002331 case eScriptLanguagePython:
2332#ifndef LLDB_DISABLE_PYTHON
2333 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2334 break;
2335#else
2336 // Fall through to the None case when python is disabled
2337#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002338 case eScriptLanguageNone:
2339 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2340 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002341 default:
2342 break;
2343 };
2344
2345 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002346}
2347
2348
2349
2350bool
2351CommandInterpreter::GetSynchronous ()
2352{
2353 return m_synchronous_execution;
2354}
2355
2356void
2357CommandInterpreter::SetSynchronous (bool value)
2358{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002359 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002360}
2361
2362void
2363CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2364 const char *word_text,
2365 const char *separator,
2366 const char *help_text,
2367 uint32_t max_word_len)
2368{
Greg Clayton238c0a12010-09-18 01:14:36 +00002369 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2370
Chris Lattner24943d22010-06-08 16:52:24 +00002371 int indent_size = max_word_len + strlen (separator) + 2;
2372
2373 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002374
2375 StreamString text_strm;
2376 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2377
2378 size_t len = text_strm.GetSize();
2379 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002380 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002381 {
2382 text_strm.EOL();
2383 len = text_strm.GetSize();
2384 }
Chris Lattner24943d22010-06-08 16:52:24 +00002385
2386 if (len < max_columns)
2387 {
2388 // Output it as a single line.
2389 strm.Printf ("%s", text);
2390 }
2391 else
2392 {
2393 // We need to break it up into multiple lines.
2394 bool first_line = true;
2395 int text_width;
2396 int start = 0;
2397 int end = start;
2398 int final_end = strlen (text);
2399 int sub_len;
2400
2401 while (end < final_end)
2402 {
2403 if (first_line)
2404 text_width = max_columns - 1;
2405 else
2406 text_width = max_columns - indent_size - 1;
2407
2408 // Don't start the 'text' on a space, since we're already outputting the indentation.
2409 if (!first_line)
2410 {
2411 while ((start < final_end) && (text[start] == ' '))
2412 start++;
2413 }
2414
2415 end = start + text_width;
2416 if (end > final_end)
2417 end = final_end;
2418 else
2419 {
2420 // If we're not at the end of the text, make sure we break the line on white space.
2421 while (end > start
2422 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2423 end--;
2424 }
2425
2426 sub_len = end - start;
2427 if (start != 0)
2428 strm.EOL();
2429 if (!first_line)
2430 strm.Indent();
2431 else
2432 first_line = false;
2433 assert (start <= final_end);
2434 assert (start + sub_len <= final_end);
2435 if (sub_len > 0)
2436 strm.Write (text + start, sub_len);
2437 start = end + 1;
2438 }
2439 }
2440 strm.EOL();
2441 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002442}
2443
2444void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002445CommandInterpreter::OutputHelpText (Stream &strm,
2446 const char *word_text,
2447 const char *separator,
2448 const char *help_text,
2449 uint32_t max_word_len)
2450{
2451 int indent_size = max_word_len + strlen (separator) + 2;
2452
2453 strm.IndentMore (indent_size);
2454
2455 StreamString text_strm;
2456 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2457
2458 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2459 bool first_line = true;
2460
2461 size_t len = text_strm.GetSize();
2462 const char *text = text_strm.GetData();
2463
2464 uint32_t chars_left = max_columns;
2465
2466 for (uint32_t i = 0; i < len; i++)
2467 {
2468 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2469 {
2470 first_line = false;
2471 chars_left = max_columns - indent_size;
2472 strm.EOL();
2473 strm.Indent();
2474 }
2475 else
2476 {
2477 strm.PutChar(text[i]);
2478 chars_left--;
2479 }
2480
2481 }
2482
2483 strm.EOL();
2484 strm.IndentLess(indent_size);
2485}
2486
2487void
Chris Lattner24943d22010-06-08 16:52:24 +00002488CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2489 StringList &commands_found, StringList &commands_help)
2490{
2491 CommandObject::CommandMap::const_iterator pos;
2492 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2493 CommandObject *sub_cmd_obj;
2494
2495 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2496 {
2497 const char * command_name = pos->first.c_str();
2498 sub_cmd_obj = pos->second.get();
2499 StreamString complete_command_name;
2500
2501 complete_command_name.Printf ("%s %s", prefix, command_name);
2502
Greg Clayton238c0a12010-09-18 01:14:36 +00002503 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002504 {
2505 commands_found.AppendString (complete_command_name.GetData());
2506 commands_help.AppendString (sub_cmd_obj->GetHelp());
2507 }
2508
2509 if (sub_cmd_obj->IsMultiwordObject())
2510 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2511 commands_help);
2512 }
2513
2514}
2515
2516void
2517CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2518 StringList &commands_help)
2519{
2520 CommandObject::CommandMap::const_iterator pos;
2521
2522 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2523 {
2524 const char *command_name = pos->first.c_str();
2525 CommandObject *cmd_obj = pos->second.get();
2526
Greg Clayton238c0a12010-09-18 01:14:36 +00002527 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002528 {
2529 commands_found.AppendString (command_name);
2530 commands_help.AppendString (cmd_obj->GetHelp());
2531 }
2532
2533 if (cmd_obj->IsMultiwordObject())
2534 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2535
2536 }
2537}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002538
2539
2540void
2541CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2542{
2543 m_exe_ctx.Clear();
2544
2545 if (override_context != NULL)
2546 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002547 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002548 }
2549 else
2550 {
2551 TargetSP target_sp (m_debugger.GetSelectedTarget());
2552 if (target_sp)
2553 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002554 m_exe_ctx.SetTargetSP (target_sp);
2555 ProcessSP process_sp (target_sp->GetProcessSP());
2556 m_exe_ctx.SetProcessSP (process_sp);
2557 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002558 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002559 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread().get());
2560 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002561 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002562 m_exe_ctx.SetThreadSP (thread_sp);
2563 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2564 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002565 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002566 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002567 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002568 if (frame_sp)
2569 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002570 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002571 if (frame_sp)
2572 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002573 }
2574 }
2575 }
2576 }
2577}
2578
Jim Ingham6247dbe2011-07-12 03:12:18 +00002579void
2580CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2581{
2582 DumpHistory (stream, 0, count - 1);
2583}
2584
2585void
2586CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2587{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002588 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2589 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002590 {
2591 if (!m_command_history[i].empty())
2592 {
2593 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002594 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002595 }
2596 }
2597}
2598
2599const char *
2600CommandInterpreter::FindHistoryString (const char *input_str) const
2601{
2602 if (input_str[0] != m_repeat_char)
2603 return NULL;
2604 if (input_str[1] == '-')
2605 {
2606 bool success;
2607 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2608 if (!success)
2609 return NULL;
2610 if (idx > m_command_history.size())
2611 return NULL;
2612 idx = m_command_history.size() - idx;
2613 return m_command_history[idx].c_str();
2614
2615 }
2616 else if (input_str[1] == m_repeat_char)
2617 {
2618 if (m_command_history.empty())
2619 return NULL;
2620 else
2621 return m_command_history.back().c_str();
2622 }
2623 else
2624 {
2625 bool success;
2626 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2627 if (!success)
2628 return NULL;
2629 if (idx >= m_command_history.size())
2630 return NULL;
2631 return m_command_history[idx].c_str();
2632 }
2633}