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