blob: 72a9df910507ded42ba67d321a37585c73d4cdbb [file] [log] [blame]
Chris Lattner30fdc8d2010-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
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000013#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000014
15#include <getopt.h>
16#include <stdlib.h>
17
Greg Clayton4a33d312011-06-23 17:59:56 +000018#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000019#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000020
Eli Friedman3afb70c2010-06-13 02:17:17 +000021#include "../Commands/CommandObjectApropos.h"
22#include "../Commands/CommandObjectArgs.h"
23#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectDisassemble.h"
25#include "../Commands/CommandObjectExpression.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectFrame.h"
27#include "../Commands/CommandObjectHelp.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000028#include "../Commands/CommandObjectLog.h"
29#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000030#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000031#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectProcess.h"
33#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectSource.h"
Jim Inghamebc09c32010-07-07 03:36:20 +000037#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000038#include "../Commands/CommandObjectSyntax.h"
39#include "../Commands/CommandObjectTarget.h"
40#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000041#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000042#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000043#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044
Greg Clayton7d2ef162013-03-29 17:03:23 +000045
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Core/Debugger.h"
Jim Ingham97a6dc72010-10-04 19:49:29 +000047#include "lldb/Core/InputReader.h"
Enrico Granatab5887262012-10-29 21:18:03 +000048#include "lldb/Core/Log.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049#include "lldb/Core/Stream.h"
50#include "lldb/Core/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000051
Greg Clayton7fb56d02011-02-01 01:31:41 +000052#include "lldb/Host/Host.h"
Enrico Granatab5887262012-10-29 21:18:03 +000053
54#include "lldb/Interpreter/Args.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000055#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000056#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000057#include "lldb/Interpreter/CommandReturnObject.h"
Enrico Granatab5887262012-10-29 21:18:03 +000058#include "lldb/Interpreter/Options.h"
59#include "lldb/Interpreter/ScriptInterpreterNone.h"
60#include "lldb/Interpreter/ScriptInterpreterPython.h"
61
62
Chris Lattner30fdc8d2010-06-08 16:52:24 +000063#include "lldb/Target/Process.h"
64#include "lldb/Target/Thread.h"
65#include "lldb/Target/TargetList.h"
66
Enrico Granatab5887262012-10-29 21:18:03 +000067#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068
69using namespace lldb;
70using namespace lldb_private;
71
Greg Clayton754a9362012-08-23 00:22:02 +000072
73static PropertyDefinition
74g_properties[] =
75{
76 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, NULL, NULL, "If true, regular expression alias commands will show the expanded command that will be executed. This can be used to debug new regular expression alias commands." },
Enrico Granatabcba2b22013-01-17 21:36:19 +000077 { "prompt-on-quit", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, LLDB will prompt you before quitting if there are any live processes being debugged. If false, LLDB will quit without asking in any case." },
Greg Clayton754a9362012-08-23 00:22:02 +000078 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
79};
80
81enum
82{
Enrico Granatabcba2b22013-01-17 21:36:19 +000083 ePropertyExpandRegexAliases = 0,
84 ePropertyPromptOnQuit = 1
Greg Clayton754a9362012-08-23 00:22:02 +000085};
86
Jim Ingham4bddaeb2012-02-16 06:50:00 +000087ConstString &
88CommandInterpreter::GetStaticBroadcasterClass ()
89{
90 static ConstString class_name ("lldb.commandInterpreter");
91 return class_name;
92}
93
Chris Lattner30fdc8d2010-06-08 16:52:24 +000094CommandInterpreter::CommandInterpreter
95(
Greg Clayton66111032010-06-23 01:19:29 +000096 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +000097 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +000098 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +000099) :
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000100 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton754a9362012-08-23 00:22:02 +0000101 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton66111032010-06-23 01:19:29 +0000102 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000103 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000104 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000105 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000106 m_script_interpreter_ap (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000107 m_comment_char ('#'),
Jim Inghama5a97eb2011-07-12 03:12:18 +0000108 m_repeat_char ('!'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000109 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000110 m_truncation_warning(eNoTruncation),
111 m_command_source_depth (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000112{
Greg Clayton67cc0632012-08-22 17:17:09 +0000113 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000114 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
115 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000116 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000117 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000118 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000119}
120
Greg Clayton754a9362012-08-23 00:22:02 +0000121bool
122CommandInterpreter::GetExpandRegexAliases () const
123{
124 const uint32_t idx = ePropertyExpandRegexAliases;
125 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
126}
127
Enrico Granatabcba2b22013-01-17 21:36:19 +0000128bool
129CommandInterpreter::GetPromptOnQuit () const
130{
131 const uint32_t idx = ePropertyPromptOnQuit;
132 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
133}
Greg Clayton754a9362012-08-23 00:22:02 +0000134
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000135void
136CommandInterpreter::Initialize ()
137{
138 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
139
140 CommandReturnObject result;
141
142 LoadCommandDictionary ();
143
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000144 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000145 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
146 if (cmd_obj_sp)
147 {
148 AddAlias ("q", cmd_obj_sp);
149 AddAlias ("exit", cmd_obj_sp);
150 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000151
Johnny Chen6d675242012-08-24 18:15:45 +0000152 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000153 if (cmd_obj_sp)
154 {
155 AddAlias ("attach", cmd_obj_sp);
156 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000157
Johnny Chen6d675242012-08-24 18:15:45 +0000158 cmd_obj_sp = GetCommandSPExact ("process detach",false);
159 if (cmd_obj_sp)
160 {
161 AddAlias ("detach", cmd_obj_sp);
162 }
163
Caroline Ticeca90c472011-05-06 21:37:15 +0000164 cmd_obj_sp = GetCommandSPExact ("process continue", false);
165 if (cmd_obj_sp)
166 {
167 AddAlias ("c", cmd_obj_sp);
168 AddAlias ("continue", cmd_obj_sp);
169 }
170
171 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
172 if (cmd_obj_sp)
173 AddAlias ("b", cmd_obj_sp);
174
Jim Inghamca36cd12012-10-05 19:16:31 +0000175 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
176 if (cmd_obj_sp)
177 AddAlias ("tbreak", cmd_obj_sp);
178
Caroline Ticeca90c472011-05-06 21:37:15 +0000179 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
180 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000181 {
182 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000183 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000184 }
185
186 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
187 if (cmd_obj_sp)
188 {
189 AddAlias ("nexti", cmd_obj_sp);
190 AddAlias ("ni", cmd_obj_sp);
191 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000192
193 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
194 if (cmd_obj_sp)
195 {
196 AddAlias ("s", cmd_obj_sp);
197 AddAlias ("step", cmd_obj_sp);
198 }
199
200 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
201 if (cmd_obj_sp)
202 {
203 AddAlias ("n", cmd_obj_sp);
204 AddAlias ("next", cmd_obj_sp);
205 }
206
207 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
208 if (cmd_obj_sp)
209 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000210 AddAlias ("finish", cmd_obj_sp);
211 }
212
Jim Ingham6d6d1072011-12-02 01:12:59 +0000213 cmd_obj_sp = GetCommandSPExact ("frame select", false);
214 if (cmd_obj_sp)
215 {
216 AddAlias ("f", cmd_obj_sp);
217 }
218
Jim Inghamca36cd12012-10-05 19:16:31 +0000219 cmd_obj_sp = GetCommandSPExact ("thread select", false);
220 if (cmd_obj_sp)
221 {
222 AddAlias ("t", cmd_obj_sp);
223 }
224
Greg Clayton6bade322013-02-01 23:33:03 +0000225 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000226 if (cmd_obj_sp)
227 {
228 AddAlias ("l", cmd_obj_sp);
229 AddAlias ("list", cmd_obj_sp);
230 }
231
Greg Claytonef5651d2013-02-12 18:52:24 +0000232 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
233 if (cmd_obj_sp)
234 {
235 AddAlias ("env", cmd_obj_sp);
236 }
237
Caroline Ticeca90c472011-05-06 21:37:15 +0000238 cmd_obj_sp = GetCommandSPExact ("memory read", false);
239 if (cmd_obj_sp)
240 AddAlias ("x", cmd_obj_sp);
241
242 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
243 if (cmd_obj_sp)
244 AddAlias ("up", cmd_obj_sp);
245
246 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
247 if (cmd_obj_sp)
248 AddAlias ("down", cmd_obj_sp);
249
Jason Molenda0c8e0062011-10-25 02:11:20 +0000250 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000251 if (cmd_obj_sp)
252 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000253
254 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
255 if (cmd_obj_sp)
256 AddAlias ("dis", cmd_obj_sp);
257
258 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
259 if (cmd_obj_sp)
260 AddAlias ("di", cmd_obj_sp);
261
262
Jason Molendabc7748b2011-10-22 01:30:52 +0000263
Jason Molenda0c8e0062011-10-25 02:11:20 +0000264 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000265 if (cmd_obj_sp)
266 AddAlias ("undisplay", cmd_obj_sp);
267
Jim Ingham71bf2992012-10-10 16:51:31 +0000268 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
269 if (cmd_obj_sp)
270 AddAlias ("bt", cmd_obj_sp);
271
Caroline Ticeca90c472011-05-06 21:37:15 +0000272 cmd_obj_sp = GetCommandSPExact ("target create", false);
273 if (cmd_obj_sp)
274 AddAlias ("file", cmd_obj_sp);
275
276 cmd_obj_sp = GetCommandSPExact ("target modules", false);
277 if (cmd_obj_sp)
278 AddAlias ("image", cmd_obj_sp);
279
280
281 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000282
Caroline Ticeca90c472011-05-06 21:37:15 +0000283 cmd_obj_sp = GetCommandSPExact ("expression", false);
284 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000285 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000286 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
287 AddAlias ("p", cmd_obj_sp);
288 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000289 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000290 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
291 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000292 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000293
294 alias_arguments_vector_sp.reset (new OptionArgVector);
Enrico Granata7b8c5132012-12-12 03:23:37 +0000295 ProcessAliasOptionsArgs (cmd_obj_sp, "-O --", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000296 AddAlias ("po", cmd_obj_sp);
297 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
298 }
299
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000300 cmd_obj_sp = GetCommandSPExact ("process kill", false);
301 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000302 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000303 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000304 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000305
Caroline Ticeca90c472011-05-06 21:37:15 +0000306 cmd_obj_sp = GetCommandSPExact ("process launch", false);
307 if (cmd_obj_sp)
308 {
309 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda85da3122012-07-06 02:46:23 +0000310#if defined (__arm__)
311 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
312#else
Greg Clayton0ca92a12012-05-18 00:04:38 +0000313 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=/bin/bash --", alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000314#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000315 AddAlias ("r", cmd_obj_sp);
316 AddAlias ("run", cmd_obj_sp);
317 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
318 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
319 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000320
321 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
322 if (cmd_obj_sp)
323 {
324 AddAlias ("add-dsym", cmd_obj_sp);
325 }
Sean Callananfc732752012-05-21 18:25:19 +0000326
327 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
328 if (cmd_obj_sp)
329 {
330 alias_arguments_vector_sp.reset (new OptionArgVector);
331 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000332 AddAlias ("rbreak", cmd_obj_sp);
333 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000334 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000335}
336
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337const char *
338CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
339{
340 // This function has not yet been implemented.
341
342 // Look for any embedded script command
343 // If found,
344 // get interpreter object from the command dictionary,
345 // call execute_one_command on it,
346 // get the results as a string,
347 // substitute that string for current stuff.
348
349 return arg;
350}
351
352
353void
354CommandInterpreter::LoadCommandDictionary ()
355{
356 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
357
Caroline Ticedaccaa92010-09-20 20:44:43 +0000358 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000359
Greg Claytona7015092010-09-18 01:14:36 +0000360 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000361 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000362 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000363 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
364 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000365 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000366 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000367 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
368 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000369 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000370 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000371 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000372 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000373 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000374 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000375 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000376 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000377 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
378 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000379 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000380 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000381 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000382
Jim Inghamca36cd12012-10-05 19:16:31 +0000383 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
384 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000385 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000386 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000387 {"^(-.*)$", "breakpoint set %1"},
388 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000389 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000390 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
391
392 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
393
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394 std::auto_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000395 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000396 "_regexp-break",
Johnny Chenb417dcd2012-08-23 00:32:22 +0000397 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000398 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
399 2,
400 CommandCompletions::eSymbolCompletion |
401 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000402
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000403 if (break_regex_cmd_ap.get())
404 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000405 bool success = true;
406 for (size_t i = 0; i < num_regexes; i++)
407 {
408 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
409 if (!success)
410 break;
411 }
412 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
413
414 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000415 {
416 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
417 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
418 }
419 }
Jim Inghamffba2292011-03-22 02:29:32 +0000420
421 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000422 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
423 "_regexp-tbreak",
424 "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000425 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
426 2,
427 CommandCompletions::eSymbolCompletion |
428 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000429
430 if (tbreak_regex_cmd_ap.get())
431 {
432 bool success = true;
433 for (size_t i = 0; i < num_regexes; i++)
434 {
435 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
436 char buffer[1024];
437 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
438 assert (num_printed < 1024);
439 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
440 if (!success)
441 break;
442 }
443 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
444
445 if (success)
446 {
447 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
448 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
449 }
450 }
451
452 std::auto_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000453 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
454 "_regexp-attach",
455 "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000456 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
457 2));
Johnny Chen6d675242012-08-24 18:15:45 +0000458 if (attach_regex_cmd_ap.get())
459 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000460 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
461 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
462 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
463 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000464 {
465 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
466 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
467 }
468 }
469
470 std::auto_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000471 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000472 "_regexp-down",
473 "Go down \"n\" frames in the stack (1 frame by default).",
474 "_regexp-down [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000475 if (down_regex_cmd_ap.get())
476 {
477 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
478 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
479 {
480 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
481 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
482 }
483 }
484
485 std::auto_ptr<CommandObjectRegexCommand>
486 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000487 "_regexp-up",
488 "Go up \"n\" frames in the stack (1 frame by default).",
489 "_regexp-up [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000490 if (up_regex_cmd_ap.get())
491 {
492 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
493 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
494 {
495 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
496 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
497 }
498 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000499
500 std::auto_ptr<CommandObjectRegexCommand>
501 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000502 "_regexp-display",
503 "Add an expression evaluation stop-hook.",
504 "_regexp-display expression", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000505 if (display_regex_cmd_ap.get())
506 {
507 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
508 {
509 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
510 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
511 }
512 }
513
514 std::auto_ptr<CommandObjectRegexCommand>
515 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000516 "_regexp-undisplay",
517 "Remove an expression evaluation stop-hook.",
518 "_regexp-undisplay stop-hook-number", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000519 if (undisplay_regex_cmd_ap.get())
520 {
521 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
522 {
523 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
524 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
525 }
526 }
527
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000528 std::auto_ptr<CommandObjectRegexCommand>
529 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000530 "gdb-remote",
531 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
532 "gdb-remote [<hostname>:]<portnum>", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000533 if (connect_gdb_remote_cmd_ap.get())
534 {
535 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
536 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
537 {
538 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
539 m_command_dict[command_sp->GetCommandName ()] = command_sp;
540 }
541 }
542
543 std::auto_ptr<CommandObjectRegexCommand>
544 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
545 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000546 "Connect to a remote KDP server. udp port 41139 is the default port number.",
547 "kdp-remote <hostname>[:<portnum>]", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000548 if (connect_kdp_remote_cmd_ap.get())
549 {
550 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000551 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000552 {
553 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
554 m_command_dict[command_sp->GetCommandName ()] = command_sp;
555 }
556 }
557
Jason Molenda4cddfed2012-10-05 05:29:32 +0000558 std::auto_ptr<CommandObjectRegexCommand>
559 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Ingham71bf2992012-10-10 16:51:31 +0000560 "_regexp-bt",
Jason Molenda4cddfed2012-10-05 05:29:32 +0000561 "Show a backtrace. An optional argument is accepted; if that argument is a number, it specifies the number of frames to display. If that argument is 'all', full backtraces of all threads are displayed.",
562 "bt [<digit>|all]", 2));
563 if (bt_regex_cmd_ap.get())
564 {
565 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
566 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
567 // so now "bt 3" is the preferred form, in line with gdb.
568 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
569 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
570 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
571 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
572 {
573 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
574 m_command_dict[command_sp->GetCommandName ()] = command_sp;
575 }
576 }
577
Greg Clayton6bade322013-02-01 23:33:03 +0000578 std::auto_ptr<CommandObjectRegexCommand>
579 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
580 "_regexp-list",
581 "Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the appropriate 'source list' commands.",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000582 "_regexp-list [<line>]\n_regexp-attach [<file>:<line>]\n_regexp-attach [<file>:<line>]",
583 2,
584 CommandCompletions::eSourceFileCompletion));
Greg Clayton6bade322013-02-01 23:33:03 +0000585 if (list_regex_cmd_ap.get())
586 {
587 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
588 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
589 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000590 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000591 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000592 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
593 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
594 {
595 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
596 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
597 }
598 }
599
Greg Claytonef5651d2013-02-12 18:52:24 +0000600 std::auto_ptr<CommandObjectRegexCommand>
601 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000602 "_regexp-env",
603 "Implements a shortcut to viewing and setting environment variables.",
604 "_regexp-env\n_regexp-env FOO=BAR", 2));
Greg Claytonef5651d2013-02-12 18:52:24 +0000605 if (env_regex_cmd_ap.get())
606 {
607 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
608 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
609 {
610 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
611 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
612 }
613 }
614
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000615}
616
617int
618CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
619 StringList &matches)
620{
621 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
622
623 if (include_aliases)
624 {
625 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
626 }
627
628 return matches.GetSize();
629}
630
631CommandObjectSP
632CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
633{
634 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000635 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000636
637 std::string cmd(cmd_cstr);
638
639 if (HasCommands())
640 {
641 pos = m_command_dict.find(cmd);
642 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000643 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000644 }
645
646 if (include_aliases && HasAliases())
647 {
648 pos = m_alias_dict.find(cmd);
649 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000650 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000651 }
652
653 if (HasUserCommands())
654 {
655 pos = m_user_dict.find(cmd);
656 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000657 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000658 }
659
Greg Claytonc7bece562013-01-25 18:06:21 +0000660 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000661 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000662 // We will only get into here if we didn't find any exact matches.
663
664 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
665
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000666 StringList local_matches;
667 if (matches == NULL)
668 matches = &local_matches;
669
Jim Ingham279a6c22010-07-06 22:46:59 +0000670 unsigned int num_cmd_matches = 0;
671 unsigned int num_alias_matches = 0;
672 unsigned int num_user_matches = 0;
673
674 // Look through the command dictionaries one by one, and if we get only one match from any of
675 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
676
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677 if (HasCommands())
678 {
679 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
680 }
681
682 if (num_cmd_matches == 1)
683 {
684 cmd.assign(matches->GetStringAtIndex(0));
685 pos = m_command_dict.find(cmd);
686 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000687 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000688 }
689
Jim Ingham490ac552010-06-24 20:28:42 +0000690 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691 {
692 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
693
694 }
695
Jim Ingham279a6c22010-07-06 22:46:59 +0000696 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000697 {
698 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
699 pos = m_alias_dict.find(cmd);
700 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000701 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000702 }
703
Jim Ingham490ac552010-06-24 20:28:42 +0000704 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000705 {
706 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
707 }
708
Jim Ingham279a6c22010-07-06 22:46:59 +0000709 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710 {
711 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
712
713 pos = m_user_dict.find (cmd);
714 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000715 user_match_sp = pos->second;
716 }
717
718 // If we got exactly one match, return that, otherwise return the match list.
719
720 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
721 {
722 if (num_cmd_matches)
723 return real_match_sp;
724 else if (num_alias_matches)
725 return alias_match_sp;
726 else
727 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000728 }
729 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000730 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000731 {
732 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733 }
734
735
Greg Claytonc7bece562013-01-25 18:06:21 +0000736 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000737}
738
Greg Claytonde164aa2011-04-20 16:37:46 +0000739bool
740CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
741{
742 if (name && name[0])
743 {
744 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000745 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
746 if (found && !can_replace)
747 return false;
748 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000749 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000750 m_command_dict[name_sstr] = cmd_sp;
751 return true;
752 }
753 return false;
754}
755
Enrico Granata223383e2011-08-16 23:24:13 +0000756bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000757CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000758 const lldb::CommandObjectSP &cmd_sp,
759 bool can_replace)
760{
Enrico Granata0a305db2011-11-07 22:57:04 +0000761 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000762 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000763
764 const char* name_cstr = name.c_str();
765
766 // do not allow replacement of internal commands
767 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000768 {
769 if (can_replace == false)
770 return false;
771 if (m_command_dict[name]->IsRemovable() == false)
772 return false;
773 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000774
Enrico Granata21dfcd92012-09-28 23:57:51 +0000775 if (UserCommandExists(name_cstr))
776 {
777 if (can_replace == false)
778 return false;
779 if (m_user_dict[name]->IsRemovable() == false)
780 return false;
781 }
782
Enrico Granata0a305db2011-11-07 22:57:04 +0000783 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000784 return true;
785 }
786 return false;
787}
Greg Claytonde164aa2011-04-20 16:37:46 +0000788
Jim Ingham279a6c22010-07-06 22:46:59 +0000789CommandObjectSP
790CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791{
Caroline Tice472362e2010-12-14 18:51:39 +0000792 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
793 CommandObjectSP ret_val; // Possibly empty return value.
794
795 if (cmd_cstr == NULL)
796 return ret_val;
797
798 if (cmd_words.GetArgumentCount() == 1)
799 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
800 else
801 {
802 // We have a multi-word command (seemingly), so we need to do more work.
803 // First, get the cmd_obj_sp for the first word in the command.
804 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
805 if (cmd_obj_sp.get() != NULL)
806 {
807 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
808 // command name), and find the appropriate sub-command SP for each command word....
809 size_t end = cmd_words.GetArgumentCount();
810 for (size_t j= 1; j < end; ++j)
811 {
812 if (cmd_obj_sp->IsMultiwordObject())
813 {
Greg Clayton998255b2012-10-13 02:07:45 +0000814 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Caroline Tice472362e2010-12-14 18:51:39 +0000815 if (cmd_obj_sp.get() == NULL)
816 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
817 return ret_val;
818 }
819 else
820 // We have more words in the command name, but we don't have a multiword object. Fail and return
821 // empty 'ret_val'.
822 return ret_val;
823 }
824 // We successfully looped through all the command words and got valid command objects for them. Assign the
825 // last object retrieved to 'ret_val'.
826 ret_val = cmd_obj_sp;
827 }
828 }
829 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000830}
831
832CommandObject *
833CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
834{
835 return GetCommandSPExact (cmd_cstr, include_aliases).get();
836}
837
838CommandObject *
839CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
840{
841 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
842
843 // If we didn't find an exact match to the command string in the commands, look in
844 // the aliases.
845
846 if (command_obj == NULL)
847 {
848 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
849 }
850
851 // Finally, if there wasn't an exact match among the aliases, look for an inexact match
852 // in both the commands and the aliases.
853
854 if (command_obj == NULL)
855 command_obj = GetCommandSP(cmd_cstr, true, false, matches).get();
856
857 return command_obj;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000858}
859
860bool
861CommandInterpreter::CommandExists (const char *cmd)
862{
863 return m_command_dict.find(cmd) != m_command_dict.end();
864}
865
866bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000867CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
868 const char *options_args,
869 OptionArgVectorSP &option_arg_vector_sp)
870{
871 bool success = true;
872 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
873
874 if (!options_args || (strlen (options_args) < 1))
875 return true;
876
877 std::string options_string (options_args);
878 Args args (options_args);
879 CommandReturnObject result;
880 // Check to see if the command being aliased can take any command options.
881 Options *options = cmd_obj_sp->GetOptions ();
882 if (options)
883 {
884 // See if any options were specified as part of the alias; if so, handle them appropriately.
885 options->NotifyOptionParsingStarting ();
886 args.Unshift ("dummy_arg");
887 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
888 args.Shift ();
889 if (result.Succeeded())
890 options->VerifyPartialOptions (result);
891 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
892 {
893 result.AppendError ("Unable to create requested alias.\n");
894 return false;
895 }
896 }
897
Greg Clayton5521f992011-10-28 21:38:01 +0000898 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +0000899 {
900 if (cmd_obj_sp->WantsRawCommandString ())
901 option_arg_vector->push_back (OptionArgPair ("<argument>",
902 OptionArgValue (-1,
903 options_string)));
904 else
905 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000906 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +0000907 for (size_t i = 0; i < argc; ++i)
908 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
909 option_arg_vector->push_back
910 (OptionArgPair ("<argument>",
911 OptionArgValue (-1,
912 std::string (args.GetArgumentAtIndex (i)))));
913 }
914 }
915
916 return success;
917}
918
919bool
Jim Ingham298f3782013-04-03 00:25:49 +0000920CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
921{
922 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
923 if (exact_match)
924 {
925 full_name.assign(cmd);
926 return exact_match;
927 }
928 else
929 {
930 StringList matches;
931 size_t num_alias_matches;
932 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
933 if (num_alias_matches == 1)
934 {
935 // Make sure this isn't shadowing a command in the regular command space:
936 StringList regular_matches;
937 const bool include_aliases = false;
938 const bool exact = false;
939 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
940 if (cmd_obj_sp || regular_matches.GetSize() > 0)
941 return false;
942 else
943 {
944 full_name.assign (matches.GetStringAtIndex(0));
945 return true;
946 }
947 }
948 else
949 return false;
950 }
951}
952
953bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000954CommandInterpreter::AliasExists (const char *cmd)
955{
956 return m_alias_dict.find(cmd) != m_alias_dict.end();
957}
958
959bool
960CommandInterpreter::UserCommandExists (const char *cmd)
961{
962 return m_user_dict.find(cmd) != m_user_dict.end();
963}
964
965void
966CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
967{
Jim Ingham279a6c22010-07-06 22:46:59 +0000968 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000969 m_alias_dict[alias_name] = command_obj_sp;
970}
971
972bool
973CommandInterpreter::RemoveAlias (const char *alias_name)
974{
975 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
976 if (pos != m_alias_dict.end())
977 {
978 m_alias_dict.erase(pos);
979 return true;
980 }
981 return false;
982}
983bool
984CommandInterpreter::RemoveUser (const char *alias_name)
985{
986 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
987 if (pos != m_user_dict.end())
988 {
989 m_user_dict.erase(pos);
990 return true;
991 }
992 return false;
993}
994
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000995void
996CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
997{
998 help_string.Printf ("'%s", command_name);
999 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1000
Sean Callanan9a028512012-08-09 00:50:26 +00001001 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002 {
1003 OptionArgVector *options = option_arg_vector_sp.get();
1004 for (int i = 0; i < options->size(); ++i)
1005 {
1006 OptionArgPair cur_option = (*options)[i];
1007 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001008 OptionArgValue value_pair = cur_option.second;
1009 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001010 if (opt.compare("<argument>") == 0)
1011 {
1012 help_string.Printf (" %s", value.c_str());
1013 }
1014 else
1015 {
1016 help_string.Printf (" %s", opt.c_str());
1017 if ((value.compare ("<no-argument>") != 0)
1018 && (value.compare ("<need-argument") != 0))
1019 {
1020 help_string.Printf (" %s", value.c_str());
1021 }
1022 }
1023 }
1024 }
1025
1026 help_string.Printf ("'");
1027}
1028
Greg Clayton12fc3e02010-08-26 22:05:43 +00001029size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001030CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1031{
1032 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001033 CommandObject::CommandMap::const_iterator end = dict.end();
1034 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001035
Greg Clayton12fc3e02010-08-26 22:05:43 +00001036 for (pos = dict.begin(); pos != end; ++pos)
1037 {
1038 size_t len = pos->first.size();
1039 if (max_len < len)
1040 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001041 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001042 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001043}
1044
1045void
Enrico Granata223383e2011-08-16 23:24:13 +00001046CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001047 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048{
1049 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001050 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001051
1052 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001053 {
Enrico Granata223383e2011-08-16 23:24:13 +00001054
1055 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
1056 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001057
Enrico Granata223383e2011-08-16 23:24:13 +00001058 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1059 {
1060 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1061 max_len);
1062 }
1063 result.AppendMessage("");
1064
1065 }
1066
Greg Clayton5521f992011-10-28 21:38:01 +00001067 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001068 {
Jim Ingham49e80a12010-10-22 18:47:16 +00001069 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chenb89982d2011-04-21 00:39:18 +00001070 "(see 'help command alias' for more info):");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001071 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001072 max_len = FindLongestCommandWord (m_alias_dict);
1073
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1075 {
1076 StreamString sstr;
1077 StreamString translation_and_help;
1078 std::string entry_name = pos->first;
1079 std::string second_entry = pos->second.get()->GetCommandName();
1080 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1081
1082 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1083 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1084 translation_and_help.GetData(), max_len);
1085 }
1086 result.AppendMessage("");
1087 }
1088
Greg Clayton5521f992011-10-28 21:38:01 +00001089 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001090 {
1091 result.AppendMessage ("The following is a list of your current user-defined commands:");
1092 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001093 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001094 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1095 {
Enrico Granata223383e2011-08-16 23:24:13 +00001096 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1097 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098 }
1099 result.AppendMessage("");
1100 }
1101
1102 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1103}
1104
Caroline Tice844d2302010-12-09 22:52:49 +00001105CommandObject *
1106CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001107{
Caroline Tice844d2302010-12-09 22:52:49 +00001108 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1109 // eventually be invoked by the given command line.
1110
1111 CommandObject *cmd_obj = NULL;
1112 std::string white_space (" \t\v");
1113 size_t start = command_string.find_first_not_of (white_space);
1114 size_t end = 0;
1115 bool done = false;
1116 while (!done)
1117 {
1118 if (start != std::string::npos)
1119 {
1120 // Get the next word from command_string.
1121 end = command_string.find_first_of (white_space, start);
1122 if (end == std::string::npos)
1123 end = command_string.size();
1124 std::string cmd_word = command_string.substr (start, end - start);
1125
1126 if (cmd_obj == NULL)
1127 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1128 // command or alias.
1129 cmd_obj = GetCommandObject (cmd_word.c_str());
1130 else if (cmd_obj->IsMultiwordObject ())
1131 {
1132 // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object.
Greg Clayton998255b2012-10-13 02:07:45 +00001133 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001134 if (sub_cmd_obj)
1135 cmd_obj = sub_cmd_obj;
1136 else // cmd_word was not a valid sub-command word, so we are donee
1137 done = true;
1138 }
1139 else
1140 // We have a cmd_obj and it is not a multi-word object, so we are done.
1141 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142
Caroline Tice844d2302010-12-09 22:52:49 +00001143 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1144 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1145 // next word.
1146
1147 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1148 done = true;
1149 else
1150 start = command_string.find_first_not_of (white_space, end);
1151 }
1152 else
1153 // Unable to find any more words.
1154 done = true;
1155 }
1156
1157 if (end == command_string.size())
1158 command_string.clear();
1159 else
1160 command_string = command_string.substr(end);
1161
1162 return cmd_obj;
1163}
1164
Greg Clayton51964162011-10-25 00:36:27 +00001165static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001166static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001167static void
1168StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001169{
Greg Clayton51964162011-10-25 00:36:27 +00001170 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001171 {
Greg Clayton51964162011-10-25 00:36:27 +00001172 size_t pos = s.find_first_not_of (k_white_space);
1173 if (pos == std::string::npos)
1174 s.clear();
1175 else if (pos == 0)
1176 return;
1177 s.erase (0, pos);
1178 }
1179}
1180
Greg Clayton93c62e62011-11-09 23:25:03 +00001181static size_t
1182FindArgumentTerminator (const std::string &s)
1183{
Greg Clayton93c62e62011-11-09 23:25:03 +00001184 const size_t s_len = s.size();
1185 size_t offset = 0;
1186 while (offset < s_len)
1187 {
1188 size_t pos = s.find ("--", offset);
1189 if (pos == std::string::npos)
1190 break;
1191 if (pos > 0)
1192 {
1193 if (isspace(s[pos-1]))
1194 {
1195 // Check if the string ends "\s--" (where \s is a space character)
1196 // or if we have "\s--\s".
1197 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1198 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001199 return pos;
1200 }
1201 }
1202 }
1203 offset = pos + 2;
1204 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001205 return std::string::npos;
1206}
1207
Greg Clayton51964162011-10-25 00:36:27 +00001208static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001209ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001210{
Greg Clayton5521f992011-10-28 21:38:01 +00001211 command.clear();
1212 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001213 StripLeadingSpaces (command_string);
1214
1215 bool result = false;
1216 quote_char = '\0';
1217
1218 if (!command_string.empty())
1219 {
1220 const char first_char = command_string[0];
1221 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001222 {
Greg Clayton51964162011-10-25 00:36:27 +00001223 quote_char = first_char;
1224 const size_t end_quote_pos = command_string.find (quote_char, 1);
1225 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001226 {
Greg Clayton5521f992011-10-28 21:38:01 +00001227 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001228 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001229 }
1230 else
1231 {
Greg Clayton5521f992011-10-28 21:38:01 +00001232 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001233 if (end_quote_pos + 1 < command_string.size())
1234 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1235 else
1236 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001237 }
Caroline Tice844d2302010-12-09 22:52:49 +00001238 }
1239 else
1240 {
Greg Clayton51964162011-10-25 00:36:27 +00001241 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1242 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001243 {
Greg Clayton5521f992011-10-28 21:38:01 +00001244 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001245 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001246 }
1247 else
1248 {
Greg Clayton5521f992011-10-28 21:38:01 +00001249 command.assign (command_string, 0, first_space_pos);
1250 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001251 }
Caroline Tice844d2302010-12-09 22:52:49 +00001252 }
Greg Clayton51964162011-10-25 00:36:27 +00001253 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001254 }
Greg Clayton5521f992011-10-28 21:38:01 +00001255
1256
1257 if (!command.empty())
1258 {
1259 // actual commands can't start with '-' or '_'
1260 if (command[0] != '-' && command[0] != '_')
1261 {
1262 size_t pos = command.find_first_not_of(k_valid_command_chars);
1263 if (pos > 0 && pos != std::string::npos)
1264 {
1265 suffix.assign (command.begin() + pos, command.end());
1266 command.erase (pos);
1267 }
1268 }
1269 }
Greg Clayton51964162011-10-25 00:36:27 +00001270
1271 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001272}
1273
Greg Clayton5521f992011-10-28 21:38:01 +00001274CommandObject *
1275CommandInterpreter::BuildAliasResult (const char *alias_name,
1276 std::string &raw_input_string,
1277 std::string &alias_result,
1278 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001279{
Greg Clayton5521f992011-10-28 21:38:01 +00001280 CommandObject *alias_cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001281 Args cmd_args (raw_input_string.c_str());
1282 alias_cmd_obj = GetCommandObject (alias_name);
1283 StreamString result_str;
1284
1285 if (alias_cmd_obj)
1286 {
1287 std::string alias_name_str = alias_name;
1288 if ((cmd_args.GetArgumentCount() == 0)
1289 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1290 cmd_args.Unshift (alias_name);
1291
1292 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1293 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1294
1295 if (option_arg_vector_sp.get())
1296 {
1297 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1298
1299 for (int i = 0; i < option_arg_vector->size(); ++i)
1300 {
1301 OptionArgPair option_pair = (*option_arg_vector)[i];
1302 OptionArgValue value_pair = option_pair.second;
1303 int value_type = value_pair.first;
1304 std::string option = option_pair.first;
1305 std::string value = value_pair.second;
1306 if (option.compare ("<argument>") == 0)
1307 result_str.Printf (" %s", value.c_str());
1308 else
1309 {
1310 result_str.Printf (" %s", option.c_str());
1311 if (value_type != optional_argument)
1312 result_str.Printf (" ");
1313 if (value.compare ("<no_argument>") != 0)
1314 {
1315 int index = GetOptionArgumentPosition (value.c_str());
1316 if (index == 0)
1317 result_str.Printf ("%s", value.c_str());
1318 else if (index >= cmd_args.GetArgumentCount())
1319 {
1320
1321 result.AppendErrorWithFormat
1322 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1323 index);
1324 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001325 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001326 }
1327 else
1328 {
1329 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1330 if (strpos != std::string::npos)
1331 raw_input_string = raw_input_string.erase (strpos,
1332 strlen (cmd_args.GetArgumentAtIndex (index)));
1333 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1334 }
1335 }
1336 }
1337 }
1338 }
1339
1340 alias_result = result_str.GetData();
1341 }
Greg Clayton5521f992011-10-28 21:38:01 +00001342 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001343}
1344
Greg Clayton5a314712011-10-14 07:41:33 +00001345Error
1346CommandInterpreter::PreprocessCommand (std::string &command)
1347{
1348 // The command preprocessor needs to do things to the command
1349 // line before any parsing of arguments or anything else is done.
1350 // The only current stuff that gets proprocessed is anyting enclosed
1351 // in backtick ('`') characters is evaluated as an expression and
1352 // the result of the expression must be a scalar that can be substituted
1353 // into the command. An example would be:
1354 // (lldb) memory read `$rsp + 20`
1355 Error error; // Error for any expressions that might not evaluate
1356 size_t start_backtick;
1357 size_t pos = 0;
1358 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1359 {
1360 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1361 {
1362 // The backtick was preceeded by a '\' character, remove the slash
1363 // and don't treat the backtick as the start of an expression
1364 command.erase(start_backtick-1, 1);
1365 // No need to add one to start_backtick since we just deleted a char
1366 pos = start_backtick;
1367 }
1368 else
1369 {
1370 const size_t expr_content_start = start_backtick + 1;
1371 const size_t end_backtick = command.find ('`', expr_content_start);
1372 if (end_backtick == std::string::npos)
1373 return error;
1374 else if (end_backtick == expr_content_start)
1375 {
1376 // Empty expression (two backticks in a row)
1377 command.erase (start_backtick, 2);
1378 }
1379 else
1380 {
1381 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1382
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001383 ExecutionContext exe_ctx(GetExecutionContext());
1384 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001385 // Get a dummy target to allow for calculator mode while processing backticks.
1386 // This also helps break the infinite loop caused when target is null.
1387 if (!target)
1388 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Clayton5a314712011-10-14 07:41:33 +00001389 if (target)
1390 {
Greg Clayton5a314712011-10-14 07:41:33 +00001391 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001392
Jim Ingham35e1bda2012-10-16 21:41:58 +00001393 EvaluateExpressionOptions options;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001394 options.SetCoerceToId(false)
1395 .SetUnwindOnError(true)
Jim Ingham184e9812013-01-15 02:47:48 +00001396 .SetIgnoreBreakpoints(true)
Enrico Granatad4439aa2012-09-05 20:41:26 +00001397 .SetKeepInMemory(false)
Jim Ingham35e1bda2012-10-16 21:41:58 +00001398 .SetRunOthers(true)
1399 .SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001400
Greg Clayton5a314712011-10-14 07:41:33 +00001401 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad4439aa2012-09-05 20:41:26 +00001402 exe_ctx.GetFramePtr(),
Enrico Granata3372f582012-07-16 23:10:35 +00001403 expr_result_valobj_sp,
Enrico Granatad4439aa2012-09-05 20:41:26 +00001404 options);
1405
Greg Clayton5a314712011-10-14 07:41:33 +00001406 if (expr_result == eExecutionCompleted)
1407 {
1408 Scalar scalar;
1409 if (expr_result_valobj_sp->ResolveValue (scalar))
1410 {
1411 command.erase (start_backtick, end_backtick - start_backtick + 1);
1412 StreamString value_strm;
1413 const bool show_type = false;
1414 scalar.GetValue (&value_strm, show_type);
1415 size_t value_string_size = value_strm.GetSize();
1416 if (value_string_size)
1417 {
1418 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1419 pos = start_backtick + value_string_size;
1420 continue;
1421 }
1422 else
1423 {
1424 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1425 }
1426 }
1427 else
1428 {
1429 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1430 }
1431 }
1432 else
1433 {
1434 if (expr_result_valobj_sp)
1435 error = expr_result_valobj_sp->GetError();
1436 if (error.Success())
1437 {
1438
1439 switch (expr_result)
1440 {
1441 case eExecutionSetupError:
1442 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1443 break;
1444 case eExecutionCompleted:
1445 break;
1446 case eExecutionDiscarded:
1447 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1448 break;
1449 case eExecutionInterrupted:
1450 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1451 break;
Jim Ingham184e9812013-01-15 02:47:48 +00001452 case eExecutionHitBreakpoint:
1453 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1454 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001455 case eExecutionTimedOut:
1456 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1457 break;
1458 }
1459 }
1460 }
1461 }
1462 }
1463 if (error.Fail())
1464 break;
1465 }
1466 }
1467 return error;
1468}
1469
1470
Caroline Tice844d2302010-12-09 22:52:49 +00001471bool
1472CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001473 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001474 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001475 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001476 bool repeat_on_empty_command,
1477 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001478
Caroline Tice844d2302010-12-09 22:52:49 +00001479{
Jim Inghame16c50a2011-02-18 00:54:25 +00001480
Caroline Tice844d2302010-12-09 22:52:49 +00001481 bool done = false;
1482 CommandObject *cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001483 bool wants_raw_input = false;
1484 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001485 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001486
Greg Clayton5160ce52013-03-27 23:08:40 +00001487 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001488 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1489
1490 // Make a scoped cleanup object that will clear the crash description string
1491 // on exit of this function.
Enrico Granataf9fa6ee2011-07-12 00:18:11 +00001492 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001493
Caroline Tice844d2302010-12-09 22:52:49 +00001494 if (log)
1495 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001496
Jim Ingham30244832010-11-04 23:08:45 +00001497 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1498
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001499 if (!no_context_switching)
1500 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001501
1502 // <rdar://problem/11328896>
1503 bool add_to_history;
1504 if (lazy_add_to_history == eLazyBoolCalculate)
1505 add_to_history = (m_command_source_depth == 0);
1506 else
1507 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1508
Jim Inghame16c50a2011-02-18 00:54:25 +00001509 bool empty_command = false;
1510 bool comment_command = false;
1511 if (command_string.empty())
1512 empty_command = true;
1513 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001514 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001515 const char *k_space_characters = "\t\n\v\f\r ";
1516
1517 size_t non_space = command_string.find_first_not_of (k_space_characters);
1518 // Check for empty line or comment line (lines whose first
1519 // non-space character is the comment character for this interpreter)
1520 if (non_space == std::string::npos)
1521 empty_command = true;
1522 else if (command_string[non_space] == m_comment_char)
1523 comment_command = true;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001524 else if (command_string[non_space] == m_repeat_char)
1525 {
1526 const char *history_string = FindHistoryString (command_string.c_str() + non_space);
1527 if (history_string == NULL)
1528 {
1529 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1530 result.SetStatus(eReturnStatusFailed);
1531 return false;
1532 }
1533 add_to_history = false;
1534 command_string = history_string;
1535 original_command_string = history_string;
1536 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001537 }
1538
1539 if (empty_command)
1540 {
1541 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001542 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001543 if (m_command_history.empty())
1544 {
1545 result.AppendError ("empty command");
1546 result.SetStatus(eReturnStatusFailed);
1547 return false;
1548 }
1549 else
1550 {
1551 command_line = m_repeat_command.c_str();
1552 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001553 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001554 if (m_repeat_command.empty())
1555 {
1556 result.AppendErrorWithFormat("No auto repeat.\n");
1557 result.SetStatus (eReturnStatusFailed);
1558 return false;
1559 }
1560 }
1561 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001562 }
1563 else
1564 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001565 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1566 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001567 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001568 }
1569 else if (comment_command)
1570 {
1571 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1572 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001573 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001574
Greg Clayton5a314712011-10-14 07:41:33 +00001575
1576 Error error (PreprocessCommand (command_string));
1577
1578 if (error.Fail())
1579 {
1580 result.AppendError (error.AsCString());
1581 result.SetStatus(eReturnStatusFailed);
1582 return false;
1583 }
Caroline Tice844d2302010-12-09 22:52:49 +00001584 // Phase 1.
1585
1586 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1587 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1588 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1589 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1590 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
Greg Clayton710dd5a2011-01-08 20:28:42 +00001591 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001592 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001593
Caroline Tice844d2302010-12-09 22:52:49 +00001594 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001595 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001596 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001597 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001598 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001599 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001600 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001601 std::string suffix;
1602 ExtractCommand (command_string, next_word, suffix, quote_char);
1603 if (cmd_obj == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001604 {
Jim Ingham298f3782013-04-03 00:25:49 +00001605 std::string full_name;
1606 if (GetAliasFullName(next_word.c_str(), full_name))
Caroline Tice472362e2010-12-14 18:51:39 +00001607 {
Greg Clayton5521f992011-10-28 21:38:01 +00001608 std::string alias_result;
Jim Ingham298f3782013-04-03 00:25:49 +00001609 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
Greg Clayton5521f992011-10-28 21:38:01 +00001610 revised_command_line.Printf ("%s", alias_result.c_str());
1611 if (cmd_obj)
1612 {
1613 wants_raw_input = cmd_obj->WantsRawCommandString ();
1614 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1615 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001616 }
1617 else
1618 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001619 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001620 if (cmd_obj)
1621 {
1622 actual_cmd_name_len += next_word.length();
1623 revised_command_line.Printf ("%s", next_word.c_str());
1624 wants_raw_input = cmd_obj->WantsRawCommandString ();
1625 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001626 else
Greg Clayton5521f992011-10-28 21:38:01 +00001627 {
1628 revised_command_line.Printf ("%s", next_word.c_str());
1629 }
Caroline Tice844d2302010-12-09 22:52:49 +00001630 }
1631 }
1632 else
1633 {
Greg Clayton5521f992011-10-28 21:38:01 +00001634 if (cmd_obj->IsMultiwordObject ())
1635 {
Greg Clayton998255b2012-10-13 02:07:45 +00001636 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001637 if (sub_cmd_obj)
1638 {
1639 actual_cmd_name_len += next_word.length() + 1;
1640 revised_command_line.Printf (" %s", next_word.c_str());
1641 cmd_obj = sub_cmd_obj;
1642 wants_raw_input = cmd_obj->WantsRawCommandString ();
1643 }
1644 else
1645 {
1646 if (quote_char)
1647 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1648 else
1649 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1650 done = true;
1651 }
1652 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001653 else
Greg Clayton5521f992011-10-28 21:38:01 +00001654 {
1655 if (quote_char)
1656 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1657 else
1658 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1659 done = true;
1660 }
Caroline Tice844d2302010-12-09 22:52:49 +00001661 }
1662
1663 if (cmd_obj == NULL)
1664 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001665 const size_t num_matches = matches.GetSize();
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001666 if (matches.GetSize() > 1) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001667 StreamString error_msg;
1668 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001669
1670 for (uint32_t i = 0; i < num_matches; ++i) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001671 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001672 }
Greg Claytonc7bece562013-01-25 18:06:21 +00001673 result.AppendRawError (error_msg.GetString().c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001674 } else {
1675 // We didn't have only one match, otherwise we wouldn't get here.
1676 assert(num_matches == 0);
1677 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1678 }
Caroline Tice844d2302010-12-09 22:52:49 +00001679 result.SetStatus (eReturnStatusFailed);
1680 return false;
1681 }
1682
Greg Clayton5521f992011-10-28 21:38:01 +00001683 if (cmd_obj->IsMultiwordObject ())
1684 {
1685 if (!suffix.empty())
1686 {
1687
1688 result.AppendErrorWithFormat ("multi-word commands ('%s') can't have shorthand suffixes: '%s'\n",
1689 next_word.c_str(),
1690 suffix.c_str());
1691 result.SetStatus (eReturnStatusFailed);
1692 return false;
1693 }
1694 }
1695 else
1696 {
1697 // If we found a normal command, we are done
1698 done = true;
1699 if (!suffix.empty())
1700 {
1701 switch (suffix[0])
1702 {
1703 case '/':
1704 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001705 {
1706 Options *command_options = cmd_obj->GetOptions();
1707 if (command_options && command_options->SupportsLongOption("gdb-format"))
1708 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001709 std::string gdb_format_option ("--gdb-format=");
1710 gdb_format_option += (suffix.c_str() + 1);
1711
1712 bool inserted = false;
1713 std::string &cmd = revised_command_line.GetString();
1714 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1715 if (arg_terminator_idx != std::string::npos)
1716 {
1717 // Insert the gdb format option before the "--" that terminates options
1718 gdb_format_option.append(1,' ');
1719 cmd.insert(arg_terminator_idx, gdb_format_option);
1720 inserted = true;
1721 }
1722
1723 if (!inserted)
1724 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1725
1726 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1727 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001728 }
1729 else
1730 {
1731 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1732 cmd_obj->GetCommandName());
1733 result.SetStatus (eReturnStatusFailed);
1734 return false;
1735 }
1736 }
Greg Clayton5521f992011-10-28 21:38:01 +00001737 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001738
1739 default:
1740 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1741 suffix.c_str());
1742 result.SetStatus (eReturnStatusFailed);
1743 return false;
1744
Greg Clayton5521f992011-10-28 21:38:01 +00001745 }
1746 }
1747 }
Caroline Tice844d2302010-12-09 22:52:49 +00001748 if (command_string.length() == 0)
1749 done = true;
1750
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001751 }
Caroline Tice844d2302010-12-09 22:52:49 +00001752
Greg Clayton5521f992011-10-28 21:38:01 +00001753 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001754 revised_command_line.Printf (" %s", command_string.c_str());
1755
1756 // End of Phase 1.
1757 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1758 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1759 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1760 // wants_raw_input specifies whether the Execute method expects raw input or not.
1761
1762
1763 if (log)
1764 {
1765 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1766 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1767 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1768 }
1769
1770 // Phase 2.
1771 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1772 // CommandObject, with the appropriate arguments.
1773
1774 if (cmd_obj != NULL)
1775 {
1776 if (add_to_history)
1777 {
1778 Args command_args (revised_command_line.GetData());
1779 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1780 if (repeat_command != NULL)
1781 m_repeat_command.assign(repeat_command);
1782 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001783 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001784
Jim Inghama5a97eb2011-07-12 03:12:18 +00001785 // Don't keep pushing the same command onto the history...
Greg Clayton5521f992011-10-28 21:38:01 +00001786 if (m_command_history.empty() || m_command_history.back() != original_command_string)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001787 m_command_history.push_back (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001788 }
1789
1790 command_string = revised_command_line.GetData();
1791 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001792 std::string remainder;
1793 if (actual_cmd_name_len < command_string.length())
1794 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1795 // than cmd_obj->GetCommandName(), because name completion
1796 // allows users to enter short versions of the names,
1797 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001798
1799 // Remove any initial spaces
1800 std::string white_space (" \t\v");
1801 size_t pos = remainder.find_first_not_of (white_space);
1802 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001803 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001804
1805 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001806 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001807
Jim Ingham5a988412012-06-08 21:56:10 +00001808 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001809 }
1810 else
1811 {
1812 // We didn't find the first command object, so complete the first argument.
1813 Args command_args (revised_command_line.GetData());
1814 StringList matches;
1815 int num_matches;
1816 int cursor_index = 0;
1817 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1818 bool word_complete;
1819 num_matches = HandleCompletionMatches (command_args,
1820 cursor_index,
1821 cursor_char_position,
1822 0,
1823 -1,
1824 word_complete,
1825 matches);
1826
1827 if (num_matches > 0)
1828 {
1829 std::string error_msg;
1830 error_msg.assign ("ambiguous command '");
1831 error_msg.append(command_args.GetArgumentAtIndex(0));
1832 error_msg.append ("'.");
1833
1834 error_msg.append (" Possible completions:");
1835 for (int i = 0; i < num_matches; i++)
1836 {
1837 error_msg.append ("\n\t");
1838 error_msg.append (matches.GetStringAtIndex (i));
1839 }
1840 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001841 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001842 }
1843 else
1844 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1845
1846 result.SetStatus (eReturnStatusFailed);
1847 }
1848
Jason Molendabfb36ff2011-08-25 00:20:04 +00001849 if (log)
1850 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1851
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001852 return result.Succeeded();
1853}
1854
1855int
1856CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1857 int &cursor_index,
1858 int &cursor_char_position,
1859 int match_start_point,
1860 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001861 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001862 StringList &matches)
1863{
1864 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001865 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001866
1867 // For any of the command completions a unique match will be a complete word.
1868 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001869
1870 if (cursor_index == -1)
1871 {
1872 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001873 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001874 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1875 }
1876 else if (cursor_index == 0)
1877 {
1878 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001879 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001880 num_command_matches = matches.GetSize();
1881
1882 if (num_command_matches == 1
1883 && cmd_obj && cmd_obj->IsMultiwordObject()
1884 && matches.GetStringAtIndex(0) != NULL
1885 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1886 {
1887 look_for_subcommand = true;
1888 num_command_matches = 0;
1889 matches.DeleteStringAtIndex(0);
1890 parsed_line.AppendArgument ("");
1891 cursor_index++;
1892 cursor_char_position = 0;
1893 }
1894 }
1895
1896 if (cursor_index > 0 || look_for_subcommand)
1897 {
1898 // We are completing further on into a commands arguments, so find the command and tell it
1899 // to complete the command.
1900 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001901 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001902 if (command_object == NULL)
1903 {
1904 return 0;
1905 }
1906 else
1907 {
1908 parsed_line.Shift();
1909 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001910 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001911 cursor_index,
1912 cursor_char_position,
1913 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001914 max_return_elements,
1915 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001916 matches);
1917 }
1918 }
1919
1920 return num_command_matches;
1921
1922}
1923
1924int
1925CommandInterpreter::HandleCompletion (const char *current_line,
1926 const char *cursor,
1927 const char *last_char,
1928 int match_start_point,
1929 int max_return_elements,
1930 StringList &matches)
1931{
1932 // We parse the argument up to the cursor, so the last argument in parsed_line is
1933 // the one containing the cursor, and the cursor is after the last character.
1934
1935 Args parsed_line(current_line, last_char - current_line);
1936 Args partial_parsed_line(current_line, cursor - current_line);
1937
Jim Inghama5a97eb2011-07-12 03:12:18 +00001938 // Don't complete comments, and if the line we are completing is just the history repeat character,
1939 // substitute the appropriate history line.
1940 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1941 if (first_arg)
1942 {
1943 if (first_arg[0] == m_comment_char)
1944 return 0;
1945 else if (first_arg[0] == m_repeat_char)
1946 {
1947 const char *history_string = FindHistoryString (first_arg);
1948 if (history_string != NULL)
1949 {
1950 matches.Clear();
1951 matches.InsertStringAtIndex(0, history_string);
1952 return -2;
1953 }
1954 else
1955 return 0;
1956
1957 }
1958 }
1959
1960
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001961 int num_args = partial_parsed_line.GetArgumentCount();
1962 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1963 int cursor_char_position;
1964
1965 if (cursor_index == -1)
1966 cursor_char_position = 0;
1967 else
1968 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00001969
1970 if (cursor > current_line && cursor[-1] == ' ')
1971 {
1972 // We are just after a space. If we are in an argument, then we will continue
1973 // parsing, but if we are between arguments, then we have to complete whatever the next
1974 // element would be.
1975 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1976 // protected by a quote) then the space will also be in the parsed argument...
1977
1978 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1979 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1980 {
1981 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
1982 cursor_index++;
1983 cursor_char_position = 0;
1984 }
1985 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001986
1987 int num_command_matches;
1988
1989 matches.Clear();
1990
1991 // Only max_return_elements == -1 is supported at present:
1992 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00001993 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00001994 num_command_matches = HandleCompletionMatches (parsed_line,
1995 cursor_index,
1996 cursor_char_position,
1997 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001998 max_return_elements,
1999 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002000 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002001
2002 if (num_command_matches <= 0)
2003 return num_command_matches;
2004
2005 if (num_args == 0)
2006 {
2007 // If we got an empty string, insert nothing.
2008 matches.InsertStringAtIndex(0, "");
2009 }
2010 else
2011 {
2012 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2013 // put an empty string in element 0.
2014 std::string command_partial_str;
2015 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002016 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2017 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002018
2019 std::string common_prefix;
2020 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002021 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002022
2023 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002024 // Only do this if the completer told us this was a complete word, however...
2025 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002026 {
2027 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2028 if (quote_char != '\0')
2029 common_prefix.push_back(quote_char);
2030
2031 common_prefix.push_back(' ');
2032 }
2033 common_prefix.erase (0, partial_name_len);
2034 matches.InsertStringAtIndex(0, common_prefix.c_str());
2035 }
2036 return num_command_matches;
2037}
2038
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002039
2040CommandInterpreter::~CommandInterpreter ()
2041{
2042}
2043
2044const char *
2045CommandInterpreter::GetPrompt ()
2046{
Caroline Ticedaccaa92010-09-20 20:44:43 +00002047 return m_debugger.GetPrompt();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002048}
2049
2050void
2051CommandInterpreter::SetPrompt (const char *new_prompt)
2052{
Caroline Ticedaccaa92010-09-20 20:44:43 +00002053 m_debugger.SetPrompt (new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002054}
2055
Jim Ingham97a6dc72010-10-04 19:49:29 +00002056size_t
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002057CommandInterpreter::GetConfirmationInputReaderCallback
2058(
2059 void *baton,
2060 InputReader &reader,
2061 lldb::InputReaderAction action,
2062 const char *bytes,
2063 size_t bytes_len
2064)
Jim Ingham97a6dc72010-10-04 19:49:29 +00002065{
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002066 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002067 bool *response_ptr = (bool *) baton;
2068
2069 switch (action)
2070 {
2071 case eInputReaderActivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002072 if (out_file.IsValid())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002073 {
2074 if (reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002075 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002076 out_file.Printf ("%s", reader.GetPrompt());
2077 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002078 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002079 }
2080 break;
2081
2082 case eInputReaderDeactivate:
2083 break;
2084
2085 case eInputReaderReactivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002086 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002087 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002088 out_file.Printf ("%s", reader.GetPrompt());
2089 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002090 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002091 break;
Caroline Tice969ed3d2011-05-02 20:41:46 +00002092
2093 case eInputReaderAsynchronousOutputWritten:
2094 break;
2095
Jim Ingham97a6dc72010-10-04 19:49:29 +00002096 case eInputReaderGotToken:
2097 if (bytes_len == 0)
2098 {
2099 reader.SetIsDone(true);
2100 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002101 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002102 {
2103 *response_ptr = true;
2104 reader.SetIsDone(true);
2105 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002106 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002107 {
2108 *response_ptr = false;
2109 reader.SetIsDone(true);
2110 }
2111 else
2112 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002113 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002114 {
Jim Ingham78d61482011-11-17 01:22:00 +00002115 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002116 out_file.Flush ();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002117 }
2118 }
2119 break;
2120
Caroline Ticeefed6132010-11-19 20:47:54 +00002121 case eInputReaderInterrupt:
2122 case eInputReaderEndOfFile:
2123 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2124 reader.SetIsDone (true);
2125 break;
2126
Jim Ingham97a6dc72010-10-04 19:49:29 +00002127 case eInputReaderDone:
2128 break;
2129 }
2130
2131 return bytes_len;
2132
2133}
2134
2135bool
2136CommandInterpreter::Confirm (const char *message, bool default_answer)
2137{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002138 // Check AutoConfirm first:
2139 if (m_debugger.GetAutoConfirm())
2140 return default_answer;
2141
Jim Ingham97a6dc72010-10-04 19:49:29 +00002142 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2143 bool response = default_answer;
2144 if (reader_sp)
2145 {
2146 std::string prompt(message);
2147 prompt.append(": [");
2148 if (default_answer)
2149 prompt.append ("Y/n] ");
2150 else
2151 prompt.append ("y/N] ");
2152
2153 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2154 &response, // baton
2155 eInputReaderGranularityLine, // token size, to pass to callback function
2156 NULL, // end token
2157 prompt.c_str(), // prompt
2158 true)); // echo input
2159 if (err.Success())
2160 {
2161 GetDebugger().PushInputReader (reader_sp);
2162 }
2163 reader_sp->WaitOnReaderIsDone();
2164 }
2165 return response;
2166}
2167
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002168OptionArgVectorSP
2169CommandInterpreter::GetAliasOptions (const char *alias_name)
2170{
2171 OptionArgMap::iterator pos;
2172 OptionArgVectorSP ret_val;
2173
2174 std::string alias (alias_name);
2175
2176 if (HasAliasOptions())
2177 {
2178 pos = m_alias_options.find (alias);
2179 if (pos != m_alias_options.end())
2180 ret_val = pos->second;
2181 }
2182
2183 return ret_val;
2184}
2185
2186void
2187CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2188{
2189 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2190 if (pos != m_alias_options.end())
2191 {
2192 m_alias_options.erase (pos);
2193 }
2194}
2195
2196void
2197CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2198{
2199 m_alias_options[alias_name] = option_arg_vector_sp;
2200}
2201
2202bool
2203CommandInterpreter::HasCommands ()
2204{
2205 return (!m_command_dict.empty());
2206}
2207
2208bool
2209CommandInterpreter::HasAliases ()
2210{
2211 return (!m_alias_dict.empty());
2212}
2213
2214bool
2215CommandInterpreter::HasUserCommands ()
2216{
2217 return (!m_user_dict.empty());
2218}
2219
2220bool
2221CommandInterpreter::HasAliasOptions ()
2222{
2223 return (!m_alias_options.empty());
2224}
2225
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002226void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002227CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2228 const char *alias_name,
2229 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002230 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002231 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002232{
2233 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002234
2235 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002236
Caroline Ticed9d63362010-12-07 19:58:26 +00002237 // Make sure that the alias name is the 0th element in cmd_args
2238 std::string alias_name_str = alias_name;
2239 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2240 cmd_args.Unshift (alias_name);
2241
2242 Args new_args (alias_cmd_obj->GetCommandName());
2243 if (new_args.GetArgumentCount() == 2)
2244 new_args.Shift();
2245
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002246 if (option_arg_vector_sp.get())
2247 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002248 if (wants_raw_input)
2249 {
2250 // We have a command that both has command options and takes raw input. Make *sure* it has a
2251 // " -- " in the right place in the raw_input_string.
2252 size_t pos = raw_input_string.find(" -- ");
2253 if (pos == std::string::npos)
2254 {
2255 // None found; assume it goes at the beginning of the raw input string
2256 raw_input_string.insert (0, " -- ");
2257 }
2258 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002259
2260 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002261 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002262 std::vector<bool> used (old_size + 1, false);
2263
2264 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002265
2266 for (int i = 0; i < option_arg_vector->size(); ++i)
2267 {
2268 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002269 OptionArgValue value_pair = option_pair.second;
2270 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002271 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002272 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002273 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002274 {
2275 if (!wants_raw_input
2276 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2277 new_args.AppendArgument (value.c_str());
2278 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002279 else
2280 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002281 if (value_type != optional_argument)
2282 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002283 if (value.compare ("<no-argument>") != 0)
2284 {
2285 int index = GetOptionArgumentPosition (value.c_str());
2286 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002287 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002288 // value was NOT a positional argument; must be a real value
Caroline Ticed9d63362010-12-07 19:58:26 +00002289 if (value_type != optional_argument)
2290 new_args.AppendArgument (value.c_str());
2291 else
2292 {
2293 char buffer[255];
2294 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2295 new_args.AppendArgument (buffer);
2296 }
2297
2298 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002299 else if (index >= cmd_args.GetArgumentCount())
2300 {
2301 result.AppendErrorWithFormat
2302 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2303 index);
2304 result.SetStatus (eReturnStatusFailed);
2305 return;
2306 }
2307 else
2308 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002309 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2310 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2311 if (strpos != std::string::npos)
2312 {
2313 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2314 }
2315
2316 if (value_type != optional_argument)
2317 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2318 else
2319 {
2320 char buffer[255];
2321 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2322 cmd_args.GetArgumentAtIndex (index));
2323 new_args.AppendArgument (buffer);
2324 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002325 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326 }
2327 }
2328 }
2329 }
2330
2331 for (int j = 0; j < cmd_args.GetArgumentCount(); ++j)
2332 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002333 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002334 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2335 }
2336
2337 cmd_args.Clear();
2338 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2339 }
2340 else
2341 {
2342 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002343 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2344 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2345 // input string.
2346 if (wants_raw_input)
2347 {
2348 cmd_args.Clear();
2349 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2350 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002351 return;
2352 }
2353
2354 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2355 return;
2356}
2357
2358
2359int
2360CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2361{
2362 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2363 // of zero.
2364
2365 char *cptr = (char *) in_string;
2366
2367 // Does it start with '%'
2368 if (cptr[0] == '%')
2369 {
2370 ++cptr;
2371
2372 // Is the rest of it entirely digits?
2373 if (isdigit (cptr[0]))
2374 {
2375 const char *start = cptr;
2376 while (isdigit (cptr[0]))
2377 ++cptr;
2378
2379 // We've gotten to the end of the digits; are we at the end of the string?
2380 if (cptr[0] == '\0')
2381 position = atoi (start);
2382 }
2383 }
2384
2385 return position;
2386}
2387
2388void
2389CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2390{
Jim Ingham16e0c682011-08-12 23:34:31 +00002391 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002392 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002393 {
Greg Clayton14a35512011-09-11 00:01:44 +00002394 // In the current working directory we don't load any program specific
2395 // .lldbinit files, we only look for a "./.lldbinit" file.
2396 if (m_skip_lldbinit_files)
2397 return;
2398
2399 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002400 }
Greg Clayton14a35512011-09-11 00:01:44 +00002401 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002402 {
Greg Clayton14a35512011-09-11 00:01:44 +00002403 // If we aren't looking in the current working directory we are looking
2404 // in the home directory. We will first see if there is an application
2405 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2406 // "-" and the name of the program. If this file doesn't exist, we fall
2407 // back to just the "~/.lldbinit" file. We also obey any requests to not
2408 // load the init files.
2409 const char *init_file_path = "~/.lldbinit";
2410
2411 if (m_skip_app_init_files == false)
2412 {
2413 FileSpec program_file_spec (Host::GetProgramFileSpec());
2414 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002415
Greg Clayton14a35512011-09-11 00:01:44 +00002416 if (program_name)
2417 {
2418 char program_init_file_name[PATH_MAX];
2419 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2420 init_file.SetFile (program_init_file_name, true);
2421 if (!init_file.Exists())
2422 init_file.Clear();
2423 }
2424 }
2425
2426 if (!init_file && !m_skip_lldbinit_files)
2427 init_file.SetFile (init_file_path, true);
2428 }
2429
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002430 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2431 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2432
2433 if (init_file.Exists())
2434 {
Jim Inghame16c50a2011-02-18 00:54:25 +00002435 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2436 bool stop_on_continue = true;
2437 bool stop_on_error = false;
2438 bool echo_commands = false;
2439 bool print_results = false;
2440
Enrico Granata5f5ab602012-05-31 01:09:06 +00002441 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002442 }
2443 else
2444 {
2445 // nothing to be done if the file doesn't exist
2446 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2447 }
2448}
2449
Greg Clayton8b82f082011-04-12 05:54:46 +00002450PlatformSP
2451CommandInterpreter::GetPlatform (bool prefer_target_platform)
2452{
2453 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002454 if (prefer_target_platform)
2455 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002456 ExecutionContext exe_ctx(GetExecutionContext());
2457 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002458 if (target)
2459 platform_sp = target->GetPlatform();
2460 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002461
2462 if (!platform_sp)
2463 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2464 return platform_sp;
2465}
2466
Jim Inghame16c50a2011-02-18 00:54:25 +00002467void
Jim Inghambad87fe2011-03-11 01:51:49 +00002468CommandInterpreter::HandleCommands (const StringList &commands,
Jim Inghame16c50a2011-02-18 00:54:25 +00002469 ExecutionContext *override_context,
2470 bool stop_on_continue,
2471 bool stop_on_error,
2472 bool echo_commands,
2473 bool print_results,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002474 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002475 CommandReturnObject &result)
2476{
2477 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002478
2479 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2480 // Make sure you reset this value anywhere you return from the function.
2481
2482 bool old_async_execution = m_debugger.GetAsyncExecution();
2483
2484 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2485 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2486
2487 if (override_context != NULL)
Greg Clayton8b82f082011-04-12 05:54:46 +00002488 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002489
2490 if (!stop_on_continue)
2491 {
2492 m_debugger.SetAsyncExecution (false);
2493 }
2494
2495 for (int idx = 0; idx < num_lines; idx++)
2496 {
2497 const char *cmd = commands.GetStringAtIndex(idx);
2498 if (cmd[0] == '\0')
2499 continue;
2500
Jim Inghame16c50a2011-02-18 00:54:25 +00002501 if (echo_commands)
2502 {
2503 result.AppendMessageWithFormat ("%s %s\n",
2504 GetPrompt(),
2505 cmd);
2506 }
2507
Greg Clayton9d0402b2011-02-20 02:15:07 +00002508 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002509 // If override_context is not NULL, pass no_context_switching = true for
2510 // HandleCommand() since we updated our context already.
Enrico Granata5f5ab602012-05-31 01:09:06 +00002511 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002512 NULL, /* override_context */
2513 true, /* repeat_on_empty_command */
2514 override_context != NULL /* no_context_switching */);
Jim Inghame16c50a2011-02-18 00:54:25 +00002515
2516 if (print_results)
2517 {
2518 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002519 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002520 }
2521
2522 if (!success || !tmp_result.Succeeded())
2523 {
Jim Inghama5038812012-04-24 02:25:07 +00002524 const char *error_msg = tmp_result.GetErrorData();
2525 if (error_msg == NULL || error_msg[0] == '\0')
2526 error_msg = "<unknown error>.\n";
Jim Inghame16c50a2011-02-18 00:54:25 +00002527 if (stop_on_error)
2528 {
Jim Inghama5038812012-04-24 02:25:07 +00002529 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' failed with %s",
2530 idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002531 result.SetStatus (eReturnStatusFailed);
2532 m_debugger.SetAsyncExecution (old_async_execution);
2533 return;
2534 }
2535 else if (print_results)
2536 {
Jim Inghama5038812012-04-24 02:25:07 +00002537 result.AppendMessageWithFormat ("Command #%d '%s' failed with %s",
Jim Inghame16c50a2011-02-18 00:54:25 +00002538 idx + 1,
2539 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002540 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002541 }
2542 }
2543
Caroline Tice969ed3d2011-05-02 20:41:46 +00002544 if (result.GetImmediateOutputStream())
2545 result.GetImmediateOutputStream()->Flush();
2546
2547 if (result.GetImmediateErrorStream())
2548 result.GetImmediateErrorStream()->Flush();
2549
Jim Inghame16c50a2011-02-18 00:54:25 +00002550 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2551 // could be running (for instance in Breakpoint Commands.
2552 // So we check the return value to see if it is has running in it.
2553 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2554 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2555 {
2556 if (stop_on_continue)
2557 {
2558 // If we caused the target to proceed, and we're going to stop in that case, set the
2559 // status in our real result before returning. This is an error if the continue was not the
2560 // last command in the set of commands to be run.
2561 if (idx != num_lines - 1)
2562 result.AppendErrorWithFormat("Aborting reading of commands after command #%d: '%s' continued the target.\n",
2563 idx + 1, cmd);
2564 else
2565 result.AppendMessageWithFormat ("Command #%d '%s' continued the target.\n", idx + 1, cmd);
2566
2567 result.SetStatus(tmp_result.GetStatus());
2568 m_debugger.SetAsyncExecution (old_async_execution);
2569
2570 return;
2571 }
2572 }
2573
2574 }
2575
2576 result.SetStatus (eReturnStatusSuccessFinishResult);
2577 m_debugger.SetAsyncExecution (old_async_execution);
2578
2579 return;
2580}
2581
2582void
2583CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2584 ExecutionContext *context,
2585 bool stop_on_continue,
2586 bool stop_on_error,
2587 bool echo_command,
2588 bool print_result,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002589 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002590 CommandReturnObject &result)
2591{
2592 if (cmd_file.Exists())
2593 {
2594 bool success;
2595 StringList commands;
2596 success = commands.ReadFileLines(cmd_file);
2597 if (!success)
2598 {
2599 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2600 result.SetStatus (eReturnStatusFailed);
2601 return;
2602 }
Enrico Granata5f5ab602012-05-31 01:09:06 +00002603 m_command_source_depth++;
2604 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2605 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002606 }
2607 else
2608 {
2609 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2610 cmd_file.GetFilename().AsCString());
2611 result.SetStatus (eReturnStatusFailed);
2612 return;
2613 }
2614}
2615
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002616ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002617CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002618{
Enrico Granatab5887262012-10-29 21:18:03 +00002619 if (m_script_interpreter_ap.get() != NULL)
2620 return m_script_interpreter_ap.get();
2621
2622 if (!can_create)
2623 return NULL;
2624
Enrico Granataa29bdad2012-07-10 18:23:48 +00002625 // <rdar://problem/11751427>
2626 // we need to protect the initialization of the script interpreter
2627 // otherwise we could end up with two threads both trying to create
2628 // their instance of it, and for some languages (e.g. Python)
2629 // this is a bulletproof recipe for disaster!
2630 // this needs to be a function-level static because multiple Debugger instances living in the same process
2631 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002632 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2633 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002634
Greg Clayton5160ce52013-03-27 23:08:40 +00002635 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002636 if (log)
2637 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002638
Caroline Tice2f88aad2011-01-14 00:29:16 +00002639 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2640 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002641 {
Greg Claytondce502e2011-11-04 03:34:56 +00002642 case eScriptLanguagePython:
2643#ifndef LLDB_DISABLE_PYTHON
2644 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2645 break;
2646#else
2647 // Fall through to the None case when python is disabled
2648#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002649 case eScriptLanguageNone:
2650 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2651 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002652 };
2653
2654 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002655}
2656
2657
2658
2659bool
2660CommandInterpreter::GetSynchronous ()
2661{
2662 return m_synchronous_execution;
2663}
2664
2665void
2666CommandInterpreter::SetSynchronous (bool value)
2667{
Johnny Chenc066ab42010-10-14 01:22:03 +00002668 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002669}
2670
2671void
2672CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2673 const char *word_text,
2674 const char *separator,
2675 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002676 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002677{
Greg Claytona7015092010-09-18 01:14:36 +00002678 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2679
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002680 int indent_size = max_word_len + strlen (separator) + 2;
2681
2682 strm.IndentMore (indent_size);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002683
2684 StreamString text_strm;
Greg Claytonc7bece562013-01-25 18:06:21 +00002685 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002686
2687 size_t len = text_strm.GetSize();
2688 const char *text = text_strm.GetData();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002689 if (text[len - 1] == '\n')
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002690 {
2691 text_strm.EOL();
2692 len = text_strm.GetSize();
2693 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002694
2695 if (len < max_columns)
2696 {
2697 // Output it as a single line.
2698 strm.Printf ("%s", text);
2699 }
2700 else
2701 {
2702 // We need to break it up into multiple lines.
2703 bool first_line = true;
2704 int text_width;
Greg Claytonc7bece562013-01-25 18:06:21 +00002705 size_t start = 0;
2706 size_t end = start;
2707 const size_t final_end = strlen (text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002708
2709 while (end < final_end)
2710 {
2711 if (first_line)
2712 text_width = max_columns - 1;
2713 else
2714 text_width = max_columns - indent_size - 1;
2715
2716 // Don't start the 'text' on a space, since we're already outputting the indentation.
2717 if (!first_line)
2718 {
2719 while ((start < final_end) && (text[start] == ' '))
2720 start++;
2721 }
2722
2723 end = start + text_width;
2724 if (end > final_end)
2725 end = final_end;
2726 else
2727 {
2728 // If we're not at the end of the text, make sure we break the line on white space.
2729 while (end > start
2730 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2731 end--;
Greg Clayton67cc0632012-08-22 17:17:09 +00002732 assert (end > 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002733 }
2734
Greg Claytonc7bece562013-01-25 18:06:21 +00002735 const size_t sub_len = end - start;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736 if (start != 0)
2737 strm.EOL();
2738 if (!first_line)
2739 strm.Indent();
2740 else
2741 first_line = false;
2742 assert (start <= final_end);
2743 assert (start + sub_len <= final_end);
2744 if (sub_len > 0)
2745 strm.Write (text + start, sub_len);
2746 start = end + 1;
2747 }
2748 }
2749 strm.EOL();
2750 strm.IndentLess(indent_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002751}
2752
2753void
Enrico Granata82a7d982011-07-07 00:38:40 +00002754CommandInterpreter::OutputHelpText (Stream &strm,
2755 const char *word_text,
2756 const char *separator,
2757 const char *help_text,
2758 uint32_t max_word_len)
2759{
2760 int indent_size = max_word_len + strlen (separator) + 2;
2761
2762 strm.IndentMore (indent_size);
2763
2764 StreamString text_strm;
2765 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2766
2767 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002768
2769 size_t len = text_strm.GetSize();
2770 const char *text = text_strm.GetData();
2771
2772 uint32_t chars_left = max_columns;
2773
2774 for (uint32_t i = 0; i < len; i++)
2775 {
2776 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2777 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002778 chars_left = max_columns - indent_size;
2779 strm.EOL();
2780 strm.Indent();
2781 }
2782 else
2783 {
2784 strm.PutChar(text[i]);
2785 chars_left--;
2786 }
2787
2788 }
2789
2790 strm.EOL();
2791 strm.IndentLess(indent_size);
2792}
2793
2794void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002795CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
2796 StringList &commands_help)
2797{
2798 CommandObject::CommandMap::const_iterator pos;
2799
2800 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
2801 {
2802 const char *command_name = pos->first.c_str();
2803 CommandObject *cmd_obj = pos->second.get();
2804
Greg Claytona7015092010-09-18 01:14:36 +00002805 if (cmd_obj->HelpTextContainsWord (search_word))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002806 {
2807 commands_found.AppendString (command_name);
2808 commands_help.AppendString (cmd_obj->GetHelp());
2809 }
2810
2811 if (cmd_obj->IsMultiwordObject())
Greg Clayton998255b2012-10-13 02:07:45 +00002812 cmd_obj->AproposAllSubCommands (command_name,
2813 search_word,
2814 commands_found,
2815 commands_help);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002816
2817 }
2818}
Greg Clayton8b82f082011-04-12 05:54:46 +00002819
2820
2821void
2822CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2823{
Greg Clayton8b82f082011-04-12 05:54:46 +00002824 if (override_context != NULL)
2825 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002826 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002827 }
2828 else
2829 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002830 const bool adopt_selected = true;
2831 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002832 }
2833}
2834
Jim Inghama5a97eb2011-07-12 03:12:18 +00002835void
2836CommandInterpreter::DumpHistory (Stream &stream, uint32_t count) const
2837{
2838 DumpHistory (stream, 0, count - 1);
2839}
2840
2841void
2842CommandInterpreter::DumpHistory (Stream &stream, uint32_t start, uint32_t end) const
2843{
Jim Inghamd1715e12013-02-22 23:23:42 +00002844 const size_t last_idx = std::min<size_t>(m_command_history.size(), end==UINT32_MAX ? UINT32_MAX : end + 1);
Greg Clayton5521f992011-10-28 21:38:01 +00002845 for (size_t i = start; i < last_idx; i++)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002846 {
2847 if (!m_command_history[i].empty())
2848 {
2849 stream.Indent();
Greg Clayton5521f992011-10-28 21:38:01 +00002850 stream.Printf ("%4zu: %s\n", i, m_command_history[i].c_str());
Jim Inghama5a97eb2011-07-12 03:12:18 +00002851 }
2852 }
2853}
2854
2855const char *
2856CommandInterpreter::FindHistoryString (const char *input_str) const
2857{
2858 if (input_str[0] != m_repeat_char)
2859 return NULL;
2860 if (input_str[1] == '-')
2861 {
2862 bool success;
Greg Claytonc7bece562013-01-25 18:06:21 +00002863 size_t idx = Args::StringToUInt32 (input_str+2, 0, 0, &success);
Jim Inghama5a97eb2011-07-12 03:12:18 +00002864 if (!success)
2865 return NULL;
2866 if (idx > m_command_history.size())
2867 return NULL;
2868 idx = m_command_history.size() - idx;
2869 return m_command_history[idx].c_str();
2870
2871 }
2872 else if (input_str[1] == m_repeat_char)
2873 {
2874 if (m_command_history.empty())
2875 return NULL;
2876 else
2877 return m_command_history.back().c_str();
2878 }
2879 else
2880 {
2881 bool success;
2882 uint32_t idx = Args::StringToUInt32 (input_str+1, 0, 0, &success);
2883 if (!success)
2884 return NULL;
2885 if (idx >= m_command_history.size())
2886 return NULL;
2887 return m_command_history[idx].c_str();
2888 }
2889}