blob: 8b4dc81561b77e11dd346a40e000053b639bf479 [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
Jim Ingham5a15e692012-02-16 06:50:00 +000062ConstString &
63CommandInterpreter::GetStaticBroadcasterClass ()
64{
65 static ConstString class_name ("lldb.commandInterpreter");
66 return class_name;
67}
68
Chris Lattner24943d22010-06-08 16:52:24 +000069CommandInterpreter::CommandInterpreter
70(
Greg Clayton63094e02010-06-23 01:19:29 +000071 Debugger &debugger,
Chris Lattner24943d22010-06-08 16:52:24 +000072 ScriptLanguage script_language,
Greg Clayton63094e02010-06-23 01:19:29 +000073 bool synchronous_execution
Chris Lattner24943d22010-06-08 16:52:24 +000074) :
Jim Ingham5a15e692012-02-16 06:50:00 +000075 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton63094e02010-06-23 01:19:29 +000076 m_debugger (debugger),
Greg Clayton887aa282010-10-11 01:05:37 +000077 m_synchronous_execution (synchronous_execution),
Caroline Tice0aa2e552011-01-14 00:29:16 +000078 m_skip_lldbinit_files (false),
Jim Ingham574c3d62011-08-12 23:34:31 +000079 m_skip_app_init_files (false),
Jim Ingham949d5ac2011-02-18 00:54:25 +000080 m_script_interpreter_ap (),
Caroline Tice892fadd2011-06-16 16:27:19 +000081 m_comment_char ('#'),
Jim Ingham6247dbe2011-07-12 03:12:18 +000082 m_repeat_char ('!'),
Enrico Granata293a7b32011-08-15 19:24:02 +000083 m_batch_command_mode (false),
84 m_truncation_warning(eNoTruncation)
Chris Lattner24943d22010-06-08 16:52:24 +000085{
Caroline Tice6e4c5ce2010-09-04 00:03:46 +000086 const char *dbg_name = debugger.GetInstanceName().AsCString();
87 std::string lang_name = ScriptInterpreter::LanguageToString (script_language);
88 StreamString var_name;
89 var_name.Printf ("[%s].script-lang", dbg_name);
Caroline Tice1d2aefd2010-09-09 06:25:08 +000090 debugger.GetSettingsController()->SetVariable (var_name.GetData(), lang_name.c_str(),
Greg Claytonb3448432011-03-24 21:19:54 +000091 eVarSetOperationAssign, false,
Greg Clayton49ce6822010-10-31 03:01:06 +000092 m_debugger.GetInstanceName().AsCString());
93 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
94 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
95 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham5a15e692012-02-16 06:50:00 +000096
97 CheckInWithManager ();
Chris Lattner24943d22010-06-08 16:52:24 +000098}
99
100void
101CommandInterpreter::Initialize ()
102{
103 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
104
105 CommandReturnObject result;
106
107 LoadCommandDictionary ();
108
Chris Lattner24943d22010-06-08 16:52:24 +0000109 // Set up some initial aliases.
Caroline Tice5ddbe212011-05-06 21:37:15 +0000110 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
111 if (cmd_obj_sp)
112 {
113 AddAlias ("q", cmd_obj_sp);
114 AddAlias ("exit", cmd_obj_sp);
115 }
116
117 cmd_obj_sp = GetCommandSPExact ("process continue", false);
118 if (cmd_obj_sp)
119 {
120 AddAlias ("c", cmd_obj_sp);
121 AddAlias ("continue", cmd_obj_sp);
122 }
123
124 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
125 if (cmd_obj_sp)
126 AddAlias ("b", cmd_obj_sp);
127
128 cmd_obj_sp = GetCommandSPExact ("thread backtrace", false);
129 if (cmd_obj_sp)
130 AddAlias ("bt", cmd_obj_sp);
131
132 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
133 if (cmd_obj_sp)
Jason Molenda47eb00e2011-10-22 00:47:41 +0000134 {
135 AddAlias ("stepi", cmd_obj_sp);
Caroline Tice5ddbe212011-05-06 21:37:15 +0000136 AddAlias ("si", cmd_obj_sp);
Jason Molenda47eb00e2011-10-22 00:47:41 +0000137 }
138
139 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
140 if (cmd_obj_sp)
141 {
142 AddAlias ("nexti", cmd_obj_sp);
143 AddAlias ("ni", cmd_obj_sp);
144 }
Caroline Tice5ddbe212011-05-06 21:37:15 +0000145
146 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
147 if (cmd_obj_sp)
148 {
149 AddAlias ("s", cmd_obj_sp);
150 AddAlias ("step", cmd_obj_sp);
151 }
152
153 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
154 if (cmd_obj_sp)
155 {
156 AddAlias ("n", cmd_obj_sp);
157 AddAlias ("next", cmd_obj_sp);
158 }
159
160 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
161 if (cmd_obj_sp)
162 {
Caroline Tice5ddbe212011-05-06 21:37:15 +0000163 AddAlias ("finish", cmd_obj_sp);
164 }
165
Jim Ingham59355252011-12-02 01:12:59 +0000166 cmd_obj_sp = GetCommandSPExact ("frame select", false);
167 if (cmd_obj_sp)
168 {
169 AddAlias ("f", cmd_obj_sp);
170 }
171
Caroline Tice5ddbe212011-05-06 21:37:15 +0000172 cmd_obj_sp = GetCommandSPExact ("source list", false);
173 if (cmd_obj_sp)
174 {
175 AddAlias ("l", cmd_obj_sp);
176 AddAlias ("list", cmd_obj_sp);
177 }
178
179 cmd_obj_sp = GetCommandSPExact ("memory read", false);
180 if (cmd_obj_sp)
181 AddAlias ("x", cmd_obj_sp);
182
183 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
184 if (cmd_obj_sp)
185 AddAlias ("up", cmd_obj_sp);
186
187 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
188 if (cmd_obj_sp)
189 AddAlias ("down", cmd_obj_sp);
190
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000191 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000192 if (cmd_obj_sp)
193 AddAlias ("display", cmd_obj_sp);
Jim Ingham9d1acc12011-10-24 18:37:00 +0000194
195 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
196 if (cmd_obj_sp)
197 AddAlias ("dis", cmd_obj_sp);
198
199 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
200 if (cmd_obj_sp)
201 AddAlias ("di", cmd_obj_sp);
202
203
Jason Molenda730cae02011-10-22 01:30:52 +0000204
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000205 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molenda730cae02011-10-22 01:30:52 +0000206 if (cmd_obj_sp)
207 AddAlias ("undisplay", cmd_obj_sp);
208
Caroline Tice5ddbe212011-05-06 21:37:15 +0000209 cmd_obj_sp = GetCommandSPExact ("target create", false);
210 if (cmd_obj_sp)
211 AddAlias ("file", cmd_obj_sp);
212
213 cmd_obj_sp = GetCommandSPExact ("target modules", false);
214 if (cmd_obj_sp)
215 AddAlias ("image", cmd_obj_sp);
216
217
218 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghame56493f2011-03-22 02:29:32 +0000219
Caroline Tice5ddbe212011-05-06 21:37:15 +0000220 cmd_obj_sp = GetCommandSPExact ("expression", false);
221 if (cmd_obj_sp)
222 {
223 AddAlias ("expr", cmd_obj_sp);
224
225 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
226 AddAlias ("p", cmd_obj_sp);
227 AddAlias ("print", cmd_obj_sp);
228 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
229 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
230
231 alias_arguments_vector_sp.reset (new OptionArgVector);
232 ProcessAliasOptionsArgs (cmd_obj_sp, "-o --", alias_arguments_vector_sp);
233 AddAlias ("po", cmd_obj_sp);
234 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
235 }
236
237 cmd_obj_sp = GetCommandSPExact ("process launch", false);
238 if (cmd_obj_sp)
239 {
240 alias_arguments_vector_sp.reset (new OptionArgVector);
241 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
242 AddAlias ("r", cmd_obj_sp);
243 AddAlias ("run", cmd_obj_sp);
244 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
245 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
246 }
Chris Lattner24943d22010-06-08 16:52:24 +0000247}
248
Chris Lattner24943d22010-06-08 16:52:24 +0000249const char *
250CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
251{
252 // This function has not yet been implemented.
253
254 // Look for any embedded script command
255 // If found,
256 // get interpreter object from the command dictionary,
257 // call execute_one_command on it,
258 // get the results as a string,
259 // substitute that string for current stuff.
260
261 return arg;
262}
263
264
265void
266CommandInterpreter::LoadCommandDictionary ()
267{
268 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
269
270 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
271 //
272 // Command objects that are used as cross reference objects (i.e. they inherit from CommandObjectCrossref)
273 // *MUST* be created and put into the command dictionary *BEFORE* any multi-word commands (which may use
274 // the cross-referencing stuff) are created!!!
275 //
276 // **** IMPORTANT **** IMPORTANT *** IMPORTANT *** **** IMPORTANT **** IMPORTANT *** IMPORTANT ***
277
278
279 // Command objects that inherit from CommandObjectCrossref must be created before other command objects
280 // are created. This is so that when another command is created that needs to go into a crossref object,
281 // the crossref object exists and is ready to take the cross reference. Put the cross referencing command
282 // objects into the CommandDictionary now, so they are ready for use when the other commands get created.
283
Chris Lattner24943d22010-06-08 16:52:24 +0000284 // Non-CommandObjectCrossref commands can now be created.
285
Caroline Tice5bc8c972010-09-20 20:44:43 +0000286 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000287
Greg Clayton238c0a12010-09-18 01:14:36 +0000288 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000289 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000290 //m_command_dict["call"] = CommandObjectSP (new CommandObjectCall (*this));
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000291 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000292 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
293 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Claytonabe0fed2011-04-18 08:33:37 +0000294// m_command_dict["file"] = CommandObjectSP (new CommandObjectFile (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000295 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000296 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Claytone1f50b92011-05-03 22:09:39 +0000297 /// m_command_dict["image"] = CommandObjectSP (new CommandObjectImage (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000298 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
299 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonb1888f22011-03-19 01:12:21 +0000300 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000301 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000302 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000303 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Clayton238c0a12010-09-18 01:14:36 +0000304 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice6e4c5ce2010-09-04 00:03:46 +0000305 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Ingham767af882010-07-07 03:36:20 +0000306 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton63094e02010-06-23 01:19:29 +0000307 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
308 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata6b1596d2011-08-16 23:24:13 +0000309 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen902e0182010-12-23 20:21:44 +0000310 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chen01acfa72011-09-22 18:04:58 +0000311 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner24943d22010-06-08 16:52:24 +0000312
313 std::auto_ptr<CommandObjectRegexCommand>
Greg Clayton238c0a12010-09-18 01:14:36 +0000314 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000315 "_regexp-break",
Caroline Ticec1ad82e2010-09-07 22:38:08 +0000316 "Set a breakpoint using a regular expression to specify the location.",
Greg Claytonb72d0f02011-04-12 05:54:46 +0000317 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2));
Chris Lattner24943d22010-06-08 16:52:24 +0000318 if (break_regex_cmd_ap.get())
319 {
320 if (break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2") &&
321 break_regex_cmd_ap->AddRegexCommand("^(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1") &&
322 break_regex_cmd_ap->AddRegexCommand("^[\"']?([-+]\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'") &&
Greg Claytonb72d0f02011-04-12 05:54:46 +0000323 break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000324 break_regex_cmd_ap->AddRegexCommand("^(-.*)$", "breakpoint set %1") &&
Greg Claytonb01000f2011-01-17 03:46:26 +0000325 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'") &&
Chris Lattner24943d22010-06-08 16:52:24 +0000326 break_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"))
327 {
328 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
329 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
330 }
331 }
Jim Inghame56493f2011-03-22 02:29:32 +0000332
333 std::auto_ptr<CommandObjectRegexCommand>
334 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000335 "_regexp-down",
336 "Go down \"n\" frames in the stack (1 frame by default).",
337 "_regexp-down [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000338 if (down_regex_cmd_ap.get())
339 {
340 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
341 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
342 {
343 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
344 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
345 }
346 }
347
348 std::auto_ptr<CommandObjectRegexCommand>
349 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb72d0f02011-04-12 05:54:46 +0000350 "_regexp-up",
351 "Go up \"n\" frames in the stack (1 frame by default).",
352 "_regexp-up [n]", 2));
Jim Inghame56493f2011-03-22 02:29:32 +0000353 if (up_regex_cmd_ap.get())
354 {
355 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
356 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
357 {
358 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
359 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
360 }
361 }
Jason Molenda730cae02011-10-22 01:30:52 +0000362
363 std::auto_ptr<CommandObjectRegexCommand>
364 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000365 "_regexp-display",
Jason Molenda730cae02011-10-22 01:30:52 +0000366 "Add an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000367 "_regexp-display expression", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000368 if (display_regex_cmd_ap.get())
369 {
370 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
371 {
372 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
373 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
374 }
375 }
376
377 std::auto_ptr<CommandObjectRegexCommand>
378 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000379 "_regexp-undisplay",
Jason Molenda730cae02011-10-22 01:30:52 +0000380 "Remove an expression evaluation stop-hook.",
Jason Molenda3f2ec9b2011-10-25 02:11:20 +0000381 "_regexp-undisplay stop-hook-number", 2));
Jason Molenda730cae02011-10-22 01:30:52 +0000382 if (undisplay_regex_cmd_ap.get())
383 {
384 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
385 {
386 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
387 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
388 }
389 }
390
Chris Lattner24943d22010-06-08 16:52:24 +0000391}
392
393int
394CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
395 StringList &matches)
396{
397 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
398
399 if (include_aliases)
400 {
401 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
402 }
403
404 return matches.GetSize();
405}
406
407CommandObjectSP
408CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
409{
410 CommandObject::CommandMap::iterator pos;
411 CommandObjectSP ret_val;
412
413 std::string cmd(cmd_cstr);
414
415 if (HasCommands())
416 {
417 pos = m_command_dict.find(cmd);
418 if (pos != m_command_dict.end())
419 ret_val = pos->second;
420 }
421
422 if (include_aliases && HasAliases())
423 {
424 pos = m_alias_dict.find(cmd);
425 if (pos != m_alias_dict.end())
426 ret_val = pos->second;
427 }
428
429 if (HasUserCommands())
430 {
431 pos = m_user_dict.find(cmd);
432 if (pos != m_user_dict.end())
433 ret_val = pos->second;
434 }
435
436 if (!exact && ret_val == NULL)
437 {
Jim Inghamd40f8a62010-07-06 22:46:59 +0000438 // We will only get into here if we didn't find any exact matches.
439
440 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
441
Chris Lattner24943d22010-06-08 16:52:24 +0000442 StringList local_matches;
443 if (matches == NULL)
444 matches = &local_matches;
445
Jim Inghamd40f8a62010-07-06 22:46:59 +0000446 unsigned int num_cmd_matches = 0;
447 unsigned int num_alias_matches = 0;
448 unsigned int num_user_matches = 0;
449
450 // Look through the command dictionaries one by one, and if we get only one match from any of
451 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
452
Chris Lattner24943d22010-06-08 16:52:24 +0000453 if (HasCommands())
454 {
455 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
456 }
457
458 if (num_cmd_matches == 1)
459 {
460 cmd.assign(matches->GetStringAtIndex(0));
461 pos = m_command_dict.find(cmd);
462 if (pos != m_command_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000463 real_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000464 }
465
Jim Ingham9a574172010-06-24 20:28:42 +0000466 if (include_aliases && HasAliases())
Chris Lattner24943d22010-06-08 16:52:24 +0000467 {
468 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
469
470 }
471
Jim Inghamd40f8a62010-07-06 22:46:59 +0000472 if (num_alias_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000473 {
474 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
475 pos = m_alias_dict.find(cmd);
476 if (pos != m_alias_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000477 alias_match_sp = pos->second;
Chris Lattner24943d22010-06-08 16:52:24 +0000478 }
479
Jim Ingham9a574172010-06-24 20:28:42 +0000480 if (HasUserCommands())
Chris Lattner24943d22010-06-08 16:52:24 +0000481 {
482 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
483 }
484
Jim Inghamd40f8a62010-07-06 22:46:59 +0000485 if (num_user_matches == 1)
Chris Lattner24943d22010-06-08 16:52:24 +0000486 {
487 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
488
489 pos = m_user_dict.find (cmd);
490 if (pos != m_user_dict.end())
Jim Inghamd40f8a62010-07-06 22:46:59 +0000491 user_match_sp = pos->second;
492 }
493
494 // If we got exactly one match, return that, otherwise return the match list.
495
496 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
497 {
498 if (num_cmd_matches)
499 return real_match_sp;
500 else if (num_alias_matches)
501 return alias_match_sp;
502 else
503 return user_match_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000504 }
505 }
Jim Inghamd40f8a62010-07-06 22:46:59 +0000506 else if (matches && ret_val != NULL)
507 {
508 matches->AppendString (cmd_cstr);
Chris Lattner24943d22010-06-08 16:52:24 +0000509 }
510
511
512 return ret_val;
513}
514
Greg Claytond12aeab2011-04-20 16:37:46 +0000515bool
516CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
517{
518 if (name && name[0])
519 {
520 std::string name_sstr(name);
521 if (!can_replace)
522 {
523 if (m_command_dict.find (name_sstr) != m_command_dict.end())
524 return false;
525 }
526 m_command_dict[name_sstr] = cmd_sp;
527 return true;
528 }
529 return false;
530}
531
Enrico Granata6b1596d2011-08-16 23:24:13 +0000532bool
Enrico Granata6010ace2011-11-07 22:57:04 +0000533CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata6b1596d2011-08-16 23:24:13 +0000534 const lldb::CommandObjectSP &cmd_sp,
535 bool can_replace)
536{
Enrico Granata6010ace2011-11-07 22:57:04 +0000537 if (!name.empty())
Enrico Granata6b1596d2011-08-16 23:24:13 +0000538 {
Enrico Granata6010ace2011-11-07 22:57:04 +0000539
540 const char* name_cstr = name.c_str();
541
542 // do not allow replacement of internal commands
543 if (CommandExists(name_cstr))
544 return false;
545
546 if (can_replace == false && UserCommandExists(name_cstr))
547 return false;
548
549 m_user_dict[name] = cmd_sp;
Enrico Granata6b1596d2011-08-16 23:24:13 +0000550 return true;
551 }
552 return false;
553}
Greg Claytond12aeab2011-04-20 16:37:46 +0000554
Jim Inghamd40f8a62010-07-06 22:46:59 +0000555CommandObjectSP
556CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner24943d22010-06-08 16:52:24 +0000557{
Caroline Tice56d2fc42010-12-14 18:51:39 +0000558 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
559 CommandObjectSP ret_val; // Possibly empty return value.
560
561 if (cmd_cstr == NULL)
562 return ret_val;
563
564 if (cmd_words.GetArgumentCount() == 1)
565 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
566 else
567 {
568 // We have a multi-word command (seemingly), so we need to do more work.
569 // First, get the cmd_obj_sp for the first word in the command.
570 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
571 if (cmd_obj_sp.get() != NULL)
572 {
573 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
574 // command name), and find the appropriate sub-command SP for each command word....
575 size_t end = cmd_words.GetArgumentCount();
576 for (size_t j= 1; j < end; ++j)
577 {
578 if (cmd_obj_sp->IsMultiwordObject())
579 {
580 cmd_obj_sp = ((CommandObjectMultiword *) cmd_obj_sp.get())->GetSubcommandSP
581 (cmd_words.GetArgumentAtIndex (j));
582 if (cmd_obj_sp.get() == NULL)
583 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
584 return ret_val;
585 }
586 else
587 // We have more words in the command name, but we don't have a multiword object. Fail and return
588 // empty 'ret_val'.
589 return ret_val;
590 }
591 // We successfully looped through all the command words and got valid command objects for them. Assign the
592 // last object retrieved to 'ret_val'.
593 ret_val = cmd_obj_sp;
594 }
595 }
596 return ret_val;
Jim Inghamd40f8a62010-07-06 22:46:59 +0000597}
598
599CommandObject *
600CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
601{
602 return GetCommandSPExact (cmd_cstr, include_aliases).get();
603}
604
605CommandObject *
606CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
607{
608 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
609
610 // If we didn't find an exact match to the command string in the commands, look in
611 // the aliases.
612
613 if (command_obj == NULL)
614 {
615 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
616 }
617
618 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
619 // in both the commands and the aliases.
620
621 if (command_obj == NULL)
622 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
623
624 return command_obj;
Chris Lattner24943d22010-06-08 16:52:24 +0000625}
626
627bool
628CommandInterpreter::CommandExists (const char *cmd)
629{
630 return m_command_dict.find(cmd) != m_command_dict.end();
631}
632
633bool
Caroline Tice5ddbe212011-05-06 21:37:15 +0000634CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
635 const char *options_args,
636 OptionArgVectorSP &option_arg_vector_sp)
637{
638 bool success = true;
639 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
640
641 if (!options_args || (strlen (options_args) < 1))
642 return true;
643
644 std::string options_string (options_args);
645 Args args (options_args);
646 CommandReturnObject result;
647 // Check to see if the command being aliased can take any command options.
648 Options *options = cmd_obj_sp->GetOptions ();
649 if (options)
650 {
651 // See if any options were specified as part of the alias; if so, handle them appropriately.
652 options->NotifyOptionParsingStarting ();
653 args.Unshift ("dummy_arg");
654 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
655 args.Shift ();
656 if (result.Succeeded())
657 options->VerifyPartialOptions (result);
658 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
659 {
660 result.AppendError ("Unable to create requested alias.\n");
661 return false;
662 }
663 }
664
Greg Clayton7268b4c2011-10-28 21:38:01 +0000665 if (!options_string.empty())
Caroline Tice5ddbe212011-05-06 21:37:15 +0000666 {
667 if (cmd_obj_sp->WantsRawCommandString ())
668 option_arg_vector->push_back (OptionArgPair ("<argument>",
669 OptionArgValue (-1,
670 options_string)));
671 else
672 {
673 int argc = args.GetArgumentCount();
674 for (size_t i = 0; i < argc; ++i)
675 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
676 option_arg_vector->push_back
677 (OptionArgPair ("<argument>",
678 OptionArgValue (-1,
679 std::string (args.GetArgumentAtIndex (i)))));
680 }
681 }
682
683 return success;
684}
685
686bool
Chris Lattner24943d22010-06-08 16:52:24 +0000687CommandInterpreter::AliasExists (const char *cmd)
688{
689 return m_alias_dict.find(cmd) != m_alias_dict.end();
690}
691
692bool
693CommandInterpreter::UserCommandExists (const char *cmd)
694{
695 return m_user_dict.find(cmd) != m_user_dict.end();
696}
697
698void
699CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
700{
Jim Inghamd40f8a62010-07-06 22:46:59 +0000701 command_obj_sp->SetIsAlias (true);
Chris Lattner24943d22010-06-08 16:52:24 +0000702 m_alias_dict[alias_name] = command_obj_sp;
703}
704
705bool
706CommandInterpreter::RemoveAlias (const char *alias_name)
707{
708 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
709 if (pos != m_alias_dict.end())
710 {
711 m_alias_dict.erase(pos);
712 return true;
713 }
714 return false;
715}
716bool
717CommandInterpreter::RemoveUser (const char *alias_name)
718{
719 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
720 if (pos != m_user_dict.end())
721 {
722 m_user_dict.erase(pos);
723 return true;
724 }
725 return false;
726}
727
Chris Lattner24943d22010-06-08 16:52:24 +0000728void
729CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
730{
731 help_string.Printf ("'%s", command_name);
732 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
733
734 if (option_arg_vector_sp != NULL)
735 {
736 OptionArgVector *options = option_arg_vector_sp.get();
737 for (int i = 0; i < options->size(); ++i)
738 {
739 OptionArgPair cur_option = (*options)[i];
740 std::string opt = cur_option.first;
Caroline Tice44c841d2010-12-07 19:58:26 +0000741 OptionArgValue value_pair = cur_option.second;
742 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +0000743 if (opt.compare("<argument>") == 0)
744 {
745 help_string.Printf (" %s", value.c_str());
746 }
747 else
748 {
749 help_string.Printf (" %s", opt.c_str());
750 if ((value.compare ("<no-argument>") != 0)
751 && (value.compare ("<need-argument") != 0))
752 {
753 help_string.Printf (" %s", value.c_str());
754 }
755 }
756 }
757 }
758
759 help_string.Printf ("'");
760}
761
Greg Clayton65124ea2010-08-26 22:05:43 +0000762size_t
Chris Lattner24943d22010-06-08 16:52:24 +0000763CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
764{
765 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000766 CommandObject::CommandMap::const_iterator end = dict.end();
767 size_t max_len = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000768
Greg Clayton65124ea2010-08-26 22:05:43 +0000769 for (pos = dict.begin(); pos != end; ++pos)
770 {
771 size_t len = pos->first.size();
772 if (max_len < len)
773 max_len = len;
Chris Lattner24943d22010-06-08 16:52:24 +0000774 }
Greg Clayton65124ea2010-08-26 22:05:43 +0000775 return max_len;
Chris Lattner24943d22010-06-08 16:52:24 +0000776}
777
778void
Enrico Granata6b1596d2011-08-16 23:24:13 +0000779CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata1ac6d1f2011-09-09 17:49:36 +0000780 uint32_t cmd_types)
Chris Lattner24943d22010-06-08 16:52:24 +0000781{
782 CommandObject::CommandMap::const_iterator pos;
Greg Clayton65124ea2010-08-26 22:05:43 +0000783 uint32_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata6b1596d2011-08-16 23:24:13 +0000784
785 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner24943d22010-06-08 16:52:24 +0000786 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000787
788 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
789 result.AppendMessage("");
Chris Lattner24943d22010-06-08 16:52:24 +0000790
Enrico Granata6b1596d2011-08-16 23:24:13 +0000791 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
792 {
793 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
794 max_len);
795 }
796 result.AppendMessage("");
797
798 }
799
Greg Clayton7268b4c2011-10-28 21:38:01 +0000800 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner24943d22010-06-08 16:52:24 +0000801 {
Jim Inghame3663e82010-10-22 18:47:16 +0000802 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chen9e4c3d72011-04-21 00:39:18 +0000803 "(see 'help command alias' for more info):");
Chris Lattner24943d22010-06-08 16:52:24 +0000804 result.AppendMessage("");
Greg Clayton65124ea2010-08-26 22:05:43 +0000805 max_len = FindLongestCommandWord (m_alias_dict);
806
Chris Lattner24943d22010-06-08 16:52:24 +0000807 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
808 {
809 StreamString sstr;
810 StreamString translation_and_help;
811 std::string entry_name = pos->first;
812 std::string second_entry = pos->second.get()->GetCommandName();
813 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
814
815 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
816 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
817 translation_and_help.GetData(), max_len);
818 }
819 result.AppendMessage("");
820 }
821
Greg Clayton7268b4c2011-10-28 21:38:01 +0000822 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner24943d22010-06-08 16:52:24 +0000823 {
824 result.AppendMessage ("The following is a list of your current user-defined commands:");
825 result.AppendMessage("");
Enrico Granata6b1596d2011-08-16 23:24:13 +0000826 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner24943d22010-06-08 16:52:24 +0000827 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
828 {
Enrico Granata6b1596d2011-08-16 23:24:13 +0000829 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
830 max_len);
Chris Lattner24943d22010-06-08 16:52:24 +0000831 }
832 result.AppendMessage("");
833 }
834
835 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
836}
837
Caroline Ticee0da7a52010-12-09 22:52:49 +0000838CommandObject *
839CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner24943d22010-06-08 16:52:24 +0000840{
Caroline Ticee0da7a52010-12-09 22:52:49 +0000841 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
842 // eventually be invoked by the given command line.
843
844 CommandObject *cmd_obj = NULL;
845 std::string white_space (" \t\v");
846 size_t start = command_string.find_first_not_of (white_space);
847 size_t end = 0;
848 bool done = false;
849 while (!done)
850 {
851 if (start != std::string::npos)
852 {
853 // Get the next word from command_string.
854 end = command_string.find_first_of (white_space, start);
855 if (end == std::string::npos)
856 end = command_string.size();
857 std::string cmd_word = command_string.substr (start, end - start);
858
859 if (cmd_obj == NULL)
860 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
861 // command or alias.
862 cmd_obj = GetCommandObject (cmd_word.c_str());
863 else if (cmd_obj->IsMultiwordObject ())
864 {
865 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
866 CommandObject *sub_cmd_obj =
867 ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (cmd_word.c_str());
868 if (sub_cmd_obj)
869 cmd_obj = sub_cmd_obj;
870 else // cmd_word was not a valid sub-command word, so we are donee
871 done = true;
872 }
873 else
874 // We have a cmd_obj and it is not a multi-word object, so we are done.
875 done = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000876
Caroline Ticee0da7a52010-12-09 22:52:49 +0000877 // If we didn't find a valid command object, or our command object is not a multi-word object, or
878 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
879 // next word.
880
881 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
882 done = true;
883 else
884 start = command_string.find_first_not_of (white_space, end);
885 }
886 else
887 // Unable to find any more words.
888 done = true;
889 }
890
891 if (end == command_string.size())
892 command_string.clear();
893 else
894 command_string = command_string.substr(end);
895
896 return cmd_obj;
897}
898
Greg Clayton9d855c62011-10-25 00:36:27 +0000899static const char *k_white_space = " \t\v";
Greg Clayton7268b4c2011-10-28 21:38:01 +0000900static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton9d855c62011-10-25 00:36:27 +0000901static void
902StripLeadingSpaces (std::string &s)
Caroline Ticee0da7a52010-12-09 22:52:49 +0000903{
Greg Clayton9d855c62011-10-25 00:36:27 +0000904 if (!s.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +0000905 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000906 size_t pos = s.find_first_not_of (k_white_space);
907 if (pos == std::string::npos)
908 s.clear();
909 else if (pos == 0)
910 return;
911 s.erase (0, pos);
912 }
913}
914
Greg Clayton3840cd72011-11-09 23:25:03 +0000915static size_t
916FindArgumentTerminator (const std::string &s)
917{
Greg Clayton3840cd72011-11-09 23:25:03 +0000918 const size_t s_len = s.size();
919 size_t offset = 0;
920 while (offset < s_len)
921 {
922 size_t pos = s.find ("--", offset);
923 if (pos == std::string::npos)
924 break;
925 if (pos > 0)
926 {
927 if (isspace(s[pos-1]))
928 {
929 // Check if the string ends "\s--" (where \s is a space character)
930 // or if we have "\s--\s".
931 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
932 {
Greg Clayton3840cd72011-11-09 23:25:03 +0000933 return pos;
934 }
935 }
936 }
937 offset = pos + 2;
938 }
Greg Clayton3840cd72011-11-09 23:25:03 +0000939 return std::string::npos;
940}
941
Greg Clayton9d855c62011-10-25 00:36:27 +0000942static bool
Greg Clayton7268b4c2011-10-28 21:38:01 +0000943ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton9d855c62011-10-25 00:36:27 +0000944{
Greg Clayton7268b4c2011-10-28 21:38:01 +0000945 command.clear();
946 suffix.clear();
Greg Clayton9d855c62011-10-25 00:36:27 +0000947 StripLeadingSpaces (command_string);
948
949 bool result = false;
950 quote_char = '\0';
951
952 if (!command_string.empty())
953 {
954 const char first_char = command_string[0];
955 if (first_char == '\'' || first_char == '"')
Caroline Ticee0da7a52010-12-09 22:52:49 +0000956 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000957 quote_char = first_char;
958 const size_t end_quote_pos = command_string.find (quote_char, 1);
959 if (end_quote_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000960 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000961 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000962 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000963 }
964 else
965 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000966 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton9d855c62011-10-25 00:36:27 +0000967 if (end_quote_pos + 1 < command_string.size())
968 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
969 else
970 command_string.erase ();
Caroline Tice649116c2011-05-11 16:07:06 +0000971 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000972 }
973 else
974 {
Greg Clayton9d855c62011-10-25 00:36:27 +0000975 const size_t first_space_pos = command_string.find_first_of (k_white_space);
976 if (first_space_pos == std::string::npos)
Caroline Tice649116c2011-05-11 16:07:06 +0000977 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000978 command.swap (command_string);
Greg Clayton9d855c62011-10-25 00:36:27 +0000979 command_string.erase();
Caroline Tice649116c2011-05-11 16:07:06 +0000980 }
981 else
982 {
Greg Clayton7268b4c2011-10-28 21:38:01 +0000983 command.assign (command_string, 0, first_space_pos);
984 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice649116c2011-05-11 16:07:06 +0000985 }
Caroline Ticee0da7a52010-12-09 22:52:49 +0000986 }
Greg Clayton9d855c62011-10-25 00:36:27 +0000987 result = true;
Caroline Ticee0da7a52010-12-09 22:52:49 +0000988 }
Greg Clayton7268b4c2011-10-28 21:38:01 +0000989
990
991 if (!command.empty())
992 {
993 // actual commands can't start with '-' or '_'
994 if (command[0] != '-' && command[0] != '_')
995 {
996 size_t pos = command.find_first_not_of(k_valid_command_chars);
997 if (pos > 0 && pos != std::string::npos)
998 {
999 suffix.assign (command.begin() + pos, command.end());
1000 command.erase (pos);
1001 }
1002 }
1003 }
Greg Clayton9d855c62011-10-25 00:36:27 +00001004
1005 return result;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001006}
1007
Greg Clayton7268b4c2011-10-28 21:38:01 +00001008CommandObject *
1009CommandInterpreter::BuildAliasResult (const char *alias_name,
1010 std::string &raw_input_string,
1011 std::string &alias_result,
1012 CommandReturnObject &result)
Caroline Ticee0da7a52010-12-09 22:52:49 +00001013{
Greg Clayton7268b4c2011-10-28 21:38:01 +00001014 CommandObject *alias_cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001015 Args cmd_args (raw_input_string.c_str());
1016 alias_cmd_obj = GetCommandObject (alias_name);
1017 StreamString result_str;
1018
1019 if (alias_cmd_obj)
1020 {
1021 std::string alias_name_str = alias_name;
1022 if ((cmd_args.GetArgumentCount() == 0)
1023 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1024 cmd_args.Unshift (alias_name);
1025
1026 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1027 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1028
1029 if (option_arg_vector_sp.get())
1030 {
1031 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1032
1033 for (int i = 0; i < option_arg_vector->size(); ++i)
1034 {
1035 OptionArgPair option_pair = (*option_arg_vector)[i];
1036 OptionArgValue value_pair = option_pair.second;
1037 int value_type = value_pair.first;
1038 std::string option = option_pair.first;
1039 std::string value = value_pair.second;
1040 if (option.compare ("<argument>") == 0)
1041 result_str.Printf (" %s", value.c_str());
1042 else
1043 {
1044 result_str.Printf (" %s", option.c_str());
1045 if (value_type != optional_argument)
1046 result_str.Printf (" ");
1047 if (value.compare ("<no_argument>") != 0)
1048 {
1049 int index = GetOptionArgumentPosition (value.c_str());
1050 if (index == 0)
1051 result_str.Printf ("%s", value.c_str());
1052 else if (index >= cmd_args.GetArgumentCount())
1053 {
1054
1055 result.AppendErrorWithFormat
1056 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1057 index);
1058 result.SetStatus (eReturnStatusFailed);
Greg Clayton7268b4c2011-10-28 21:38:01 +00001059 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001060 }
1061 else
1062 {
1063 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1064 if (strpos != std::string::npos)
1065 raw_input_string = raw_input_string.erase (strpos,
1066 strlen (cmd_args.GetArgumentAtIndex (index)));
1067 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1068 }
1069 }
1070 }
1071 }
1072 }
1073
1074 alias_result = result_str.GetData();
1075 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001076 return alias_cmd_obj;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001077}
1078
Greg Claytonf5c0c722011-10-14 07:41:33 +00001079Error
1080CommandInterpreter::PreprocessCommand (std::string &command)
1081{
1082 // The command preprocessor needs to do things to the command
1083 // line before any parsing of arguments or anything else is done.
1084 // The only current stuff that gets proprocessed is anyting enclosed
1085 // in backtick ('`') characters is evaluated as an expression and
1086 // the result of the expression must be a scalar that can be substituted
1087 // into the command. An example would be:
1088 // (lldb) memory read `$rsp + 20`
1089 Error error; // Error for any expressions that might not evaluate
1090 size_t start_backtick;
1091 size_t pos = 0;
1092 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1093 {
1094 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1095 {
1096 // The backtick was preceeded by a '\' character, remove the slash
1097 // and don't treat the backtick as the start of an expression
1098 command.erase(start_backtick-1, 1);
1099 // No need to add one to start_backtick since we just deleted a char
1100 pos = start_backtick;
1101 }
1102 else
1103 {
1104 const size_t expr_content_start = start_backtick + 1;
1105 const size_t end_backtick = command.find ('`', expr_content_start);
1106 if (end_backtick == std::string::npos)
1107 return error;
1108 else if (end_backtick == expr_content_start)
1109 {
1110 // Empty expression (two backticks in a row)
1111 command.erase (start_backtick, 2);
1112 }
1113 else
1114 {
1115 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1116
1117 Target *target = m_exe_ctx.GetTargetPtr();
Johnny Chenb09f8472011-10-29 00:21:50 +00001118 // Get a dummy target to allow for calculator mode while processing backticks.
1119 // This also helps break the infinite loop caused when target is null.
1120 if (!target)
1121 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Claytonf5c0c722011-10-14 07:41:33 +00001122 if (target)
1123 {
Sean Callanandaa6efe2011-12-21 22:22:58 +00001124 const bool coerce_to_id = false;
Greg Claytonf5c0c722011-10-14 07:41:33 +00001125 const bool unwind_on_error = true;
1126 const bool keep_in_memory = false;
1127 ValueObjectSP expr_result_valobj_sp;
1128 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
1129 m_exe_ctx.GetFramePtr(),
1130 eExecutionPolicyOnlyWhenNeeded,
Sean Callanandaa6efe2011-12-21 22:22:58 +00001131 coerce_to_id,
1132 unwind_on_error,
1133 keep_in_memory,
Greg Claytonf5c0c722011-10-14 07:41:33 +00001134 eNoDynamicValues,
1135 expr_result_valobj_sp);
1136 if (expr_result == eExecutionCompleted)
1137 {
1138 Scalar scalar;
1139 if (expr_result_valobj_sp->ResolveValue (scalar))
1140 {
1141 command.erase (start_backtick, end_backtick - start_backtick + 1);
1142 StreamString value_strm;
1143 const bool show_type = false;
1144 scalar.GetValue (&value_strm, show_type);
1145 size_t value_string_size = value_strm.GetSize();
1146 if (value_string_size)
1147 {
1148 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1149 pos = start_backtick + value_string_size;
1150 continue;
1151 }
1152 else
1153 {
1154 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1155 }
1156 }
1157 else
1158 {
1159 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1160 }
1161 }
1162 else
1163 {
1164 if (expr_result_valobj_sp)
1165 error = expr_result_valobj_sp->GetError();
1166 if (error.Success())
1167 {
1168
1169 switch (expr_result)
1170 {
1171 case eExecutionSetupError:
1172 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1173 break;
1174 case eExecutionCompleted:
1175 break;
1176 case eExecutionDiscarded:
1177 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1178 break;
1179 case eExecutionInterrupted:
1180 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1181 break;
1182 case eExecutionTimedOut:
1183 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1184 break;
1185 }
1186 }
1187 }
1188 }
1189 }
1190 if (error.Fail())
1191 break;
1192 }
1193 }
1194 return error;
1195}
1196
1197
Caroline Ticee0da7a52010-12-09 22:52:49 +00001198bool
1199CommandInterpreter::HandleCommand (const char *command_line,
1200 bool add_to_history,
1201 CommandReturnObject &result,
Jim Ingham949d5ac2011-02-18 00:54:25 +00001202 ExecutionContext *override_context,
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001203 bool repeat_on_empty_command,
1204 bool no_context_switching)
Jim Ingham949d5ac2011-02-18 00:54:25 +00001205
Caroline Ticee0da7a52010-12-09 22:52:49 +00001206{
Jim Ingham949d5ac2011-02-18 00:54:25 +00001207
Caroline Ticee0da7a52010-12-09 22:52:49 +00001208 bool done = false;
1209 CommandObject *cmd_obj = NULL;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001210 bool wants_raw_input = false;
1211 std::string command_string (command_line);
Jim Ingham6247dbe2011-07-12 03:12:18 +00001212 std::string original_command_string (command_line);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001213
1214 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Claytone98ac252010-11-10 04:57:04 +00001215 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1216
1217 // Make a scoped cleanup object that will clear the crash description string
1218 // on exit of this function.
Enrico Granata1a102082011-07-12 00:18:11 +00001219 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Claytone98ac252010-11-10 04:57:04 +00001220
Caroline Ticee0da7a52010-12-09 22:52:49 +00001221 if (log)
1222 log->Printf ("Processing command: %s", command_line);
Chris Lattner24943d22010-06-08 16:52:24 +00001223
Jim Inghamabab14b2010-11-04 23:08:45 +00001224 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1225
Johnny Chen8bdf57c2011-10-05 00:42:59 +00001226 if (!no_context_switching)
1227 UpdateExecutionContext (override_context);
Chris Lattner24943d22010-06-08 16:52:24 +00001228
Jim Ingham949d5ac2011-02-18 00:54:25 +00001229 bool empty_command = false;
1230 bool comment_command = false;
1231 if (command_string.empty())
1232 empty_command = true;
1233 else
Chris Lattner24943d22010-06-08 16:52:24 +00001234 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001235 const char *k_space_characters = "\t\n\v\f\r ";
1236
1237 size_t non_space = command_string.find_first_not_of (k_space_characters);
1238 // Check for empty line or comment line (lines whose first
1239 // non-space character is the comment character for this interpreter)
1240 if (non_space == std::string::npos)
1241 empty_command = true;
1242 else if (command_string[non_space] == m_comment_char)
1243 comment_command = true;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001244 else if (command_string[non_space] == m_repeat_char)
1245 {
1246 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1247 if (history_string == NULL)
1248 {
1249 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1250 result.SetStatus(eReturnStatusFailed);
1251 return false;
1252 }
1253 add_to_history = false;
1254 command_string = history_string;
1255 original_command_string = history_string;
1256 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001257 }
1258
1259 if (empty_command)
1260 {
1261 if (repeat_on_empty_command)
Chris Lattner24943d22010-06-08 16:52:24 +00001262 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001263 if (m_command_history.empty())
1264 {
1265 result.AppendError ("empty command");
1266 result.SetStatus(eReturnStatusFailed);
1267 return false;
1268 }
1269 else
1270 {
1271 command_line = m_repeat_command.c_str();
1272 command_string = command_line;
Jim Ingham6247dbe2011-07-12 03:12:18 +00001273 original_command_string = command_line;
Jim Ingham949d5ac2011-02-18 00:54:25 +00001274 if (m_repeat_command.empty())
1275 {
1276 result.AppendErrorWithFormat("No auto repeat.\n");
1277 result.SetStatus (eReturnStatusFailed);
1278 return false;
1279 }
1280 }
1281 add_to_history = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001282 }
1283 else
1284 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00001285 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1286 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001287 }
Jim Ingham949d5ac2011-02-18 00:54:25 +00001288 }
1289 else if (comment_command)
1290 {
1291 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1292 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001293 }
Caroline Tice649116c2011-05-11 16:07:06 +00001294
Greg Claytonf5c0c722011-10-14 07:41:33 +00001295
1296 Error error (PreprocessCommand (command_string));
1297
1298 if (error.Fail())
1299 {
1300 result.AppendError (error.AsCString());
1301 result.SetStatus(eReturnStatusFailed);
1302 return false;
1303 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001304 // Phase 1.
1305
1306 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1307 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1308 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1309 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1310 // 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 +00001311 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Ticee0da7a52010-12-09 22:52:49 +00001312 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Tice44c841d2010-12-07 19:58:26 +00001313
Caroline Ticee0da7a52010-12-09 22:52:49 +00001314 StreamString revised_command_line;
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001315 size_t actual_cmd_name_len = 0;
Greg Clayton7268b4c2011-10-28 21:38:01 +00001316 std::string next_word;
Caroline Ticee0da7a52010-12-09 22:52:49 +00001317 while (!done)
Chris Lattner24943d22010-06-08 16:52:24 +00001318 {
Caroline Tice649116c2011-05-11 16:07:06 +00001319 char quote_char = '\0';
Greg Clayton7268b4c2011-10-28 21:38:01 +00001320 std::string suffix;
1321 ExtractCommand (command_string, next_word, suffix, quote_char);
1322 if (cmd_obj == NULL)
Chris Lattner24943d22010-06-08 16:52:24 +00001323 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001324 if (AliasExists (next_word.c_str()))
Caroline Tice56d2fc42010-12-14 18:51:39 +00001325 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001326 std::string alias_result;
1327 cmd_obj = BuildAliasResult (next_word.c_str(), command_string, alias_result, result);
1328 revised_command_line.Printf ("%s", alias_result.c_str());
1329 if (cmd_obj)
1330 {
1331 wants_raw_input = cmd_obj->WantsRawCommandString ();
1332 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1333 }
Chris Lattner24943d22010-06-08 16:52:24 +00001334 }
1335 else
1336 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001337 cmd_obj = GetCommandObject (next_word.c_str());
1338 if (cmd_obj)
1339 {
1340 actual_cmd_name_len += next_word.length();
1341 revised_command_line.Printf ("%s", next_word.c_str());
1342 wants_raw_input = cmd_obj->WantsRawCommandString ();
1343 }
Caroline Tice649116c2011-05-11 16:07:06 +00001344 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001345 {
1346 revised_command_line.Printf ("%s", next_word.c_str());
1347 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001348 }
1349 }
1350 else
1351 {
Greg Clayton7268b4c2011-10-28 21:38:01 +00001352 if (cmd_obj->IsMultiwordObject ())
1353 {
1354 CommandObject *sub_cmd_obj = ((CommandObjectMultiword *) cmd_obj)->GetSubcommandObject (next_word.c_str());
1355 if (sub_cmd_obj)
1356 {
1357 actual_cmd_name_len += next_word.length() + 1;
1358 revised_command_line.Printf (" %s", next_word.c_str());
1359 cmd_obj = sub_cmd_obj;
1360 wants_raw_input = cmd_obj->WantsRawCommandString ();
1361 }
1362 else
1363 {
1364 if (quote_char)
1365 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1366 else
1367 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1368 done = true;
1369 }
1370 }
Caroline Tice649116c2011-05-11 16:07:06 +00001371 else
Greg Clayton7268b4c2011-10-28 21:38:01 +00001372 {
1373 if (quote_char)
1374 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1375 else
1376 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1377 done = true;
1378 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001379 }
1380
1381 if (cmd_obj == NULL)
1382 {
1383 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1384 result.SetStatus (eReturnStatusFailed);
1385 return false;
1386 }
1387
Greg Clayton7268b4c2011-10-28 21:38:01 +00001388 if (cmd_obj->IsMultiwordObject ())
1389 {
1390 if (!suffix.empty())
1391 {
1392
1393 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1394 next_word.c_str(),
1395 suffix.c_str());
1396 result.SetStatus (eReturnStatusFailed);
1397 return false;
1398 }
1399 }
1400 else
1401 {
1402 // If we found a normal command, we are done
1403 done = true;
1404 if (!suffix.empty())
1405 {
1406 switch (suffix[0])
1407 {
1408 case '/':
1409 // GDB format suffixes
Greg Claytond8a218d2011-10-29 00:57:28 +00001410 {
1411 Options *command_options = cmd_obj->GetOptions();
1412 if (command_options && command_options->SupportsLongOption("gdb-format"))
1413 {
Greg Clayton3840cd72011-11-09 23:25:03 +00001414 std::string gdb_format_option ("--gdb-format=");
1415 gdb_format_option += (suffix.c_str() + 1);
1416
1417 bool inserted = false;
1418 std::string &cmd = revised_command_line.GetString();
1419 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1420 if (arg_terminator_idx != std::string::npos)
1421 {
1422 // Insert the gdb format option before the "--" that terminates options
1423 gdb_format_option.append(1,' ');
1424 cmd.insert(arg_terminator_idx, gdb_format_option);
1425 inserted = true;
1426 }
1427
1428 if (!inserted)
1429 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1430
1431 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1432 revised_command_line.PutCString (" --");
Greg Claytond8a218d2011-10-29 00:57:28 +00001433 }
1434 else
1435 {
1436 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1437 cmd_obj->GetCommandName());
1438 result.SetStatus (eReturnStatusFailed);
1439 return false;
1440 }
1441 }
Greg Clayton7268b4c2011-10-28 21:38:01 +00001442 break;
Johnny Chen8ca450b2011-10-31 22:22:06 +00001443
1444 default:
1445 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1446 suffix.c_str());
1447 result.SetStatus (eReturnStatusFailed);
1448 return false;
1449
Greg Clayton7268b4c2011-10-28 21:38:01 +00001450 }
1451 }
1452 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001453 if (command_string.length() == 0)
1454 done = true;
1455
Chris Lattner24943d22010-06-08 16:52:24 +00001456 }
Caroline Ticee0da7a52010-12-09 22:52:49 +00001457
Greg Clayton7268b4c2011-10-28 21:38:01 +00001458 if (!command_string.empty())
Caroline Ticee0da7a52010-12-09 22:52:49 +00001459 revised_command_line.Printf (" %s", command_string.c_str());
1460
1461 // End of Phase 1.
1462 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1463 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1464 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1465 // wants_raw_input specifies whether the Execute method expects raw input or not.
1466
1467
1468 if (log)
1469 {
1470 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1471 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1472 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1473 }
1474
1475 // Phase 2.
1476 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1477 // CommandObject, with the appropriate arguments.
1478
1479 if (cmd_obj != NULL)
1480 {
1481 if (add_to_history)
1482 {
1483 Args command_args (revised_command_line.GetData());
1484 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1485 if (repeat_command != NULL)
1486 m_repeat_command.assign(repeat_command);
1487 else
Jim Ingham6247dbe2011-07-12 03:12:18 +00001488 m_repeat_command.assign(original_command_string.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001489
Jim Ingham6247dbe2011-07-12 03:12:18 +00001490 // Don't keep pushing the same command onto the history...
Greg Clayton7268b4c2011-10-28 21:38:01 +00001491 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Ingham6247dbe2011-07-12 03:12:18 +00001492 m_command_history.push_back (original_command_string);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001493 }
1494
1495 command_string = revised_command_line.GetData();
1496 std::string command_name (cmd_obj->GetCommandName());
Caroline Ticeea6e3df2010-12-11 08:16:56 +00001497 std::string remainder;
1498 if (actual_cmd_name_len < command_string.length())
1499 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1500 // than cmd_obj->GetCommandName(), because name completion
1501 // allows users to enter short versions of the names,
1502 // e.g. 'br s' for 'breakpoint set'.
Caroline Ticee0da7a52010-12-09 22:52:49 +00001503
1504 // Remove any initial spaces
1505 std::string white_space (" \t\v");
1506 size_t pos = remainder.find_first_not_of (white_space);
1507 if (pos != 0 && pos != std::string::npos)
Greg Clayton91c9dcf2011-04-22 20:58:45 +00001508 remainder.erase(0, pos);
Caroline Ticee0da7a52010-12-09 22:52:49 +00001509
1510 if (log)
Jason Molenda24c991c2011-08-25 00:20:04 +00001511 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Ticee0da7a52010-12-09 22:52:49 +00001512
1513
1514 if (wants_raw_input)
1515 cmd_obj->ExecuteRawCommandString (remainder.c_str(), result);
1516 else
1517 {
1518 Args cmd_args (remainder.c_str());
1519 cmd_obj->ExecuteWithOptions (cmd_args, result);
1520 }
1521 }
1522 else
1523 {
1524 // We didn't find the first command object, so complete the first argument.
1525 Args command_args (revised_command_line.GetData());
1526 StringList matches;
1527 int num_matches;
1528 int cursor_index = 0;
1529 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1530 bool word_complete;
1531 num_matches = HandleCompletionMatches (command_args,
1532 cursor_index,
1533 cursor_char_position,
1534 0,
1535 -1,
1536 word_complete,
1537 matches);
1538
1539 if (num_matches > 0)
1540 {
1541 std::string error_msg;
1542 error_msg.assign ("ambiguous command '");
1543 error_msg.append(command_args.GetArgumentAtIndex(0));
1544 error_msg.append ("'.");
1545
1546 error_msg.append (" Possible completions:");
1547 for (int i = 0; i < num_matches; i++)
1548 {
1549 error_msg.append ("\n\t");
1550 error_msg.append (matches.GetStringAtIndex (i));
1551 }
1552 error_msg.append ("\n");
1553 result.AppendRawError (error_msg.c_str(), error_msg.size());
1554 }
1555 else
1556 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1557
1558 result.SetStatus (eReturnStatusFailed);
1559 }
1560
Jason Molenda24c991c2011-08-25 00:20:04 +00001561 if (log)
1562 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1563
Chris Lattner24943d22010-06-08 16:52:24 +00001564 return result.Succeeded();
1565}
1566
1567int
1568CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1569 int &cursor_index,
1570 int &cursor_char_position,
1571 int match_start_point,
1572 int max_return_elements,
Jim Ingham802f8b02010-06-30 05:02:46 +00001573 bool &word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001574 StringList &matches)
1575{
1576 int num_command_matches = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001577 bool look_for_subcommand = false;
Jim Ingham802f8b02010-06-30 05:02:46 +00001578
1579 // For any of the command completions a unique match will be a complete word.
1580 word_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001581
1582 if (cursor_index == -1)
1583 {
1584 // We got nothing on the command line, so return the list of commands
Jim Inghamd40f8a62010-07-06 22:46:59 +00001585 bool include_aliases = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001586 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1587 }
1588 else if (cursor_index == 0)
1589 {
1590 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Inghamd40f8a62010-07-06 22:46:59 +00001591 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001592 num_command_matches = matches.GetSize();
1593
1594 if (num_command_matches == 1
1595 && cmd_obj && cmd_obj->IsMultiwordObject()
1596 && matches.GetStringAtIndex(0) != NULL
1597 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1598 {
1599 look_for_subcommand = true;
1600 num_command_matches = 0;
1601 matches.DeleteStringAtIndex(0);
1602 parsed_line.AppendArgument ("");
1603 cursor_index++;
1604 cursor_char_position = 0;
1605 }
1606 }
1607
1608 if (cursor_index > 0 || look_for_subcommand)
1609 {
1610 // We are completing further on into a commands arguments, so find the command and tell it
1611 // to complete the command.
1612 // First see if there is a matching initial command:
Jim Inghamd40f8a62010-07-06 22:46:59 +00001613 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner24943d22010-06-08 16:52:24 +00001614 if (command_object == NULL)
1615 {
1616 return 0;
1617 }
1618 else
1619 {
1620 parsed_line.Shift();
1621 cursor_index--;
Greg Clayton238c0a12010-09-18 01:14:36 +00001622 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton63094e02010-06-23 01:19:29 +00001623 cursor_index,
1624 cursor_char_position,
1625 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001626 max_return_elements,
1627 word_complete,
Chris Lattner24943d22010-06-08 16:52:24 +00001628 matches);
1629 }
1630 }
1631
1632 return num_command_matches;
1633
1634}
1635
1636int
1637CommandInterpreter::HandleCompletion (const char *current_line,
1638 const char *cursor,
1639 const char *last_char,
1640 int match_start_point,
1641 int max_return_elements,
1642 StringList &matches)
1643{
1644 // We parse the argument up to the cursor, so the last argument in parsed_line is
1645 // the one containing the cursor, and the cursor is after the last character.
1646
1647 Args parsed_line(current_line, last_char - current_line);
1648 Args partial_parsed_line(current_line, cursor - current_line);
1649
Jim Ingham6247dbe2011-07-12 03:12:18 +00001650 // Don't complete comments, and if the line we are completing is just the history repeat character,
1651 // substitute the appropriate history line.
1652 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1653 if (first_arg)
1654 {
1655 if (first_arg[0] == m_comment_char)
1656 return 0;
1657 else if (first_arg[0] == m_repeat_char)
1658 {
1659 const char *history_string = FindHistoryString (first_arg);
1660 if (history_string != NULL)
1661 {
1662 matches.Clear();
1663 matches.InsertStringAtIndex(0, history_string);
1664 return -2;
1665 }
1666 else
1667 return 0;
1668
1669 }
1670 }
1671
1672
Chris Lattner24943d22010-06-08 16:52:24 +00001673 int num_args = partial_parsed_line.GetArgumentCount();
1674 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1675 int cursor_char_position;
1676
1677 if (cursor_index == -1)
1678 cursor_char_position = 0;
1679 else
1680 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamcf037652010-12-14 19:56:01 +00001681
1682 if (cursor > current_line && cursor[-1] == ' ')
1683 {
1684 // We are just after a space. If we are in an argument, then we will continue
1685 // parsing, but if we are between arguments, then we have to complete whatever the next
1686 // element would be.
1687 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1688 // protected by a quote) then the space will also be in the parsed argument...
1689
1690 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1691 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1692 {
1693 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1694 cursor_index++;
1695 cursor_char_position = 0;
1696 }
1697 }
Chris Lattner24943d22010-06-08 16:52:24 +00001698
1699 int num_command_matches;
1700
1701 matches.Clear();
1702
1703 // Only max_return_elements == -1 is supported at present:
1704 assert (max_return_elements == -1);
Jim Ingham802f8b02010-06-30 05:02:46 +00001705 bool word_complete;
Greg Clayton63094e02010-06-23 01:19:29 +00001706 num_command_matches = HandleCompletionMatches (parsed_line,
1707 cursor_index,
1708 cursor_char_position,
1709 match_start_point,
Jim Ingham802f8b02010-06-30 05:02:46 +00001710 max_return_elements,
1711 word_complete,
Greg Clayton63094e02010-06-23 01:19:29 +00001712 matches);
Chris Lattner24943d22010-06-08 16:52:24 +00001713
1714 if (num_command_matches <= 0)
1715 return num_command_matches;
1716
1717 if (num_args == 0)
1718 {
1719 // If we got an empty string, insert nothing.
1720 matches.InsertStringAtIndex(0, "");
1721 }
1722 else
1723 {
1724 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
1725 // put an empty string in element 0.
1726 std::string command_partial_str;
1727 if (cursor_index >= 0)
Jim Inghame3663e82010-10-22 18:47:16 +00001728 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
1729 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner24943d22010-06-08 16:52:24 +00001730
1731 std::string common_prefix;
1732 matches.LongestCommonPrefix (common_prefix);
1733 int partial_name_len = command_partial_str.size();
1734
1735 // If we matched a unique single command, add a space...
Jim Ingham802f8b02010-06-30 05:02:46 +00001736 // Only do this if the completer told us this was a complete word, however...
1737 if (num_command_matches == 1 && word_complete)
Chris Lattner24943d22010-06-08 16:52:24 +00001738 {
1739 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
1740 if (quote_char != '\0')
1741 common_prefix.push_back(quote_char);
1742
1743 common_prefix.push_back(' ');
1744 }
1745 common_prefix.erase (0, partial_name_len);
1746 matches.InsertStringAtIndex(0, common_prefix.c_str());
1747 }
1748 return num_command_matches;
1749}
1750
Chris Lattner24943d22010-06-08 16:52:24 +00001751
1752CommandInterpreter::~CommandInterpreter ()
1753{
1754}
1755
1756const char *
1757CommandInterpreter::GetPrompt ()
1758{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001759 return m_debugger.GetPrompt();
Chris Lattner24943d22010-06-08 16:52:24 +00001760}
1761
1762void
1763CommandInterpreter::SetPrompt (const char *new_prompt)
1764{
Caroline Tice5bc8c972010-09-20 20:44:43 +00001765 m_debugger.SetPrompt (new_prompt);
Chris Lattner24943d22010-06-08 16:52:24 +00001766}
1767
Jim Ingham5e16ef52010-10-04 19:49:29 +00001768size_t
Greg Clayton58928562011-02-09 01:08:52 +00001769CommandInterpreter::GetConfirmationInputReaderCallback
1770(
1771 void *baton,
1772 InputReader &reader,
1773 lldb::InputReaderAction action,
1774 const char *bytes,
1775 size_t bytes_len
1776)
Jim Ingham5e16ef52010-10-04 19:49:29 +00001777{
Greg Clayton58928562011-02-09 01:08:52 +00001778 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001779 bool *response_ptr = (bool *) baton;
1780
1781 switch (action)
1782 {
1783 case eInputReaderActivate:
Greg Clayton58928562011-02-09 01:08:52 +00001784 if (out_file.IsValid())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001785 {
1786 if (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 }
1792 break;
1793
1794 case eInputReaderDeactivate:
1795 break;
1796
1797 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001798 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice22a60092011-02-02 01:17:56 +00001799 {
Greg Clayton58928562011-02-09 01:08:52 +00001800 out_file.Printf ("%s", reader.GetPrompt());
1801 out_file.Flush ();
Caroline Tice22a60092011-02-02 01:17:56 +00001802 }
Jim Ingham5e16ef52010-10-04 19:49:29 +00001803 break;
Caroline Tice4a348082011-05-02 20:41:46 +00001804
1805 case eInputReaderAsynchronousOutputWritten:
1806 break;
1807
Jim Ingham5e16ef52010-10-04 19:49:29 +00001808 case eInputReaderGotToken:
1809 if (bytes_len == 0)
1810 {
1811 reader.SetIsDone(true);
1812 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001813 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001814 {
1815 *response_ptr = true;
1816 reader.SetIsDone(true);
1817 }
Jim Ingham36fe9912011-11-14 20:02:01 +00001818 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham5e16ef52010-10-04 19:49:29 +00001819 {
1820 *response_ptr = false;
1821 reader.SetIsDone(true);
1822 }
1823 else
1824 {
Greg Clayton58928562011-02-09 01:08:52 +00001825 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham5e16ef52010-10-04 19:49:29 +00001826 {
Jim Ingham26183802011-11-17 01:22:00 +00001827 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton58928562011-02-09 01:08:52 +00001828 out_file.Flush ();
Jim Ingham5e16ef52010-10-04 19:49:29 +00001829 }
1830 }
1831 break;
1832
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001833 case eInputReaderInterrupt:
1834 case eInputReaderEndOfFile:
1835 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
1836 reader.SetIsDone (true);
1837 break;
1838
Jim Ingham5e16ef52010-10-04 19:49:29 +00001839 case eInputReaderDone:
1840 break;
1841 }
1842
1843 return bytes_len;
1844
1845}
1846
1847bool
1848CommandInterpreter::Confirm (const char *message, bool default_answer)
1849{
Jim Ingham93057472010-10-04 22:44:14 +00001850 // Check AutoConfirm first:
1851 if (m_debugger.GetAutoConfirm())
1852 return default_answer;
1853
Jim Ingham5e16ef52010-10-04 19:49:29 +00001854 InputReaderSP reader_sp (new InputReader(GetDebugger()));
1855 bool response = default_answer;
1856 if (reader_sp)
1857 {
1858 std::string prompt(message);
1859 prompt.append(": [");
1860 if (default_answer)
1861 prompt.append ("Y/n] ");
1862 else
1863 prompt.append ("y/N] ");
1864
1865 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
1866 &response, // baton
1867 eInputReaderGranularityLine, // token size, to pass to callback function
1868 NULL, // end token
1869 prompt.c_str(), // prompt
1870 true)); // echo input
1871 if (err.Success())
1872 {
1873 GetDebugger().PushInputReader (reader_sp);
1874 }
1875 reader_sp->WaitOnReaderIsDone();
1876 }
1877 return response;
1878}
1879
1880
Chris Lattner24943d22010-06-08 16:52:24 +00001881void
1882CommandInterpreter::CrossRegisterCommand (const char * dest_cmd, const char * object_type)
1883{
Jim Inghamd40f8a62010-07-06 22:46:59 +00001884 CommandObjectSP cmd_obj_sp = GetCommandSPExact (dest_cmd, true);
Chris Lattner24943d22010-06-08 16:52:24 +00001885
1886 if (cmd_obj_sp != NULL)
1887 {
1888 CommandObject *cmd_obj = cmd_obj_sp.get();
1889 if (cmd_obj->IsCrossRefObject ())
1890 cmd_obj->AddObject (object_type);
1891 }
1892}
1893
Chris Lattner24943d22010-06-08 16:52:24 +00001894OptionArgVectorSP
1895CommandInterpreter::GetAliasOptions (const char *alias_name)
1896{
1897 OptionArgMap::iterator pos;
1898 OptionArgVectorSP ret_val;
1899
1900 std::string alias (alias_name);
1901
1902 if (HasAliasOptions())
1903 {
1904 pos = m_alias_options.find (alias);
1905 if (pos != m_alias_options.end())
1906 ret_val = pos->second;
1907 }
1908
1909 return ret_val;
1910}
1911
1912void
1913CommandInterpreter::RemoveAliasOptions (const char *alias_name)
1914{
1915 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
1916 if (pos != m_alias_options.end())
1917 {
1918 m_alias_options.erase (pos);
1919 }
1920}
1921
1922void
1923CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
1924{
1925 m_alias_options[alias_name] = option_arg_vector_sp;
1926}
1927
1928bool
1929CommandInterpreter::HasCommands ()
1930{
1931 return (!m_command_dict.empty());
1932}
1933
1934bool
1935CommandInterpreter::HasAliases ()
1936{
1937 return (!m_alias_dict.empty());
1938}
1939
1940bool
1941CommandInterpreter::HasUserCommands ()
1942{
1943 return (!m_user_dict.empty());
1944}
1945
1946bool
1947CommandInterpreter::HasAliasOptions ()
1948{
1949 return (!m_alias_options.empty());
1950}
1951
Chris Lattner24943d22010-06-08 16:52:24 +00001952void
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001953CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
1954 const char *alias_name,
1955 Args &cmd_args,
Caroline Tice44c841d2010-12-07 19:58:26 +00001956 std::string &raw_input_string,
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001957 CommandReturnObject &result)
Chris Lattner24943d22010-06-08 16:52:24 +00001958{
1959 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Tice44c841d2010-12-07 19:58:26 +00001960
1961 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner24943d22010-06-08 16:52:24 +00001962
Caroline Tice44c841d2010-12-07 19:58:26 +00001963 // Make sure that the alias name is the 0th element in cmd_args
1964 std::string alias_name_str = alias_name;
1965 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
1966 cmd_args.Unshift (alias_name);
1967
1968 Args new_args (alias_cmd_obj->GetCommandName());
1969 if (new_args.GetArgumentCount() == 2)
1970 new_args.Shift();
1971
Chris Lattner24943d22010-06-08 16:52:24 +00001972 if (option_arg_vector_sp.get())
1973 {
Caroline Tice44c841d2010-12-07 19:58:26 +00001974 if (wants_raw_input)
1975 {
1976 // We have a command that both has command options and takes raw input. Make *sure* it has a
1977 // " -- " in the right place in the raw_input_string.
1978 size_t pos = raw_input_string.find(" -- ");
1979 if (pos == std::string::npos)
1980 {
1981 // None found; assume it goes at the beginning of the raw input string
1982 raw_input_string.insert (0, " -- ");
1983 }
1984 }
Chris Lattner24943d22010-06-08 16:52:24 +00001985
1986 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1987 int old_size = cmd_args.GetArgumentCount();
Caroline Ticebd5c63e2010-10-12 21:57:09 +00001988 std::vector<bool> used (old_size + 1, false);
1989
1990 used[0] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00001991
1992 for (int i = 0; i < option_arg_vector->size(); ++i)
1993 {
1994 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Tice44c841d2010-12-07 19:58:26 +00001995 OptionArgValue value_pair = option_pair.second;
1996 int value_type = value_pair.first;
Chris Lattner24943d22010-06-08 16:52:24 +00001997 std::string option = option_pair.first;
Caroline Tice44c841d2010-12-07 19:58:26 +00001998 std::string value = value_pair.second;
Chris Lattner24943d22010-06-08 16:52:24 +00001999 if (option.compare ("<argument>") == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002000 {
2001 if (!wants_raw_input
2002 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2003 new_args.AppendArgument (value.c_str());
2004 }
Chris Lattner24943d22010-06-08 16:52:24 +00002005 else
2006 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002007 if (value_type != optional_argument)
2008 new_args.AppendArgument (option.c_str());
Chris Lattner24943d22010-06-08 16:52:24 +00002009 if (value.compare ("<no-argument>") != 0)
2010 {
2011 int index = GetOptionArgumentPosition (value.c_str());
2012 if (index == 0)
Caroline Tice44c841d2010-12-07 19:58:26 +00002013 {
Chris Lattner24943d22010-06-08 16:52:24 +00002014 // value was NOT a positional argument; must be a real value
Caroline Tice44c841d2010-12-07 19:58:26 +00002015 if (value_type != optional_argument)
2016 new_args.AppendArgument (value.c_str());
2017 else
2018 {
2019 char buffer[255];
2020 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2021 new_args.AppendArgument (buffer);
2022 }
2023
2024 }
Chris Lattner24943d22010-06-08 16:52:24 +00002025 else if (index >= cmd_args.GetArgumentCount())
2026 {
2027 result.AppendErrorWithFormat
2028 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2029 index);
2030 result.SetStatus (eReturnStatusFailed);
2031 return;
2032 }
2033 else
2034 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002035 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2036 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2037 if (strpos != std::string::npos)
2038 {
2039 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2040 }
2041
2042 if (value_type != optional_argument)
2043 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2044 else
2045 {
2046 char buffer[255];
2047 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2048 cmd_args.GetArgumentAtIndex (index));
2049 new_args.AppendArgument (buffer);
2050 }
Caroline Ticebd5c63e2010-10-12 21:57:09 +00002051 used[index] = true;
Chris Lattner24943d22010-06-08 16:52:24 +00002052 }
2053 }
2054 }
2055 }
2056
2057 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2058 {
Caroline Tice44c841d2010-12-07 19:58:26 +00002059 if (!used[j] && !wants_raw_input)
Chris Lattner24943d22010-06-08 16:52:24 +00002060 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2061 }
2062
2063 cmd_args.Clear();
2064 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2065 }
2066 else
2067 {
2068 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Tice44c841d2010-12-07 19:58:26 +00002069 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2070 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2071 // input string.
2072 if (wants_raw_input)
2073 {
2074 cmd_args.Clear();
2075 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2076 }
Chris Lattner24943d22010-06-08 16:52:24 +00002077 return;
2078 }
2079
2080 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2081 return;
2082}
2083
2084
2085int
2086CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2087{
2088 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2089 // of zero.
2090
2091 char *cptr = (char *) in_string;
2092
2093 // Does it start with '%'
2094 if (cptr[0] == '%')
2095 {
2096 ++cptr;
2097
2098 // Is the rest of it entirely digits?
2099 if (isdigit (cptr[0]))
2100 {
2101 const char *start = cptr;
2102 while (isdigit (cptr[0]))
2103 ++cptr;
2104
2105 // We've gotten to the end of the digits; are we at the end of the string?
2106 if (cptr[0] == '\0')
2107 position = atoi (start);
2108 }
2109 }
2110
2111 return position;
2112}
2113
2114void
2115CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2116{
Jim Ingham574c3d62011-08-12 23:34:31 +00002117 FileSpec init_file;
Greg Claytond6edcb52011-09-11 00:01:44 +00002118 if (in_cwd)
Jim Ingham574c3d62011-08-12 23:34:31 +00002119 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002120 // In the current working directory we don't load any program specific
2121 // .lldbinit files, we only look for a "./.lldbinit" file.
2122 if (m_skip_lldbinit_files)
2123 return;
2124
2125 init_file.SetFile ("./.lldbinit", true);
Jim Ingham574c3d62011-08-12 23:34:31 +00002126 }
Greg Claytond6edcb52011-09-11 00:01:44 +00002127 else
Jim Ingham574c3d62011-08-12 23:34:31 +00002128 {
Greg Claytond6edcb52011-09-11 00:01:44 +00002129 // If we aren't looking in the current working directory we are looking
2130 // in the home directory. We will first see if there is an application
2131 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2132 // "-" and the name of the program. If this file doesn't exist, we fall
2133 // back to just the "~/.lldbinit" file. We also obey any requests to not
2134 // load the init files.
2135 const char *init_file_path = "~/.lldbinit";
2136
2137 if (m_skip_app_init_files == false)
2138 {
2139 FileSpec program_file_spec (Host::GetProgramFileSpec());
2140 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham574c3d62011-08-12 23:34:31 +00002141
Greg Claytond6edcb52011-09-11 00:01:44 +00002142 if (program_name)
2143 {
2144 char program_init_file_name[PATH_MAX];
2145 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2146 init_file.SetFile (program_init_file_name, true);
2147 if (!init_file.Exists())
2148 init_file.Clear();
2149 }
2150 }
2151
2152 if (!init_file && !m_skip_lldbinit_files)
2153 init_file.SetFile (init_file_path, true);
2154 }
2155
Chris Lattner24943d22010-06-08 16:52:24 +00002156 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2157 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2158
2159 if (init_file.Exists())
2160 {
Jim Ingham949d5ac2011-02-18 00:54:25 +00002161 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2162 bool stop_on_continue = true;
2163 bool stop_on_error = false;
2164 bool echo_commands = false;
2165 bool print_results = false;
2166
2167 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, result);
Chris Lattner24943d22010-06-08 16:52:24 +00002168 }
2169 else
2170 {
2171 // nothing to be done if the file doesn't exist
2172 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2173 }
2174}
2175
Greg Claytonb72d0f02011-04-12 05:54:46 +00002176PlatformSP
2177CommandInterpreter::GetPlatform (bool prefer_target_platform)
2178{
2179 PlatformSP platform_sp;
Greg Clayton567e7f32011-09-22 04:58:26 +00002180 if (prefer_target_platform)
2181 {
2182 Target *target = m_exe_ctx.GetTargetPtr();
2183 if (target)
2184 platform_sp = target->GetPlatform();
2185 }
Greg Claytonb72d0f02011-04-12 05:54:46 +00002186
2187 if (!platform_sp)
2188 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2189 return platform_sp;
2190}
2191
Jim Ingham949d5ac2011-02-18 00:54:25 +00002192void
Jim Inghama4fede32011-03-11 01:51:49 +00002193CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham949d5ac2011-02-18 00:54:25 +00002194 ExecutionContext *override_context,
2195 bool stop_on_continue,
2196 bool stop_on_error,
2197 bool echo_commands,
2198 bool print_results,
2199 CommandReturnObject &result)
2200{
2201 size_t num_lines = commands.GetSize();
Jim Ingham949d5ac2011-02-18 00:54:25 +00002202
2203 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2204 // Make sure you reset this value anywhere you return from the function.
2205
2206 bool old_async_execution = m_debugger.GetAsyncExecution();
2207
2208 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2209 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2210
2211 if (override_context != NULL)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002212 UpdateExecutionContext (override_context);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002213
2214 if (!stop_on_continue)
2215 {
2216 m_debugger.SetAsyncExecution (false);
2217 }
2218
2219 for (int idx = 0; idx < num_lines; idx++)
2220 {
2221 const char *cmd = commands.GetStringAtIndex(idx);
2222 if (cmd[0] == '\0')
2223 continue;
2224
Jim Ingham949d5ac2011-02-18 00:54:25 +00002225 if (echo_commands)
2226 {
2227 result.AppendMessageWithFormat ("%s %s\n",
2228 GetPrompt(),
2229 cmd);
2230 }
2231
Greg Claytonaa378b12011-02-20 02:15:07 +00002232 CommandReturnObject tmp_result;
Johnny Chen8bdf57c2011-10-05 00:42:59 +00002233 // If override_context is not NULL, pass no_context_switching = true for
2234 // HandleCommand() since we updated our context already.
2235 bool success = HandleCommand(cmd, false, tmp_result,
2236 NULL, /* override_context */
2237 true, /* repeat_on_empty_command */
2238 override_context != NULL /* no_context_switching */);
Jim Ingham949d5ac2011-02-18 00:54:25 +00002239
2240 if (print_results)
2241 {
2242 if (tmp_result.Succeeded())
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002243 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002244 }
2245
2246 if (!success || !tmp_result.Succeeded())
2247 {
2248 if (stop_on_error)
2249 {
2250 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed.\n",
2251 idx, cmd);
2252 result.SetStatus (eReturnStatusFailed);
2253 m_debugger.SetAsyncExecution (old_async_execution);
2254 return;
2255 }
2256 else if (print_results)
2257 {
2258 result.AppendMessageWithFormat ("Command #%d '%s' failed with error: %s.\n",
2259 idx + 1,
2260 cmd,
Jim Ingham2e8cb8a2011-02-19 02:53:09 +00002261 tmp_result.GetErrorData());
Jim Ingham949d5ac2011-02-18 00:54:25 +00002262 }
2263 }
2264
Caroline Tice4a348082011-05-02 20:41:46 +00002265 if (result.GetImmediateOutputStream())
2266 result.GetImmediateOutputStream()->Flush();
2267
2268 if (result.GetImmediateErrorStream())
2269 result.GetImmediateErrorStream()->Flush();
2270
Jim Ingham949d5ac2011-02-18 00:54:25 +00002271 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2272 // could be running (for instance in Breakpoint Commands.
2273 // So we check the return value to see if it is has running in it.
2274 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2275 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2276 {
2277 if (stop_on_continue)
2278 {
2279 // If we caused the target to proceed, and we're going to stop in that case, set the
2280 // status in our real result before returning. This is an error if the continue was not the
2281 // last command in the set of commands to be run.
2282 if (idx != num_lines - 1)
2283 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2284 idx + 1, cmd);
2285 else
2286 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2287
2288 result.SetStatus(tmp_result.GetStatus());
2289 m_debugger.SetAsyncExecution (old_async_execution);
2290
2291 return;
2292 }
2293 }
2294
2295 }
2296
2297 result.SetStatus (eReturnStatusSuccessFinishResult);
2298 m_debugger.SetAsyncExecution (old_async_execution);
2299
2300 return;
2301}
2302
2303void
2304CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2305 ExecutionContext *context,
2306 bool stop_on_continue,
2307 bool stop_on_error,
2308 bool echo_command,
2309 bool print_result,
2310 CommandReturnObject &result)
2311{
2312 if (cmd_file.Exists())
2313 {
2314 bool success;
2315 StringList commands;
2316 success = commands.ReadFileLines(cmd_file);
2317 if (!success)
2318 {
2319 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2320 result.SetStatus (eReturnStatusFailed);
2321 return;
2322 }
2323 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, result);
2324 }
2325 else
2326 {
2327 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2328 cmd_file.GetFilename().AsCString());
2329 result.SetStatus (eReturnStatusFailed);
2330 return;
2331 }
2332}
2333
Chris Lattner24943d22010-06-08 16:52:24 +00002334ScriptInterpreter *
2335CommandInterpreter::GetScriptInterpreter ()
2336{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002337 if (m_script_interpreter_ap.get() != NULL)
2338 return m_script_interpreter_ap.get();
Greg Clayton63094e02010-06-23 01:19:29 +00002339
Caroline Tice0aa2e552011-01-14 00:29:16 +00002340 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2341 switch (script_lang)
Chris Lattner24943d22010-06-08 16:52:24 +00002342 {
Greg Clayton3e4238d2011-11-04 03:34:56 +00002343 case eScriptLanguagePython:
2344#ifndef LLDB_DISABLE_PYTHON
2345 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2346 break;
2347#else
2348 // Fall through to the None case when python is disabled
2349#endif
Caroline Tice0aa2e552011-01-14 00:29:16 +00002350 case eScriptLanguageNone:
2351 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2352 break;
Caroline Tice0aa2e552011-01-14 00:29:16 +00002353 default:
2354 break;
2355 };
2356
2357 return m_script_interpreter_ap.get();
Chris Lattner24943d22010-06-08 16:52:24 +00002358}
2359
2360
2361
2362bool
2363CommandInterpreter::GetSynchronous ()
2364{
2365 return m_synchronous_execution;
2366}
2367
2368void
2369CommandInterpreter::SetSynchronous (bool value)
2370{
Johnny Chend7a4eb02010-10-14 01:22:03 +00002371 m_synchronous_execution = value;
Chris Lattner24943d22010-06-08 16:52:24 +00002372}
2373
2374void
2375CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2376 const char *word_text,
2377 const char *separator,
2378 const char *help_text,
2379 uint32_t max_word_len)
2380{
Greg Clayton238c0a12010-09-18 01:14:36 +00002381 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2382
Chris Lattner24943d22010-06-08 16:52:24 +00002383 int indent_size = max_word_len + strlen (separator) + 2;
2384
2385 strm.IndentMore (indent_size);
Greg Claytond284b662011-02-18 01:44:25 +00002386
2387 StreamString text_strm;
2388 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2389
2390 size_t len = text_strm.GetSize();
2391 const char *text = text_strm.GetData();
Chris Lattner24943d22010-06-08 16:52:24 +00002392 if (text[len - 1] == '\n')
Greg Claytond284b662011-02-18 01:44:25 +00002393 {
2394 text_strm.EOL();
2395 len = text_strm.GetSize();
2396 }
Chris Lattner24943d22010-06-08 16:52:24 +00002397
2398 if (len < max_columns)
2399 {
2400 // Output it as a single line.
2401 strm.Printf ("%s", text);
2402 }
2403 else
2404 {
2405 // We need to break it up into multiple lines.
2406 bool first_line = true;
2407 int text_width;
2408 int start = 0;
2409 int end = start;
2410 int final_end = strlen (text);
2411 int sub_len;
2412
2413 while (end < final_end)
2414 {
2415 if (first_line)
2416 text_width = max_columns - 1;
2417 else
2418 text_width = max_columns - indent_size - 1;
2419
2420 // Don't start the 'text' on a space, since we're already outputting the indentation.
2421 if (!first_line)
2422 {
2423 while ((start < final_end) && (text[start] == ' '))
2424 start++;
2425 }
2426
2427 end = start + text_width;
2428 if (end > final_end)
2429 end = final_end;
2430 else
2431 {
2432 // If we're not at the end of the text, make sure we break the line on white space.
2433 while (end > start
2434 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2435 end--;
2436 }
2437
2438 sub_len = end - start;
2439 if (start != 0)
2440 strm.EOL();
2441 if (!first_line)
2442 strm.Indent();
2443 else
2444 first_line = false;
2445 assert (start <= final_end);
2446 assert (start + sub_len <= final_end);
2447 if (sub_len > 0)
2448 strm.Write (text + start, sub_len);
2449 start = end + 1;
2450 }
2451 }
2452 strm.EOL();
2453 strm.IndentLess(indent_size);
Chris Lattner24943d22010-06-08 16:52:24 +00002454}
2455
2456void
Enrico Granata1bba6e52011-07-07 00:38:40 +00002457CommandInterpreter::OutputHelpText (Stream &strm,
2458 const char *word_text,
2459 const char *separator,
2460 const char *help_text,
2461 uint32_t max_word_len)
2462{
2463 int indent_size = max_word_len + strlen (separator) + 2;
2464
2465 strm.IndentMore (indent_size);
2466
2467 StreamString text_strm;
2468 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2469
2470 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2471 bool first_line = true;
2472
2473 size_t len = text_strm.GetSize();
2474 const char *text = text_strm.GetData();
2475
2476 uint32_t chars_left = max_columns;
2477
2478 for (uint32_t i = 0; i < len; i++)
2479 {
2480 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2481 {
2482 first_line = false;
2483 chars_left = max_columns - indent_size;
2484 strm.EOL();
2485 strm.Indent();
2486 }
2487 else
2488 {
2489 strm.PutChar(text[i]);
2490 chars_left--;
2491 }
2492
2493 }
2494
2495 strm.EOL();
2496 strm.IndentLess(indent_size);
2497}
2498
2499void
Chris Lattner24943d22010-06-08 16:52:24 +00002500CommandInterpreter::AproposAllSubCommands (CommandObject *cmd_obj, const char *prefix, const char *search_word,
2501 StringList &commands_found, StringList &commands_help)
2502{
2503 CommandObject::CommandMap::const_iterator pos;
2504 CommandObject::CommandMap sub_cmd_dict = ((CommandObjectMultiword *) cmd_obj)->m_subcommand_dict;
2505 CommandObject *sub_cmd_obj;
2506
2507 for (pos = sub_cmd_dict.begin(); pos != sub_cmd_dict.end(); ++pos)
2508 {
2509 const char * command_name = pos->first.c_str();
2510 sub_cmd_obj = pos->second.get();
2511 StreamString complete_command_name;
2512
2513 complete_command_name.Printf ("%s %s", prefix, command_name);
2514
Greg Clayton238c0a12010-09-18 01:14:36 +00002515 if (sub_cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002516 {
2517 commands_found.AppendString (complete_command_name.GetData());
2518 commands_help.AppendString (sub_cmd_obj->GetHelp());
2519 }
2520
2521 if (sub_cmd_obj->IsMultiwordObject())
2522 AproposAllSubCommands (sub_cmd_obj, complete_command_name.GetData(), search_word, commands_found,
2523 commands_help);
2524 }
2525
2526}
2527
2528void
2529CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2530 StringList &commands_help)
2531{
2532 CommandObject::CommandMap::const_iterator pos;
2533
2534 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2535 {
2536 const char *command_name = pos->first.c_str();
2537 CommandObject *cmd_obj = pos->second.get();
2538
Greg Clayton238c0a12010-09-18 01:14:36 +00002539 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner24943d22010-06-08 16:52:24 +00002540 {
2541 commands_found.AppendString (command_name);
2542 commands_help.AppendString (cmd_obj->GetHelp());
2543 }
2544
2545 if (cmd_obj->IsMultiwordObject())
2546 AproposAllSubCommands (cmd_obj, command_name, search_word, commands_found, commands_help);
2547
2548 }
2549}
Greg Claytonb72d0f02011-04-12 05:54:46 +00002550
2551
2552void
2553CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2554{
2555 m_exe_ctx.Clear();
2556
2557 if (override_context != NULL)
2558 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002559 m_exe_ctx = *override_context;
Greg Claytonb72d0f02011-04-12 05:54:46 +00002560 }
2561 else
2562 {
2563 TargetSP target_sp (m_debugger.GetSelectedTarget());
2564 if (target_sp)
2565 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002566 m_exe_ctx.SetTargetSP (target_sp);
2567 ProcessSP process_sp (target_sp->GetProcessSP());
2568 m_exe_ctx.SetProcessSP (process_sp);
2569 if (process_sp && process_sp->IsAlive() && !process_sp->IsRunning())
Greg Claytonb72d0f02011-04-12 05:54:46 +00002570 {
Greg Clayton13d24fb2012-01-29 20:56:30 +00002571 ThreadSP thread_sp (process_sp->GetThreadList().GetSelectedThread());
Greg Clayton567e7f32011-09-22 04:58:26 +00002572 if (thread_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002573 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002574 m_exe_ctx.SetThreadSP (thread_sp);
2575 StackFrameSP frame_sp (thread_sp->GetSelectedFrame());
2576 if (!frame_sp)
Greg Claytonb72d0f02011-04-12 05:54:46 +00002577 {
Greg Clayton567e7f32011-09-22 04:58:26 +00002578 frame_sp = thread_sp->GetStackFrameAtIndex (0);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002579 // If we didn't have a selected frame select one here.
Greg Clayton567e7f32011-09-22 04:58:26 +00002580 if (frame_sp)
2581 thread_sp->SetSelectedFrame(frame_sp.get());
Greg Claytonb72d0f02011-04-12 05:54:46 +00002582 }
Greg Clayton567e7f32011-09-22 04:58:26 +00002583 if (frame_sp)
2584 m_exe_ctx.SetFrameSP (frame_sp);
Greg Claytonb72d0f02011-04-12 05:54:46 +00002585 }
2586 }
2587 }
2588 }
2589}
2590
Jim Ingham6247dbe2011-07-12 03:12:18 +00002591void
2592CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2593{
2594 DumpHistory (stream, 0, count - 1);
2595}
2596
2597void
2598CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2599{
Greg Clayton7268b4c2011-10-28 21:38:01 +00002600 const size_t last_idx = std::min<size_t>(m_command_history.size(), end + 1);
2601 for (size_t i = start; i < last_idx; i++)
Jim Ingham6247dbe2011-07-12 03:12:18 +00002602 {
2603 if (!m_command_history[i].empty())
2604 {
2605 stream.Indent();
Greg Clayton7268b4c2011-10-28 21:38:01 +00002606 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Ingham6247dbe2011-07-12 03:12:18 +00002607 }
2608 }
2609}
2610
2611const char *
2612CommandInterpreter::FindHistoryString (const char *input_str) const
2613{
2614 if (input_str[0] != m_repeat_char)
2615 return NULL;
2616 if (input_str[1] == '-')
2617 {
2618 bool success;
2619 uint32_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
2620 if (!success)
2621 return NULL;
2622 if (idx > m_command_history.size())
2623 return NULL;
2624 idx = m_command_history.size() - idx;
2625 return m_command_history[idx].c_str();
2626
2627 }
2628 else if (input_str[1] == m_repeat_char)
2629 {
2630 if (m_command_history.empty())
2631 return NULL;
2632 else
2633 return m_command_history.back().c_str();
2634 }
2635 else
2636 {
2637 bool success;
2638 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2639 if (!success)
2640 return NULL;
2641 if (idx >= m_command_history.size())
2642 return NULL;
2643 return m_command_history[idx].c_str();
2644 }
2645}