blob: 9757a08b1a2d1c9743c8aca87d51bf085874f70f [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"
25#include "../Commands/CommandObjectHelp.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectLog.h"
27#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000028#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000029#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000030#include "../Commands/CommandObjectProcess.h"
31#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSource.h"
Jim Inghamebc09c32010-07-07 03:36:20 +000035#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000036#include "../Commands/CommandObjectSyntax.h"
37#include "../Commands/CommandObjectTarget.h"
38#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000039#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000040#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000041#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042
Greg Clayton7d2ef162013-03-29 17:03:23 +000043
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044#include "lldb/Core/Debugger.h"
Jim Ingham97a6dc72010-10-04 19:49:29 +000045#include "lldb/Core/InputReader.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"
48#include "lldb/Core/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000049
Greg Clayton7fb56d02011-02-01 01:31:41 +000050#include "lldb/Host/Host.h"
Enrico Granatab5887262012-10-29 21:18:03 +000051
52#include "lldb/Interpreter/Args.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000053#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000054#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000055#include "lldb/Interpreter/CommandReturnObject.h"
Enrico Granatab5887262012-10-29 21:18:03 +000056#include "lldb/Interpreter/Options.h"
57#include "lldb/Interpreter/ScriptInterpreterNone.h"
58#include "lldb/Interpreter/ScriptInterpreterPython.h"
59
60
Chris Lattner30fdc8d2010-06-08 16:52:24 +000061#include "lldb/Target/Process.h"
62#include "lldb/Target/Thread.h"
63#include "lldb/Target/TargetList.h"
64
Enrico Granatab5887262012-10-29 21:18:03 +000065#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000066
67using namespace lldb;
68using namespace lldb_private;
69
Greg Clayton754a9362012-08-23 00:22:02 +000070
71static PropertyDefinition
72g_properties[] =
73{
74 { "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 +000075 { "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 +000076 { "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 +000077 { NULL , OptionValue::eTypeInvalid, true, 0 , NULL, NULL, NULL }
78};
79
80enum
81{
Enrico Granatabcba2b22013-01-17 21:36:19 +000082 ePropertyExpandRegexAliases = 0,
Enrico Granata012d4fc2013-06-11 01:26:35 +000083 ePropertyPromptOnQuit = 1,
84 ePropertyStopCmdSourceOnError = 2
Greg Clayton754a9362012-08-23 00:22:02 +000085};
86
Jim Ingham4bddaeb2012-02-16 06:50:00 +000087ConstString &
88CommandInterpreter::GetStaticBroadcasterClass ()
89{
90 static ConstString class_name ("lldb.commandInterpreter");
91 return class_name;
92}
93
Chris Lattner30fdc8d2010-06-08 16:52:24 +000094CommandInterpreter::CommandInterpreter
95(
Greg Clayton66111032010-06-23 01:19:29 +000096 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +000097 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +000098 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +000099) :
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000100 Broadcaster (&debugger, "lldb.command-interpreter"),
Greg Clayton754a9362012-08-23 00:22:02 +0000101 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton66111032010-06-23 01:19:29 +0000102 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000103 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000104 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000105 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000106 m_script_interpreter_ap (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000107 m_comment_char ('#'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000108 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000109 m_truncation_warning(eNoTruncation),
110 m_command_source_depth (0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000111{
Greg Clayton67cc0632012-08-22 17:17:09 +0000112 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000113 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
114 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000115 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000116 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000117 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000118}
119
Greg Clayton754a9362012-08-23 00:22:02 +0000120bool
121CommandInterpreter::GetExpandRegexAliases () const
122{
123 const uint32_t idx = ePropertyExpandRegexAliases;
124 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
125}
126
Enrico Granatabcba2b22013-01-17 21:36:19 +0000127bool
128CommandInterpreter::GetPromptOnQuit () const
129{
130 const uint32_t idx = ePropertyPromptOnQuit;
131 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
132}
Greg Clayton754a9362012-08-23 00:22:02 +0000133
Enrico Granata012d4fc2013-06-11 01:26:35 +0000134bool
135CommandInterpreter::GetStopCmdSourceOnError () const
136{
137 const uint32_t idx = ePropertyStopCmdSourceOnError;
138 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
139}
140
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000141void
142CommandInterpreter::Initialize ()
143{
144 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
145
146 CommandReturnObject result;
147
148 LoadCommandDictionary ();
149
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000150 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000151 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
152 if (cmd_obj_sp)
153 {
154 AddAlias ("q", cmd_obj_sp);
155 AddAlias ("exit", cmd_obj_sp);
156 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000157
Johnny Chen6d675242012-08-24 18:15:45 +0000158 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000159 if (cmd_obj_sp)
160 {
161 AddAlias ("attach", cmd_obj_sp);
162 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000163
Johnny Chen6d675242012-08-24 18:15:45 +0000164 cmd_obj_sp = GetCommandSPExact ("process detach",false);
165 if (cmd_obj_sp)
166 {
167 AddAlias ("detach", cmd_obj_sp);
168 }
169
Caroline Ticeca90c472011-05-06 21:37:15 +0000170 cmd_obj_sp = GetCommandSPExact ("process continue", false);
171 if (cmd_obj_sp)
172 {
173 AddAlias ("c", cmd_obj_sp);
174 AddAlias ("continue", cmd_obj_sp);
175 }
176
177 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
178 if (cmd_obj_sp)
179 AddAlias ("b", cmd_obj_sp);
180
Jim Inghamca36cd12012-10-05 19:16:31 +0000181 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
182 if (cmd_obj_sp)
183 AddAlias ("tbreak", cmd_obj_sp);
184
Caroline Ticeca90c472011-05-06 21:37:15 +0000185 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
186 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000187 {
188 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000189 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000190 }
191
192 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
193 if (cmd_obj_sp)
194 {
195 AddAlias ("nexti", cmd_obj_sp);
196 AddAlias ("ni", cmd_obj_sp);
197 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000198
199 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
200 if (cmd_obj_sp)
201 {
202 AddAlias ("s", cmd_obj_sp);
203 AddAlias ("step", cmd_obj_sp);
204 }
205
206 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
207 if (cmd_obj_sp)
208 {
209 AddAlias ("n", cmd_obj_sp);
210 AddAlias ("next", cmd_obj_sp);
211 }
212
213 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
214 if (cmd_obj_sp)
215 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000216 AddAlias ("finish", cmd_obj_sp);
217 }
218
Jim Ingham6d6d1072011-12-02 01:12:59 +0000219 cmd_obj_sp = GetCommandSPExact ("frame select", false);
220 if (cmd_obj_sp)
221 {
222 AddAlias ("f", cmd_obj_sp);
223 }
224
Jim Inghamca36cd12012-10-05 19:16:31 +0000225 cmd_obj_sp = GetCommandSPExact ("thread select", false);
226 if (cmd_obj_sp)
227 {
228 AddAlias ("t", cmd_obj_sp);
229 }
230
Richard Mittonf86248d2013-09-12 02:20:34 +0000231 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
232 if (cmd_obj_sp)
233 {
234 AddAlias ("j", cmd_obj_sp);
235 AddAlias ("jump", cmd_obj_sp);
236 }
237
Greg Clayton6bade322013-02-01 23:33:03 +0000238 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000239 if (cmd_obj_sp)
240 {
241 AddAlias ("l", cmd_obj_sp);
242 AddAlias ("list", cmd_obj_sp);
243 }
244
Greg Claytonef5651d2013-02-12 18:52:24 +0000245 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
246 if (cmd_obj_sp)
247 {
248 AddAlias ("env", cmd_obj_sp);
249 }
250
Caroline Ticeca90c472011-05-06 21:37:15 +0000251 cmd_obj_sp = GetCommandSPExact ("memory read", false);
252 if (cmd_obj_sp)
253 AddAlias ("x", cmd_obj_sp);
254
255 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
256 if (cmd_obj_sp)
257 AddAlias ("up", cmd_obj_sp);
258
259 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
260 if (cmd_obj_sp)
261 AddAlias ("down", cmd_obj_sp);
262
Jason Molenda0c8e0062011-10-25 02:11:20 +0000263 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000264 if (cmd_obj_sp)
265 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000266
267 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
268 if (cmd_obj_sp)
269 AddAlias ("dis", cmd_obj_sp);
270
271 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
272 if (cmd_obj_sp)
273 AddAlias ("di", cmd_obj_sp);
274
275
Jason Molendabc7748b2011-10-22 01:30:52 +0000276
Jason Molenda0c8e0062011-10-25 02:11:20 +0000277 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000278 if (cmd_obj_sp)
279 AddAlias ("undisplay", cmd_obj_sp);
280
Jim Ingham71bf2992012-10-10 16:51:31 +0000281 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
282 if (cmd_obj_sp)
283 AddAlias ("bt", cmd_obj_sp);
284
Caroline Ticeca90c472011-05-06 21:37:15 +0000285 cmd_obj_sp = GetCommandSPExact ("target create", false);
286 if (cmd_obj_sp)
287 AddAlias ("file", cmd_obj_sp);
288
289 cmd_obj_sp = GetCommandSPExact ("target modules", false);
290 if (cmd_obj_sp)
291 AddAlias ("image", cmd_obj_sp);
292
293
294 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000295
Caroline Ticeca90c472011-05-06 21:37:15 +0000296 cmd_obj_sp = GetCommandSPExact ("expression", false);
297 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000298 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000299 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
300 AddAlias ("p", cmd_obj_sp);
301 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000302 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000303 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
304 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000305 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000306
307 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton9e57dcd2013-05-15 01:03:08 +0000308 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000309 AddAlias ("po", cmd_obj_sp);
310 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
311 }
312
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000313 cmd_obj_sp = GetCommandSPExact ("process kill", false);
314 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000315 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000316 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000317 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000318
Caroline Ticeca90c472011-05-06 21:37:15 +0000319 cmd_obj_sp = GetCommandSPExact ("process launch", false);
320 if (cmd_obj_sp)
321 {
322 alias_arguments_vector_sp.reset (new OptionArgVector);
Jason Molenda85da3122012-07-06 02:46:23 +0000323#if defined (__arm__)
324 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
325#else
Ed Maste7c566672013-09-05 21:38:45 +0000326 ProcessAliasOptionsArgs (cmd_obj_sp, "--shell=" LLDB_DEFAULT_SHELL " --", alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000327#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000328 AddAlias ("r", cmd_obj_sp);
329 AddAlias ("run", cmd_obj_sp);
330 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
331 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
332 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000333
334 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
335 if (cmd_obj_sp)
336 {
337 AddAlias ("add-dsym", cmd_obj_sp);
338 }
Sean Callananfc732752012-05-21 18:25:19 +0000339
340 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
341 if (cmd_obj_sp)
342 {
343 alias_arguments_vector_sp.reset (new OptionArgVector);
344 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000345 AddAlias ("rbreak", cmd_obj_sp);
346 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000347 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000348}
349
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000350const char *
351CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
352{
353 // This function has not yet been implemented.
354
355 // Look for any embedded script command
356 // If found,
357 // get interpreter object from the command dictionary,
358 // call execute_one_command on it,
359 // get the results as a string,
360 // substitute that string for current stuff.
361
362 return arg;
363}
364
365
366void
367CommandInterpreter::LoadCommandDictionary ()
368{
369 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
370
Caroline Ticedaccaa92010-09-20 20:44:43 +0000371 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000372
Greg Claytona7015092010-09-18 01:14:36 +0000373 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000374 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000375 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000376 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
377 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000378 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000379 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000380 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
381 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000382 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000383 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000384 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000385 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000386 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000387 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000388 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000389 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000390 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
391 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000392 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000393 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000394 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395
Jim Inghamca36cd12012-10-05 19:16:31 +0000396 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
397 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000398 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000399 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000400 {"^(-.*)$", "breakpoint set %1"},
401 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000402 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000403 {"^(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1'"}};
404
405 size_t num_regexes = sizeof break_regexes/sizeof(char *[2]);
406
Greg Clayton7b0992d2013-04-18 22:45:39 +0000407 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000408 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000409 "_regexp-break",
Johnny Chenb417dcd2012-08-23 00:32:22 +0000410 "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 +0000411 "_regexp-break [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
412 2,
413 CommandCompletions::eSymbolCompletion |
414 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000415
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000416 if (break_regex_cmd_ap.get())
417 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000418 bool success = true;
419 for (size_t i = 0; i < num_regexes; i++)
420 {
421 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
422 if (!success)
423 break;
424 }
425 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
426
427 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000428 {
429 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
430 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
431 }
432 }
Jim Inghamffba2292011-03-22 02:29:32 +0000433
Greg Clayton7b0992d2013-04-18 22:45:39 +0000434 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000435 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
436 "_regexp-tbreak",
437 "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 +0000438 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
439 2,
440 CommandCompletions::eSymbolCompletion |
441 CommandCompletions::eSourceFileCompletion));
Jim Inghamca36cd12012-10-05 19:16:31 +0000442
443 if (tbreak_regex_cmd_ap.get())
444 {
445 bool success = true;
446 for (size_t i = 0; i < num_regexes; i++)
447 {
448 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
449 char buffer[1024];
450 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
451 assert (num_printed < 1024);
452 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
453 if (!success)
454 break;
455 }
456 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
457
458 if (success)
459 {
460 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
461 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
462 }
463 }
464
Greg Clayton7b0992d2013-04-18 22:45:39 +0000465 std::unique_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000466 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
467 "_regexp-attach",
468 "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 +0000469 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
470 2));
Johnny Chen6d675242012-08-24 18:15:45 +0000471 if (attach_regex_cmd_ap.get())
472 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000473 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
474 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
475 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
476 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000477 {
478 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
479 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
480 }
481 }
482
Greg Clayton7b0992d2013-04-18 22:45:39 +0000483 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000484 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000485 "_regexp-down",
486 "Go down \"n\" frames in the stack (1 frame by default).",
487 "_regexp-down [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000488 if (down_regex_cmd_ap.get())
489 {
490 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
491 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
492 {
493 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
494 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
495 }
496 }
497
Greg Clayton7b0992d2013-04-18 22:45:39 +0000498 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000499 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000500 "_regexp-up",
501 "Go up \"n\" frames in the stack (1 frame by default).",
502 "_regexp-up [n]", 2));
Jim Inghamffba2292011-03-22 02:29:32 +0000503 if (up_regex_cmd_ap.get())
504 {
505 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
506 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
507 {
508 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
509 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
510 }
511 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000512
Greg Clayton7b0992d2013-04-18 22:45:39 +0000513 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000514 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000515 "_regexp-display",
516 "Add an expression evaluation stop-hook.",
517 "_regexp-display expression", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000518 if (display_regex_cmd_ap.get())
519 {
520 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
521 {
522 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
523 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
524 }
525 }
526
Greg Clayton7b0992d2013-04-18 22:45:39 +0000527 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000528 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000529 "_regexp-undisplay",
530 "Remove an expression evaluation stop-hook.",
531 "_regexp-undisplay stop-hook-number", 2));
Jason Molendabc7748b2011-10-22 01:30:52 +0000532 if (undisplay_regex_cmd_ap.get())
533 {
534 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
535 {
536 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
537 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
538 }
539 }
540
Greg Clayton7b0992d2013-04-18 22:45:39 +0000541 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000542 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000543 "gdb-remote",
544 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
545 "gdb-remote [<hostname>:]<portnum>", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000546 if (connect_gdb_remote_cmd_ap.get())
547 {
548 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
549 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
550 {
551 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
552 m_command_dict[command_sp->GetCommandName ()] = command_sp;
553 }
554 }
555
Greg Clayton7b0992d2013-04-18 22:45:39 +0000556 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000557 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
558 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000559 "Connect to a remote KDP server. udp port 41139 is the default port number.",
560 "kdp-remote <hostname>[:<portnum>]", 2));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000561 if (connect_kdp_remote_cmd_ap.get())
562 {
563 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000564 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000565 {
566 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
567 m_command_dict[command_sp->GetCommandName ()] = command_sp;
568 }
569 }
570
Greg Clayton7b0992d2013-04-18 22:45:39 +0000571 std::unique_ptr<CommandObjectRegexCommand>
Jason Molenda4cddfed2012-10-05 05:29:32 +0000572 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Jim Ingham71bf2992012-10-10 16:51:31 +0000573 "_regexp-bt",
Jason Molenda4cddfed2012-10-05 05:29:32 +0000574 "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.",
575 "bt [<digit>|all]", 2));
576 if (bt_regex_cmd_ap.get())
577 {
578 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
579 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
580 // so now "bt 3" is the preferred form, in line with gdb.
581 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
582 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
583 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
584 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
585 {
586 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
587 m_command_dict[command_sp->GetCommandName ()] = command_sp;
588 }
589 }
590
Greg Clayton7b0992d2013-04-18 22:45:39 +0000591 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton6bade322013-02-01 23:33:03 +0000592 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
593 "_regexp-list",
594 "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 +0000595 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000596 2,
597 CommandCompletions::eSourceFileCompletion));
Greg Clayton6bade322013-02-01 23:33:03 +0000598 if (list_regex_cmd_ap.get())
599 {
600 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
601 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
602 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000603 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000604 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000605 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
606 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
607 {
608 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
609 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
610 }
611 }
612
Greg Clayton7b0992d2013-04-18 22:45:39 +0000613 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytonef5651d2013-02-12 18:52:24 +0000614 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000615 "_regexp-env",
616 "Implements a shortcut to viewing and setting environment variables.",
617 "_regexp-env\n_regexp-env FOO=BAR", 2));
Greg Claytonef5651d2013-02-12 18:52:24 +0000618 if (env_regex_cmd_ap.get())
619 {
620 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
621 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
622 {
623 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
624 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
625 }
626 }
627
Richard Mittonf86248d2013-09-12 02:20:34 +0000628 std::unique_ptr<CommandObjectRegexCommand>
629 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
630 "_regexp-jump",
631 "Sets the program counter to a new address.",
632 "_regexp-jump [<line>]\n"
633 "_regexp-jump [<+-lineoffset>]\n"
634 "_regexp-jump [<file>:<line>]\n"
635 "_regexp-jump [*<addr>]\n", 2));
636 if (jump_regex_cmd_ap.get())
637 {
638 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
639 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
640 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
641 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
642 {
643 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
644 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
645 }
646 }
647
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000648}
649
650int
651CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
652 StringList &matches)
653{
654 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
655
656 if (include_aliases)
657 {
658 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
659 }
660
661 return matches.GetSize();
662}
663
664CommandObjectSP
665CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
666{
667 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000668 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000669
670 std::string cmd(cmd_cstr);
671
672 if (HasCommands())
673 {
674 pos = m_command_dict.find(cmd);
675 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000676 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000677 }
678
679 if (include_aliases && HasAliases())
680 {
681 pos = m_alias_dict.find(cmd);
682 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000683 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000684 }
685
686 if (HasUserCommands())
687 {
688 pos = m_user_dict.find(cmd);
689 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000690 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000691 }
692
Greg Claytonc7bece562013-01-25 18:06:21 +0000693 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000694 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000695 // We will only get into here if we didn't find any exact matches.
696
697 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
698
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000699 StringList local_matches;
700 if (matches == NULL)
701 matches = &local_matches;
702
Jim Ingham279a6c22010-07-06 22:46:59 +0000703 unsigned int num_cmd_matches = 0;
704 unsigned int num_alias_matches = 0;
705 unsigned int num_user_matches = 0;
706
707 // Look through the command dictionaries one by one, and if we get only one match from any of
708 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
709
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000710 if (HasCommands())
711 {
712 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
713 }
714
715 if (num_cmd_matches == 1)
716 {
717 cmd.assign(matches->GetStringAtIndex(0));
718 pos = m_command_dict.find(cmd);
719 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000720 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721 }
722
Jim Ingham490ac552010-06-24 20:28:42 +0000723 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724 {
725 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
726
727 }
728
Jim Ingham279a6c22010-07-06 22:46:59 +0000729 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730 {
731 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
732 pos = m_alias_dict.find(cmd);
733 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000734 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000735 }
736
Jim Ingham490ac552010-06-24 20:28:42 +0000737 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738 {
739 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
740 }
741
Jim Ingham279a6c22010-07-06 22:46:59 +0000742 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000743 {
744 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
745
746 pos = m_user_dict.find (cmd);
747 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000748 user_match_sp = pos->second;
749 }
750
751 // If we got exactly one match, return that, otherwise return the match list.
752
753 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
754 {
755 if (num_cmd_matches)
756 return real_match_sp;
757 else if (num_alias_matches)
758 return alias_match_sp;
759 else
760 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761 }
762 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000763 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000764 {
765 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000766 }
767
768
Greg Claytonc7bece562013-01-25 18:06:21 +0000769 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000770}
771
Greg Claytonde164aa2011-04-20 16:37:46 +0000772bool
773CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
774{
775 if (name && name[0])
776 {
777 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000778 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
779 if (found && !can_replace)
780 return false;
781 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000782 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000783 m_command_dict[name_sstr] = cmd_sp;
784 return true;
785 }
786 return false;
787}
788
Enrico Granata223383e2011-08-16 23:24:13 +0000789bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000790CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000791 const lldb::CommandObjectSP &cmd_sp,
792 bool can_replace)
793{
Enrico Granata0a305db2011-11-07 22:57:04 +0000794 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000795 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000796
797 const char* name_cstr = name.c_str();
798
799 // do not allow replacement of internal commands
800 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000801 {
802 if (can_replace == false)
803 return false;
804 if (m_command_dict[name]->IsRemovable() == false)
805 return false;
806 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000807
Enrico Granata21dfcd92012-09-28 23:57:51 +0000808 if (UserCommandExists(name_cstr))
809 {
810 if (can_replace == false)
811 return false;
812 if (m_user_dict[name]->IsRemovable() == false)
813 return false;
814 }
815
Enrico Granata0a305db2011-11-07 22:57:04 +0000816 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000817 return true;
818 }
819 return false;
820}
Greg Claytonde164aa2011-04-20 16:37:46 +0000821
Jim Ingham279a6c22010-07-06 22:46:59 +0000822CommandObjectSP
823CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000824{
Caroline Tice472362e2010-12-14 18:51:39 +0000825 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
826 CommandObjectSP ret_val; // Possibly empty return value.
827
828 if (cmd_cstr == NULL)
829 return ret_val;
830
831 if (cmd_words.GetArgumentCount() == 1)
832 return GetCommandSP(cmd_cstr, include_aliases, true, NULL);
833 else
834 {
835 // We have a multi-word command (seemingly), so we need to do more work.
836 // First, get the cmd_obj_sp for the first word in the command.
837 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, NULL);
838 if (cmd_obj_sp.get() != NULL)
839 {
840 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
841 // command name), and find the appropriate sub-command SP for each command word....
842 size_t end = cmd_words.GetArgumentCount();
843 for (size_t j= 1; j < end; ++j)
844 {
845 if (cmd_obj_sp->IsMultiwordObject())
846 {
Greg Clayton998255b2012-10-13 02:07:45 +0000847 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Caroline Tice472362e2010-12-14 18:51:39 +0000848 if (cmd_obj_sp.get() == NULL)
849 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
850 return ret_val;
851 }
852 else
853 // We have more words in the command name, but we don't have a multiword object. Fail and return
854 // empty 'ret_val'.
855 return ret_val;
856 }
857 // We successfully looped through all the command words and got valid command objects for them. Assign the
858 // last object retrieved to 'ret_val'.
859 ret_val = cmd_obj_sp;
860 }
861 }
862 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000863}
864
865CommandObject *
866CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
867{
868 return GetCommandSPExact (cmd_cstr, include_aliases).get();
869}
870
871CommandObject *
872CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
873{
874 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
875
876 // If we didn't find an exact match to the command string in the commands, look in
877 // the aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000878
879 if (command_obj)
880 return command_obj;
Jim Ingham279a6c22010-07-06 22:46:59 +0000881
Enrico Granata5342c442013-06-18 18:01:08 +0000882 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
Jim Ingham279a6c22010-07-06 22:46:59 +0000883
Enrico Granata5342c442013-06-18 18:01:08 +0000884 if (command_obj)
885 return command_obj;
886
887 // If there wasn't an exact match then look for an inexact one in just the commands
888 command_obj = GetCommandSP(cmd_cstr, false, false, NULL).get();
Matt Kopec038ff812013-04-23 16:17:32 +0000889
890 // Finally, if there wasn't an inexact match among the commands, look for an inexact
891 // match in both the commands and aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000892
893 if (command_obj)
894 {
895 if (matches)
896 matches->AppendString(command_obj->GetCommandName());
897 return command_obj;
898 }
899
900 return GetCommandSP(cmd_cstr, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000901}
902
903bool
904CommandInterpreter::CommandExists (const char *cmd)
905{
906 return m_command_dict.find(cmd) != m_command_dict.end();
907}
908
909bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000910CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
911 const char *options_args,
912 OptionArgVectorSP &option_arg_vector_sp)
913{
914 bool success = true;
915 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
916
917 if (!options_args || (strlen (options_args) < 1))
918 return true;
919
920 std::string options_string (options_args);
921 Args args (options_args);
922 CommandReturnObject result;
923 // Check to see if the command being aliased can take any command options.
924 Options *options = cmd_obj_sp->GetOptions ();
925 if (options)
926 {
927 // See if any options were specified as part of the alias; if so, handle them appropriately.
928 options->NotifyOptionParsingStarting ();
929 args.Unshift ("dummy_arg");
930 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
931 args.Shift ();
932 if (result.Succeeded())
933 options->VerifyPartialOptions (result);
934 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
935 {
936 result.AppendError ("Unable to create requested alias.\n");
937 return false;
938 }
939 }
940
Greg Clayton5521f992011-10-28 21:38:01 +0000941 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +0000942 {
943 if (cmd_obj_sp->WantsRawCommandString ())
944 option_arg_vector->push_back (OptionArgPair ("<argument>",
945 OptionArgValue (-1,
946 options_string)));
947 else
948 {
Greg Claytonc7bece562013-01-25 18:06:21 +0000949 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +0000950 for (size_t i = 0; i < argc; ++i)
951 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
952 option_arg_vector->push_back
953 (OptionArgPair ("<argument>",
954 OptionArgValue (-1,
955 std::string (args.GetArgumentAtIndex (i)))));
956 }
957 }
958
959 return success;
960}
961
962bool
Jim Ingham298f3782013-04-03 00:25:49 +0000963CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
964{
965 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
966 if (exact_match)
967 {
968 full_name.assign(cmd);
969 return exact_match;
970 }
971 else
972 {
973 StringList matches;
974 size_t num_alias_matches;
975 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
976 if (num_alias_matches == 1)
977 {
978 // Make sure this isn't shadowing a command in the regular command space:
979 StringList regular_matches;
980 const bool include_aliases = false;
981 const bool exact = false;
982 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
983 if (cmd_obj_sp || regular_matches.GetSize() > 0)
984 return false;
985 else
986 {
987 full_name.assign (matches.GetStringAtIndex(0));
988 return true;
989 }
990 }
991 else
992 return false;
993 }
994}
995
996bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000997CommandInterpreter::AliasExists (const char *cmd)
998{
999 return m_alias_dict.find(cmd) != m_alias_dict.end();
1000}
1001
1002bool
1003CommandInterpreter::UserCommandExists (const char *cmd)
1004{
1005 return m_user_dict.find(cmd) != m_user_dict.end();
1006}
1007
1008void
1009CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1010{
Jim Ingham279a6c22010-07-06 22:46:59 +00001011 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001012 m_alias_dict[alias_name] = command_obj_sp;
1013}
1014
1015bool
1016CommandInterpreter::RemoveAlias (const char *alias_name)
1017{
1018 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1019 if (pos != m_alias_dict.end())
1020 {
1021 m_alias_dict.erase(pos);
1022 return true;
1023 }
1024 return false;
1025}
1026bool
1027CommandInterpreter::RemoveUser (const char *alias_name)
1028{
1029 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1030 if (pos != m_user_dict.end())
1031 {
1032 m_user_dict.erase(pos);
1033 return true;
1034 }
1035 return false;
1036}
1037
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001038void
1039CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1040{
1041 help_string.Printf ("'%s", command_name);
1042 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1043
Sean Callanan9a028512012-08-09 00:50:26 +00001044 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001045 {
1046 OptionArgVector *options = option_arg_vector_sp.get();
Andy Gibbsa297a972013-06-19 19:04:53 +00001047 for (size_t i = 0; i < options->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048 {
1049 OptionArgPair cur_option = (*options)[i];
1050 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001051 OptionArgValue value_pair = cur_option.second;
1052 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001053 if (opt.compare("<argument>") == 0)
1054 {
1055 help_string.Printf (" %s", value.c_str());
1056 }
1057 else
1058 {
1059 help_string.Printf (" %s", opt.c_str());
1060 if ((value.compare ("<no-argument>") != 0)
1061 && (value.compare ("<need-argument") != 0))
1062 {
1063 help_string.Printf (" %s", value.c_str());
1064 }
1065 }
1066 }
1067 }
1068
1069 help_string.Printf ("'");
1070}
1071
Greg Clayton12fc3e02010-08-26 22:05:43 +00001072size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001073CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1074{
1075 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001076 CommandObject::CommandMap::const_iterator end = dict.end();
1077 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001078
Greg Clayton12fc3e02010-08-26 22:05:43 +00001079 for (pos = dict.begin(); pos != end; ++pos)
1080 {
1081 size_t len = pos->first.size();
1082 if (max_len < len)
1083 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001085 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086}
1087
1088void
Enrico Granata223383e2011-08-16 23:24:13 +00001089CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001090 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001091{
1092 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001093 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001094
1095 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001096 {
Enrico Granata223383e2011-08-16 23:24:13 +00001097
1098 result.AppendMessage("The following is a list of built-in, permanent debugger commands:");
1099 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001100
Enrico Granata223383e2011-08-16 23:24:13 +00001101 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1102 {
1103 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1104 max_len);
1105 }
1106 result.AppendMessage("");
1107
1108 }
1109
Greg Clayton5521f992011-10-28 21:38:01 +00001110 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111 {
Jim Ingham49e80a12010-10-22 18:47:16 +00001112 result.AppendMessage("The following is a list of your current command abbreviations "
Johnny Chenb89982d2011-04-21 00:39:18 +00001113 "(see 'help command alias' for more info):");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001114 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001115 max_len = FindLongestCommandWord (m_alias_dict);
1116
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001117 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1118 {
1119 StreamString sstr;
1120 StreamString translation_and_help;
1121 std::string entry_name = pos->first;
1122 std::string second_entry = pos->second.get()->GetCommandName();
1123 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1124
1125 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1126 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1127 translation_and_help.GetData(), max_len);
1128 }
1129 result.AppendMessage("");
1130 }
1131
Greg Clayton5521f992011-10-28 21:38:01 +00001132 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001133 {
1134 result.AppendMessage ("The following is a list of your current user-defined commands:");
1135 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001136 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001137 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1138 {
Enrico Granata223383e2011-08-16 23:24:13 +00001139 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1140 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141 }
1142 result.AppendMessage("");
1143 }
1144
1145 result.AppendMessage("For more information on any particular command, try 'help <command-name>'.");
1146}
1147
Caroline Tice844d2302010-12-09 22:52:49 +00001148CommandObject *
1149CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150{
Caroline Tice844d2302010-12-09 22:52:49 +00001151 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1152 // eventually be invoked by the given command line.
1153
1154 CommandObject *cmd_obj = NULL;
1155 std::string white_space (" \t\v");
1156 size_t start = command_string.find_first_not_of (white_space);
1157 size_t end = 0;
1158 bool done = false;
1159 while (!done)
1160 {
1161 if (start != std::string::npos)
1162 {
1163 // Get the next word from command_string.
1164 end = command_string.find_first_of (white_space, start);
1165 if (end == std::string::npos)
1166 end = command_string.size();
1167 std::string cmd_word = command_string.substr (start, end - start);
1168
1169 if (cmd_obj == NULL)
1170 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1171 // command or alias.
1172 cmd_obj = GetCommandObject (cmd_word.c_str());
1173 else if (cmd_obj->IsMultiwordObject ())
1174 {
1175 // 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 +00001176 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001177 if (sub_cmd_obj)
1178 cmd_obj = sub_cmd_obj;
1179 else // cmd_word was not a valid sub-command word, so we are donee
1180 done = true;
1181 }
1182 else
1183 // We have a cmd_obj and it is not a multi-word object, so we are done.
1184 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001185
Caroline Tice844d2302010-12-09 22:52:49 +00001186 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1187 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1188 // next word.
1189
1190 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1191 done = true;
1192 else
1193 start = command_string.find_first_not_of (white_space, end);
1194 }
1195 else
1196 // Unable to find any more words.
1197 done = true;
1198 }
1199
1200 if (end == command_string.size())
1201 command_string.clear();
1202 else
1203 command_string = command_string.substr(end);
1204
1205 return cmd_obj;
1206}
1207
Greg Clayton51964162011-10-25 00:36:27 +00001208static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001209static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001210static void
1211StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001212{
Greg Clayton51964162011-10-25 00:36:27 +00001213 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001214 {
Greg Clayton51964162011-10-25 00:36:27 +00001215 size_t pos = s.find_first_not_of (k_white_space);
1216 if (pos == std::string::npos)
1217 s.clear();
1218 else if (pos == 0)
1219 return;
1220 s.erase (0, pos);
1221 }
1222}
1223
Greg Clayton93c62e62011-11-09 23:25:03 +00001224static size_t
1225FindArgumentTerminator (const std::string &s)
1226{
Greg Clayton93c62e62011-11-09 23:25:03 +00001227 const size_t s_len = s.size();
1228 size_t offset = 0;
1229 while (offset < s_len)
1230 {
1231 size_t pos = s.find ("--", offset);
1232 if (pos == std::string::npos)
1233 break;
1234 if (pos > 0)
1235 {
1236 if (isspace(s[pos-1]))
1237 {
1238 // Check if the string ends "\s--" (where \s is a space character)
1239 // or if we have "\s--\s".
1240 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1241 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001242 return pos;
1243 }
1244 }
1245 }
1246 offset = pos + 2;
1247 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001248 return std::string::npos;
1249}
1250
Greg Clayton51964162011-10-25 00:36:27 +00001251static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001252ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001253{
Greg Clayton5521f992011-10-28 21:38:01 +00001254 command.clear();
1255 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001256 StripLeadingSpaces (command_string);
1257
1258 bool result = false;
1259 quote_char = '\0';
1260
1261 if (!command_string.empty())
1262 {
1263 const char first_char = command_string[0];
1264 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001265 {
Greg Clayton51964162011-10-25 00:36:27 +00001266 quote_char = first_char;
1267 const size_t end_quote_pos = command_string.find (quote_char, 1);
1268 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001269 {
Greg Clayton5521f992011-10-28 21:38:01 +00001270 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001271 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001272 }
1273 else
1274 {
Greg Clayton5521f992011-10-28 21:38:01 +00001275 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001276 if (end_quote_pos + 1 < command_string.size())
1277 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1278 else
1279 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001280 }
Caroline Tice844d2302010-12-09 22:52:49 +00001281 }
1282 else
1283 {
Greg Clayton51964162011-10-25 00:36:27 +00001284 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1285 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001286 {
Greg Clayton5521f992011-10-28 21:38:01 +00001287 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001288 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001289 }
1290 else
1291 {
Greg Clayton5521f992011-10-28 21:38:01 +00001292 command.assign (command_string, 0, first_space_pos);
1293 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001294 }
Caroline Tice844d2302010-12-09 22:52:49 +00001295 }
Greg Clayton51964162011-10-25 00:36:27 +00001296 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001297 }
Greg Clayton5521f992011-10-28 21:38:01 +00001298
1299
1300 if (!command.empty())
1301 {
1302 // actual commands can't start with '-' or '_'
1303 if (command[0] != '-' && command[0] != '_')
1304 {
1305 size_t pos = command.find_first_not_of(k_valid_command_chars);
1306 if (pos > 0 && pos != std::string::npos)
1307 {
1308 suffix.assign (command.begin() + pos, command.end());
1309 command.erase (pos);
1310 }
1311 }
1312 }
Greg Clayton51964162011-10-25 00:36:27 +00001313
1314 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001315}
1316
Greg Clayton5521f992011-10-28 21:38:01 +00001317CommandObject *
1318CommandInterpreter::BuildAliasResult (const char *alias_name,
1319 std::string &raw_input_string,
1320 std::string &alias_result,
1321 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001322{
Greg Clayton5521f992011-10-28 21:38:01 +00001323 CommandObject *alias_cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001324 Args cmd_args (raw_input_string.c_str());
1325 alias_cmd_obj = GetCommandObject (alias_name);
1326 StreamString result_str;
1327
1328 if (alias_cmd_obj)
1329 {
1330 std::string alias_name_str = alias_name;
1331 if ((cmd_args.GetArgumentCount() == 0)
1332 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1333 cmd_args.Unshift (alias_name);
1334
1335 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1336 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1337
1338 if (option_arg_vector_sp.get())
1339 {
1340 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1341
Andy Gibbsa297a972013-06-19 19:04:53 +00001342 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Caroline Tice844d2302010-12-09 22:52:49 +00001343 {
1344 OptionArgPair option_pair = (*option_arg_vector)[i];
1345 OptionArgValue value_pair = option_pair.second;
1346 int value_type = value_pair.first;
1347 std::string option = option_pair.first;
1348 std::string value = value_pair.second;
1349 if (option.compare ("<argument>") == 0)
1350 result_str.Printf (" %s", value.c_str());
1351 else
1352 {
1353 result_str.Printf (" %s", option.c_str());
Virgile Belloe2607b52013-09-05 16:42:23 +00001354 if (value_type != OptionParser::eOptionalArgument)
Caroline Tice844d2302010-12-09 22:52:49 +00001355 result_str.Printf (" ");
Virgile Belloe2607b52013-09-05 16:42:23 +00001356 if (value.compare ("<OptionParser::eNoArgument>") != 0)
Caroline Tice844d2302010-12-09 22:52:49 +00001357 {
1358 int index = GetOptionArgumentPosition (value.c_str());
1359 if (index == 0)
1360 result_str.Printf ("%s", value.c_str());
1361 else if (index >= cmd_args.GetArgumentCount())
1362 {
1363
1364 result.AppendErrorWithFormat
1365 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1366 index);
1367 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001368 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001369 }
1370 else
1371 {
1372 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1373 if (strpos != std::string::npos)
1374 raw_input_string = raw_input_string.erase (strpos,
1375 strlen (cmd_args.GetArgumentAtIndex (index)));
1376 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1377 }
1378 }
1379 }
1380 }
1381 }
1382
1383 alias_result = result_str.GetData();
1384 }
Greg Clayton5521f992011-10-28 21:38:01 +00001385 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001386}
1387
Greg Clayton5a314712011-10-14 07:41:33 +00001388Error
1389CommandInterpreter::PreprocessCommand (std::string &command)
1390{
1391 // The command preprocessor needs to do things to the command
1392 // line before any parsing of arguments or anything else is done.
1393 // The only current stuff that gets proprocessed is anyting enclosed
1394 // in backtick ('`') characters is evaluated as an expression and
1395 // the result of the expression must be a scalar that can be substituted
1396 // into the command. An example would be:
1397 // (lldb) memory read `$rsp + 20`
1398 Error error; // Error for any expressions that might not evaluate
1399 size_t start_backtick;
1400 size_t pos = 0;
1401 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1402 {
1403 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1404 {
1405 // The backtick was preceeded by a '\' character, remove the slash
1406 // and don't treat the backtick as the start of an expression
1407 command.erase(start_backtick-1, 1);
1408 // No need to add one to start_backtick since we just deleted a char
1409 pos = start_backtick;
1410 }
1411 else
1412 {
1413 const size_t expr_content_start = start_backtick + 1;
1414 const size_t end_backtick = command.find ('`', expr_content_start);
1415 if (end_backtick == std::string::npos)
1416 return error;
1417 else if (end_backtick == expr_content_start)
1418 {
1419 // Empty expression (two backticks in a row)
1420 command.erase (start_backtick, 2);
1421 }
1422 else
1423 {
1424 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1425
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001426 ExecutionContext exe_ctx(GetExecutionContext());
1427 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001428 // Get a dummy target to allow for calculator mode while processing backticks.
1429 // This also helps break the infinite loop caused when target is null.
1430 if (!target)
1431 target = Host::GetDummyTarget(GetDebugger()).get();
Greg Clayton5a314712011-10-14 07:41:33 +00001432 if (target)
1433 {
Greg Clayton5a314712011-10-14 07:41:33 +00001434 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001435
Jim Ingham35e1bda2012-10-16 21:41:58 +00001436 EvaluateExpressionOptions options;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00001437 options.SetCoerceToId(false);
1438 options.SetUnwindOnError(true);
1439 options.SetIgnoreBreakpoints(true);
1440 options.SetKeepInMemory(false);
1441 options.SetTryAllThreads(true);
1442 options.SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001443
Greg Clayton5a314712011-10-14 07:41:33 +00001444 ExecutionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granatad4439aa2012-09-05 20:41:26 +00001445 exe_ctx.GetFramePtr(),
Enrico Granata3372f582012-07-16 23:10:35 +00001446 expr_result_valobj_sp,
Enrico Granatad4439aa2012-09-05 20:41:26 +00001447 options);
1448
Greg Clayton5a314712011-10-14 07:41:33 +00001449 if (expr_result == eExecutionCompleted)
1450 {
1451 Scalar scalar;
1452 if (expr_result_valobj_sp->ResolveValue (scalar))
1453 {
1454 command.erase (start_backtick, end_backtick - start_backtick + 1);
1455 StreamString value_strm;
1456 const bool show_type = false;
1457 scalar.GetValue (&value_strm, show_type);
1458 size_t value_string_size = value_strm.GetSize();
1459 if (value_string_size)
1460 {
1461 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1462 pos = start_backtick + value_string_size;
1463 continue;
1464 }
1465 else
1466 {
1467 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1468 }
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 if (expr_result_valobj_sp)
1478 error = expr_result_valobj_sp->GetError();
1479 if (error.Success())
1480 {
1481
1482 switch (expr_result)
1483 {
1484 case eExecutionSetupError:
1485 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1486 break;
1487 case eExecutionCompleted:
1488 break;
1489 case eExecutionDiscarded:
1490 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1491 break;
1492 case eExecutionInterrupted:
1493 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1494 break;
Jim Ingham184e9812013-01-15 02:47:48 +00001495 case eExecutionHitBreakpoint:
1496 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1497 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001498 case eExecutionTimedOut:
1499 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1500 break;
1501 }
1502 }
1503 }
1504 }
1505 }
1506 if (error.Fail())
1507 break;
1508 }
1509 }
1510 return error;
1511}
1512
1513
Caroline Tice844d2302010-12-09 22:52:49 +00001514bool
1515CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001516 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001517 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001518 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001519 bool repeat_on_empty_command,
1520 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001521
Caroline Tice844d2302010-12-09 22:52:49 +00001522{
Jim Inghame16c50a2011-02-18 00:54:25 +00001523
Caroline Tice844d2302010-12-09 22:52:49 +00001524 bool done = false;
1525 CommandObject *cmd_obj = NULL;
Caroline Tice844d2302010-12-09 22:52:49 +00001526 bool wants_raw_input = false;
1527 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001528 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001529
Greg Clayton5160ce52013-03-27 23:08:40 +00001530 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001531 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1532
1533 // Make a scoped cleanup object that will clear the crash description string
1534 // on exit of this function.
Enrico Granataf9fa6ee2011-07-12 00:18:11 +00001535 lldb_utility::CleanUp <const char *> crash_description_cleanup(NULL, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001536
Caroline Tice844d2302010-12-09 22:52:49 +00001537 if (log)
1538 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001539
Jim Ingham30244832010-11-04 23:08:45 +00001540 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1541
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001542 if (!no_context_switching)
1543 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001544
Enrico Granata5f5ab602012-05-31 01:09:06 +00001545 bool add_to_history;
1546 if (lazy_add_to_history == eLazyBoolCalculate)
1547 add_to_history = (m_command_source_depth == 0);
1548 else
1549 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1550
Jim Inghame16c50a2011-02-18 00:54:25 +00001551 bool empty_command = false;
1552 bool comment_command = false;
1553 if (command_string.empty())
1554 empty_command = true;
1555 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001556 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001557 const char *k_space_characters = "\t\n\v\f\r ";
1558
1559 size_t non_space = command_string.find_first_not_of (k_space_characters);
1560 // Check for empty line or comment line (lines whose first
1561 // non-space character is the comment character for this interpreter)
1562 if (non_space == std::string::npos)
1563 empty_command = true;
1564 else if (command_string[non_space] == m_comment_char)
1565 comment_command = true;
Enrico Granata7594f142013-06-17 22:51:50 +00001566 else if (command_string[non_space] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001567 {
Enrico Granata7594f142013-06-17 22:51:50 +00001568 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001569 if (history_string == NULL)
1570 {
1571 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1572 result.SetStatus(eReturnStatusFailed);
1573 return false;
1574 }
1575 add_to_history = false;
1576 command_string = history_string;
1577 original_command_string = history_string;
1578 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001579 }
1580
1581 if (empty_command)
1582 {
1583 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001584 {
Enrico Granata7594f142013-06-17 22:51:50 +00001585 if (m_command_history.IsEmpty())
Jim Inghame16c50a2011-02-18 00:54:25 +00001586 {
1587 result.AppendError ("empty command");
1588 result.SetStatus(eReturnStatusFailed);
1589 return false;
1590 }
1591 else
1592 {
1593 command_line = m_repeat_command.c_str();
1594 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001595 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001596 if (m_repeat_command.empty())
1597 {
1598 result.AppendErrorWithFormat("No auto repeat.\n");
1599 result.SetStatus (eReturnStatusFailed);
1600 return false;
1601 }
1602 }
1603 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001604 }
1605 else
1606 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001607 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1608 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001609 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001610 }
1611 else if (comment_command)
1612 {
1613 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1614 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001615 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001616
Greg Clayton5a314712011-10-14 07:41:33 +00001617
1618 Error error (PreprocessCommand (command_string));
1619
1620 if (error.Fail())
1621 {
1622 result.AppendError (error.AsCString());
1623 result.SetStatus(eReturnStatusFailed);
1624 return false;
1625 }
Caroline Tice844d2302010-12-09 22:52:49 +00001626 // Phase 1.
1627
1628 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1629 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1630 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1631 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1632 // 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 +00001633 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001634 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001635
Caroline Tice844d2302010-12-09 22:52:49 +00001636 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001637 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001638 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001639 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001640 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001641 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001642 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001643 std::string suffix;
1644 ExtractCommand (command_string, next_word, suffix, quote_char);
1645 if (cmd_obj == NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001646 {
Jim Ingham298f3782013-04-03 00:25:49 +00001647 std::string full_name;
1648 if (GetAliasFullName(next_word.c_str(), full_name))
Caroline Tice472362e2010-12-14 18:51:39 +00001649 {
Greg Clayton5521f992011-10-28 21:38:01 +00001650 std::string alias_result;
Jim Ingham298f3782013-04-03 00:25:49 +00001651 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
Greg Clayton5521f992011-10-28 21:38:01 +00001652 revised_command_line.Printf ("%s", alias_result.c_str());
1653 if (cmd_obj)
1654 {
1655 wants_raw_input = cmd_obj->WantsRawCommandString ();
1656 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1657 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001658 }
1659 else
1660 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001661 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001662 if (cmd_obj)
1663 {
1664 actual_cmd_name_len += next_word.length();
1665 revised_command_line.Printf ("%s", next_word.c_str());
1666 wants_raw_input = cmd_obj->WantsRawCommandString ();
1667 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001668 else
Greg Clayton5521f992011-10-28 21:38:01 +00001669 {
1670 revised_command_line.Printf ("%s", next_word.c_str());
1671 }
Caroline Tice844d2302010-12-09 22:52:49 +00001672 }
1673 }
1674 else
1675 {
Greg Clayton5521f992011-10-28 21:38:01 +00001676 if (cmd_obj->IsMultiwordObject ())
1677 {
Greg Clayton998255b2012-10-13 02:07:45 +00001678 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001679 if (sub_cmd_obj)
1680 {
1681 actual_cmd_name_len += next_word.length() + 1;
1682 revised_command_line.Printf (" %s", next_word.c_str());
1683 cmd_obj = sub_cmd_obj;
1684 wants_raw_input = cmd_obj->WantsRawCommandString ();
1685 }
1686 else
1687 {
1688 if (quote_char)
1689 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1690 else
1691 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1692 done = true;
1693 }
1694 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001695 else
Greg Clayton5521f992011-10-28 21:38:01 +00001696 {
1697 if (quote_char)
1698 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1699 else
1700 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1701 done = true;
1702 }
Caroline Tice844d2302010-12-09 22:52:49 +00001703 }
1704
1705 if (cmd_obj == NULL)
1706 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001707 const size_t num_matches = matches.GetSize();
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001708 if (matches.GetSize() > 1) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001709 StreamString error_msg;
1710 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001711
1712 for (uint32_t i = 0; i < num_matches; ++i) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001713 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001714 }
Greg Claytonc7bece562013-01-25 18:06:21 +00001715 result.AppendRawError (error_msg.GetString().c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001716 } else {
1717 // We didn't have only one match, otherwise we wouldn't get here.
1718 assert(num_matches == 0);
1719 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1720 }
Caroline Tice844d2302010-12-09 22:52:49 +00001721 result.SetStatus (eReturnStatusFailed);
1722 return false;
1723 }
1724
Greg Clayton5521f992011-10-28 21:38:01 +00001725 if (cmd_obj->IsMultiwordObject ())
1726 {
1727 if (!suffix.empty())
1728 {
1729
Enrico Granataaded51d2013-06-12 00:44:43 +00001730 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1731 cmd_obj->GetCommandName(),
1732 next_word.empty() ? "" : next_word.c_str(),
1733 next_word.empty() ? " -- " : " ",
Greg Clayton5521f992011-10-28 21:38:01 +00001734 suffix.c_str());
1735 result.SetStatus (eReturnStatusFailed);
1736 return false;
1737 }
1738 }
1739 else
1740 {
1741 // If we found a normal command, we are done
1742 done = true;
1743 if (!suffix.empty())
1744 {
1745 switch (suffix[0])
1746 {
1747 case '/':
1748 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001749 {
1750 Options *command_options = cmd_obj->GetOptions();
1751 if (command_options && command_options->SupportsLongOption("gdb-format"))
1752 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001753 std::string gdb_format_option ("--gdb-format=");
1754 gdb_format_option += (suffix.c_str() + 1);
1755
1756 bool inserted = false;
1757 std::string &cmd = revised_command_line.GetString();
1758 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1759 if (arg_terminator_idx != std::string::npos)
1760 {
1761 // Insert the gdb format option before the "--" that terminates options
1762 gdb_format_option.append(1,' ');
1763 cmd.insert(arg_terminator_idx, gdb_format_option);
1764 inserted = true;
1765 }
1766
1767 if (!inserted)
1768 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1769
1770 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1771 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001772 }
1773 else
1774 {
1775 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1776 cmd_obj->GetCommandName());
1777 result.SetStatus (eReturnStatusFailed);
1778 return false;
1779 }
1780 }
Greg Clayton5521f992011-10-28 21:38:01 +00001781 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001782
1783 default:
1784 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1785 suffix.c_str());
1786 result.SetStatus (eReturnStatusFailed);
1787 return false;
1788
Greg Clayton5521f992011-10-28 21:38:01 +00001789 }
1790 }
1791 }
Caroline Tice844d2302010-12-09 22:52:49 +00001792 if (command_string.length() == 0)
1793 done = true;
1794
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001795 }
Caroline Tice844d2302010-12-09 22:52:49 +00001796
Greg Clayton5521f992011-10-28 21:38:01 +00001797 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001798 revised_command_line.Printf (" %s", command_string.c_str());
1799
1800 // End of Phase 1.
1801 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1802 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1803 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1804 // wants_raw_input specifies whether the Execute method expects raw input or not.
1805
1806
1807 if (log)
1808 {
1809 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1810 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1811 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1812 }
1813
1814 // Phase 2.
1815 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1816 // CommandObject, with the appropriate arguments.
1817
1818 if (cmd_obj != NULL)
1819 {
1820 if (add_to_history)
1821 {
1822 Args command_args (revised_command_line.GetData());
1823 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
1824 if (repeat_command != NULL)
1825 m_repeat_command.assign(repeat_command);
1826 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001827 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001828
Enrico Granata7594f142013-06-17 22:51:50 +00001829 m_command_history.AppendString (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001830 }
1831
1832 command_string = revised_command_line.GetData();
1833 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001834 std::string remainder;
1835 if (actual_cmd_name_len < command_string.length())
1836 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1837 // than cmd_obj->GetCommandName(), because name completion
1838 // allows users to enter short versions of the names,
1839 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001840
1841 // Remove any initial spaces
1842 std::string white_space (" \t\v");
1843 size_t pos = remainder.find_first_not_of (white_space);
1844 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001845 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001846
1847 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001848 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001849
Jim Ingham5a988412012-06-08 21:56:10 +00001850 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001851 }
1852 else
1853 {
1854 // We didn't find the first command object, so complete the first argument.
1855 Args command_args (revised_command_line.GetData());
1856 StringList matches;
1857 int num_matches;
1858 int cursor_index = 0;
1859 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1860 bool word_complete;
1861 num_matches = HandleCompletionMatches (command_args,
1862 cursor_index,
1863 cursor_char_position,
1864 0,
1865 -1,
1866 word_complete,
1867 matches);
1868
1869 if (num_matches > 0)
1870 {
1871 std::string error_msg;
1872 error_msg.assign ("ambiguous command '");
1873 error_msg.append(command_args.GetArgumentAtIndex(0));
1874 error_msg.append ("'.");
1875
1876 error_msg.append (" Possible completions:");
1877 for (int i = 0; i < num_matches; i++)
1878 {
1879 error_msg.append ("\n\t");
1880 error_msg.append (matches.GetStringAtIndex (i));
1881 }
1882 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001883 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001884 }
1885 else
1886 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1887
1888 result.SetStatus (eReturnStatusFailed);
1889 }
1890
Jason Molendabfb36ff2011-08-25 00:20:04 +00001891 if (log)
1892 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1893
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001894 return result.Succeeded();
1895}
1896
1897int
1898CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1899 int &cursor_index,
1900 int &cursor_char_position,
1901 int match_start_point,
1902 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001903 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001904 StringList &matches)
1905{
1906 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001907 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001908
1909 // For any of the command completions a unique match will be a complete word.
1910 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001911
1912 if (cursor_index == -1)
1913 {
1914 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001915 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001916 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1917 }
1918 else if (cursor_index == 0)
1919 {
1920 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001921 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001922 num_command_matches = matches.GetSize();
1923
1924 if (num_command_matches == 1
1925 && cmd_obj && cmd_obj->IsMultiwordObject()
1926 && matches.GetStringAtIndex(0) != NULL
1927 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1928 {
1929 look_for_subcommand = true;
1930 num_command_matches = 0;
1931 matches.DeleteStringAtIndex(0);
1932 parsed_line.AppendArgument ("");
1933 cursor_index++;
1934 cursor_char_position = 0;
1935 }
1936 }
1937
1938 if (cursor_index > 0 || look_for_subcommand)
1939 {
1940 // We are completing further on into a commands arguments, so find the command and tell it
1941 // to complete the command.
1942 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001943 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001944 if (command_object == NULL)
1945 {
1946 return 0;
1947 }
1948 else
1949 {
1950 parsed_line.Shift();
1951 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001952 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001953 cursor_index,
1954 cursor_char_position,
1955 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001956 max_return_elements,
1957 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001958 matches);
1959 }
1960 }
1961
1962 return num_command_matches;
1963
1964}
1965
1966int
1967CommandInterpreter::HandleCompletion (const char *current_line,
1968 const char *cursor,
1969 const char *last_char,
1970 int match_start_point,
1971 int max_return_elements,
1972 StringList &matches)
1973{
1974 // We parse the argument up to the cursor, so the last argument in parsed_line is
1975 // the one containing the cursor, and the cursor is after the last character.
1976
1977 Args parsed_line(current_line, last_char - current_line);
1978 Args partial_parsed_line(current_line, cursor - current_line);
1979
Jim Inghama5a97eb2011-07-12 03:12:18 +00001980 // Don't complete comments, and if the line we are completing is just the history repeat character,
1981 // substitute the appropriate history line.
1982 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1983 if (first_arg)
1984 {
1985 if (first_arg[0] == m_comment_char)
1986 return 0;
Enrico Granata7594f142013-06-17 22:51:50 +00001987 else if (first_arg[0] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001988 {
Enrico Granata7594f142013-06-17 22:51:50 +00001989 const char *history_string = m_command_history.FindString (first_arg);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001990 if (history_string != NULL)
1991 {
1992 matches.Clear();
1993 matches.InsertStringAtIndex(0, history_string);
1994 return -2;
1995 }
1996 else
1997 return 0;
1998
1999 }
2000 }
2001
2002
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002003 int num_args = partial_parsed_line.GetArgumentCount();
2004 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2005 int cursor_char_position;
2006
2007 if (cursor_index == -1)
2008 cursor_char_position = 0;
2009 else
2010 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00002011
2012 if (cursor > current_line && cursor[-1] == ' ')
2013 {
2014 // We are just after a space. If we are in an argument, then we will continue
2015 // parsing, but if we are between arguments, then we have to complete whatever the next
2016 // element would be.
2017 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2018 // protected by a quote) then the space will also be in the parsed argument...
2019
2020 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2021 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2022 {
2023 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '"');
2024 cursor_index++;
2025 cursor_char_position = 0;
2026 }
2027 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002028
2029 int num_command_matches;
2030
2031 matches.Clear();
2032
2033 // Only max_return_elements == -1 is supported at present:
2034 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00002035 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00002036 num_command_matches = HandleCompletionMatches (parsed_line,
2037 cursor_index,
2038 cursor_char_position,
2039 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002040 max_return_elements,
2041 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002042 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002043
2044 if (num_command_matches <= 0)
2045 return num_command_matches;
2046
2047 if (num_args == 0)
2048 {
2049 // If we got an empty string, insert nothing.
2050 matches.InsertStringAtIndex(0, "");
2051 }
2052 else
2053 {
2054 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2055 // put an empty string in element 0.
2056 std::string command_partial_str;
2057 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002058 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2059 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002060
2061 std::string common_prefix;
2062 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002063 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002064
2065 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002066 // Only do this if the completer told us this was a complete word, however...
2067 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002068 {
2069 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2070 if (quote_char != '\0')
2071 common_prefix.push_back(quote_char);
2072
2073 common_prefix.push_back(' ');
2074 }
2075 common_prefix.erase (0, partial_name_len);
2076 matches.InsertStringAtIndex(0, common_prefix.c_str());
2077 }
2078 return num_command_matches;
2079}
2080
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002081
2082CommandInterpreter::~CommandInterpreter ()
2083{
2084}
2085
2086const char *
2087CommandInterpreter::GetPrompt ()
2088{
Caroline Ticedaccaa92010-09-20 20:44:43 +00002089 return m_debugger.GetPrompt();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002090}
2091
2092void
2093CommandInterpreter::SetPrompt (const char *new_prompt)
2094{
Caroline Ticedaccaa92010-09-20 20:44:43 +00002095 m_debugger.SetPrompt (new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002096}
2097
Jim Ingham97a6dc72010-10-04 19:49:29 +00002098size_t
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002099CommandInterpreter::GetConfirmationInputReaderCallback
2100(
2101 void *baton,
2102 InputReader &reader,
2103 lldb::InputReaderAction action,
2104 const char *bytes,
2105 size_t bytes_len
2106)
Jim Ingham97a6dc72010-10-04 19:49:29 +00002107{
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002108 File &out_file = reader.GetDebugger().GetOutputFile();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002109 bool *response_ptr = (bool *) baton;
2110
2111 switch (action)
2112 {
2113 case eInputReaderActivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002114 if (out_file.IsValid())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002115 {
2116 if (reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002117 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002118 out_file.Printf ("%s", reader.GetPrompt());
2119 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002120 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002121 }
2122 break;
2123
2124 case eInputReaderDeactivate:
2125 break;
2126
2127 case eInputReaderReactivate:
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002128 if (out_file.IsValid() && reader.GetPrompt())
Caroline Tice31f7d462011-02-02 01:17:56 +00002129 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002130 out_file.Printf ("%s", reader.GetPrompt());
2131 out_file.Flush ();
Caroline Tice31f7d462011-02-02 01:17:56 +00002132 }
Jim Ingham97a6dc72010-10-04 19:49:29 +00002133 break;
Caroline Tice969ed3d2011-05-02 20:41:46 +00002134
2135 case eInputReaderAsynchronousOutputWritten:
2136 break;
2137
Jim Ingham97a6dc72010-10-04 19:49:29 +00002138 case eInputReaderGotToken:
2139 if (bytes_len == 0)
2140 {
2141 reader.SetIsDone(true);
2142 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002143 else if (bytes[0] == 'y' || bytes[0] == 'Y')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002144 {
2145 *response_ptr = true;
2146 reader.SetIsDone(true);
2147 }
Jim Inghamc8b47582011-11-14 20:02:01 +00002148 else if (bytes[0] == 'n' || bytes[0] == 'N')
Jim Ingham97a6dc72010-10-04 19:49:29 +00002149 {
2150 *response_ptr = false;
2151 reader.SetIsDone(true);
2152 }
2153 else
2154 {
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002155 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Jim Ingham97a6dc72010-10-04 19:49:29 +00002156 {
Jim Ingham78d61482011-11-17 01:22:00 +00002157 out_file.Printf ("Please answer \"y\" or \"n\".\n%s", reader.GetPrompt());
Greg Clayton51b1e2d2011-02-09 01:08:52 +00002158 out_file.Flush ();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002159 }
2160 }
2161 break;
2162
Caroline Ticeefed6132010-11-19 20:47:54 +00002163 case eInputReaderInterrupt:
2164 case eInputReaderEndOfFile:
2165 *response_ptr = false; // Assume ^C or ^D means cancel the proposed action
2166 reader.SetIsDone (true);
2167 break;
2168
Jim Ingham97a6dc72010-10-04 19:49:29 +00002169 case eInputReaderDone:
2170 break;
2171 }
2172
2173 return bytes_len;
2174
2175}
2176
2177bool
2178CommandInterpreter::Confirm (const char *message, bool default_answer)
2179{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002180 // Check AutoConfirm first:
2181 if (m_debugger.GetAutoConfirm())
2182 return default_answer;
2183
Jim Ingham97a6dc72010-10-04 19:49:29 +00002184 InputReaderSP reader_sp (new InputReader(GetDebugger()));
2185 bool response = default_answer;
2186 if (reader_sp)
2187 {
2188 std::string prompt(message);
2189 prompt.append(": [");
2190 if (default_answer)
2191 prompt.append ("Y/n] ");
2192 else
2193 prompt.append ("y/N] ");
2194
2195 Error err (reader_sp->Initialize (CommandInterpreter::GetConfirmationInputReaderCallback,
2196 &response, // baton
2197 eInputReaderGranularityLine, // token size, to pass to callback function
2198 NULL, // end token
2199 prompt.c_str(), // prompt
2200 true)); // echo input
2201 if (err.Success())
2202 {
2203 GetDebugger().PushInputReader (reader_sp);
2204 }
2205 reader_sp->WaitOnReaderIsDone();
2206 }
2207 return response;
2208}
2209
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002210OptionArgVectorSP
2211CommandInterpreter::GetAliasOptions (const char *alias_name)
2212{
2213 OptionArgMap::iterator pos;
2214 OptionArgVectorSP ret_val;
2215
2216 std::string alias (alias_name);
2217
2218 if (HasAliasOptions())
2219 {
2220 pos = m_alias_options.find (alias);
2221 if (pos != m_alias_options.end())
2222 ret_val = pos->second;
2223 }
2224
2225 return ret_val;
2226}
2227
2228void
2229CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2230{
2231 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2232 if (pos != m_alias_options.end())
2233 {
2234 m_alias_options.erase (pos);
2235 }
2236}
2237
2238void
2239CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2240{
2241 m_alias_options[alias_name] = option_arg_vector_sp;
2242}
2243
2244bool
2245CommandInterpreter::HasCommands ()
2246{
2247 return (!m_command_dict.empty());
2248}
2249
2250bool
2251CommandInterpreter::HasAliases ()
2252{
2253 return (!m_alias_dict.empty());
2254}
2255
2256bool
2257CommandInterpreter::HasUserCommands ()
2258{
2259 return (!m_user_dict.empty());
2260}
2261
2262bool
2263CommandInterpreter::HasAliasOptions ()
2264{
2265 return (!m_alias_options.empty());
2266}
2267
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002268void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002269CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2270 const char *alias_name,
2271 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002272 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002273 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002274{
2275 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002276
2277 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002278
Caroline Ticed9d63362010-12-07 19:58:26 +00002279 // Make sure that the alias name is the 0th element in cmd_args
2280 std::string alias_name_str = alias_name;
2281 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2282 cmd_args.Unshift (alias_name);
2283
2284 Args new_args (alias_cmd_obj->GetCommandName());
2285 if (new_args.GetArgumentCount() == 2)
2286 new_args.Shift();
2287
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002288 if (option_arg_vector_sp.get())
2289 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002290 if (wants_raw_input)
2291 {
2292 // We have a command that both has command options and takes raw input. Make *sure* it has a
2293 // " -- " in the right place in the raw_input_string.
2294 size_t pos = raw_input_string.find(" -- ");
2295 if (pos == std::string::npos)
2296 {
2297 // None found; assume it goes at the beginning of the raw input string
2298 raw_input_string.insert (0, " -- ");
2299 }
2300 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002301
2302 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002303 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002304 std::vector<bool> used (old_size + 1, false);
2305
2306 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002307
Andy Gibbsa297a972013-06-19 19:04:53 +00002308 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002309 {
2310 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002311 OptionArgValue value_pair = option_pair.second;
2312 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002313 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002314 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002315 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002316 {
2317 if (!wants_raw_input
2318 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2319 new_args.AppendArgument (value.c_str());
2320 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002321 else
2322 {
Virgile Belloe2607b52013-09-05 16:42:23 +00002323 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002324 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325 if (value.compare ("<no-argument>") != 0)
2326 {
2327 int index = GetOptionArgumentPosition (value.c_str());
2328 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002329 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 // value was NOT a positional argument; must be a real value
Virgile Belloe2607b52013-09-05 16:42:23 +00002331 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002332 new_args.AppendArgument (value.c_str());
2333 else
2334 {
2335 char buffer[255];
2336 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2337 new_args.AppendArgument (buffer);
2338 }
2339
2340 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002341 else if (index >= cmd_args.GetArgumentCount())
2342 {
2343 result.AppendErrorWithFormat
2344 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2345 index);
2346 result.SetStatus (eReturnStatusFailed);
2347 return;
2348 }
2349 else
2350 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002351 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2352 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2353 if (strpos != std::string::npos)
2354 {
2355 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2356 }
2357
Virgile Belloe2607b52013-09-05 16:42:23 +00002358 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002359 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2360 else
2361 {
2362 char buffer[255];
2363 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2364 cmd_args.GetArgumentAtIndex (index));
2365 new_args.AppendArgument (buffer);
2366 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002367 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002368 }
2369 }
2370 }
2371 }
2372
Andy Gibbsa297a972013-06-19 19:04:53 +00002373 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002374 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002375 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002376 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2377 }
2378
2379 cmd_args.Clear();
2380 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2381 }
2382 else
2383 {
2384 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002385 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2386 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2387 // input string.
2388 if (wants_raw_input)
2389 {
2390 cmd_args.Clear();
2391 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2392 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002393 return;
2394 }
2395
2396 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2397 return;
2398}
2399
2400
2401int
2402CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2403{
2404 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2405 // of zero.
2406
2407 char *cptr = (char *) in_string;
2408
2409 // Does it start with '%'
2410 if (cptr[0] == '%')
2411 {
2412 ++cptr;
2413
2414 // Is the rest of it entirely digits?
2415 if (isdigit (cptr[0]))
2416 {
2417 const char *start = cptr;
2418 while (isdigit (cptr[0]))
2419 ++cptr;
2420
2421 // We've gotten to the end of the digits; are we at the end of the string?
2422 if (cptr[0] == '\0')
2423 position = atoi (start);
2424 }
2425 }
2426
2427 return position;
2428}
2429
2430void
2431CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2432{
Jim Ingham16e0c682011-08-12 23:34:31 +00002433 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002434 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002435 {
Greg Clayton14a35512011-09-11 00:01:44 +00002436 // In the current working directory we don't load any program specific
2437 // .lldbinit files, we only look for a "./.lldbinit" file.
2438 if (m_skip_lldbinit_files)
2439 return;
2440
2441 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002442 }
Greg Clayton14a35512011-09-11 00:01:44 +00002443 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002444 {
Greg Clayton14a35512011-09-11 00:01:44 +00002445 // If we aren't looking in the current working directory we are looking
2446 // in the home directory. We will first see if there is an application
2447 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2448 // "-" and the name of the program. If this file doesn't exist, we fall
2449 // back to just the "~/.lldbinit" file. We also obey any requests to not
2450 // load the init files.
2451 const char *init_file_path = "~/.lldbinit";
2452
2453 if (m_skip_app_init_files == false)
2454 {
2455 FileSpec program_file_spec (Host::GetProgramFileSpec());
2456 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002457
Greg Clayton14a35512011-09-11 00:01:44 +00002458 if (program_name)
2459 {
2460 char program_init_file_name[PATH_MAX];
2461 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path, program_name);
2462 init_file.SetFile (program_init_file_name, true);
2463 if (!init_file.Exists())
2464 init_file.Clear();
2465 }
2466 }
2467
2468 if (!init_file && !m_skip_lldbinit_files)
2469 init_file.SetFile (init_file_path, true);
2470 }
2471
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002472 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2473 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2474
2475 if (init_file.Exists())
2476 {
Jim Inghame16c50a2011-02-18 00:54:25 +00002477 ExecutionContext *exe_ctx = NULL; // We don't have any context yet.
2478 bool stop_on_continue = true;
2479 bool stop_on_error = false;
2480 bool echo_commands = false;
2481 bool print_results = false;
2482
Enrico Granata5f5ab602012-05-31 01:09:06 +00002483 HandleCommandsFromFile (init_file, exe_ctx, stop_on_continue, stop_on_error, echo_commands, print_results, eLazyBoolNo, result);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002484 }
2485 else
2486 {
2487 // nothing to be done if the file doesn't exist
2488 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2489 }
2490}
2491
Greg Clayton8b82f082011-04-12 05:54:46 +00002492PlatformSP
2493CommandInterpreter::GetPlatform (bool prefer_target_platform)
2494{
2495 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002496 if (prefer_target_platform)
2497 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002498 ExecutionContext exe_ctx(GetExecutionContext());
2499 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002500 if (target)
2501 platform_sp = target->GetPlatform();
2502 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002503
2504 if (!platform_sp)
2505 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2506 return platform_sp;
2507}
2508
Jim Inghame16c50a2011-02-18 00:54:25 +00002509void
Jim Inghambad87fe2011-03-11 01:51:49 +00002510CommandInterpreter::HandleCommands (const StringList &commands,
Jim Inghame16c50a2011-02-18 00:54:25 +00002511 ExecutionContext *override_context,
2512 bool stop_on_continue,
2513 bool stop_on_error,
2514 bool echo_commands,
2515 bool print_results,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002516 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002517 CommandReturnObject &result)
2518{
2519 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002520
2521 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2522 // Make sure you reset this value anywhere you return from the function.
2523
2524 bool old_async_execution = m_debugger.GetAsyncExecution();
2525
2526 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2527 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2528
2529 if (override_context != NULL)
Greg Clayton8b82f082011-04-12 05:54:46 +00002530 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002531
2532 if (!stop_on_continue)
2533 {
2534 m_debugger.SetAsyncExecution (false);
2535 }
2536
Andy Gibbsa297a972013-06-19 19:04:53 +00002537 for (size_t idx = 0; idx < num_lines; idx++)
Jim Inghame16c50a2011-02-18 00:54:25 +00002538 {
2539 const char *cmd = commands.GetStringAtIndex(idx);
2540 if (cmd[0] == '\0')
2541 continue;
2542
Jim Inghame16c50a2011-02-18 00:54:25 +00002543 if (echo_commands)
2544 {
2545 result.AppendMessageWithFormat ("%s %s\n",
2546 GetPrompt(),
2547 cmd);
2548 }
2549
Greg Clayton9d0402b2011-02-20 02:15:07 +00002550 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002551 // If override_context is not NULL, pass no_context_switching = true for
2552 // HandleCommand() since we updated our context already.
Jim Ingham076b7fc2013-05-02 23:15:37 +00002553
2554 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2555 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here.
2556 if (!add_to_history)
2557 m_command_source_depth++;
Enrico Granata5f5ab602012-05-31 01:09:06 +00002558 bool success = HandleCommand(cmd, add_to_history, tmp_result,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002559 NULL, /* override_context */
2560 true, /* repeat_on_empty_command */
2561 override_context != NULL /* no_context_switching */);
Jim Ingham076b7fc2013-05-02 23:15:37 +00002562 if (!add_to_history)
2563 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002564
2565 if (print_results)
2566 {
2567 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002568 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002569 }
2570
2571 if (!success || !tmp_result.Succeeded())
2572 {
Jim Inghama5038812012-04-24 02:25:07 +00002573 const char *error_msg = tmp_result.GetErrorData();
2574 if (error_msg == NULL || error_msg[0] == '\0')
2575 error_msg = "<unknown error>.\n";
Jim Inghame16c50a2011-02-18 00:54:25 +00002576 if (stop_on_error)
2577 {
Andy Gibbsa297a972013-06-19 19:04:53 +00002578 result.AppendErrorWithFormat("Aborting reading of commands after command #%zu: '%s' failed with %s",
Jim Inghama5038812012-04-24 02:25:07 +00002579 idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002580 result.SetStatus (eReturnStatusFailed);
2581 m_debugger.SetAsyncExecution (old_async_execution);
2582 return;
2583 }
2584 else if (print_results)
2585 {
Andy Gibbsa297a972013-06-19 19:04:53 +00002586 result.AppendMessageWithFormat ("Command #%zu '%s' failed with %s",
Jim Inghame16c50a2011-02-18 00:54:25 +00002587 idx + 1,
2588 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002589 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002590 }
2591 }
2592
Caroline Tice969ed3d2011-05-02 20:41:46 +00002593 if (result.GetImmediateOutputStream())
2594 result.GetImmediateOutputStream()->Flush();
2595
2596 if (result.GetImmediateErrorStream())
2597 result.GetImmediateErrorStream()->Flush();
2598
Jim Inghame16c50a2011-02-18 00:54:25 +00002599 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2600 // could be running (for instance in Breakpoint Commands.
2601 // So we check the return value to see if it is has running in it.
2602 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2603 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2604 {
2605 if (stop_on_continue)
2606 {
2607 // If we caused the target to proceed, and we're going to stop in that case, set the
2608 // status in our real result before returning. This is an error if the continue was not the
2609 // last command in the set of commands to be run.
2610 if (idx != num_lines - 1)
Andy Gibbsa297a972013-06-19 19:04:53 +00002611 result.AppendErrorWithFormat("Aborting reading of commands after command #%zu: '%s' continued the target.\n",
Jim Inghame16c50a2011-02-18 00:54:25 +00002612 idx + 1, cmd);
2613 else
Andy Gibbsa297a972013-06-19 19:04:53 +00002614 result.AppendMessageWithFormat ("Command #%zu '%s' continued the target.\n", idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002615
2616 result.SetStatus(tmp_result.GetStatus());
2617 m_debugger.SetAsyncExecution (old_async_execution);
2618
2619 return;
2620 }
2621 }
2622
2623 }
2624
2625 result.SetStatus (eReturnStatusSuccessFinishResult);
2626 m_debugger.SetAsyncExecution (old_async_execution);
2627
2628 return;
2629}
2630
2631void
2632CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2633 ExecutionContext *context,
2634 bool stop_on_continue,
2635 bool stop_on_error,
2636 bool echo_command,
2637 bool print_result,
Enrico Granata5f5ab602012-05-31 01:09:06 +00002638 LazyBool add_to_history,
Jim Inghame16c50a2011-02-18 00:54:25 +00002639 CommandReturnObject &result)
2640{
2641 if (cmd_file.Exists())
2642 {
2643 bool success;
2644 StringList commands;
2645 success = commands.ReadFileLines(cmd_file);
2646 if (!success)
2647 {
2648 result.AppendErrorWithFormat ("Error reading commands from file: %s.\n", cmd_file.GetFilename().AsCString());
2649 result.SetStatus (eReturnStatusFailed);
2650 return;
2651 }
Enrico Granata5f5ab602012-05-31 01:09:06 +00002652 m_command_source_depth++;
2653 HandleCommands (commands, context, stop_on_continue, stop_on_error, echo_command, print_result, add_to_history, result);
2654 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002655 }
2656 else
2657 {
2658 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
2659 cmd_file.GetFilename().AsCString());
2660 result.SetStatus (eReturnStatusFailed);
2661 return;
2662 }
2663}
2664
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002665ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002666CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002667{
Enrico Granatab5887262012-10-29 21:18:03 +00002668 if (m_script_interpreter_ap.get() != NULL)
2669 return m_script_interpreter_ap.get();
2670
2671 if (!can_create)
2672 return NULL;
2673
Enrico Granataa29bdad2012-07-10 18:23:48 +00002674 // <rdar://problem/11751427>
2675 // we need to protect the initialization of the script interpreter
2676 // otherwise we could end up with two threads both trying to create
2677 // their instance of it, and for some languages (e.g. Python)
2678 // this is a bulletproof recipe for disaster!
2679 // this needs to be a function-level static because multiple Debugger instances living in the same process
2680 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002681 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2682 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002683
Greg Clayton5160ce52013-03-27 23:08:40 +00002684 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002685 if (log)
2686 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002687
Caroline Tice2f88aad2011-01-14 00:29:16 +00002688 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2689 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002690 {
Greg Claytondce502e2011-11-04 03:34:56 +00002691 case eScriptLanguagePython:
2692#ifndef LLDB_DISABLE_PYTHON
2693 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2694 break;
2695#else
2696 // Fall through to the None case when python is disabled
2697#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002698 case eScriptLanguageNone:
2699 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2700 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002701 };
2702
2703 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002704}
2705
2706
2707
2708bool
2709CommandInterpreter::GetSynchronous ()
2710{
2711 return m_synchronous_execution;
2712}
2713
2714void
2715CommandInterpreter::SetSynchronous (bool value)
2716{
Johnny Chenc066ab42010-10-14 01:22:03 +00002717 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002718}
2719
2720void
2721CommandInterpreter::OutputFormattedHelpText (Stream &strm,
2722 const char *word_text,
2723 const char *separator,
2724 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002725 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002726{
Greg Claytona7015092010-09-18 01:14:36 +00002727 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2728
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002729 int indent_size = max_word_len + strlen (separator) + 2;
2730
2731 strm.IndentMore (indent_size);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002732
2733 StreamString text_strm;
Greg Claytonc7bece562013-01-25 18:06:21 +00002734 text_strm.Printf ("%-*s %s %s", (int)max_word_len, word_text, separator, help_text);
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002735
2736 size_t len = text_strm.GetSize();
2737 const char *text = text_strm.GetData();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002738 if (text[len - 1] == '\n')
Greg Claytonbfe5f3b2011-02-18 01:44:25 +00002739 {
2740 text_strm.EOL();
2741 len = text_strm.GetSize();
2742 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002743
2744 if (len < max_columns)
2745 {
2746 // Output it as a single line.
2747 strm.Printf ("%s", text);
2748 }
2749 else
2750 {
2751 // We need to break it up into multiple lines.
2752 bool first_line = true;
2753 int text_width;
Greg Claytonc7bece562013-01-25 18:06:21 +00002754 size_t start = 0;
2755 size_t end = start;
2756 const size_t final_end = strlen (text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002757
2758 while (end < final_end)
2759 {
2760 if (first_line)
2761 text_width = max_columns - 1;
2762 else
2763 text_width = max_columns - indent_size - 1;
2764
2765 // Don't start the 'text' on a space, since we're already outputting the indentation.
2766 if (!first_line)
2767 {
2768 while ((start < final_end) && (text[start] == ' '))
2769 start++;
2770 }
2771
2772 end = start + text_width;
2773 if (end > final_end)
2774 end = final_end;
2775 else
2776 {
2777 // If we're not at the end of the text, make sure we break the line on white space.
2778 while (end > start
2779 && text[end] != ' ' && text[end] != '\t' && text[end] != '\n')
2780 end--;
Greg Clayton67cc0632012-08-22 17:17:09 +00002781 assert (end > 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002782 }
2783
Greg Claytonc7bece562013-01-25 18:06:21 +00002784 const size_t sub_len = end - start;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002785 if (start != 0)
2786 strm.EOL();
2787 if (!first_line)
2788 strm.Indent();
2789 else
2790 first_line = false;
2791 assert (start <= final_end);
2792 assert (start + sub_len <= final_end);
2793 if (sub_len > 0)
2794 strm.Write (text + start, sub_len);
2795 start = end + 1;
2796 }
2797 }
2798 strm.EOL();
2799 strm.IndentLess(indent_size);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002800}
2801
2802void
Enrico Granata82a7d982011-07-07 00:38:40 +00002803CommandInterpreter::OutputHelpText (Stream &strm,
2804 const char *word_text,
2805 const char *separator,
2806 const char *help_text,
2807 uint32_t max_word_len)
2808{
2809 int indent_size = max_word_len + strlen (separator) + 2;
2810
2811 strm.IndentMore (indent_size);
2812
2813 StreamString text_strm;
2814 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2815
2816 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002817
2818 size_t len = text_strm.GetSize();
2819 const char *text = text_strm.GetData();
2820
2821 uint32_t chars_left = max_columns;
2822
2823 for (uint32_t i = 0; i < len; i++)
2824 {
2825 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2826 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002827 chars_left = max_columns - indent_size;
2828 strm.EOL();
2829 strm.Indent();
2830 }
2831 else
2832 {
2833 strm.PutChar(text[i]);
2834 chars_left--;
2835 }
2836
2837 }
2838
2839 strm.EOL();
2840 strm.IndentLess(indent_size);
2841}
2842
2843void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002844CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
Jim Inghamaf3753e2013-05-17 01:30:37 +00002845 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002846{
2847 CommandObject::CommandMap::const_iterator pos;
2848
Jim Inghamaf3753e2013-05-17 01:30:37 +00002849 if (search_builtin_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002850 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002851 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002852 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002853 const char *command_name = pos->first.c_str();
2854 CommandObject *cmd_obj = pos->second.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002855
Jim Inghamaf3753e2013-05-17 01:30:37 +00002856 if (cmd_obj->HelpTextContainsWord (search_word))
2857 {
2858 commands_found.AppendString (command_name);
2859 commands_help.AppendString (cmd_obj->GetHelp());
2860 }
2861
2862 if (cmd_obj->IsMultiwordObject())
2863 cmd_obj->AproposAllSubCommands (command_name,
2864 search_word,
2865 commands_found,
2866 commands_help);
2867
2868 }
2869 }
2870
2871 if (search_user_commands)
2872 {
2873 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
2874 {
2875 const char *command_name = pos->first.c_str();
2876 CommandObject *cmd_obj = pos->second.get();
2877
2878 if (cmd_obj->HelpTextContainsWord (search_word))
2879 {
2880 commands_found.AppendString (command_name);
2881 commands_help.AppendString (cmd_obj->GetHelp());
2882 }
2883
2884 if (cmd_obj->IsMultiwordObject())
2885 cmd_obj->AproposAllSubCommands (command_name,
2886 search_word,
2887 commands_found,
2888 commands_help);
2889
2890 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002891 }
2892}
Greg Clayton8b82f082011-04-12 05:54:46 +00002893
2894
2895void
2896CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2897{
Greg Clayton8b82f082011-04-12 05:54:46 +00002898 if (override_context != NULL)
2899 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002900 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002901 }
2902 else
2903 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002904 const bool adopt_selected = true;
2905 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002906 }
2907}