blob: 7a563b7c122b924d30feeee3c4a275eca7475f77 [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#include <stdlib.h>
15
Greg Clayton4a33d312011-06-23 17:59:56 +000016#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000017#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000018
Eli Friedman3afb70c2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectApropos.h"
20#include "../Commands/CommandObjectArgs.h"
21#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
Greg Clayton44d93782014-01-27 23:43:24 +000025#include "../Commands/CommandObjectGUI.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectHelp.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000027#include "../Commands/CommandObjectLog.h"
28#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000029#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000030#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectProcess.h"
32#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSource.h"
Jim Inghamebc09c32010-07-07 03:36:20 +000036#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000037#include "../Commands/CommandObjectSyntax.h"
38#include "../Commands/CommandObjectTarget.h"
39#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000040#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000041#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000042#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043
Greg Clayton7d2ef162013-03-29 17:03:23 +000044
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045#include "lldb/Core/Debugger.h"
Enrico Granatab5887262012-10-29 21:18:03 +000046#include "lldb/Core/Log.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Core/Stream.h"
Greg Clayton44d93782014-01-27 23:43:24 +000048#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049#include "lldb/Core/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000050
Greg Clayton44d93782014-01-27 23:43:24 +000051#include "lldb/Host/Editline.h"
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." },
Enrico Granata012d4fc2013-06-11 01:26:35 +000078 { "stop-command-source-on-error", OptionValue::eTypeBoolean, true, true, NULL, NULL, "If true, LLDB will stop running a 'command source' script upon encountering an error." },
Greg Clayton754a9362012-08-23 00:22:02 +000079 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
80};
81
82enum
83{
Enrico Granatabcba2b22013-01-17 21:36:19 +000084 ePropertyExpandRegexAliases = 0,
Enrico Granata012d4fc2013-06-11 01:26:35 +000085 ePropertyPromptOnQuit = 1,
86 ePropertyStopCmdSourceOnError = 2
Greg Clayton754a9362012-08-23 00:22:02 +000087};
88
Jim Ingham4bddaeb2012-02-16 06:50:00 +000089ConstString &
90CommandInterpreter::GetStaticBroadcasterClass ()
91{
92 static ConstString class_name ("lldb.commandInterpreter");
93 return class_name;
94}
95
Chris Lattner30fdc8d2010-06-08 16:52:24 +000096CommandInterpreter::CommandInterpreter
97(
Greg Clayton66111032010-06-23 01:19:29 +000098 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +000099 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +0000100 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000101) :
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000102 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton754a9362012-08-23 00:22:02 +0000103 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton44d93782014-01-27 23:43:24 +0000104 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand),
Greg Clayton66111032010-06-23 01:19:29 +0000105 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000106 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000107 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000108 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000109 m_script_interpreter_ap (),
Greg Clayton44d93782014-01-27 23:43:24 +0000110 m_command_io_handler_sp (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000111 m_comment_char ('#'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000112 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000113 m_truncation_warning(eNoTruncation),
114 m_command_source_depth (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000115{
Greg Clayton67cc0632012-08-22 17:17:09 +0000116 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000117 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
118 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000119 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000120 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000121 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000122}
123
Greg Clayton754a9362012-08-23 00:22:02 +0000124bool
125CommandInterpreter::GetExpandRegexAliases () const
126{
127 const uint32_t idx = ePropertyExpandRegexAliases;
128 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
129}
130
Enrico Granatabcba2b22013-01-17 21:36:19 +0000131bool
132CommandInterpreter::GetPromptOnQuit () const
133{
134 const uint32_t idx = ePropertyPromptOnQuit;
135 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
136}
Greg Clayton754a9362012-08-23 00:22:02 +0000137
Enrico Granata012d4fc2013-06-11 01:26:35 +0000138bool
139CommandInterpreter::GetStopCmdSourceOnError () const
140{
141 const uint32_t idx = ePropertyStopCmdSourceOnError;
142 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
143}
144
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000145void
146CommandInterpreter::Initialize ()
147{
148 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
149
150 CommandReturnObject result;
151
152 LoadCommandDictionary ();
153
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000154 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000155 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
156 if (cmd_obj_sp)
157 {
158 AddAlias ("q", cmd_obj_sp);
159 AddAlias ("exit", cmd_obj_sp);
160 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000161
Johnny Chen6d675242012-08-24 18:15:45 +0000162 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000163 if (cmd_obj_sp)
164 {
165 AddAlias ("attach", cmd_obj_sp);
166 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000167
Johnny Chen6d675242012-08-24 18:15:45 +0000168 cmd_obj_sp = GetCommandSPExact ("process detach",false);
169 if (cmd_obj_sp)
170 {
171 AddAlias ("detach", cmd_obj_sp);
172 }
173
Caroline Ticeca90c472011-05-06 21:37:15 +0000174 cmd_obj_sp = GetCommandSPExact ("process continue", false);
175 if (cmd_obj_sp)
176 {
177 AddAlias ("c", cmd_obj_sp);
178 AddAlias ("continue", cmd_obj_sp);
179 }
180
181 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
182 if (cmd_obj_sp)
183 AddAlias ("b", cmd_obj_sp);
184
Jim Inghamca36cd12012-10-05 19:16:31 +0000185 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
186 if (cmd_obj_sp)
187 AddAlias ("tbreak", cmd_obj_sp);
188
Caroline Ticeca90c472011-05-06 21:37:15 +0000189 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
190 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000191 {
192 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000193 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000194 }
195
196 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
197 if (cmd_obj_sp)
198 {
199 AddAlias ("nexti", cmd_obj_sp);
200 AddAlias ("ni", cmd_obj_sp);
201 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000202
203 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
204 if (cmd_obj_sp)
205 {
206 AddAlias ("s", cmd_obj_sp);
207 AddAlias ("step", cmd_obj_sp);
208 }
209
210 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
211 if (cmd_obj_sp)
212 {
213 AddAlias ("n", cmd_obj_sp);
214 AddAlias ("next", cmd_obj_sp);
215 }
216
217 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
218 if (cmd_obj_sp)
219 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000220 AddAlias ("finish", cmd_obj_sp);
221 }
222
Jim Ingham6d6d1072011-12-02 01:12:59 +0000223 cmd_obj_sp = GetCommandSPExact ("frame select", false);
224 if (cmd_obj_sp)
225 {
226 AddAlias ("f", cmd_obj_sp);
227 }
228
Jim Inghamca36cd12012-10-05 19:16:31 +0000229 cmd_obj_sp = GetCommandSPExact ("thread select", false);
230 if (cmd_obj_sp)
231 {
232 AddAlias ("t", cmd_obj_sp);
233 }
234
Richard Mittonf86248d2013-09-12 02:20:34 +0000235 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
236 if (cmd_obj_sp)
237 {
238 AddAlias ("j", cmd_obj_sp);
239 AddAlias ("jump", cmd_obj_sp);
240 }
241
Greg Clayton6bade322013-02-01 23:33:03 +0000242 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000243 if (cmd_obj_sp)
244 {
245 AddAlias ("l", cmd_obj_sp);
246 AddAlias ("list", cmd_obj_sp);
247 }
248
Greg Claytonef5651d2013-02-12 18:52:24 +0000249 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
250 if (cmd_obj_sp)
251 {
252 AddAlias ("env", cmd_obj_sp);
253 }
254
Caroline Ticeca90c472011-05-06 21:37:15 +0000255 cmd_obj_sp = GetCommandSPExact ("memory read", false);
256 if (cmd_obj_sp)
257 AddAlias ("x", cmd_obj_sp);
258
259 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
260 if (cmd_obj_sp)
261 AddAlias ("up", cmd_obj_sp);
262
263 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
264 if (cmd_obj_sp)
265 AddAlias ("down", cmd_obj_sp);
266
Jason Molenda0c8e0062011-10-25 02:11:20 +0000267 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000268 if (cmd_obj_sp)
269 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000270
271 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
272 if (cmd_obj_sp)
273 AddAlias ("dis", cmd_obj_sp);
274
275 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
276 if (cmd_obj_sp)
277 AddAlias ("di", cmd_obj_sp);
278
279
Jason Molendabc7748b2011-10-22 01:30:52 +0000280
Jason Molenda0c8e0062011-10-25 02:11:20 +0000281 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000282 if (cmd_obj_sp)
283 AddAlias ("undisplay", cmd_obj_sp);
284
Jim Ingham71bf2992012-10-10 16:51:31 +0000285 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
286 if (cmd_obj_sp)
287 AddAlias ("bt", cmd_obj_sp);
288
Caroline Ticeca90c472011-05-06 21:37:15 +0000289 cmd_obj_sp = GetCommandSPExact ("target create", false);
290 if (cmd_obj_sp)
291 AddAlias ("file", cmd_obj_sp);
292
293 cmd_obj_sp = GetCommandSPExact ("target modules", false);
294 if (cmd_obj_sp)
295 AddAlias ("image", cmd_obj_sp);
296
297
298 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000299
Caroline Ticeca90c472011-05-06 21:37:15 +0000300 cmd_obj_sp = GetCommandSPExact ("expression", false);
301 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000302 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000303 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
304 AddAlias ("p", cmd_obj_sp);
305 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000306 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000307 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
308 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000309 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000310
311 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton9e57dcd2013-05-15 01:03:08 +0000312 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000313 AddAlias ("po", cmd_obj_sp);
314 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
315 }
316
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000317 cmd_obj_sp = GetCommandSPExact ("process kill", false);
318 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000319 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000320 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000321 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000322
Caroline Ticeca90c472011-05-06 21:37:15 +0000323 cmd_obj_sp = GetCommandSPExact ("process launch", false);
324 if (cmd_obj_sp)
325 {
326 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda85da3122012-07-06 02:46:23 +0000327#if defined (__arm__)
328 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
329#else
Ed Maste7c566672013-09-05 21:38:45 +0000330 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=" LLDB_DEFAULT_SHELL " --", alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000331#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000332 AddAlias ("r", cmd_obj_sp);
333 AddAlias ("run", cmd_obj_sp);
334 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
335 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
336 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000337
338 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
339 if (cmd_obj_sp)
340 {
341 AddAlias ("add-dsym", cmd_obj_sp);
342 }
Sean Callananfc732752012-05-21 18:25:19 +0000343
344 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
345 if (cmd_obj_sp)
346 {
347 alias_arguments_vector_sp.reset (new OptionArgVector);
348 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000349 AddAlias ("rbreak", cmd_obj_sp);
350 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000351 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000352}
353
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000354const char *
355CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
356{
357 // This function has not yet been implemented.
358
359 // Look for any embedded script command
360 // If found,
361 // get interpreter object from the command dictionary,
362 // call execute_one_command on it,
363 // get the results as a string,
364 // substitute that string for current stuff.
365
366 return arg;
367}
368
369
370void
371CommandInterpreter::LoadCommandDictionary ()
372{
373 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
374
Caroline Ticedaccaa92010-09-20 20:44:43 +0000375 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000376
Greg Claytona7015092010-09-18 01:14:36 +0000377 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000378 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000379 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000380 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
381 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000382 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton44d93782014-01-27 23:43:24 +0000383 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000384 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000385 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
386 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000387 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000388 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000389 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000390 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000391 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000392 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000393 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000394 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000395 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
396 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000397 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000398 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000399 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400
Jim Inghamca36cd12012-10-05 19:16:31 +0000401 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
402 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000403 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000404 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000405 {"^(-.*)$", "breakpoint set %1"},
406 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000407 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000408 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
409
410 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
411
Greg Clayton7b0992d2013-04-18 22:45:39 +0000412 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000413 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000414 "_regexp-break",
Johnny Chenb417dcd2012-08-23 00:32:22 +0000415 "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 +0000416 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
417 2,
418 CommandCompletions::eSymbolCompletion |
419 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000420
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000421 if (break_regex_cmd_ap.get())
422 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000423 bool success = true;
424 for (size_t i = 0; i < num_regexes; i++)
425 {
426 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
427 if (!success)
428 break;
429 }
430 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
431
432 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000433 {
434 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
435 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
436 }
437 }
Jim Inghamffba2292011-03-22 02:29:32 +0000438
Greg Clayton7b0992d2013-04-18 22:45:39 +0000439 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000440 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
441 "_regexp-tbreak",
442 "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 +0000443 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
444 2,
445 CommandCompletions::eSymbolCompletion |
446 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000447
448 if (tbreak_regex_cmd_ap.get())
449 {
450 bool success = true;
451 for (size_t i = 0; i < num_regexes; i++)
452 {
453 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
454 char buffer[1024];
455 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
456 assert (num_printed < 1024);
457 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
458 if (!success)
459 break;
460 }
461 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
462
463 if (success)
464 {
465 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
466 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
467 }
468 }
469
Greg Clayton7b0992d2013-04-18 22:45:39 +0000470 std::unique_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000471 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
472 "_regexp-attach",
473 "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 +0000474 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
475 2));
Johnny Chen6d675242012-08-24 18:15:45 +0000476 if (attach_regex_cmd_ap.get())
477 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000478 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
479 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
480 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
481 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000482 {
483 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
484 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
485 }
486 }
487
Greg Clayton7b0992d2013-04-18 22:45:39 +0000488 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000489 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000490 "_regexp-down",
491 "Go down \"n\" frames in the stack (1 frame by default).",
492 "_regexp-down [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000493 if (down_regex_cmd_ap.get())
494 {
495 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
496 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
497 {
498 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
499 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
500 }
501 }
502
Greg Clayton7b0992d2013-04-18 22:45:39 +0000503 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000504 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000505 "_regexp-up",
506 "Go up \"n\" frames in the stack (1 frame by default).",
507 "_regexp-up [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000508 if (up_regex_cmd_ap.get())
509 {
510 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
511 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
512 {
513 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
514 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
515 }
516 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000517
Greg Clayton7b0992d2013-04-18 22:45:39 +0000518 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000519 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000520 "_regexp-display",
521 "Add an expression evaluation stop-hook.",
522 "_regexp-display expression", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000523 if (display_regex_cmd_ap.get())
524 {
525 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
526 {
527 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
528 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
529 }
530 }
531
Greg Clayton7b0992d2013-04-18 22:45:39 +0000532 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000533 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000534 "_regexp-undisplay",
535 "Remove an expression evaluation stop-hook.",
536 "_regexp-undisplay stop-hook-number", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000537 if (undisplay_regex_cmd_ap.get())
538 {
539 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
540 {
541 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
542 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
543 }
544 }
545
Greg Clayton7b0992d2013-04-18 22:45:39 +0000546 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000547 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000548 "gdb-remote",
549 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
550 "gdb-remote [<hostname>:]<portnum>", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000551 if (connect_gdb_remote_cmd_ap.get())
552 {
553 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
554 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
555 {
556 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
557 m_command_dict[command_sp->GetCommandName ()] = command_sp;
558 }
559 }
560
Greg Clayton7b0992d2013-04-18 22:45:39 +0000561 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000562 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
563 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000564 "Connect to a remote KDP server. udp port 41139 is the default port number.",
565 "kdp-remote <hostname>[:<portnum>]", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000566 if (connect_kdp_remote_cmd_ap.get())
567 {
568 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000569 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000570 {
571 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
572 m_command_dict[command_sp->GetCommandName ()] = command_sp;
573 }
574 }
575
Greg Clayton7b0992d2013-04-18 22:45:39 +0000576 std::unique_ptr<CommandObjectRegexCommand>
Jason Molenda4cddfed2012-10-05 05:29:32 +0000577 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Ingham71bf2992012-10-10 16:51:31 +0000578 "_regexp-bt",
Jason Molenda4cddfed2012-10-05 05:29:32 +0000579 "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.",
580 "bt [<digit>|all]", 2));
581 if (bt_regex_cmd_ap.get())
582 {
583 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
584 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
585 // so now "bt 3" is the preferred form, in line with gdb.
586 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
587 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
588 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
589 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
590 {
591 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
592 m_command_dict[command_sp->GetCommandName ()] = command_sp;
593 }
594 }
595
Greg Clayton7b0992d2013-04-18 22:45:39 +0000596 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton6bade322013-02-01 23:33:03 +0000597 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
598 "_regexp-list",
599 "Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the appropriate 'source list' commands.",
Ben Langmuiredb3b212013-09-26 20:00:01 +0000600 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000601 2,
602 CommandCompletions::eSourceFileCompletion));
Greg Clayton6bade322013-02-01 23:33:03 +0000603 if (list_regex_cmd_ap.get())
604 {
605 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
606 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
607 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000608 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000609 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000610 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
611 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
612 {
613 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
614 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
615 }
616 }
617
Greg Clayton7b0992d2013-04-18 22:45:39 +0000618 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytonef5651d2013-02-12 18:52:24 +0000619 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000620 "_regexp-env",
621 "Implements a shortcut to viewing and setting environment variables.",
622 "_regexp-env\n_regexp-env FOO=BAR", 2));
Greg Claytonef5651d2013-02-12 18:52:24 +0000623 if (env_regex_cmd_ap.get())
624 {
625 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
626 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
627 {
628 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
629 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
630 }
631 }
632
Richard Mittonf86248d2013-09-12 02:20:34 +0000633 std::unique_ptr<CommandObjectRegexCommand>
634 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
635 "_regexp-jump",
636 "Sets the program counter to a new address.",
637 "_regexp-jump [<line>]\n"
638 "_regexp-jump [<+-lineoffset>]\n"
639 "_regexp-jump [<file>:<line>]\n"
640 "_regexp-jump [*<addr>]\n", 2));
641 if (jump_regex_cmd_ap.get())
642 {
643 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
644 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
645 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
646 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
647 {
648 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
649 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
650 }
651 }
652
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000653}
654
655int
656CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
657 StringList &matches)
658{
659 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
660
661 if (include_aliases)
662 {
663 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
664 }
665
666 return matches.GetSize();
667}
668
669CommandObjectSP
670CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
671{
672 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000673 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000674
675 std::string cmd(cmd_cstr);
676
677 if (HasCommands())
678 {
679 pos = m_command_dict.find(cmd);
680 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000681 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000682 }
683
684 if (include_aliases && HasAliases())
685 {
686 pos = m_alias_dict.find(cmd);
687 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000688 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000689 }
690
691 if (HasUserCommands())
692 {
693 pos = m_user_dict.find(cmd);
694 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000695 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000696 }
697
Greg Claytonc7bece562013-01-25 18:06:21 +0000698 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000699 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000700 // We will only get into here if we didn't find any exact matches.
701
702 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
703
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000704 StringList local_matches;
705 if (matches == NULL)
706 matches = &local_matches;
707
Jim Ingham279a6c22010-07-06 22:46:59 +0000708 unsigned int num_cmd_matches = 0;
709 unsigned int num_alias_matches = 0;
710 unsigned int num_user_matches = 0;
711
712 // Look through the command dictionaries one by one, and if we get only one match from any of
713 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
714
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000715 if (HasCommands())
716 {
717 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
718 }
719
720 if (num_cmd_matches == 1)
721 {
722 cmd.assign(matches->GetStringAtIndex(0));
723 pos = m_command_dict.find(cmd);
724 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000725 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726 }
727
Jim Ingham490ac552010-06-24 20:28:42 +0000728 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729 {
730 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
731
732 }
733
Jim Ingham279a6c22010-07-06 22:46:59 +0000734 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735 {
736 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
737 pos = m_alias_dict.find(cmd);
738 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000739 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000740 }
741
Jim Ingham490ac552010-06-24 20:28:42 +0000742 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 {
744 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
745 }
746
Jim Ingham279a6c22010-07-06 22:46:59 +0000747 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000748 {
749 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
750
751 pos = m_user_dict.find (cmd);
752 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000753 user_match_sp = pos->second;
754 }
755
756 // If we got exactly one match, return that, otherwise return the match list.
757
758 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
759 {
760 if (num_cmd_matches)
761 return real_match_sp;
762 else if (num_alias_matches)
763 return alias_match_sp;
764 else
765 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000766 }
767 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000768 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000769 {
770 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000771 }
772
773
Greg Claytonc7bece562013-01-25 18:06:21 +0000774 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775}
776
Greg Claytonde164aa2011-04-20 16:37:46 +0000777bool
778CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
779{
780 if (name && name[0])
781 {
782 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000783 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
784 if (found && !can_replace)
785 return false;
786 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000787 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000788 m_command_dict[name_sstr] = cmd_sp;
789 return true;
790 }
791 return false;
792}
793
Enrico Granata223383e2011-08-16 23:24:13 +0000794bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000795CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000796 const lldb::CommandObjectSP &cmd_sp,
797 bool can_replace)
798{
Enrico Granata0a305db2011-11-07 22:57:04 +0000799 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000800 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000801
802 const char* name_cstr = name.c_str();
803
804 // do not allow replacement of internal commands
805 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000806 {
807 if (can_replace == false)
808 return false;
809 if (m_command_dict[name]->IsRemovable() == false)
810 return false;
811 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000812
Enrico Granata21dfcd92012-09-28 23:57:51 +0000813 if (UserCommandExists(name_cstr))
814 {
815 if (can_replace == false)
816 return false;
817 if (m_user_dict[name]->IsRemovable() == false)
818 return false;
819 }
820
Enrico Granata0a305db2011-11-07 22:57:04 +0000821 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000822 return true;
823 }
824 return false;
825}
Greg Claytonde164aa2011-04-20 16:37:46 +0000826
Jim Ingham279a6c22010-07-06 22:46:59 +0000827CommandObjectSP
828CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000829{
Caroline Tice472362e2010-12-14 18:51:39 +0000830 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
831 CommandObjectSP ret_val; // Possibly empty return value.
832
833 if (cmd_cstr == NULL)
834 return ret_val;
835
836 if (cmd_words.GetArgumentCount() == 1)
837 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
838 else
839 {
840 // We have a multi-word command (seemingly), so we need to do more work.
841 // First, get the cmd_obj_sp for the first word in the command.
842 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
843 if (cmd_obj_sp.get() != NULL)
844 {
845 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
846 // command name), and find the appropriate sub-command SP for each command word....
847 size_t end = cmd_words.GetArgumentCount();
848 for (size_t j= 1; j < end; ++j)
849 {
850 if (cmd_obj_sp->IsMultiwordObject())
851 {
Greg Clayton998255b2012-10-13 02:07:45 +0000852 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Caroline Tice472362e2010-12-14 18:51:39 +0000853 if (cmd_obj_sp.get() == NULL)
854 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
855 return ret_val;
856 }
857 else
858 // We have more words in the command name, but we don't have a multiword object. Fail and return
859 // empty 'ret_val'.
860 return ret_val;
861 }
862 // We successfully looped through all the command words and got valid command objects for them. Assign the
863 // last object retrieved to 'ret_val'.
864 ret_val = cmd_obj_sp;
865 }
866 }
867 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000868}
869
870CommandObject *
871CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
872{
873 return GetCommandSPExact (cmd_cstr, include_aliases).get();
874}
875
876CommandObject *
877CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
878{
879 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
880
881 // If we didn't find an exact match to the command string in the commands, look in
882 // the aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000883
884 if (command_obj)
885 return command_obj;
Jim Ingham279a6c22010-07-06 22:46:59 +0000886
Enrico Granata5342c442013-06-18 18:01:08 +0000887 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
Jim Ingham279a6c22010-07-06 22:46:59 +0000888
Enrico Granata5342c442013-06-18 18:01:08 +0000889 if (command_obj)
890 return command_obj;
891
892 // If there wasn't an exact match then look for an inexact one in just the commands
893 command_obj = GetCommandSP(cmd_cstr, false, false, NULL).get();
Matt Kopec038ff812013-04-23 16:17:32 +0000894
895 // Finally, if there wasn't an inexact match among the commands, look for an inexact
896 // match in both the commands and aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000897
898 if (command_obj)
899 {
900 if (matches)
901 matches->AppendString(command_obj->GetCommandName());
902 return command_obj;
903 }
904
905 return GetCommandSP(cmd_cstr, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906}
907
908bool
909CommandInterpreter::CommandExists (const char *cmd)
910{
911 return m_command_dict.find(cmd) != m_command_dict.end();
912}
913
914bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000915CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
916 const char *options_args,
917 OptionArgVectorSP &option_arg_vector_sp)
918{
919 bool success = true;
920 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
921
922 if (!options_args || (strlen (options_args) < 1))
923 return true;
924
925 std::string options_string (options_args);
926 Args args (options_args);
927 CommandReturnObject result;
928 // Check to see if the command being aliased can take any command options.
929 Options *options = cmd_obj_sp->GetOptions ();
930 if (options)
931 {
932 // See if any options were specified as part of the alias; if so, handle them appropriately.
933 options->NotifyOptionParsingStarting ();
934 args.Unshift ("dummy_arg");
935 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
936 args.Shift ();
937 if (result.Succeeded())
938 options->VerifyPartialOptions (result);
939 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
940 {
941 result.AppendError ("Unable to create requested alias.\n");
942 return false;
943 }
944 }
945
Greg Clayton5521f992011-10-28 21:38:01 +0000946 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +0000947 {
948 if (cmd_obj_sp->WantsRawCommandString ())
949 option_arg_vector->push_back (OptionArgPair ("<argument>",
950 OptionArgValue (-1,
951 options_string)));
952 else
953 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000954 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +0000955 for (size_t i = 0; i < argc; ++i)
956 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
957 option_arg_vector->push_back
958 (OptionArgPair ("<argument>",
959 OptionArgValue (-1,
960 std::string (args.GetArgumentAtIndex (i)))));
961 }
962 }
963
964 return success;
965}
966
967bool
Jim Ingham298f3782013-04-03 00:25:49 +0000968CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
969{
970 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
971 if (exact_match)
972 {
973 full_name.assign(cmd);
974 return exact_match;
975 }
976 else
977 {
978 StringList matches;
979 size_t num_alias_matches;
980 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
981 if (num_alias_matches == 1)
982 {
983 // Make sure this isn't shadowing a command in the regular command space:
984 StringList regular_matches;
985 const bool include_aliases = false;
986 const bool exact = false;
987 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
988 if (cmd_obj_sp || regular_matches.GetSize() > 0)
989 return false;
990 else
991 {
992 full_name.assign (matches.GetStringAtIndex(0));
993 return true;
994 }
995 }
996 else
997 return false;
998 }
999}
1000
1001bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001002CommandInterpreter::AliasExists (const char *cmd)
1003{
1004 return m_alias_dict.find(cmd) != m_alias_dict.end();
1005}
1006
1007bool
1008CommandInterpreter::UserCommandExists (const char *cmd)
1009{
1010 return m_user_dict.find(cmd) != m_user_dict.end();
1011}
1012
1013void
1014CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1015{
Jim Ingham279a6c22010-07-06 22:46:59 +00001016 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001017 m_alias_dict[alias_name] = command_obj_sp;
1018}
1019
1020bool
1021CommandInterpreter::RemoveAlias (const char *alias_name)
1022{
1023 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1024 if (pos != m_alias_dict.end())
1025 {
1026 m_alias_dict.erase(pos);
1027 return true;
1028 }
1029 return false;
1030}
1031bool
1032CommandInterpreter::RemoveUser (const char *alias_name)
1033{
1034 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1035 if (pos != m_user_dict.end())
1036 {
1037 m_user_dict.erase(pos);
1038 return true;
1039 }
1040 return false;
1041}
1042
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001043void
1044CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1045{
1046 help_string.Printf ("'%s", command_name);
1047 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1048
Sean Callanan9a028512012-08-09 00:50:26 +00001049 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050 {
1051 OptionArgVector *options = option_arg_vector_sp.get();
Andy Gibbsa297a972013-06-19 19:04:53 +00001052 for (size_t i = 0; i < options->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001053 {
1054 OptionArgPair cur_option = (*options)[i];
1055 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001056 OptionArgValue value_pair = cur_option.second;
1057 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058 if (opt.compare("<argument>") == 0)
1059 {
1060 help_string.Printf (" %s", value.c_str());
1061 }
1062 else
1063 {
1064 help_string.Printf (" %s", opt.c_str());
1065 if ((value.compare ("<no-argument>") != 0)
1066 && (value.compare ("<need-argument") != 0))
1067 {
1068 help_string.Printf (" %s", value.c_str());
1069 }
1070 }
1071 }
1072 }
1073
1074 help_string.Printf ("'");
1075}
1076
Greg Clayton12fc3e02010-08-26 22:05:43 +00001077size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1079{
1080 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001081 CommandObject::CommandMap::const_iterator end = dict.end();
1082 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001083
Greg Clayton12fc3e02010-08-26 22:05:43 +00001084 for (pos = dict.begin(); pos != end; ++pos)
1085 {
1086 size_t len = pos->first.size();
1087 if (max_len < len)
1088 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001090 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001091}
1092
1093void
Enrico Granata223383e2011-08-16 23:24:13 +00001094CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001095 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096{
1097 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001098 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001099
1100 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001101 {
Enrico Granata223383e2011-08-16 23:24:13 +00001102
1103 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
1104 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001105
Enrico Granata223383e2011-08-16 23:24:13 +00001106 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1107 {
1108 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1109 max_len);
1110 }
1111 result.AppendMessage("");
1112
1113 }
1114
Greg Clayton5521f992011-10-28 21:38:01 +00001115 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116 {
Jim Ingham49e80a12010-10-22 18:47:16 +00001117 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chenb89982d2011-04-21 00:39:18 +00001118 "(see 'help command alias' for more info):");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001119 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001120 max_len = FindLongestCommandWord (m_alias_dict);
1121
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1123 {
1124 StreamString sstr;
1125 StreamString translation_and_help;
1126 std::string entry_name = pos->first;
1127 std::string second_entry = pos->second.get()->GetCommandName();
1128 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1129
1130 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1131 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1132 translation_and_help.GetData(), max_len);
1133 }
1134 result.AppendMessage("");
1135 }
1136
Greg Clayton5521f992011-10-28 21:38:01 +00001137 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001138 {
1139 result.AppendMessage ("The following is a list of your current user-defined commands:");
1140 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001141 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1143 {
Enrico Granata223383e2011-08-16 23:24:13 +00001144 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1145 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146 }
1147 result.AppendMessage("");
1148 }
1149
1150 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1151}
1152
Caroline Tice844d2302010-12-09 22:52:49 +00001153CommandObject *
1154CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155{
Caroline Tice844d2302010-12-09 22:52:49 +00001156 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1157 // eventually be invoked by the given command line.
1158
1159 CommandObject *cmd_obj = NULL;
1160 std::string white_space (" \t\v");
1161 size_t start = command_string.find_first_not_of (white_space);
1162 size_t end = 0;
1163 bool done = false;
1164 while (!done)
1165 {
1166 if (start != std::string::npos)
1167 {
1168 // Get the next word from command_string.
1169 end = command_string.find_first_of (white_space, start);
1170 if (end == std::string::npos)
1171 end = command_string.size();
1172 std::string cmd_word = command_string.substr (start, end - start);
1173
1174 if (cmd_obj == NULL)
1175 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1176 // command or alias.
1177 cmd_obj = GetCommandObject (cmd_word.c_str());
1178 else if (cmd_obj->IsMultiwordObject ())
1179 {
1180 // 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 +00001181 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001182 if (sub_cmd_obj)
1183 cmd_obj = sub_cmd_obj;
1184 else // cmd_word was not a valid sub-command word, so we are donee
1185 done = true;
1186 }
1187 else
1188 // We have a cmd_obj and it is not a multi-word object, so we are done.
1189 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001190
Caroline Tice844d2302010-12-09 22:52:49 +00001191 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1192 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1193 // next word.
1194
1195 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1196 done = true;
1197 else
1198 start = command_string.find_first_not_of (white_space, end);
1199 }
1200 else
1201 // Unable to find any more words.
1202 done = true;
1203 }
1204
1205 if (end == command_string.size())
1206 command_string.clear();
1207 else
1208 command_string = command_string.substr(end);
1209
1210 return cmd_obj;
1211}
1212
Greg Clayton51964162011-10-25 00:36:27 +00001213static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001214static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001215static void
1216StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001217{
Greg Clayton51964162011-10-25 00:36:27 +00001218 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001219 {
Greg Clayton51964162011-10-25 00:36:27 +00001220 size_t pos = s.find_first_not_of (k_white_space);
1221 if (pos == std::string::npos)
1222 s.clear();
1223 else if (pos == 0)
1224 return;
1225 s.erase (0, pos);
1226 }
1227}
1228
Greg Clayton93c62e62011-11-09 23:25:03 +00001229static size_t
1230FindArgumentTerminator (const std::string &s)
1231{
Greg Clayton93c62e62011-11-09 23:25:03 +00001232 const size_t s_len = s.size();
1233 size_t offset = 0;
1234 while (offset < s_len)
1235 {
1236 size_t pos = s.find ("--", offset);
1237 if (pos == std::string::npos)
1238 break;
1239 if (pos > 0)
1240 {
1241 if (isspace(s[pos-1]))
1242 {
1243 // Check if the string ends "\s--" (where \s is a space character)
1244 // or if we have "\s--\s".
1245 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1246 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001247 return pos;
1248 }
1249 }
1250 }
1251 offset = pos + 2;
1252 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001253 return std::string::npos;
1254}
1255
Greg Clayton51964162011-10-25 00:36:27 +00001256static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001257ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001258{
Greg Clayton5521f992011-10-28 21:38:01 +00001259 command.clear();
1260 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001261 StripLeadingSpaces (command_string);
1262
1263 bool result = false;
1264 quote_char = '\0';
1265
1266 if (!command_string.empty())
1267 {
1268 const char first_char = command_string[0];
1269 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001270 {
Greg Clayton51964162011-10-25 00:36:27 +00001271 quote_char = first_char;
1272 const size_t end_quote_pos = command_string.find (quote_char, 1);
1273 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001274 {
Greg Clayton5521f992011-10-28 21:38:01 +00001275 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001276 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001277 }
1278 else
1279 {
Greg Clayton5521f992011-10-28 21:38:01 +00001280 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001281 if (end_quote_pos + 1 < command_string.size())
1282 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1283 else
1284 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001285 }
Caroline Tice844d2302010-12-09 22:52:49 +00001286 }
1287 else
1288 {
Greg Clayton51964162011-10-25 00:36:27 +00001289 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1290 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001291 {
Greg Clayton5521f992011-10-28 21:38:01 +00001292 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001293 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001294 }
1295 else
1296 {
Greg Clayton5521f992011-10-28 21:38:01 +00001297 command.assign (command_string, 0, first_space_pos);
1298 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001299 }
Caroline Tice844d2302010-12-09 22:52:49 +00001300 }
Greg Clayton51964162011-10-25 00:36:27 +00001301 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001302 }
Greg Clayton5521f992011-10-28 21:38:01 +00001303
1304
1305 if (!command.empty())
1306 {
1307 // actual commands can't start with '-' or '_'
1308 if (command[0] != '-' && command[0] != '_')
1309 {
1310 size_t pos = command.find_first_not_of(k_valid_command_chars);
1311 if (pos > 0 && pos != std::string::npos)
1312 {
1313 suffix.assign (command.begin() + pos, command.end());
1314 command.erase (pos);
1315 }
1316 }
1317 }
Greg Clayton51964162011-10-25 00:36:27 +00001318
1319 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001320}
1321
Greg Clayton5521f992011-10-28 21:38:01 +00001322CommandObject *
1323CommandInterpreter::BuildAliasResult (const char *alias_name,
1324 std::string &raw_input_string,
1325 std::string &alias_result,
1326 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001327{
Greg Clayton5521f992011-10-28 21:38:01 +00001328 CommandObject *alias_cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001329 Args cmd_args (raw_input_string.c_str());
1330 alias_cmd_obj = GetCommandObject (alias_name);
1331 StreamString result_str;
1332
1333 if (alias_cmd_obj)
1334 {
1335 std::string alias_name_str = alias_name;
1336 if ((cmd_args.GetArgumentCount() == 0)
1337 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1338 cmd_args.Unshift (alias_name);
1339
1340 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1341 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1342
1343 if (option_arg_vector_sp.get())
1344 {
1345 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1346
Andy Gibbsa297a972013-06-19 19:04:53 +00001347 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Caroline Tice844d2302010-12-09 22:52:49 +00001348 {
1349 OptionArgPair option_pair = (*option_arg_vector)[i];
1350 OptionArgValue value_pair = option_pair.second;
1351 int value_type = value_pair.first;
1352 std::string option = option_pair.first;
1353 std::string value = value_pair.second;
1354 if (option.compare ("<argument>") == 0)
1355 result_str.Printf (" %s", value.c_str());
1356 else
1357 {
1358 result_str.Printf (" %s", option.c_str());
Virgile Belloe2607b52013-09-05 16:42:23 +00001359 if (value_type != OptionParser::eOptionalArgument)
Caroline Tice844d2302010-12-09 22:52:49 +00001360 result_str.Printf (" ");
Virgile Belloe2607b52013-09-05 16:42:23 +00001361 if (value.compare ("<OptionParser::eNoArgument>") != 0)
Caroline Tice844d2302010-12-09 22:52:49 +00001362 {
1363 int index = GetOptionArgumentPosition (value.c_str());
1364 if (index == 0)
1365 result_str.Printf ("%s", value.c_str());
1366 else if (index >= cmd_args.GetArgumentCount())
1367 {
1368
1369 result.AppendErrorWithFormat
1370 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1371 index);
1372 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001373 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001374 }
1375 else
1376 {
1377 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1378 if (strpos != std::string::npos)
1379 raw_input_string = raw_input_string.erase (strpos,
1380 strlen (cmd_args.GetArgumentAtIndex (index)));
1381 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1382 }
1383 }
1384 }
1385 }
1386 }
1387
1388 alias_result = result_str.GetData();
1389 }
Greg Clayton5521f992011-10-28 21:38:01 +00001390 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001391}
1392
Greg Clayton5a314712011-10-14 07:41:33 +00001393Error
1394CommandInterpreter::PreprocessCommand (std::string &command)
1395{
1396 // The command preprocessor needs to do things to the command
1397 // line before any parsing of arguments or anything else is done.
1398 // The only current stuff that gets proprocessed is anyting enclosed
1399 // in backtick ('`') characters is evaluated as an expression and
1400 // the result of the expression must be a scalar that can be substituted
1401 // into the command. An example would be:
1402 // (lldb) memory read `$rsp + 20`
1403 Error error; // Error for any expressions that might not evaluate
1404 size_t start_backtick;
1405 size_t pos = 0;
1406 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1407 {
1408 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1409 {
1410 // The backtick was preceeded by a '\' character, remove the slash
1411 // and don't treat the backtick as the start of an expression
1412 command.erase(start_backtick-1, 1);
1413 // No need to add one to start_backtick since we just deleted a char
1414 pos = start_backtick;
1415 }
1416 else
1417 {
1418 const size_t expr_content_start = start_backtick + 1;
1419 const size_t end_backtick = command.find ('`', expr_content_start);
1420 if (end_backtick == std::string::npos)
1421 return error;
1422 else if (end_backtick == expr_content_start)
1423 {
1424 // Empty expression (two backticks in a row)
1425 command.erase (start_backtick, 2);
1426 }
1427 else
1428 {
1429 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1430
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001431 ExecutionContext exe_ctx(GetExecutionContext());
1432 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001433 // Get a dummy target to allow for calculator mode while processing backticks.
1434 // This also helps break the infinite loop caused when target is null.
1435 if (!target)
1436 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Clayton5a314712011-10-14 07:41:33 +00001437 if (target)
1438 {
Greg Clayton5a314712011-10-14 07:41:33 +00001439 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001440
Jim Ingham35e1bda2012-10-16 21:41:58 +00001441 EvaluateExpressionOptions options;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00001442 options.SetCoerceToId(false);
1443 options.SetUnwindOnError(true);
1444 options.SetIgnoreBreakpoints(true);
1445 options.SetKeepInMemory(false);
1446 options.SetTryAllThreads(true);
1447 options.SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001448
Greg Clayton5a314712011-10-14 07:41:33 +00001449 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad4439aa2012-09-05 20:41:26 +00001450 exe_ctx.GetFramePtr(),
Enrico Granata3372f582012-07-16 23:10:35 +00001451 expr_result_valobj_sp,
Enrico Granatad4439aa2012-09-05 20:41:26 +00001452 options);
1453
Greg Clayton5a314712011-10-14 07:41:33 +00001454 if (expr_result == eExecutionCompleted)
1455 {
1456 Scalar scalar;
1457 if (expr_result_valobj_sp->ResolveValue (scalar))
1458 {
1459 command.erase (start_backtick, end_backtick - start_backtick + 1);
1460 StreamString value_strm;
1461 const bool show_type = false;
1462 scalar.GetValue (&value_strm, show_type);
1463 size_t value_string_size = value_strm.GetSize();
1464 if (value_string_size)
1465 {
1466 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1467 pos = start_backtick + value_string_size;
1468 continue;
1469 }
1470 else
1471 {
1472 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1473 }
1474 }
1475 else
1476 {
1477 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1478 }
1479 }
1480 else
1481 {
1482 if (expr_result_valobj_sp)
1483 error = expr_result_valobj_sp->GetError();
1484 if (error.Success())
1485 {
1486
1487 switch (expr_result)
1488 {
1489 case eExecutionSetupError:
1490 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1491 break;
1492 case eExecutionCompleted:
1493 break;
1494 case eExecutionDiscarded:
1495 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1496 break;
1497 case eExecutionInterrupted:
1498 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1499 break;
Jim Ingham184e9812013-01-15 02:47:48 +00001500 case eExecutionHitBreakpoint:
1501 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1502 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001503 case eExecutionTimedOut:
1504 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1505 break;
Greg Claytonc28ce782013-11-08 23:38:26 +00001506 case eExecutionStoppedForDebug:
1507 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1508 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001509 }
1510 }
1511 }
1512 }
1513 }
1514 if (error.Fail())
1515 break;
1516 }
1517 }
1518 return error;
1519}
1520
1521
Caroline Tice844d2302010-12-09 22:52:49 +00001522bool
1523CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001524 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001525 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001526 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001527 bool repeat_on_empty_command,
1528 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001529
Caroline Tice844d2302010-12-09 22:52:49 +00001530{
Jim Inghame16c50a2011-02-18 00:54:25 +00001531
Caroline Tice844d2302010-12-09 22:52:49 +00001532 bool done = false;
1533 CommandObject *cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001534 bool wants_raw_input = false;
1535 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001536 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001537
Greg Clayton5160ce52013-03-27 23:08:40 +00001538 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001539 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1540
1541 // Make a scoped cleanup object that will clear the crash description string
1542 // on exit of this function.
Enrico Granataf9fa6ee2011-07-12 00:18:11 +00001543 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001544
Caroline Tice844d2302010-12-09 22:52:49 +00001545 if (log)
1546 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001547
Jim Ingham30244832010-11-04 23:08:45 +00001548 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1549
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001550 if (!no_context_switching)
1551 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001552
Enrico Granata5f5ab602012-05-31 01:09:06 +00001553 bool add_to_history;
1554 if (lazy_add_to_history == eLazyBoolCalculate)
1555 add_to_history = (m_command_source_depth == 0);
1556 else
1557 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1558
Jim Inghame16c50a2011-02-18 00:54:25 +00001559 bool empty_command = false;
1560 bool comment_command = false;
1561 if (command_string.empty())
1562 empty_command = true;
1563 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001564 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001565 const char *k_space_characters = "\t\n\v\f\r ";
1566
1567 size_t non_space = command_string.find_first_not_of (k_space_characters);
1568 // Check for empty line or comment line (lines whose first
1569 // non-space character is the comment character for this interpreter)
1570 if (non_space == std::string::npos)
1571 empty_command = true;
1572 else if (command_string[non_space] == m_comment_char)
1573 comment_command = true;
Enrico Granata7594f142013-06-17 22:51:50 +00001574 else if (command_string[non_space] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001575 {
Enrico Granata7594f142013-06-17 22:51:50 +00001576 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001577 if (history_string == NULL)
1578 {
1579 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1580 result.SetStatus(eReturnStatusFailed);
1581 return false;
1582 }
1583 add_to_history = false;
1584 command_string = history_string;
1585 original_command_string = history_string;
1586 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001587 }
1588
1589 if (empty_command)
1590 {
1591 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001592 {
Enrico Granata7594f142013-06-17 22:51:50 +00001593 if (m_command_history.IsEmpty())
Jim Inghame16c50a2011-02-18 00:54:25 +00001594 {
1595 result.AppendError ("empty command");
1596 result.SetStatus(eReturnStatusFailed);
1597 return false;
1598 }
1599 else
1600 {
1601 command_line = m_repeat_command.c_str();
1602 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001603 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001604 if (m_repeat_command.empty())
1605 {
1606 result.AppendErrorWithFormat("No auto repeat.\n");
1607 result.SetStatus (eReturnStatusFailed);
1608 return false;
1609 }
1610 }
1611 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001612 }
1613 else
1614 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001615 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1616 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001617 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001618 }
1619 else if (comment_command)
1620 {
1621 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1622 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001623 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001624
Greg Clayton5a314712011-10-14 07:41:33 +00001625
1626 Error error (PreprocessCommand (command_string));
1627
1628 if (error.Fail())
1629 {
1630 result.AppendError (error.AsCString());
1631 result.SetStatus(eReturnStatusFailed);
1632 return false;
1633 }
Caroline Tice844d2302010-12-09 22:52:49 +00001634 // Phase 1.
1635
1636 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1637 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1638 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1639 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1640 // 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 +00001641 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001642 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001643
Caroline Tice844d2302010-12-09 22:52:49 +00001644 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001645 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001646 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001647 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001648 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001649 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001650 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001651 std::string suffix;
1652 ExtractCommand (command_string, next_word, suffix, quote_char);
1653 if (cmd_obj == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001654 {
Jim Ingham298f3782013-04-03 00:25:49 +00001655 std::string full_name;
1656 if (GetAliasFullName(next_word.c_str(), full_name))
Caroline Tice472362e2010-12-14 18:51:39 +00001657 {
Greg Clayton5521f992011-10-28 21:38:01 +00001658 std::string alias_result;
Jim Ingham298f3782013-04-03 00:25:49 +00001659 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
Greg Clayton5521f992011-10-28 21:38:01 +00001660 revised_command_line.Printf ("%s", alias_result.c_str());
1661 if (cmd_obj)
1662 {
1663 wants_raw_input = cmd_obj->WantsRawCommandString ();
1664 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1665 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001666 }
1667 else
1668 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001669 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001670 if (cmd_obj)
1671 {
1672 actual_cmd_name_len += next_word.length();
1673 revised_command_line.Printf ("%s", next_word.c_str());
1674 wants_raw_input = cmd_obj->WantsRawCommandString ();
1675 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001676 else
Greg Clayton5521f992011-10-28 21:38:01 +00001677 {
1678 revised_command_line.Printf ("%s", next_word.c_str());
1679 }
Caroline Tice844d2302010-12-09 22:52:49 +00001680 }
1681 }
1682 else
1683 {
Greg Clayton5521f992011-10-28 21:38:01 +00001684 if (cmd_obj->IsMultiwordObject ())
1685 {
Greg Clayton998255b2012-10-13 02:07:45 +00001686 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001687 if (sub_cmd_obj)
1688 {
1689 actual_cmd_name_len += next_word.length() + 1;
1690 revised_command_line.Printf (" %s", next_word.c_str());
1691 cmd_obj = sub_cmd_obj;
1692 wants_raw_input = cmd_obj->WantsRawCommandString ();
1693 }
1694 else
1695 {
1696 if (quote_char)
1697 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1698 else
1699 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1700 done = true;
1701 }
1702 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001703 else
Greg Clayton5521f992011-10-28 21:38:01 +00001704 {
1705 if (quote_char)
1706 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1707 else
1708 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1709 done = true;
1710 }
Caroline Tice844d2302010-12-09 22:52:49 +00001711 }
1712
1713 if (cmd_obj == NULL)
1714 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001715 const size_t num_matches = matches.GetSize();
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001716 if (matches.GetSize() > 1) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001717 StreamString error_msg;
1718 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001719
1720 for (uint32_t i = 0; i < num_matches; ++i) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001721 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001722 }
Greg Claytonc7bece562013-01-25 18:06:21 +00001723 result.AppendRawError (error_msg.GetString().c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001724 } else {
1725 // We didn't have only one match, otherwise we wouldn't get here.
1726 assert(num_matches == 0);
1727 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1728 }
Caroline Tice844d2302010-12-09 22:52:49 +00001729 result.SetStatus (eReturnStatusFailed);
1730 return false;
1731 }
1732
Greg Clayton5521f992011-10-28 21:38:01 +00001733 if (cmd_obj->IsMultiwordObject ())
1734 {
1735 if (!suffix.empty())
1736 {
1737
Enrico Granataaded51d2013-06-12 00:44:43 +00001738 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1739 cmd_obj->GetCommandName(),
1740 next_word.empty() ? "" : next_word.c_str(),
1741 next_word.empty() ? " -- " : " ",
Greg Clayton5521f992011-10-28 21:38:01 +00001742 suffix.c_str());
1743 result.SetStatus (eReturnStatusFailed);
1744 return false;
1745 }
1746 }
1747 else
1748 {
1749 // If we found a normal command, we are done
1750 done = true;
1751 if (!suffix.empty())
1752 {
1753 switch (suffix[0])
1754 {
1755 case '/':
1756 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001757 {
1758 Options *command_options = cmd_obj->GetOptions();
1759 if (command_options && command_options->SupportsLongOption("gdb-format"))
1760 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001761 std::string gdb_format_option ("--gdb-format=");
1762 gdb_format_option += (suffix.c_str() + 1);
1763
1764 bool inserted = false;
1765 std::string &cmd = revised_command_line.GetString();
1766 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1767 if (arg_terminator_idx != std::string::npos)
1768 {
1769 // Insert the gdb format option before the "--" that terminates options
1770 gdb_format_option.append(1,' ');
1771 cmd.insert(arg_terminator_idx, gdb_format_option);
1772 inserted = true;
1773 }
1774
1775 if (!inserted)
1776 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1777
1778 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1779 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001780 }
1781 else
1782 {
1783 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1784 cmd_obj->GetCommandName());
1785 result.SetStatus (eReturnStatusFailed);
1786 return false;
1787 }
1788 }
Greg Clayton5521f992011-10-28 21:38:01 +00001789 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001790
1791 default:
1792 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1793 suffix.c_str());
1794 result.SetStatus (eReturnStatusFailed);
1795 return false;
1796
Greg Clayton5521f992011-10-28 21:38:01 +00001797 }
1798 }
1799 }
Caroline Tice844d2302010-12-09 22:52:49 +00001800 if (command_string.length() == 0)
1801 done = true;
1802
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001803 }
Caroline Tice844d2302010-12-09 22:52:49 +00001804
Greg Clayton5521f992011-10-28 21:38:01 +00001805 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001806 revised_command_line.Printf (" %s", command_string.c_str());
1807
1808 // End of Phase 1.
1809 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1810 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1811 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1812 // wants_raw_input specifies whether the Execute method expects raw input or not.
1813
1814
1815 if (log)
1816 {
1817 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1818 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1819 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1820 }
1821
1822 // Phase 2.
1823 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1824 // CommandObject, with the appropriate arguments.
1825
1826 if (cmd_obj != NULL)
1827 {
1828 if (add_to_history)
1829 {
1830 Args command_args (revised_command_line.GetData());
1831 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1832 if (repeat_command != NULL)
1833 m_repeat_command.assign(repeat_command);
1834 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001835 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001836
Enrico Granata7594f142013-06-17 22:51:50 +00001837 m_command_history.AppendString (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001838 }
1839
1840 command_string = revised_command_line.GetData();
1841 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001842 std::string remainder;
1843 if (actual_cmd_name_len < command_string.length())
1844 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1845 // than cmd_obj->GetCommandName(), because name completion
1846 // allows users to enter short versions of the names,
1847 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001848
1849 // Remove any initial spaces
1850 std::string white_space (" \t\v");
1851 size_t pos = remainder.find_first_not_of (white_space);
1852 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001853 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001854
1855 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001856 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001857
Jim Ingham5a988412012-06-08 21:56:10 +00001858 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001859 }
1860 else
1861 {
1862 // We didn't find the first command object, so complete the first argument.
1863 Args command_args (revised_command_line.GetData());
1864 StringList matches;
1865 int num_matches;
1866 int cursor_index = 0;
1867 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1868 bool word_complete;
1869 num_matches = HandleCompletionMatches (command_args,
1870 cursor_index,
1871 cursor_char_position,
1872 0,
1873 -1,
1874 word_complete,
1875 matches);
1876
1877 if (num_matches > 0)
1878 {
1879 std::string error_msg;
1880 error_msg.assign ("ambiguous command '");
1881 error_msg.append(command_args.GetArgumentAtIndex(0));
1882 error_msg.append ("'.");
1883
1884 error_msg.append (" Possible completions:");
1885 for (int i = 0; i < num_matches; i++)
1886 {
1887 error_msg.append ("\n\t");
1888 error_msg.append (matches.GetStringAtIndex (i));
1889 }
1890 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001891 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001892 }
1893 else
1894 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1895
1896 result.SetStatus (eReturnStatusFailed);
1897 }
1898
Jason Molendabfb36ff2011-08-25 00:20:04 +00001899 if (log)
1900 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1901
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001902 return result.Succeeded();
1903}
1904
1905int
1906CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1907 int &cursor_index,
1908 int &cursor_char_position,
1909 int match_start_point,
1910 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001911 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001912 StringList &matches)
1913{
1914 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001915 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001916
1917 // For any of the command completions a unique match will be a complete word.
1918 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001919
1920 if (cursor_index == -1)
1921 {
1922 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001923 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001924 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1925 }
1926 else if (cursor_index == 0)
1927 {
1928 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001929 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001930 num_command_matches = matches.GetSize();
1931
1932 if (num_command_matches == 1
1933 && cmd_obj && cmd_obj->IsMultiwordObject()
1934 && matches.GetStringAtIndex(0) != NULL
1935 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1936 {
Greg Clayton765d2e22013-12-10 19:14:04 +00001937 if (parsed_line.GetArgumentCount() == 1)
1938 {
1939 word_complete = true;
1940 }
1941 else
1942 {
1943 look_for_subcommand = true;
1944 num_command_matches = 0;
1945 matches.DeleteStringAtIndex(0);
1946 parsed_line.AppendArgument ("");
1947 cursor_index++;
1948 cursor_char_position = 0;
1949 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001950 }
1951 }
1952
1953 if (cursor_index > 0 || look_for_subcommand)
1954 {
1955 // We are completing further on into a commands arguments, so find the command and tell it
1956 // to complete the command.
1957 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001958 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001959 if (command_object == NULL)
1960 {
1961 return 0;
1962 }
1963 else
1964 {
1965 parsed_line.Shift();
1966 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001967 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001968 cursor_index,
1969 cursor_char_position,
1970 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001971 max_return_elements,
1972 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001973 matches);
1974 }
1975 }
1976
1977 return num_command_matches;
1978
1979}
1980
1981int
1982CommandInterpreter::HandleCompletion (const char *current_line,
1983 const char *cursor,
1984 const char *last_char,
1985 int match_start_point,
1986 int max_return_elements,
1987 StringList &matches)
1988{
1989 // We parse the argument up to the cursor, so the last argument in parsed_line is
1990 // the one containing the cursor, and the cursor is after the last character.
1991
1992 Args parsed_line(current_line, last_char - current_line);
1993 Args partial_parsed_line(current_line, cursor - current_line);
1994
Jim Inghama5a97eb2011-07-12 03:12:18 +00001995 // Don't complete comments, and if the line we are completing is just the history repeat character,
1996 // substitute the appropriate history line.
1997 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1998 if (first_arg)
1999 {
2000 if (first_arg[0] == m_comment_char)
2001 return 0;
Enrico Granata7594f142013-06-17 22:51:50 +00002002 else if (first_arg[0] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002003 {
Enrico Granata7594f142013-06-17 22:51:50 +00002004 const char *history_string = m_command_history.FindString (first_arg);
Jim Inghama5a97eb2011-07-12 03:12:18 +00002005 if (history_string != NULL)
2006 {
2007 matches.Clear();
2008 matches.InsertStringAtIndex(0, history_string);
2009 return -2;
2010 }
2011 else
2012 return 0;
2013
2014 }
2015 }
2016
2017
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002018 int num_args = partial_parsed_line.GetArgumentCount();
2019 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2020 int cursor_char_position;
2021
2022 if (cursor_index == -1)
2023 cursor_char_position = 0;
2024 else
2025 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00002026
2027 if (cursor > current_line && cursor[-1] == ' ')
2028 {
2029 // We are just after a space. If we are in an argument, then we will continue
2030 // parsing, but if we are between arguments, then we have to complete whatever the next
2031 // element would be.
2032 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2033 // protected by a quote) then the space will also be in the parsed argument...
2034
2035 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2036 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2037 {
Greg Clayton765d2e22013-12-10 19:14:04 +00002038 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
Jim Inghamfe0c4252010-12-14 19:56:01 +00002039 cursor_index++;
2040 cursor_char_position = 0;
2041 }
2042 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002043
2044 int num_command_matches;
2045
2046 matches.Clear();
2047
2048 // Only max_return_elements == -1 is supported at present:
2049 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00002050 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00002051 num_command_matches = HandleCompletionMatches (parsed_line,
2052 cursor_index,
2053 cursor_char_position,
2054 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002055 max_return_elements,
2056 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002057 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002058
2059 if (num_command_matches <= 0)
2060 return num_command_matches;
2061
2062 if (num_args == 0)
2063 {
2064 // If we got an empty string, insert nothing.
2065 matches.InsertStringAtIndex(0, "");
2066 }
2067 else
2068 {
2069 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2070 // put an empty string in element 0.
2071 std::string command_partial_str;
2072 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002073 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2074 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002075
2076 std::string common_prefix;
2077 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002078 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002079
2080 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002081 // Only do this if the completer told us this was a complete word, however...
2082 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002083 {
2084 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2085 if (quote_char != '\0')
2086 common_prefix.push_back(quote_char);
2087
2088 common_prefix.push_back(' ');
2089 }
2090 common_prefix.erase (0, partial_name_len);
2091 matches.InsertStringAtIndex(0, common_prefix.c_str());
2092 }
2093 return num_command_matches;
2094}
2095
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002096
2097CommandInterpreter::~CommandInterpreter ()
2098{
2099}
2100
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002101void
Greg Clayton44d93782014-01-27 23:43:24 +00002102CommandInterpreter::UpdatePrompt (const char *new_prompt)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002103{
Greg Clayton44d93782014-01-27 23:43:24 +00002104 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2105 BroadcastEvent (prompt_change_event_sp);
2106 if (m_command_io_handler_sp)
2107 m_command_io_handler_sp->SetPrompt(new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002108}
2109
Jim Ingham97a6dc72010-10-04 19:49:29 +00002110
2111bool
2112CommandInterpreter::Confirm (const char *message, bool default_answer)
2113{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002114 // Check AutoConfirm first:
2115 if (m_debugger.GetAutoConfirm())
2116 return default_answer;
Greg Clayton44d93782014-01-27 23:43:24 +00002117
2118 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2119 message,
2120 default_answer);
2121 IOHandlerSP io_handler_sp (confirm);
2122 m_debugger.RunIOHandler (io_handler_sp);
2123 return confirm->GetResponse();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002124}
2125
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126OptionArgVectorSP
2127CommandInterpreter::GetAliasOptions (const char *alias_name)
2128{
2129 OptionArgMap::iterator pos;
2130 OptionArgVectorSP ret_val;
2131
2132 std::string alias (alias_name);
2133
2134 if (HasAliasOptions())
2135 {
2136 pos = m_alias_options.find (alias);
2137 if (pos != m_alias_options.end())
2138 ret_val = pos->second;
2139 }
2140
2141 return ret_val;
2142}
2143
2144void
2145CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2146{
2147 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2148 if (pos != m_alias_options.end())
2149 {
2150 m_alias_options.erase (pos);
2151 }
2152}
2153
2154void
2155CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2156{
2157 m_alias_options[alias_name] = option_arg_vector_sp;
2158}
2159
2160bool
2161CommandInterpreter::HasCommands ()
2162{
2163 return (!m_command_dict.empty());
2164}
2165
2166bool
2167CommandInterpreter::HasAliases ()
2168{
2169 return (!m_alias_dict.empty());
2170}
2171
2172bool
2173CommandInterpreter::HasUserCommands ()
2174{
2175 return (!m_user_dict.empty());
2176}
2177
2178bool
2179CommandInterpreter::HasAliasOptions ()
2180{
2181 return (!m_alias_options.empty());
2182}
2183
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002184void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002185CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2186 const char *alias_name,
2187 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002188 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002189 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002190{
2191 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002192
2193 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002194
Caroline Ticed9d63362010-12-07 19:58:26 +00002195 // Make sure that the alias name is the 0th element in cmd_args
2196 std::string alias_name_str = alias_name;
2197 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2198 cmd_args.Unshift (alias_name);
2199
2200 Args new_args (alias_cmd_obj->GetCommandName());
2201 if (new_args.GetArgumentCount() == 2)
2202 new_args.Shift();
2203
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002204 if (option_arg_vector_sp.get())
2205 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002206 if (wants_raw_input)
2207 {
2208 // We have a command that both has command options and takes raw input. Make *sure* it has a
2209 // " -- " in the right place in the raw_input_string.
2210 size_t pos = raw_input_string.find(" -- ");
2211 if (pos == std::string::npos)
2212 {
2213 // None found; assume it goes at the beginning of the raw input string
2214 raw_input_string.insert (0, " -- ");
2215 }
2216 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002217
2218 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002219 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002220 std::vector<bool> used (old_size + 1, false);
2221
2222 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002223
Andy Gibbsa297a972013-06-19 19:04:53 +00002224 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002225 {
2226 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002227 OptionArgValue value_pair = option_pair.second;
2228 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002229 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002230 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002231 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002232 {
2233 if (!wants_raw_input
2234 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2235 new_args.AppendArgument (value.c_str());
2236 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002237 else
2238 {
Virgile Belloe2607b52013-09-05 16:42:23 +00002239 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002240 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002241 if (value.compare ("<no-argument>") != 0)
2242 {
2243 int index = GetOptionArgumentPosition (value.c_str());
2244 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002245 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002246 // value was NOT a positional argument; must be a real value
Virgile Belloe2607b52013-09-05 16:42:23 +00002247 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002248 new_args.AppendArgument (value.c_str());
2249 else
2250 {
2251 char buffer[255];
2252 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2253 new_args.AppendArgument (buffer);
2254 }
2255
2256 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002257 else if (index >= cmd_args.GetArgumentCount())
2258 {
2259 result.AppendErrorWithFormat
2260 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2261 index);
2262 result.SetStatus (eReturnStatusFailed);
2263 return;
2264 }
2265 else
2266 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002267 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2268 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2269 if (strpos != std::string::npos)
2270 {
2271 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2272 }
2273
Virgile Belloe2607b52013-09-05 16:42:23 +00002274 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002275 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2276 else
2277 {
2278 char buffer[255];
2279 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2280 cmd_args.GetArgumentAtIndex (index));
2281 new_args.AppendArgument (buffer);
2282 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002283 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002284 }
2285 }
2286 }
2287 }
2288
Andy Gibbsa297a972013-06-19 19:04:53 +00002289 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002290 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002291 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2293 }
2294
2295 cmd_args.Clear();
2296 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2297 }
2298 else
2299 {
2300 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002301 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2302 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2303 // input string.
2304 if (wants_raw_input)
2305 {
2306 cmd_args.Clear();
2307 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2308 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002309 return;
2310 }
2311
2312 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2313 return;
2314}
2315
2316
2317int
2318CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2319{
2320 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2321 // of zero.
2322
2323 char *cptr = (char *) in_string;
2324
2325 // Does it start with '%'
2326 if (cptr[0] == '%')
2327 {
2328 ++cptr;
2329
2330 // Is the rest of it entirely digits?
2331 if (isdigit (cptr[0]))
2332 {
2333 const char *start = cptr;
2334 while (isdigit (cptr[0]))
2335 ++cptr;
2336
2337 // We've gotten to the end of the digits; are we at the end of the string?
2338 if (cptr[0] == '\0')
2339 position = atoi (start);
2340 }
2341 }
2342
2343 return position;
2344}
2345
2346void
2347CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2348{
Jim Ingham16e0c682011-08-12 23:34:31 +00002349 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002350 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002351 {
Greg Clayton14a35512011-09-11 00:01:44 +00002352 // In the current working directory we don't load any program specific
2353 // .lldbinit files, we only look for a "./.lldbinit" file.
2354 if (m_skip_lldbinit_files)
2355 return;
2356
2357 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002358 }
Greg Clayton14a35512011-09-11 00:01:44 +00002359 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002360 {
Greg Clayton14a35512011-09-11 00:01:44 +00002361 // If we aren't looking in the current working directory we are looking
2362 // in the home directory. We will first see if there is an application
2363 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2364 // "-" and the name of the program. If this file doesn't exist, we fall
2365 // back to just the "~/.lldbinit" file. We also obey any requests to not
2366 // load the init files.
2367 const char *init_file_path = "~/.lldbinit";
2368
2369 if (m_skip_app_init_files == false)
2370 {
2371 FileSpec program_file_spec (Host::GetProgramFileSpec());
2372 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002373
Greg Clayton14a35512011-09-11 00:01:44 +00002374 if (program_name)
2375 {
2376 char program_init_file_name[PATH_MAX];
2377 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2378 init_file.SetFile (program_init_file_name, true);
2379 if (!init_file.Exists())
2380 init_file.Clear();
2381 }
2382 }
2383
2384 if (!init_file && !m_skip_lldbinit_files)
2385 init_file.SetFile (init_file_path, true);
2386 }
2387
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002388 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2389 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2390
2391 if (init_file.Exists())
2392 {
Greg Clayton44d93782014-01-27 23:43:24 +00002393 const bool saved_batch = SetBatchCommandMode (true);
Greg Clayton340b0302014-02-05 17:57:57 +00002394 HandleCommandsFromFile (init_file,
2395 NULL, // Execution context
2396 eLazyBoolYes, // Stop on continue
2397 eLazyBoolNo, // Stop on error
2398 eLazyBoolNo, // Don't echo commands
2399 eLazyBoolNo, // Don't print command output
2400 eLazyBoolNo, // Don't add the commands that are sourced into the history buffer
2401 result);
Greg Clayton44d93782014-01-27 23:43:24 +00002402 SetBatchCommandMode (saved_batch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002403 }
2404 else
2405 {
2406 // nothing to be done if the file doesn't exist
2407 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2408 }
2409}
2410
Greg Clayton8b82f082011-04-12 05:54:46 +00002411PlatformSP
2412CommandInterpreter::GetPlatform (bool prefer_target_platform)
2413{
2414 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002415 if (prefer_target_platform)
2416 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002417 ExecutionContext exe_ctx(GetExecutionContext());
2418 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002419 if (target)
2420 platform_sp = target->GetPlatform();
2421 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002422
2423 if (!platform_sp)
2424 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2425 return platform_sp;
2426}
2427
Jim Inghame16c50a2011-02-18 00:54:25 +00002428void
Jim Inghambad87fe2011-03-11 01:51:49 +00002429CommandInterpreter::HandleCommands (const StringList &commands,
Jim Inghame16c50a2011-02-18 00:54:25 +00002430 ExecutionContext *override_context,
2431 bool stop_on_continue,
2432 bool stop_on_error,
2433 bool echo_commands,
2434 bool print_results,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002435 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002436 CommandReturnObject &result)
2437{
2438 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002439
2440 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2441 // Make sure you reset this value anywhere you return from the function.
2442
2443 bool old_async_execution = m_debugger.GetAsyncExecution();
2444
2445 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2446 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2447
2448 if (override_context != NULL)
Greg Clayton8b82f082011-04-12 05:54:46 +00002449 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002450
2451 if (!stop_on_continue)
2452 {
2453 m_debugger.SetAsyncExecution (false);
2454 }
2455
Andy Gibbsa297a972013-06-19 19:04:53 +00002456 for (size_t idx = 0; idx < num_lines; idx++)
Jim Inghame16c50a2011-02-18 00:54:25 +00002457 {
2458 const char *cmd = commands.GetStringAtIndex(idx);
2459 if (cmd[0] == '\0')
2460 continue;
2461
Jim Inghame16c50a2011-02-18 00:54:25 +00002462 if (echo_commands)
2463 {
2464 result.AppendMessageWithFormat ("%s %s\n",
Greg Clayton44d93782014-01-27 23:43:24 +00002465 m_debugger.GetPrompt(),
2466 cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002467 }
2468
Greg Clayton9d0402b2011-02-20 02:15:07 +00002469 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002470 // If override_context is not NULL, pass no_context_switching = true for
2471 // HandleCommand() since we updated our context already.
Jim Ingham076b7fc2013-05-02 23:15:37 +00002472
2473 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2474 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here.
2475 if (!add_to_history)
2476 m_command_source_depth++;
Enrico Granata5f5ab602012-05-31 01:09:06 +00002477 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002478 NULL, /* override_context */
2479 true, /* repeat_on_empty_command */
2480 override_context != NULL /* no_context_switching */);
Jim Ingham076b7fc2013-05-02 23:15:37 +00002481 if (!add_to_history)
2482 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002483
2484 if (print_results)
2485 {
2486 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002487 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002488 }
2489
2490 if (!success || !tmp_result.Succeeded())
2491 {
Jim Inghama5038812012-04-24 02:25:07 +00002492 const char *error_msg = tmp_result.GetErrorData();
2493 if (error_msg == NULL || error_msg[0] == '\0')
2494 error_msg = "<unknown error>.\n";
Jim Inghame16c50a2011-02-18 00:54:25 +00002495 if (stop_on_error)
2496 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002497 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s",
2498 (uint64_t)idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002499 result.SetStatus (eReturnStatusFailed);
2500 m_debugger.SetAsyncExecution (old_async_execution);
2501 return;
2502 }
2503 else if (print_results)
2504 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002505 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s",
2506 (uint64_t)idx + 1,
Jim Inghame16c50a2011-02-18 00:54:25 +00002507 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002508 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002509 }
2510 }
2511
Caroline Tice969ed3d2011-05-02 20:41:46 +00002512 if (result.GetImmediateOutputStream())
2513 result.GetImmediateOutputStream()->Flush();
2514
2515 if (result.GetImmediateErrorStream())
2516 result.GetImmediateErrorStream()->Flush();
2517
Jim Inghame16c50a2011-02-18 00:54:25 +00002518 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2519 // could be running (for instance in Breakpoint Commands.
2520 // So we check the return value to see if it is has running in it.
2521 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2522 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2523 {
2524 if (stop_on_continue)
2525 {
2526 // If we caused the target to proceed, and we're going to stop in that case, set the
2527 // status in our real result before returning. This is an error if the continue was not the
2528 // last command in the set of commands to be run.
2529 if (idx != num_lines - 1)
Deepak Panickal99fbc072014-03-03 15:39:47 +00002530 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n",
2531 (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002532 else
Deepak Panickal99fbc072014-03-03 15:39:47 +00002533 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002534
2535 result.SetStatus(tmp_result.GetStatus());
2536 m_debugger.SetAsyncExecution (old_async_execution);
2537
2538 return;
2539 }
2540 }
2541
2542 }
2543
2544 result.SetStatus (eReturnStatusSuccessFinishResult);
2545 m_debugger.SetAsyncExecution (old_async_execution);
2546
2547 return;
2548}
2549
Greg Clayton340b0302014-02-05 17:57:57 +00002550// Make flags that we can pass into the IOHandler so our delegates can do the right thing
2551enum {
2552 eHandleCommandFlagStopOnContinue = (1u << 0),
2553 eHandleCommandFlagStopOnError = (1u << 1),
2554 eHandleCommandFlagEchoCommand = (1u << 2),
2555 eHandleCommandFlagPrintResult = (1u << 3)
2556};
2557
Jim Inghame16c50a2011-02-18 00:54:25 +00002558void
2559CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2560 ExecutionContext *context,
Greg Clayton340b0302014-02-05 17:57:57 +00002561 LazyBool stop_on_continue,
2562 LazyBool stop_on_error,
2563 LazyBool echo_command,
2564 LazyBool print_result,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002565 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002566 CommandReturnObject &result)
2567{
2568 if (cmd_file.Exists())
2569 {
Greg Clayton44d93782014-01-27 23:43:24 +00002570 StreamFileSP input_file_sp (new StreamFile());
2571
2572 std::string cmd_file_path = cmd_file.GetPath();
2573 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2574
2575 if (error.Success())
2576 {
2577 Debugger &debugger = GetDebugger();
2578
Greg Clayton340b0302014-02-05 17:57:57 +00002579 uint32_t flags = 0;
2580
2581 if (stop_on_continue == eLazyBoolCalculate)
2582 {
2583 if (m_command_source_flags.empty())
2584 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002585 // Stop on continue by default
Greg Clayton340b0302014-02-05 17:57:57 +00002586 flags |= eHandleCommandFlagStopOnContinue;
2587 }
2588 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2589 {
2590 flags |= eHandleCommandFlagStopOnContinue;
2591 }
2592 }
2593 else if (stop_on_continue == eLazyBoolYes)
2594 {
2595 flags |= eHandleCommandFlagStopOnContinue;
2596 }
2597
2598 if (stop_on_error == eLazyBoolCalculate)
2599 {
2600 if (m_command_source_flags.empty())
2601 {
2602 if (GetStopCmdSourceOnError())
2603 flags |= eHandleCommandFlagStopOnError;
2604 }
2605 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2606 {
2607 flags |= eHandleCommandFlagStopOnError;
2608 }
2609 }
2610 else if (stop_on_error == eLazyBoolYes)
2611 {
2612 flags |= eHandleCommandFlagStopOnError;
2613 }
2614
2615 if (echo_command == eLazyBoolCalculate)
2616 {
2617 if (m_command_source_flags.empty())
2618 {
2619 // Echo command by default
2620 flags |= eHandleCommandFlagEchoCommand;
2621 }
2622 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2623 {
2624 flags |= eHandleCommandFlagEchoCommand;
2625 }
2626 }
2627 else if (echo_command == eLazyBoolYes)
2628 {
2629 flags |= eHandleCommandFlagEchoCommand;
2630 }
2631
2632 if (print_result == eLazyBoolCalculate)
2633 {
2634 if (m_command_source_flags.empty())
2635 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002636 // Print output by default
2637 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002638 }
Greg Claytone4e462c2014-02-05 21:03:22 +00002639 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
Greg Clayton340b0302014-02-05 17:57:57 +00002640 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002641 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002642 }
2643 }
2644 else if (print_result == eLazyBoolYes)
2645 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002646 flags |= eHandleCommandFlagPrintResult;
2647 }
2648
2649 if (flags & eHandleCommandFlagPrintResult)
2650 {
Greg Clayton8ee67312014-02-05 21:46:20 +00002651 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
Greg Clayton340b0302014-02-05 17:57:57 +00002652 }
2653
2654 // Used for inheriting the right settings when "command source" might have
2655 // nested "command source" commands
Greg Claytone4e462c2014-02-05 21:03:22 +00002656 lldb::StreamFileSP empty_stream_sp;
Greg Clayton340b0302014-02-05 17:57:57 +00002657 m_command_source_flags.push_back(flags);
Greg Clayton44d93782014-01-27 23:43:24 +00002658 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
2659 input_file_sp,
Greg Claytone4e462c2014-02-05 21:03:22 +00002660 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2661 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
Greg Clayton340b0302014-02-05 17:57:57 +00002662 flags,
Greg Clayton44d93782014-01-27 23:43:24 +00002663 NULL, // Pass in NULL for "editline_name" so no history is saved, or written
Greg Clayton8ee67312014-02-05 21:46:20 +00002664 debugger.GetPrompt(),
Greg Clayton44d93782014-01-27 23:43:24 +00002665 false, // Not multi-line
2666 *this));
Greg Clayton8ee67312014-02-05 21:46:20 +00002667 const bool old_async_execution = debugger.GetAsyncExecution();
2668
2669 // Set synchronous execution if we not stopping when we continue
2670 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2671 debugger.SetAsyncExecution (false);
2672
Greg Clayton340b0302014-02-05 17:57:57 +00002673 m_command_source_depth++;
Greg Clayton8ee67312014-02-05 21:46:20 +00002674
2675 debugger.RunIOHandler(io_handler_sp);
Greg Clayton340b0302014-02-05 17:57:57 +00002676 if (!m_command_source_flags.empty())
2677 m_command_source_flags.pop_back();
2678 m_command_source_depth--;
Greg Clayton44d93782014-01-27 23:43:24 +00002679 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Greg Clayton8ee67312014-02-05 21:46:20 +00002680 debugger.SetAsyncExecution (old_async_execution);
Greg Clayton44d93782014-01-27 23:43:24 +00002681 }
2682 else
2683 {
2684 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2685 result.SetStatus (eReturnStatusFailed);
2686 }
Greg Clayton8ee67312014-02-05 21:46:20 +00002687
2688
Jim Inghame16c50a2011-02-18 00:54:25 +00002689 }
2690 else
2691 {
2692 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2693 cmd_file.GetFilename().AsCString());
2694 result.SetStatus (eReturnStatusFailed);
2695 return;
2696 }
2697}
2698
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002699ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002700CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002701{
Enrico Granatab5887262012-10-29 21:18:03 +00002702 if (m_script_interpreter_ap.get() != NULL)
2703 return m_script_interpreter_ap.get();
2704
2705 if (!can_create)
2706 return NULL;
2707
Enrico Granataa29bdad2012-07-10 18:23:48 +00002708 // <rdar://problem/11751427>
2709 // we need to protect the initialization of the script interpreter
2710 // otherwise we could end up with two threads both trying to create
2711 // their instance of it, and for some languages (e.g. Python)
2712 // this is a bulletproof recipe for disaster!
2713 // this needs to be a function-level static because multiple Debugger instances living in the same process
2714 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002715 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2716 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002717
Greg Clayton5160ce52013-03-27 23:08:40 +00002718 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002719 if (log)
2720 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002721
Caroline Tice2f88aad2011-01-14 00:29:16 +00002722 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2723 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002724 {
Greg Claytondce502e2011-11-04 03:34:56 +00002725 case eScriptLanguagePython:
2726#ifndef LLDB_DISABLE_PYTHON
2727 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2728 break;
2729#else
2730 // Fall through to the None case when python is disabled
2731#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002732 case eScriptLanguageNone:
2733 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2734 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002735 };
2736
2737 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738}
2739
2740
2741
2742bool
2743CommandInterpreter::GetSynchronous ()
2744{
2745 return m_synchronous_execution;
2746}
2747
2748void
2749CommandInterpreter::SetSynchronous (bool value)
2750{
Johnny Chenc066ab42010-10-14 01:22:03 +00002751 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002752}
2753
2754void
2755CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2756 const char *word_text,
2757 const char *separator,
2758 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002759 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002760{
Greg Claytona7015092010-09-18 01:14:36 +00002761 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2762
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002763 int indent_size = max_word_len + strlen (separator) + 2;
2764
2765 strm.IndentMore (indent_size);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002766
2767 StreamString text_strm;
Greg Claytonc7bece562013-01-25 18:06:21 +00002768 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002769
2770 size_t len = text_strm.GetSize();
2771 const char *text = text_strm.GetData();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002772 if (text[len - 1] == '\n')
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002773 {
2774 text_strm.EOL();
2775 len = text_strm.GetSize();
2776 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002777
2778 if (len < max_columns)
2779 {
2780 // Output it as a single line.
2781 strm.Printf ("%s", text);
2782 }
2783 else
2784 {
2785 // We need to break it up into multiple lines.
2786 bool first_line = true;
2787 int text_width;
Greg Claytonc7bece562013-01-25 18:06:21 +00002788 size_t start = 0;
2789 size_t end = start;
2790 const size_t final_end = strlen (text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002791
2792 while (end < final_end)
2793 {
2794 if (first_line)
2795 text_width = max_columns - 1;
2796 else
2797 text_width = max_columns - indent_size - 1;
2798
2799 // Don't start the 'text' on a space, since we're already outputting the indentation.
2800 if (!first_line)
2801 {
2802 while ((start < final_end) && (text[start] == ' '))
2803 start++;
2804 }
2805
2806 end = start + text_width;
2807 if (end > final_end)
2808 end = final_end;
2809 else
2810 {
2811 // If we're not at the end of the text, make sure we break the line on white space.
2812 while (end > start
2813 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2814 end--;
Greg Clayton67cc0632012-08-22 17:17:09 +00002815 assert (end > 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002816 }
2817
Greg Claytonc7bece562013-01-25 18:06:21 +00002818 const size_t sub_len = end - start;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002819 if (start != 0)
2820 strm.EOL();
2821 if (!first_line)
2822 strm.Indent();
2823 else
2824 first_line = false;
2825 assert (start <= final_end);
2826 assert (start + sub_len <= final_end);
2827 if (sub_len > 0)
2828 strm.Write (text + start, sub_len);
2829 start = end + 1;
2830 }
2831 }
2832 strm.EOL();
2833 strm.IndentLess(indent_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002834}
2835
2836void
Enrico Granata82a7d982011-07-07 00:38:40 +00002837CommandInterpreter::OutputHelpText (Stream &strm,
2838 const char *word_text,
2839 const char *separator,
2840 const char *help_text,
2841 uint32_t max_word_len)
2842{
2843 int indent_size = max_word_len + strlen (separator) + 2;
2844
2845 strm.IndentMore (indent_size);
2846
2847 StreamString text_strm;
2848 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2849
2850 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002851
2852 size_t len = text_strm.GetSize();
2853 const char *text = text_strm.GetData();
2854
2855 uint32_t chars_left = max_columns;
2856
2857 for (uint32_t i = 0; i < len; i++)
2858 {
2859 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2860 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002861 chars_left = max_columns - indent_size;
2862 strm.EOL();
2863 strm.Indent();
2864 }
2865 else
2866 {
2867 strm.PutChar(text[i]);
2868 chars_left--;
2869 }
2870
2871 }
2872
2873 strm.EOL();
2874 strm.IndentLess(indent_size);
2875}
2876
2877void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002878CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
Jim Inghamaf3753e2013-05-17 01:30:37 +00002879 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880{
2881 CommandObject::CommandMap::const_iterator pos;
2882
Jim Inghamaf3753e2013-05-17 01:30:37 +00002883 if (search_builtin_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002884 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002885 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002886 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002887 const char *command_name = pos->first.c_str();
2888 CommandObject *cmd_obj = pos->second.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002889
Jim Inghamaf3753e2013-05-17 01:30:37 +00002890 if (cmd_obj->HelpTextContainsWord (search_word))
2891 {
2892 commands_found.AppendString (command_name);
2893 commands_help.AppendString (cmd_obj->GetHelp());
2894 }
2895
2896 if (cmd_obj->IsMultiwordObject())
2897 cmd_obj->AproposAllSubCommands (command_name,
2898 search_word,
2899 commands_found,
2900 commands_help);
2901
2902 }
2903 }
2904
2905 if (search_user_commands)
2906 {
2907 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
2908 {
2909 const char *command_name = pos->first.c_str();
2910 CommandObject *cmd_obj = pos->second.get();
2911
2912 if (cmd_obj->HelpTextContainsWord (search_word))
2913 {
2914 commands_found.AppendString (command_name);
2915 commands_help.AppendString (cmd_obj->GetHelp());
2916 }
2917
2918 if (cmd_obj->IsMultiwordObject())
2919 cmd_obj->AproposAllSubCommands (command_name,
2920 search_word,
2921 commands_found,
2922 commands_help);
2923
2924 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002925 }
2926}
Greg Clayton8b82f082011-04-12 05:54:46 +00002927
Greg Clayton8b82f082011-04-12 05:54:46 +00002928void
2929CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2930{
Greg Clayton8b82f082011-04-12 05:54:46 +00002931 if (override_context != NULL)
2932 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002933 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002934 }
2935 else
2936 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002937 const bool adopt_selected = true;
2938 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002939 }
2940}
Greg Clayton44d93782014-01-27 23:43:24 +00002941
2942
2943size_t
2944CommandInterpreter::GetProcessOutput ()
2945{
2946 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2947 char stdio_buffer[1024];
2948 size_t len;
2949 size_t total_bytes = 0;
2950 Error error;
2951 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2952 if (target_sp)
2953 {
2954 ProcessSP process_sp (target_sp->GetProcessSP());
2955 if (process_sp)
2956 {
2957 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2958 {
2959 size_t bytes_written = len;
2960 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
2961 total_bytes += len;
2962 }
2963 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2964 {
2965 size_t bytes_written = len;
2966 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
2967 total_bytes += len;
2968 }
2969 }
2970 }
2971 return total_bytes;
2972}
2973
2974void
2975CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
2976{
Greg Clayton340b0302014-02-05 17:57:57 +00002977 const bool is_interactive = io_handler.GetIsInteractive();
2978 if (is_interactive == false)
2979 {
2980 // When we are not interactive, don't execute blank lines. This will happen
2981 // sourcing a commands file. We don't want blank lines to repeat the previous
2982 // command and cause any errors to occur (like redefining an alias, get an error
2983 // and stop parsing the commands file).
2984 if (line.empty())
2985 return;
2986
2987 // When using a non-interactive file handle (like when sourcing commands from a file)
2988 // we need to echo the command out so we don't just see the command output and no
2989 // command...
2990 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2991 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
2992 }
2993
Greg Clayton44d93782014-01-27 23:43:24 +00002994 lldb_private::CommandReturnObject result;
2995 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2996
Greg Clayton44d93782014-01-27 23:43:24 +00002997 // Now emit the command output text from the command we just executed
Greg Clayton340b0302014-02-05 17:57:57 +00002998 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
2999 {
3000 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3001 GetProcessOutput ();
3002
Greg Clayton8ee67312014-02-05 21:46:20 +00003003 if (!result.GetImmediateOutputStream())
3004 {
3005 const char *output = result.GetOutputData();
3006 if (output && output[0])
3007 io_handler.GetOutputStreamFile()->PutCString(output);
3008 }
Greg Clayton44d93782014-01-27 23:43:24 +00003009
Greg Clayton340b0302014-02-05 17:57:57 +00003010 // Now emit the command error text from the command we just executed
Greg Clayton8ee67312014-02-05 21:46:20 +00003011 if (!result.GetImmediateErrorStream())
3012 {
3013 const char *error = result.GetErrorData();
3014 if (error && error[0])
3015 io_handler.GetErrorStreamFile()->PutCString(error);
3016 }
Greg Clayton340b0302014-02-05 17:57:57 +00003017 }
Greg Clayton44d93782014-01-27 23:43:24 +00003018
3019 switch (result.GetStatus())
3020 {
3021 case eReturnStatusInvalid:
3022 case eReturnStatusSuccessFinishNoResult:
3023 case eReturnStatusSuccessFinishResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003024 case eReturnStatusStarted:
3025 break;
3026
Greg Clayton44d93782014-01-27 23:43:24 +00003027 case eReturnStatusSuccessContinuingNoResult:
3028 case eReturnStatusSuccessContinuingResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003029 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3030 io_handler.SetIsDone(true);
3031 break;
3032
Greg Clayton44d93782014-01-27 23:43:24 +00003033 case eReturnStatusFailed:
Greg Clayton340b0302014-02-05 17:57:57 +00003034 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3035 io_handler.SetIsDone(true);
Greg Clayton44d93782014-01-27 23:43:24 +00003036 break;
3037
3038 case eReturnStatusQuit:
3039 io_handler.SetIsDone(true);
3040 break;
3041 }
3042}
3043
3044void
3045CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3046 IOHandlerDelegate &delegate,
3047 bool asynchronously,
3048 void *baton)
3049{
3050 Debugger &debugger = GetDebugger();
3051 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3052 "lldb", // Name of input reader for history
3053 prompt, // Prompt
3054 true, // Get multiple lines
3055 delegate)); // IOHandlerDelegate
3056
3057 if (io_handler_sp)
3058 {
3059 io_handler_sp->SetUserData (baton);
3060 if (asynchronously)
3061 debugger.PushIOHandler(io_handler_sp);
3062 else
3063 debugger.RunIOHandler(io_handler_sp);
3064 }
3065
3066}
3067
3068
3069void
3070CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3071 IOHandlerDelegate &delegate,
3072 bool asynchronously,
3073 void *baton)
3074{
3075 Debugger &debugger = GetDebugger();
3076 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
3077 "lldb-python", // Name of input reader for history
3078 prompt, // Prompt
3079 true, // Get multiple lines
3080 delegate)); // IOHandlerDelegate
3081
3082 if (io_handler_sp)
3083 {
3084 io_handler_sp->SetUserData (baton);
3085 if (asynchronously)
3086 debugger.PushIOHandler(io_handler_sp);
3087 else
3088 debugger.RunIOHandler(io_handler_sp);
3089 }
3090
3091}
3092
3093bool
3094CommandInterpreter::IsActive ()
3095{
3096 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3097}
3098
3099void
3100CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
3101 bool spawn_thread)
3102{
3103 const bool multiple_lines = false; // Only get one line at a time
3104 if (!m_command_io_handler_sp)
3105 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3106 m_debugger.GetInputFile(),
3107 m_debugger.GetOutputFile(),
3108 m_debugger.GetErrorFile(),
Greg Clayton340b0302014-02-05 17:57:57 +00003109 eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult,
Greg Clayton44d93782014-01-27 23:43:24 +00003110 "lldb",
3111 m_debugger.GetPrompt(),
3112 multiple_lines,
3113 *this));
3114 m_debugger.PushIOHandler(m_command_io_handler_sp);
3115
3116 if (auto_handle_events)
3117 m_debugger.StartEventHandlerThread();
3118
3119 if (spawn_thread)
3120 {
3121 m_debugger.StartIOHandlerThread();
3122 }
3123 else
3124 {
3125 m_debugger.ExecuteIOHanders();
3126
3127 if (auto_handle_events)
3128 m_debugger.StopEventHandlerThread();
3129 }
3130
3131}
3132