blob: fe47723831393abfbe0ed9a7449117f6940ca7ae [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000013#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000014#include <stdlib.h>
15
Greg Clayton4a33d312011-06-23 17:59:56 +000016#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000017#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000018
Eli Friedman3afb70c2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectApropos.h"
20#include "../Commands/CommandObjectArgs.h"
21#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
Greg Clayton44d93782014-01-27 23:43:24 +000025#include "../Commands/CommandObjectGUI.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectHelp.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000027#include "../Commands/CommandObjectLog.h"
28#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000029#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000030#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectProcess.h"
32#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSource.h"
Jim Inghamebc09c32010-07-07 03:36:20 +000036#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000037#include "../Commands/CommandObjectSyntax.h"
38#include "../Commands/CommandObjectTarget.h"
39#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000040#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000041#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000042#include "../Commands/CommandObjectWatchpoint.h"
Colin Rileyc9c55a22015-05-04 18:39:38 +000043#include "../Commands/CommandObjectLanguage.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044
Greg Clayton7d2ef162013-03-29 17:03:23 +000045
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046#include "lldb/Core/Debugger.h"
Enrico Granatab5887262012-10-29 21:18:03 +000047#include "lldb/Core/Log.h"
Greg Claytonf0066ad2014-05-02 00:45:31 +000048#include "lldb/Core/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049#include "lldb/Core/Stream.h"
Greg Clayton44d93782014-01-27 23:43:24 +000050#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000051#include "lldb/Core/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000052
Todd Fialacacde7d2014-09-27 16:54:22 +000053#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000054#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000055#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000056#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000057#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000058
59#include "lldb/Interpreter/Args.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000060#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000061#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000062#include "lldb/Interpreter/CommandReturnObject.h"
Enrico Granatab5887262012-10-29 21:18:03 +000063#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000064#include "lldb/Interpreter/OptionValueProperties.h"
65#include "lldb/Interpreter/Property.h"
Enrico Granatab5887262012-10-29 21:18:03 +000066#include "lldb/Interpreter/ScriptInterpreterNone.h"
67#include "lldb/Interpreter/ScriptInterpreterPython.h"
68
69
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070#include "lldb/Target/Process.h"
71#include "lldb/Target/Thread.h"
72#include "lldb/Target/TargetList.h"
73
Enrico Granatab5887262012-10-29 21:18:03 +000074#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075
Zachary Turnera21fee02014-08-21 21:49:24 +000076#include "llvm/ADT/SmallString.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000077#include "llvm/ADT/STLExtras.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000078#include "llvm/Support/Path.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000079
Chris Lattner30fdc8d2010-06-08 16:52:24 +000080using namespace lldb;
81using namespace lldb_private;
82
Adrian McCarthy2304b6f2015-04-23 20:00:25 +000083static const char *k_white_space = " \t\v";
Greg Clayton754a9362012-08-23 00:22:02 +000084
85static PropertyDefinition
86g_properties[] =
87{
Ed Masted78c9572014-04-20 00:31:37 +000088 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "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." },
89 { "prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "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." },
90 { "stop-command-source-on-error", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will stop running a 'command source' script upon encountering an error." },
91 { nullptr , OptionValue::eTypeInvalid, true, 0 , nullptr, nullptr, nullptr }
Greg Clayton754a9362012-08-23 00:22:02 +000092};
93
94enum
95{
Enrico Granatabcba2b22013-01-17 21:36:19 +000096 ePropertyExpandRegexAliases = 0,
Enrico Granata012d4fc2013-06-11 01:26:35 +000097 ePropertyPromptOnQuit = 1,
98 ePropertyStopCmdSourceOnError = 2
Greg Clayton754a9362012-08-23 00:22:02 +000099};
100
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000101ConstString &
102CommandInterpreter::GetStaticBroadcasterClass ()
103{
104 static ConstString class_name ("lldb.commandInterpreter");
105 return class_name;
106}
107
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000108CommandInterpreter::CommandInterpreter
109(
Greg Clayton66111032010-06-23 01:19:29 +0000110 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000111 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +0000112 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000113) :
Ilia K8a00a562015-03-17 16:54:52 +0000114 Broadcaster (&debugger, CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
Greg Clayton754a9362012-08-23 00:22:02 +0000115 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton44d93782014-01-27 23:43:24 +0000116 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand),
Greg Clayton66111032010-06-23 01:19:29 +0000117 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000118 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000119 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000120 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000121 m_script_interpreter_ap (),
Greg Clayton44d93782014-01-27 23:43:24 +0000122 m_command_io_handler_sp (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000123 m_comment_char ('#'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000124 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000125 m_truncation_warning(eNoTruncation),
Jim Ingham26c7bf92014-10-11 00:38:27 +0000126 m_command_source_depth (0),
127 m_num_errors(0),
Jim Inghamffc9f1d2014-10-14 01:20:07 +0000128 m_quit_requested(false),
129 m_stopped_for_crash(false)
Jim Ingham26c7bf92014-10-11 00:38:27 +0000130
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000131{
Greg Clayton67cc0632012-08-22 17:17:09 +0000132 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000133 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
134 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000135 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000136 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000137 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000138}
139
Greg Clayton754a9362012-08-23 00:22:02 +0000140bool
141CommandInterpreter::GetExpandRegexAliases () const
142{
143 const uint32_t idx = ePropertyExpandRegexAliases;
Ed Masted78c9572014-04-20 00:31:37 +0000144 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000145}
146
Enrico Granatabcba2b22013-01-17 21:36:19 +0000147bool
148CommandInterpreter::GetPromptOnQuit () const
149{
150 const uint32_t idx = ePropertyPromptOnQuit;
Ed Masted78c9572014-04-20 00:31:37 +0000151 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000152}
Greg Clayton754a9362012-08-23 00:22:02 +0000153
Ilia Kacf28be2015-03-23 22:45:13 +0000154void
155CommandInterpreter::SetPromptOnQuit (bool b)
156{
157 const uint32_t idx = ePropertyPromptOnQuit;
158 m_collection_sp->SetPropertyAtIndexAsBoolean (nullptr, idx, b);
159}
160
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000161void
162CommandInterpreter::ResolveCommand(const char *command_line, CommandReturnObject &result)
163{
164 std::string command = command_line;
165 if (ResolveCommandImpl(command, result) != nullptr) {
166 result.AppendMessageWithFormat("%s", command.c_str());
167 result.SetStatus(eReturnStatusSuccessFinishResult);
168 }
169}
170
171
Enrico Granata012d4fc2013-06-11 01:26:35 +0000172bool
173CommandInterpreter::GetStopCmdSourceOnError () const
174{
175 const uint32_t idx = ePropertyStopCmdSourceOnError;
Ed Masted78c9572014-04-20 00:31:37 +0000176 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000177}
178
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000179void
180CommandInterpreter::Initialize ()
181{
182 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
183
184 CommandReturnObject result;
185
186 LoadCommandDictionary ();
187
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000188 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000189 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
190 if (cmd_obj_sp)
191 {
192 AddAlias ("q", cmd_obj_sp);
193 AddAlias ("exit", cmd_obj_sp);
194 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000195
Johnny Chen6d675242012-08-24 18:15:45 +0000196 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000197 if (cmd_obj_sp)
198 {
199 AddAlias ("attach", cmd_obj_sp);
200 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000201
Johnny Chen6d675242012-08-24 18:15:45 +0000202 cmd_obj_sp = GetCommandSPExact ("process detach",false);
203 if (cmd_obj_sp)
204 {
205 AddAlias ("detach", cmd_obj_sp);
206 }
207
Caroline Ticeca90c472011-05-06 21:37:15 +0000208 cmd_obj_sp = GetCommandSPExact ("process continue", false);
209 if (cmd_obj_sp)
210 {
211 AddAlias ("c", cmd_obj_sp);
212 AddAlias ("continue", cmd_obj_sp);
213 }
214
215 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
216 if (cmd_obj_sp)
217 AddAlias ("b", cmd_obj_sp);
218
Jim Inghamca36cd12012-10-05 19:16:31 +0000219 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
220 if (cmd_obj_sp)
221 AddAlias ("tbreak", cmd_obj_sp);
222
Caroline Ticeca90c472011-05-06 21:37:15 +0000223 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
224 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000225 {
226 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000227 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000228 }
229
230 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
231 if (cmd_obj_sp)
232 {
233 AddAlias ("nexti", cmd_obj_sp);
234 AddAlias ("ni", cmd_obj_sp);
235 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000236
237 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
238 if (cmd_obj_sp)
239 {
240 AddAlias ("s", cmd_obj_sp);
241 AddAlias ("step", cmd_obj_sp);
242 }
243
244 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
245 if (cmd_obj_sp)
246 {
247 AddAlias ("n", cmd_obj_sp);
248 AddAlias ("next", cmd_obj_sp);
249 }
250
251 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
252 if (cmd_obj_sp)
253 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000254 AddAlias ("finish", cmd_obj_sp);
255 }
256
Jim Ingham6d6d1072011-12-02 01:12:59 +0000257 cmd_obj_sp = GetCommandSPExact ("frame select", false);
258 if (cmd_obj_sp)
259 {
260 AddAlias ("f", cmd_obj_sp);
261 }
262
Jim Inghamca36cd12012-10-05 19:16:31 +0000263 cmd_obj_sp = GetCommandSPExact ("thread select", false);
264 if (cmd_obj_sp)
265 {
266 AddAlias ("t", cmd_obj_sp);
267 }
268
Richard Mittonf86248d2013-09-12 02:20:34 +0000269 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
270 if (cmd_obj_sp)
271 {
272 AddAlias ("j", cmd_obj_sp);
273 AddAlias ("jump", cmd_obj_sp);
274 }
275
Greg Clayton6bade322013-02-01 23:33:03 +0000276 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000277 if (cmd_obj_sp)
278 {
279 AddAlias ("l", cmd_obj_sp);
280 AddAlias ("list", cmd_obj_sp);
281 }
282
Greg Claytonef5651d2013-02-12 18:52:24 +0000283 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
284 if (cmd_obj_sp)
285 {
286 AddAlias ("env", cmd_obj_sp);
287 }
288
Caroline Ticeca90c472011-05-06 21:37:15 +0000289 cmd_obj_sp = GetCommandSPExact ("memory read", false);
290 if (cmd_obj_sp)
291 AddAlias ("x", cmd_obj_sp);
292
293 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
294 if (cmd_obj_sp)
295 AddAlias ("up", cmd_obj_sp);
296
297 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
298 if (cmd_obj_sp)
299 AddAlias ("down", cmd_obj_sp);
300
Jason Molenda0c8e0062011-10-25 02:11:20 +0000301 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000302 if (cmd_obj_sp)
303 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000304
305 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
306 if (cmd_obj_sp)
307 AddAlias ("dis", cmd_obj_sp);
308
309 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
310 if (cmd_obj_sp)
311 AddAlias ("di", cmd_obj_sp);
312
313
Jason Molendabc7748b2011-10-22 01:30:52 +0000314
Jason Molenda0c8e0062011-10-25 02:11:20 +0000315 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000316 if (cmd_obj_sp)
317 AddAlias ("undisplay", cmd_obj_sp);
318
Jim Ingham71bf2992012-10-10 16:51:31 +0000319 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
320 if (cmd_obj_sp)
321 AddAlias ("bt", cmd_obj_sp);
322
Caroline Ticeca90c472011-05-06 21:37:15 +0000323 cmd_obj_sp = GetCommandSPExact ("target create", false);
324 if (cmd_obj_sp)
325 AddAlias ("file", cmd_obj_sp);
326
327 cmd_obj_sp = GetCommandSPExact ("target modules", false);
328 if (cmd_obj_sp)
329 AddAlias ("image", cmd_obj_sp);
330
331
332 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000333
Caroline Ticeca90c472011-05-06 21:37:15 +0000334 cmd_obj_sp = GetCommandSPExact ("expression", false);
335 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000336 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000337 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
338 AddAlias ("p", cmd_obj_sp);
339 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000340 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000341 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
342 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000343 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000344
345 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton9e57dcd2013-05-15 01:03:08 +0000346 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000347 AddAlias ("po", cmd_obj_sp);
348 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
349 }
350
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000351 cmd_obj_sp = GetCommandSPExact ("process kill", false);
352 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000353 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000354 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000355 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000356
Caroline Ticeca90c472011-05-06 21:37:15 +0000357 cmd_obj_sp = GetCommandSPExact ("process launch", false);
358 if (cmd_obj_sp)
359 {
360 alias_arguments_vector_sp.reset (new OptionArgVector);
Todd Fiala013434e2014-07-09 01:29:05 +0000361#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Jason Molenda85da3122012-07-06 02:46:23 +0000362 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
363#else
Zachary Turner10687b02014-10-20 17:46:43 +0000364 std::string shell_option;
365 shell_option.append("--shell=");
366 shell_option.append(HostInfo::GetDefaultShell().GetPath());
367 shell_option.append(" --");
368 ProcessAliasOptionsArgs (cmd_obj_sp, shell_option.c_str(), alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000369#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000370 AddAlias ("r", cmd_obj_sp);
371 AddAlias ("run", cmd_obj_sp);
372 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
373 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
374 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000375
376 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
377 if (cmd_obj_sp)
378 {
379 AddAlias ("add-dsym", cmd_obj_sp);
380 }
Sean Callananfc732752012-05-21 18:25:19 +0000381
382 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
383 if (cmd_obj_sp)
384 {
385 alias_arguments_vector_sp.reset (new OptionArgVector);
386 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000387 AddAlias ("rbreak", cmd_obj_sp);
388 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000389 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000390}
391
Greg Clayton0c4129f2014-04-25 00:35:14 +0000392void
393CommandInterpreter::Clear()
394{
395 m_command_io_handler_sp.reset();
Greg Claytoned6499f2014-04-25 23:55:12 +0000396
397 if (m_script_interpreter_ap)
398 m_script_interpreter_ap->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000399}
400
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401const char *
402CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
403{
404 // This function has not yet been implemented.
405
406 // Look for any embedded script command
407 // If found,
408 // get interpreter object from the command dictionary,
409 // call execute_one_command on it,
410 // get the results as a string,
411 // substitute that string for current stuff.
412
413 return arg;
414}
415
416
417void
418CommandInterpreter::LoadCommandDictionary ()
419{
420 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
421
Caroline Ticedaccaa92010-09-20 20:44:43 +0000422 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000423
Greg Claytona7015092010-09-18 01:14:36 +0000424 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000425 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000426 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000427 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
428 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000429 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton44d93782014-01-27 23:43:24 +0000430 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000431 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000432 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
433 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000434 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000435 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000436 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000437 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000438 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000439 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000440 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000441 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000442 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
443 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000444 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000445 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000446 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Colin Rileyc9c55a22015-05-04 18:39:38 +0000447 m_command_dict["language"] = CommandObjectSP (new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000448
Jim Inghamca36cd12012-10-05 19:16:31 +0000449 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
Greg Claytond90ac932014-12-01 22:34:03 +0000450 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000451 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000452 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000453 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000454 {"^(-.*)$", "breakpoint set %1"},
455 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000456 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Greg Clayton2d4b5122014-08-14 17:58:33 +0000457 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}};
Jim Inghamca36cd12012-10-05 19:16:31 +0000458
Saleem Abdulrasool28606952014-06-27 05:17:41 +0000459 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000460
Greg Clayton7b0992d2013-04-18 22:45:39 +0000461 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000462 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000463 "_regexp-break",
Greg Clayton910db5c2015-03-07 00:01:46 +0000464 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.\n",
465 "\n_regexp-break <filename>:<linenum> # _regexp-break main.c:12 // Break on line 12 of main.c\n"
466 "_regexp-break <linenum> # _regexp-break 12 // Break on line 12 of current file\n"
467 "_regexp-break <address> # _regexp-break 0x1234000 // Break on address 0x1234000\n"
468 "_regexp-break <name> # _regexp-break main // Break in 'main' after the prologue\n"
469 "_regexp-break &<name> # _regexp-break &main // Break on the first instruction in 'main'\n"
470 "_regexp-break <module>`<name> # _regexp-break libc.so`malloc // Break in 'malloc' only in the 'libc.so' shared library\n"
471 "_regexp-break /<source-regex>/ # _regexp-break /break here/ // Break on all lines that match the regular expression 'break here' in the current file.\n",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000472 2,
473 CommandCompletions::eSymbolCompletion |
Greg Claytonb5472782015-01-09 19:08:20 +0000474 CommandCompletions::eSourceFileCompletion,
475 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000476
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000477 if (break_regex_cmd_ap.get())
478 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000479 bool success = true;
480 for (size_t i = 0; i < num_regexes; i++)
481 {
482 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
483 if (!success)
484 break;
485 }
486 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
487
488 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000489 {
490 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
491 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
492 }
493 }
Jim Inghamffba2292011-03-22 02:29:32 +0000494
Greg Clayton7b0992d2013-04-18 22:45:39 +0000495 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000496 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
497 "_regexp-tbreak",
498 "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 +0000499 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
500 2,
501 CommandCompletions::eSymbolCompletion |
Greg Claytonb5472782015-01-09 19:08:20 +0000502 CommandCompletions::eSourceFileCompletion,
503 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000504
505 if (tbreak_regex_cmd_ap.get())
506 {
507 bool success = true;
508 for (size_t i = 0; i < num_regexes; i++)
509 {
510 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
511 char buffer[1024];
512 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
513 assert (num_printed < 1024);
Eric Christopher5c91d5c12014-09-09 19:26:45 +0000514 // Quiet unused variable warning for release builds.
Eric Christopher9ad83942014-09-09 08:57:33 +0000515 (void) num_printed;
Jim Inghamca36cd12012-10-05 19:16:31 +0000516 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
517 if (!success)
518 break;
519 }
520 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
521
522 if (success)
523 {
524 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
525 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
526 }
527 }
528
Greg Clayton7b0992d2013-04-18 22:45:39 +0000529 std::unique_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000530 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
531 "_regexp-attach",
532 "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 +0000533 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
Greg Claytonb5472782015-01-09 19:08:20 +0000534 2,
535 0,
536 false));
Johnny Chen6d675242012-08-24 18:15:45 +0000537 if (attach_regex_cmd_ap.get())
538 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000539 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
540 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
541 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
542 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000543 {
544 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
545 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
546 }
547 }
548
Greg Clayton7b0992d2013-04-18 22:45:39 +0000549 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000550 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000551 "_regexp-down",
552 "Go down \"n\" frames in the stack (1 frame by default).",
Greg Claytonb5472782015-01-09 19:08:20 +0000553 "_regexp-down [n]",
554 2,
555 0,
556 false));
Jim Inghamffba2292011-03-22 02:29:32 +0000557 if (down_regex_cmd_ap.get())
558 {
559 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
560 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
561 {
562 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
563 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
564 }
565 }
566
Greg Clayton7b0992d2013-04-18 22:45:39 +0000567 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000568 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000569 "_regexp-up",
570 "Go up \"n\" frames in the stack (1 frame by default).",
Greg Claytonb5472782015-01-09 19:08:20 +0000571 "_regexp-up [n]",
572 2,
573 0,
574 false));
Jim Inghamffba2292011-03-22 02:29:32 +0000575 if (up_regex_cmd_ap.get())
576 {
577 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
578 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
579 {
580 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
581 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
582 }
583 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000584
Greg Clayton7b0992d2013-04-18 22:45:39 +0000585 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000586 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000587 "_regexp-display",
588 "Add an expression evaluation stop-hook.",
Greg Claytonb5472782015-01-09 19:08:20 +0000589 "_regexp-display expression",
590 2,
591 0,
592 false));
Jason Molendabc7748b2011-10-22 01:30:52 +0000593 if (display_regex_cmd_ap.get())
594 {
595 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
596 {
597 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
598 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
599 }
600 }
601
Greg Clayton7b0992d2013-04-18 22:45:39 +0000602 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000603 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000604 "_regexp-undisplay",
605 "Remove an expression evaluation stop-hook.",
Greg Claytonb5472782015-01-09 19:08:20 +0000606 "_regexp-undisplay stop-hook-number",
607 2,
608 0,
609 false));
Jason Molendabc7748b2011-10-22 01:30:52 +0000610 if (undisplay_regex_cmd_ap.get())
611 {
612 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
613 {
614 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
615 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
616 }
617 }
618
Greg Clayton7b0992d2013-04-18 22:45:39 +0000619 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000620 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000621 "gdb-remote",
622 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
Greg Claytonb5472782015-01-09 19:08:20 +0000623 "gdb-remote [<hostname>:]<portnum>",
624 2,
625 0,
626 false));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000627 if (connect_gdb_remote_cmd_ap.get())
628 {
629 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
630 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
631 {
632 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
633 m_command_dict[command_sp->GetCommandName ()] = command_sp;
634 }
635 }
636
Greg Clayton7b0992d2013-04-18 22:45:39 +0000637 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000638 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
639 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000640 "Connect to a remote KDP server. udp port 41139 is the default port number.",
Greg Claytonb5472782015-01-09 19:08:20 +0000641 "kdp-remote <hostname>[:<portnum>]",
642 2,
643 0,
644 false));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000645 if (connect_kdp_remote_cmd_ap.get())
646 {
647 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000648 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000649 {
650 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
651 m_command_dict[command_sp->GetCommandName ()] = command_sp;
652 }
653 }
654
Greg Clayton7b0992d2013-04-18 22:45:39 +0000655 std::unique_ptr<CommandObjectRegexCommand>
Jason Molenda4cddfed2012-10-05 05:29:32 +0000656 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb5472782015-01-09 19:08:20 +0000657 "_regexp-bt",
658 "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.",
659 "bt [<digit>|all]",
660 2,
661 0,
662 false));
Jason Molenda4cddfed2012-10-05 05:29:32 +0000663 if (bt_regex_cmd_ap.get())
664 {
665 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
666 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
667 // so now "bt 3" is the preferred form, in line with gdb.
668 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
669 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
670 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
671 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
672 {
673 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
674 m_command_dict[command_sp->GetCommandName ()] = command_sp;
675 }
676 }
677
Greg Clayton7b0992d2013-04-18 22:45:39 +0000678 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton6bade322013-02-01 23:33:03 +0000679 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
680 "_regexp-list",
681 "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 +0000682 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000683 2,
Greg Claytonb5472782015-01-09 19:08:20 +0000684 CommandCompletions::eSourceFileCompletion,
685 false));
Greg Clayton6bade322013-02-01 23:33:03 +0000686 if (list_regex_cmd_ap.get())
687 {
688 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
689 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
690 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000691 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000692 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000693 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
694 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
695 {
696 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
697 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
698 }
699 }
700
Greg Clayton7b0992d2013-04-18 22:45:39 +0000701 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytonef5651d2013-02-12 18:52:24 +0000702 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000703 "_regexp-env",
704 "Implements a shortcut to viewing and setting environment variables.",
Greg Claytonb5472782015-01-09 19:08:20 +0000705 "_regexp-env\n_regexp-env FOO=BAR",
706 2,
707 0,
708 false));
Greg Claytonef5651d2013-02-12 18:52:24 +0000709 if (env_regex_cmd_ap.get())
710 {
711 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
712 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
713 {
714 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
715 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
716 }
717 }
718
Richard Mittonf86248d2013-09-12 02:20:34 +0000719 std::unique_ptr<CommandObjectRegexCommand>
720 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
721 "_regexp-jump",
722 "Sets the program counter to a new address.",
723 "_regexp-jump [<line>]\n"
724 "_regexp-jump [<+-lineoffset>]\n"
725 "_regexp-jump [<file>:<line>]\n"
Greg Claytonb5472782015-01-09 19:08:20 +0000726 "_regexp-jump [*<addr>]\n",
727 2,
728 0,
729 false));
Richard Mittonf86248d2013-09-12 02:20:34 +0000730 if (jump_regex_cmd_ap.get())
731 {
732 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
733 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
734 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
735 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
736 {
737 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
738 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
739 }
740 }
741
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742}
743
744int
745CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
746 StringList &matches)
747{
748 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
749
750 if (include_aliases)
751 {
752 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
753 }
754
755 return matches.GetSize();
756}
757
758CommandObjectSP
759CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
760{
761 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000762 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000763
764 std::string cmd(cmd_cstr);
765
766 if (HasCommands())
767 {
768 pos = m_command_dict.find(cmd);
769 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000770 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000771 }
772
773 if (include_aliases && HasAliases())
774 {
775 pos = m_alias_dict.find(cmd);
776 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000777 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778 }
779
780 if (HasUserCommands())
781 {
782 pos = m_user_dict.find(cmd);
783 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000784 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785 }
786
Greg Claytonc7bece562013-01-25 18:06:21 +0000787 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000788 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000789 // We will only get into here if we didn't find any exact matches.
790
791 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
792
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793 StringList local_matches;
Ed Masted78c9572014-04-20 00:31:37 +0000794 if (matches == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795 matches = &local_matches;
796
Jim Ingham279a6c22010-07-06 22:46:59 +0000797 unsigned int num_cmd_matches = 0;
798 unsigned int num_alias_matches = 0;
799 unsigned int num_user_matches = 0;
800
801 // Look through the command dictionaries one by one, and if we get only one match from any of
802 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
803
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000804 if (HasCommands())
805 {
806 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
807 }
808
809 if (num_cmd_matches == 1)
810 {
811 cmd.assign(matches->GetStringAtIndex(0));
812 pos = m_command_dict.find(cmd);
813 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000814 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000815 }
816
Jim Ingham490ac552010-06-24 20:28:42 +0000817 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000818 {
819 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
820
821 }
822
Jim Ingham279a6c22010-07-06 22:46:59 +0000823 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000824 {
825 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
826 pos = m_alias_dict.find(cmd);
827 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000828 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000829 }
830
Jim Ingham490ac552010-06-24 20:28:42 +0000831 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000832 {
833 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
834 }
835
Jim Ingham279a6c22010-07-06 22:46:59 +0000836 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000837 {
838 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
839
840 pos = m_user_dict.find (cmd);
841 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000842 user_match_sp = pos->second;
843 }
844
845 // If we got exactly one match, return that, otherwise return the match list.
846
847 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
848 {
849 if (num_cmd_matches)
850 return real_match_sp;
851 else if (num_alias_matches)
852 return alias_match_sp;
853 else
854 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000855 }
856 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000857 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000858 {
859 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000860 }
861
862
Greg Claytonc7bece562013-01-25 18:06:21 +0000863 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000864}
865
Greg Claytonde164aa2011-04-20 16:37:46 +0000866bool
867CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
868{
869 if (name && name[0])
870 {
871 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000872 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
873 if (found && !can_replace)
874 return false;
875 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000876 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000877 m_command_dict[name_sstr] = cmd_sp;
878 return true;
879 }
880 return false;
881}
882
Enrico Granata223383e2011-08-16 23:24:13 +0000883bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000884CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000885 const lldb::CommandObjectSP &cmd_sp,
886 bool can_replace)
887{
Enrico Granata0a305db2011-11-07 22:57:04 +0000888 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000889 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000890
891 const char* name_cstr = name.c_str();
892
893 // do not allow replacement of internal commands
894 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000895 {
896 if (can_replace == false)
897 return false;
898 if (m_command_dict[name]->IsRemovable() == false)
899 return false;
900 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000901
Enrico Granata21dfcd92012-09-28 23:57:51 +0000902 if (UserCommandExists(name_cstr))
903 {
904 if (can_replace == false)
905 return false;
906 if (m_user_dict[name]->IsRemovable() == false)
907 return false;
908 }
909
Enrico Granata0a305db2011-11-07 22:57:04 +0000910 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000911 return true;
912 }
913 return false;
914}
Greg Claytonde164aa2011-04-20 16:37:46 +0000915
Jim Ingham279a6c22010-07-06 22:46:59 +0000916CommandObjectSP
917CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000918{
Caroline Tice472362e2010-12-14 18:51:39 +0000919 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
920 CommandObjectSP ret_val; // Possibly empty return value.
921
Ed Masted78c9572014-04-20 00:31:37 +0000922 if (cmd_cstr == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000923 return ret_val;
924
925 if (cmd_words.GetArgumentCount() == 1)
Ed Masted78c9572014-04-20 00:31:37 +0000926 return GetCommandSP(cmd_cstr, include_aliases, true, nullptr);
Caroline Tice472362e2010-12-14 18:51:39 +0000927 else
928 {
929 // We have a multi-word command (seemingly), so we need to do more work.
930 // First, get the cmd_obj_sp for the first word in the command.
Ed Masted78c9572014-04-20 00:31:37 +0000931 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr);
932 if (cmd_obj_sp.get() != nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000933 {
934 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
935 // command name), and find the appropriate sub-command SP for each command word....
936 size_t end = cmd_words.GetArgumentCount();
937 for (size_t j= 1; j < end; ++j)
938 {
939 if (cmd_obj_sp->IsMultiwordObject())
940 {
Greg Clayton998255b2012-10-13 02:07:45 +0000941 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Ed Masted78c9572014-04-20 00:31:37 +0000942 if (cmd_obj_sp.get() == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000943 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
944 return ret_val;
945 }
946 else
947 // We have more words in the command name, but we don't have a multiword object. Fail and return
948 // empty 'ret_val'.
949 return ret_val;
950 }
951 // We successfully looped through all the command words and got valid command objects for them. Assign the
952 // last object retrieved to 'ret_val'.
953 ret_val = cmd_obj_sp;
954 }
955 }
956 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000957}
958
959CommandObject *
960CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
961{
962 return GetCommandSPExact (cmd_cstr, include_aliases).get();
963}
964
965CommandObject *
966CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
967{
968 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
969
970 // If we didn't find an exact match to the command string in the commands, look in
971 // the aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000972
973 if (command_obj)
974 return command_obj;
Jim Ingham279a6c22010-07-06 22:46:59 +0000975
Enrico Granata5342c442013-06-18 18:01:08 +0000976 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
Jim Ingham279a6c22010-07-06 22:46:59 +0000977
Enrico Granata5342c442013-06-18 18:01:08 +0000978 if (command_obj)
979 return command_obj;
980
981 // If there wasn't an exact match then look for an inexact one in just the commands
Ed Masted78c9572014-04-20 00:31:37 +0000982 command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get();
Matt Kopec038ff812013-04-23 16:17:32 +0000983
984 // Finally, if there wasn't an inexact match among the commands, look for an inexact
985 // match in both the commands and aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000986
987 if (command_obj)
988 {
989 if (matches)
990 matches->AppendString(command_obj->GetCommandName());
991 return command_obj;
992 }
993
994 return GetCommandSP(cmd_cstr, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000995}
996
997bool
998CommandInterpreter::CommandExists (const char *cmd)
999{
1000 return m_command_dict.find(cmd) != m_command_dict.end();
1001}
1002
1003bool
Caroline Ticeca90c472011-05-06 21:37:15 +00001004CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
1005 const char *options_args,
1006 OptionArgVectorSP &option_arg_vector_sp)
1007{
1008 bool success = true;
1009 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1010
1011 if (!options_args || (strlen (options_args) < 1))
1012 return true;
1013
1014 std::string options_string (options_args);
1015 Args args (options_args);
1016 CommandReturnObject result;
1017 // Check to see if the command being aliased can take any command options.
1018 Options *options = cmd_obj_sp->GetOptions ();
1019 if (options)
1020 {
1021 // See if any options were specified as part of the alias; if so, handle them appropriately.
1022 options->NotifyOptionParsingStarting ();
1023 args.Unshift ("dummy_arg");
1024 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
1025 args.Shift ();
1026 if (result.Succeeded())
1027 options->VerifyPartialOptions (result);
1028 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
1029 {
1030 result.AppendError ("Unable to create requested alias.\n");
1031 return false;
1032 }
1033 }
1034
Greg Clayton5521f992011-10-28 21:38:01 +00001035 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +00001036 {
1037 if (cmd_obj_sp->WantsRawCommandString ())
1038 option_arg_vector->push_back (OptionArgPair ("<argument>",
1039 OptionArgValue (-1,
1040 options_string)));
1041 else
1042 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001043 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +00001044 for (size_t i = 0; i < argc; ++i)
1045 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
1046 option_arg_vector->push_back
1047 (OptionArgPair ("<argument>",
1048 OptionArgValue (-1,
1049 std::string (args.GetArgumentAtIndex (i)))));
1050 }
1051 }
1052
1053 return success;
1054}
1055
1056bool
Jim Ingham298f3782013-04-03 00:25:49 +00001057CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
1058{
1059 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1060 if (exact_match)
1061 {
1062 full_name.assign(cmd);
1063 return exact_match;
1064 }
1065 else
1066 {
1067 StringList matches;
1068 size_t num_alias_matches;
1069 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
1070 if (num_alias_matches == 1)
1071 {
1072 // Make sure this isn't shadowing a command in the regular command space:
1073 StringList regular_matches;
1074 const bool include_aliases = false;
1075 const bool exact = false;
1076 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
1077 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1078 return false;
1079 else
1080 {
1081 full_name.assign (matches.GetStringAtIndex(0));
1082 return true;
1083 }
1084 }
1085 else
1086 return false;
1087 }
1088}
1089
1090bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001091CommandInterpreter::AliasExists (const char *cmd)
1092{
1093 return m_alias_dict.find(cmd) != m_alias_dict.end();
1094}
1095
1096bool
1097CommandInterpreter::UserCommandExists (const char *cmd)
1098{
1099 return m_user_dict.find(cmd) != m_user_dict.end();
1100}
1101
1102void
1103CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1104{
Jim Ingham279a6c22010-07-06 22:46:59 +00001105 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106 m_alias_dict[alias_name] = command_obj_sp;
1107}
1108
1109bool
1110CommandInterpreter::RemoveAlias (const char *alias_name)
1111{
1112 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1113 if (pos != m_alias_dict.end())
1114 {
1115 m_alias_dict.erase(pos);
1116 return true;
1117 }
1118 return false;
1119}
Greg Claytonb5472782015-01-09 19:08:20 +00001120
1121bool
1122CommandInterpreter::RemoveCommand (const char *cmd)
1123{
1124 auto pos = m_command_dict.find(cmd);
1125 if (pos != m_command_dict.end())
1126 {
1127 if (pos->second->IsRemovable())
1128 {
1129 // Only regular expression objects or python commands are removable
1130 m_command_dict.erase(pos);
1131 return true;
1132 }
1133 }
1134 return false;
1135}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001136bool
1137CommandInterpreter::RemoveUser (const char *alias_name)
1138{
1139 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1140 if (pos != m_user_dict.end())
1141 {
1142 m_user_dict.erase(pos);
1143 return true;
1144 }
1145 return false;
1146}
1147
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001148void
1149CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1150{
1151 help_string.Printf ("'%s", command_name);
1152 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1153
Sean Callanan9a028512012-08-09 00:50:26 +00001154 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155 {
1156 OptionArgVector *options = option_arg_vector_sp.get();
Andy Gibbsa297a972013-06-19 19:04:53 +00001157 for (size_t i = 0; i < options->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001158 {
1159 OptionArgPair cur_option = (*options)[i];
1160 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001161 OptionArgValue value_pair = cur_option.second;
1162 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001163 if (opt.compare("<argument>") == 0)
1164 {
1165 help_string.Printf (" %s", value.c_str());
1166 }
1167 else
1168 {
1169 help_string.Printf (" %s", opt.c_str());
1170 if ((value.compare ("<no-argument>") != 0)
1171 && (value.compare ("<need-argument") != 0))
1172 {
1173 help_string.Printf (" %s", value.c_str());
1174 }
1175 }
1176 }
1177 }
1178
1179 help_string.Printf ("'");
1180}
1181
Greg Clayton12fc3e02010-08-26 22:05:43 +00001182size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001183CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1184{
1185 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001186 CommandObject::CommandMap::const_iterator end = dict.end();
1187 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001188
Greg Clayton12fc3e02010-08-26 22:05:43 +00001189 for (pos = dict.begin(); pos != end; ++pos)
1190 {
1191 size_t len = pos->first.size();
1192 if (max_len < len)
1193 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001195 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001196}
1197
1198void
Enrico Granata223383e2011-08-16 23:24:13 +00001199CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001200 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001201{
Kate Stonea487aa42015-01-15 00:52:41 +00001202 const char * help_prologue = GetDebugger().GetIOHandlerHelpPrologue();
1203 if (help_prologue != NULL)
1204 {
1205 OutputFormattedHelpText(result.GetOutputStream(), NULL, help_prologue);
1206 }
1207
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001208 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001209 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001210
1211 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001212 {
Kate Stonea487aa42015-01-15 00:52:41 +00001213 result.AppendMessage("Debugger commands:");
Enrico Granata223383e2011-08-16 23:24:13 +00001214 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001215
Enrico Granata223383e2011-08-16 23:24:13 +00001216 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1217 {
Kate Stonea487aa42015-01-15 00:52:41 +00001218 if (!(cmd_types & eCommandTypesHidden) && (pos->first.compare(0, 1, "_") == 0))
1219 continue;
1220
Enrico Granata223383e2011-08-16 23:24:13 +00001221 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1222 max_len);
1223 }
1224 result.AppendMessage("");
1225
1226 }
1227
Greg Clayton5521f992011-10-28 21:38:01 +00001228 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001229 {
Kate Stonea487aa42015-01-15 00:52:41 +00001230 result.AppendMessageWithFormat("Current command abbreviations "
1231 "(type '%shelp command alias' for more info):\n",
1232 GetCommandPrefix());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001233 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001234 max_len = FindLongestCommandWord (m_alias_dict);
1235
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001236 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1237 {
1238 StreamString sstr;
1239 StreamString translation_and_help;
1240 std::string entry_name = pos->first;
1241 std::string second_entry = pos->second.get()->GetCommandName();
1242 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1243
1244 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1245 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1246 translation_and_help.GetData(), max_len);
1247 }
1248 result.AppendMessage("");
1249 }
1250
Greg Clayton5521f992011-10-28 21:38:01 +00001251 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001252 {
Kate Stonea487aa42015-01-15 00:52:41 +00001253 result.AppendMessage ("Current user-defined commands:");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001254 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001255 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001256 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1257 {
Enrico Granata223383e2011-08-16 23:24:13 +00001258 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1259 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001260 }
1261 result.AppendMessage("");
1262 }
1263
Kate Stonea487aa42015-01-15 00:52:41 +00001264 result.AppendMessageWithFormat("For more information on any command, type '%shelp <command-name>'.\n",
1265 GetCommandPrefix());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001266}
1267
Caroline Tice844d2302010-12-09 22:52:49 +00001268CommandObject *
1269CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001270{
Caroline Tice844d2302010-12-09 22:52:49 +00001271 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1272 // eventually be invoked by the given command line.
1273
Ed Masted78c9572014-04-20 00:31:37 +00001274 CommandObject *cmd_obj = nullptr;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001275 size_t start = command_string.find_first_not_of (k_white_space);
Caroline Tice844d2302010-12-09 22:52:49 +00001276 size_t end = 0;
1277 bool done = false;
1278 while (!done)
1279 {
1280 if (start != std::string::npos)
1281 {
1282 // Get the next word from command_string.
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001283 end = command_string.find_first_of (k_white_space, start);
Caroline Tice844d2302010-12-09 22:52:49 +00001284 if (end == std::string::npos)
1285 end = command_string.size();
1286 std::string cmd_word = command_string.substr (start, end - start);
1287
Ed Masted78c9572014-04-20 00:31:37 +00001288 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001289 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1290 // command or alias.
1291 cmd_obj = GetCommandObject (cmd_word.c_str());
1292 else if (cmd_obj->IsMultiwordObject ())
1293 {
1294 // 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 +00001295 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001296 if (sub_cmd_obj)
1297 cmd_obj = sub_cmd_obj;
1298 else // cmd_word was not a valid sub-command word, so we are donee
1299 done = true;
1300 }
1301 else
1302 // We have a cmd_obj and it is not a multi-word object, so we are done.
1303 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001304
Caroline Tice844d2302010-12-09 22:52:49 +00001305 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1306 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1307 // next word.
1308
1309 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1310 done = true;
1311 else
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001312 start = command_string.find_first_not_of (k_white_space, end);
Caroline Tice844d2302010-12-09 22:52:49 +00001313 }
1314 else
1315 // Unable to find any more words.
1316 done = true;
1317 }
1318
1319 if (end == command_string.size())
1320 command_string.clear();
1321 else
1322 command_string = command_string.substr(end);
1323
1324 return cmd_obj;
1325}
1326
Greg Clayton5521f992011-10-28 21:38:01 +00001327static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001328static void
1329StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001330{
Greg Clayton51964162011-10-25 00:36:27 +00001331 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001332 {
Greg Clayton51964162011-10-25 00:36:27 +00001333 size_t pos = s.find_first_not_of (k_white_space);
1334 if (pos == std::string::npos)
1335 s.clear();
1336 else if (pos == 0)
1337 return;
1338 s.erase (0, pos);
1339 }
1340}
1341
Greg Clayton93c62e62011-11-09 23:25:03 +00001342static size_t
1343FindArgumentTerminator (const std::string &s)
1344{
Greg Clayton93c62e62011-11-09 23:25:03 +00001345 const size_t s_len = s.size();
1346 size_t offset = 0;
1347 while (offset < s_len)
1348 {
1349 size_t pos = s.find ("--", offset);
1350 if (pos == std::string::npos)
1351 break;
1352 if (pos > 0)
1353 {
1354 if (isspace(s[pos-1]))
1355 {
1356 // Check if the string ends "\s--" (where \s is a space character)
1357 // or if we have "\s--\s".
1358 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1359 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001360 return pos;
1361 }
1362 }
1363 }
1364 offset = pos + 2;
1365 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001366 return std::string::npos;
1367}
1368
Greg Clayton51964162011-10-25 00:36:27 +00001369static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001370ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001371{
Greg Clayton5521f992011-10-28 21:38:01 +00001372 command.clear();
1373 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001374 StripLeadingSpaces (command_string);
1375
1376 bool result = false;
1377 quote_char = '\0';
1378
1379 if (!command_string.empty())
1380 {
1381 const char first_char = command_string[0];
1382 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001383 {
Greg Clayton51964162011-10-25 00:36:27 +00001384 quote_char = first_char;
1385 const size_t end_quote_pos = command_string.find (quote_char, 1);
1386 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001387 {
Greg Clayton5521f992011-10-28 21:38:01 +00001388 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001389 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001390 }
1391 else
1392 {
Greg Clayton5521f992011-10-28 21:38:01 +00001393 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001394 if (end_quote_pos + 1 < command_string.size())
1395 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1396 else
1397 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001398 }
Caroline Tice844d2302010-12-09 22:52:49 +00001399 }
1400 else
1401 {
Greg Clayton51964162011-10-25 00:36:27 +00001402 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1403 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001404 {
Greg Clayton5521f992011-10-28 21:38:01 +00001405 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001406 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001407 }
1408 else
1409 {
Greg Clayton5521f992011-10-28 21:38:01 +00001410 command.assign (command_string, 0, first_space_pos);
1411 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001412 }
Caroline Tice844d2302010-12-09 22:52:49 +00001413 }
Greg Clayton51964162011-10-25 00:36:27 +00001414 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001415 }
Greg Clayton5521f992011-10-28 21:38:01 +00001416
1417
1418 if (!command.empty())
1419 {
1420 // actual commands can't start with '-' or '_'
1421 if (command[0] != '-' && command[0] != '_')
1422 {
1423 size_t pos = command.find_first_not_of(k_valid_command_chars);
1424 if (pos > 0 && pos != std::string::npos)
1425 {
1426 suffix.assign (command.begin() + pos, command.end());
1427 command.erase (pos);
1428 }
1429 }
1430 }
Greg Clayton51964162011-10-25 00:36:27 +00001431
1432 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001433}
1434
Greg Clayton5521f992011-10-28 21:38:01 +00001435CommandObject *
1436CommandInterpreter::BuildAliasResult (const char *alias_name,
1437 std::string &raw_input_string,
1438 std::string &alias_result,
1439 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001440{
Ed Masted78c9572014-04-20 00:31:37 +00001441 CommandObject *alias_cmd_obj = nullptr;
Pavel Labath00b7f952015-03-02 12:46:22 +00001442 Args cmd_args (raw_input_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001443 alias_cmd_obj = GetCommandObject (alias_name);
1444 StreamString result_str;
1445
1446 if (alias_cmd_obj)
1447 {
1448 std::string alias_name_str = alias_name;
1449 if ((cmd_args.GetArgumentCount() == 0)
1450 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1451 cmd_args.Unshift (alias_name);
1452
1453 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1454 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1455
1456 if (option_arg_vector_sp.get())
1457 {
1458 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1459
Andy Gibbsa297a972013-06-19 19:04:53 +00001460 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Caroline Tice844d2302010-12-09 22:52:49 +00001461 {
1462 OptionArgPair option_pair = (*option_arg_vector)[i];
1463 OptionArgValue value_pair = option_pair.second;
1464 int value_type = value_pair.first;
1465 std::string option = option_pair.first;
1466 std::string value = value_pair.second;
1467 if (option.compare ("<argument>") == 0)
1468 result_str.Printf (" %s", value.c_str());
1469 else
1470 {
1471 result_str.Printf (" %s", option.c_str());
Ted Woodwarde7e8e3c2015-04-06 21:55:14 +00001472 if (value_type != OptionParser::eNoArgument)
Caroline Tice844d2302010-12-09 22:52:49 +00001473 {
Ted Woodwarde7e8e3c2015-04-06 21:55:14 +00001474 if (value_type != OptionParser::eOptionalArgument)
1475 result_str.Printf (" ");
Caroline Tice844d2302010-12-09 22:52:49 +00001476 int index = GetOptionArgumentPosition (value.c_str());
1477 if (index == 0)
1478 result_str.Printf ("%s", value.c_str());
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001479 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Caroline Tice844d2302010-12-09 22:52:49 +00001480 {
1481
1482 result.AppendErrorWithFormat
1483 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1484 index);
1485 result.SetStatus (eReturnStatusFailed);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001486 return nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001487 }
1488 else
1489 {
1490 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1491 if (strpos != std::string::npos)
1492 raw_input_string = raw_input_string.erase (strpos,
1493 strlen (cmd_args.GetArgumentAtIndex (index)));
1494 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1495 }
1496 }
1497 }
1498 }
1499 }
1500
1501 alias_result = result_str.GetData();
1502 }
Greg Clayton5521f992011-10-28 21:38:01 +00001503 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001504}
1505
Greg Clayton5a314712011-10-14 07:41:33 +00001506Error
1507CommandInterpreter::PreprocessCommand (std::string &command)
1508{
1509 // The command preprocessor needs to do things to the command
1510 // line before any parsing of arguments or anything else is done.
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001511 // The only current stuff that gets preprocessed is anything enclosed
Greg Clayton5a314712011-10-14 07:41:33 +00001512 // in backtick ('`') characters is evaluated as an expression and
1513 // the result of the expression must be a scalar that can be substituted
1514 // into the command. An example would be:
1515 // (lldb) memory read `$rsp + 20`
1516 Error error; // Error for any expressions that might not evaluate
1517 size_t start_backtick;
1518 size_t pos = 0;
1519 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1520 {
1521 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1522 {
1523 // The backtick was preceeded by a '\' character, remove the slash
1524 // and don't treat the backtick as the start of an expression
1525 command.erase(start_backtick-1, 1);
1526 // No need to add one to start_backtick since we just deleted a char
1527 pos = start_backtick;
1528 }
1529 else
1530 {
1531 const size_t expr_content_start = start_backtick + 1;
1532 const size_t end_backtick = command.find ('`', expr_content_start);
1533 if (end_backtick == std::string::npos)
1534 return error;
1535 else if (end_backtick == expr_content_start)
1536 {
1537 // Empty expression (two backticks in a row)
1538 command.erase (start_backtick, 2);
1539 }
1540 else
1541 {
1542 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1543
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001544 ExecutionContext exe_ctx(GetExecutionContext());
1545 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001546 // Get a dummy target to allow for calculator mode while processing backticks.
1547 // This also helps break the infinite loop caused when target is null.
1548 if (!target)
Jim Ingham893c9322014-11-22 01:42:44 +00001549 target = m_debugger.GetDummyTarget();
Greg Clayton5a314712011-10-14 07:41:33 +00001550 if (target)
1551 {
Greg Clayton5a314712011-10-14 07:41:33 +00001552 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001553
Jim Ingham35e1bda2012-10-16 21:41:58 +00001554 EvaluateExpressionOptions options;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00001555 options.SetCoerceToId(false);
1556 options.SetUnwindOnError(true);
1557 options.SetIgnoreBreakpoints(true);
1558 options.SetKeepInMemory(false);
1559 options.SetTryAllThreads(true);
1560 options.SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001561
Jim Ingham1624a2d2014-05-05 02:26:40 +00001562 ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granataca0e5ad2014-10-09 23:09:40 +00001563 exe_ctx.GetFramePtr(),
1564 expr_result_valobj_sp,
1565 options);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001566
Jim Ingham8646d3c2014-05-05 02:47:44 +00001567 if (expr_result == eExpressionCompleted)
Greg Clayton5a314712011-10-14 07:41:33 +00001568 {
1569 Scalar scalar;
Enrico Granataca0e5ad2014-10-09 23:09:40 +00001570 if (expr_result_valobj_sp)
1571 expr_result_valobj_sp = expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(expr_result_valobj_sp->GetDynamicValueType(), true);
Greg Clayton5a314712011-10-14 07:41:33 +00001572 if (expr_result_valobj_sp->ResolveValue (scalar))
1573 {
1574 command.erase (start_backtick, end_backtick - start_backtick + 1);
1575 StreamString value_strm;
1576 const bool show_type = false;
1577 scalar.GetValue (&value_strm, show_type);
1578 size_t value_string_size = value_strm.GetSize();
1579 if (value_string_size)
1580 {
1581 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1582 pos = start_backtick + value_string_size;
1583 continue;
1584 }
1585 else
1586 {
1587 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1588 }
1589 }
1590 else
1591 {
1592 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1593 }
1594 }
1595 else
1596 {
1597 if (expr_result_valobj_sp)
1598 error = expr_result_valobj_sp->GetError();
1599 if (error.Success())
1600 {
1601
1602 switch (expr_result)
1603 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00001604 case eExpressionSetupError:
Greg Clayton5a314712011-10-14 07:41:33 +00001605 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1606 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001607 case eExpressionParseError:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001608 error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str());
1609 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001610 case eExpressionResultUnavailable:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001611 error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str());
Jim Ingham8646d3c2014-05-05 02:47:44 +00001612 case eExpressionCompleted:
Greg Clayton5a314712011-10-14 07:41:33 +00001613 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001614 case eExpressionDiscarded:
Greg Clayton5a314712011-10-14 07:41:33 +00001615 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1616 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001617 case eExpressionInterrupted:
Greg Clayton5a314712011-10-14 07:41:33 +00001618 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1619 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001620 case eExpressionHitBreakpoint:
Jim Ingham184e9812013-01-15 02:47:48 +00001621 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1622 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001623 case eExpressionTimedOut:
Greg Clayton5a314712011-10-14 07:41:33 +00001624 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1625 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001626 case eExpressionStoppedForDebug:
Greg Claytonc28ce782013-11-08 23:38:26 +00001627 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1628 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001629 }
1630 }
1631 }
1632 }
1633 }
1634 if (error.Fail())
1635 break;
1636 }
1637 }
1638 return error;
1639}
1640
1641
Caroline Tice844d2302010-12-09 22:52:49 +00001642bool
1643CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001644 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001645 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001646 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001647 bool repeat_on_empty_command,
1648 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001649
Caroline Tice844d2302010-12-09 22:52:49 +00001650{
Jim Inghame16c50a2011-02-18 00:54:25 +00001651
Caroline Tice844d2302010-12-09 22:52:49 +00001652 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001653 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001654
Greg Clayton5160ce52013-03-27 23:08:40 +00001655 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001656 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1657
1658 // Make a scoped cleanup object that will clear the crash description string
1659 // on exit of this function.
Ed Masted78c9572014-04-20 00:31:37 +00001660 lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001661
Caroline Tice844d2302010-12-09 22:52:49 +00001662 if (log)
1663 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001664
Jim Ingham30244832010-11-04 23:08:45 +00001665 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1666
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001667 if (!no_context_switching)
1668 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001669
Enrico Granata5f5ab602012-05-31 01:09:06 +00001670 bool add_to_history;
1671 if (lazy_add_to_history == eLazyBoolCalculate)
1672 add_to_history = (m_command_source_depth == 0);
1673 else
1674 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1675
Jim Inghame16c50a2011-02-18 00:54:25 +00001676 bool empty_command = false;
1677 bool comment_command = false;
1678 if (command_string.empty())
1679 empty_command = true;
1680 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001681 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001682 const char *k_space_characters = "\t\n\v\f\r ";
1683
1684 size_t non_space = command_string.find_first_not_of (k_space_characters);
1685 // Check for empty line or comment line (lines whose first
1686 // non-space character is the comment character for this interpreter)
1687 if (non_space == std::string::npos)
1688 empty_command = true;
1689 else if (command_string[non_space] == m_comment_char)
1690 comment_command = true;
Enrico Granata7594f142013-06-17 22:51:50 +00001691 else if (command_string[non_space] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001692 {
Enrico Granata7594f142013-06-17 22:51:50 +00001693 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
Ed Masted78c9572014-04-20 00:31:37 +00001694 if (history_string == nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001695 {
1696 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1697 result.SetStatus(eReturnStatusFailed);
1698 return false;
1699 }
1700 add_to_history = false;
1701 command_string = history_string;
1702 original_command_string = history_string;
1703 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001704 }
1705
1706 if (empty_command)
1707 {
1708 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001709 {
Enrico Granata7594f142013-06-17 22:51:50 +00001710 if (m_command_history.IsEmpty())
Jim Inghame16c50a2011-02-18 00:54:25 +00001711 {
1712 result.AppendError ("empty command");
1713 result.SetStatus(eReturnStatusFailed);
1714 return false;
1715 }
1716 else
1717 {
1718 command_line = m_repeat_command.c_str();
1719 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001720 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001721 if (m_repeat_command.empty())
1722 {
1723 result.AppendErrorWithFormat("No auto repeat.\n");
1724 result.SetStatus (eReturnStatusFailed);
1725 return false;
1726 }
1727 }
1728 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001729 }
1730 else
1731 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001732 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1733 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001734 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001735 }
1736 else if (comment_command)
1737 {
1738 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1739 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001740 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001741
Greg Clayton5a314712011-10-14 07:41:33 +00001742
1743 Error error (PreprocessCommand (command_string));
1744
1745 if (error.Fail())
1746 {
1747 result.AppendError (error.AsCString());
1748 result.SetStatus(eReturnStatusFailed);
1749 return false;
1750 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001751
Caroline Tice844d2302010-12-09 22:52:49 +00001752 // Phase 1.
1753
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001754 // Before we do ANY kind of argument processing, we need to figure out what
1755 // the real/final command object is for the specified command. This gets
1756 // complicated by the fact that the user could have specified an alias, and,
1757 // in translating the alias, there may also be command options and/or even
1758 // data (including raw text strings) that need to be found and inserted into
1759 // the command line as part of the translation. So this first step is plain
1760 // look-up and replacement, resulting in:
1761 // 1. the command object whose Execute method will actually be called
1762 // 2. a revised command string, with all substitutions and replacements
1763 // taken care of
1764 // From 1 above, we can determine whether the Execute function wants raw
1765 // input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001766
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001767 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
Caroline Tice844d2302010-12-09 22:52:49 +00001768
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001769 // Although the user may have abbreviated the command, the command_string now
1770 // has the command expanded to the full name. For example, if the input
1771 // was "br s -n main", command_string is now "breakpoint set -n main".
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001772
Caroline Tice844d2302010-12-09 22:52:49 +00001773 if (log)
1774 {
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001775 log->Printf("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1776 log->Printf("HandleCommand, (revised) command_string: '%s'", command_string.c_str());
1777 const bool wants_raw_input = (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1778 log->Printf("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
Caroline Tice844d2302010-12-09 22:52:49 +00001779 }
1780
1781 // Phase 2.
1782 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1783 // CommandObject, with the appropriate arguments.
1784
Ed Masted78c9572014-04-20 00:31:37 +00001785 if (cmd_obj != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001786 {
1787 if (add_to_history)
1788 {
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001789 Args command_args (command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001790 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
Ed Masted78c9572014-04-20 00:31:37 +00001791 if (repeat_command != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001792 m_repeat_command.assign(repeat_command);
1793 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001794 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001795
Enrico Granata7594f142013-06-17 22:51:50 +00001796 m_command_history.AppendString (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001797 }
1798
Caroline Tice01274c02010-12-11 08:16:56 +00001799 std::string remainder;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001800 const std::size_t actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001801 if (actual_cmd_name_len < command_string.length())
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001802 remainder = command_string.substr (actual_cmd_name_len);
Caroline Tice844d2302010-12-09 22:52:49 +00001803
1804 // Remove any initial spaces
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001805 size_t pos = remainder.find_first_not_of (k_white_space);
Caroline Tice844d2302010-12-09 22:52:49 +00001806 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001807 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001808
1809 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001810 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001811
Jim Ingham5a988412012-06-08 21:56:10 +00001812 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001813 }
1814 else
1815 {
1816 // We didn't find the first command object, so complete the first argument.
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001817 Args command_args (command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001818 StringList matches;
1819 int num_matches;
1820 int cursor_index = 0;
1821 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1822 bool word_complete;
1823 num_matches = HandleCompletionMatches (command_args,
1824 cursor_index,
1825 cursor_char_position,
1826 0,
1827 -1,
1828 word_complete,
1829 matches);
1830
1831 if (num_matches > 0)
1832 {
1833 std::string error_msg;
1834 error_msg.assign ("ambiguous command '");
1835 error_msg.append(command_args.GetArgumentAtIndex(0));
1836 error_msg.append ("'.");
1837
1838 error_msg.append (" Possible completions:");
1839 for (int i = 0; i < num_matches; i++)
1840 {
1841 error_msg.append ("\n\t");
1842 error_msg.append (matches.GetStringAtIndex (i));
1843 }
1844 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001845 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001846 }
1847 else
1848 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1849
1850 result.SetStatus (eReturnStatusFailed);
1851 }
1852
Jason Molendabfb36ff2011-08-25 00:20:04 +00001853 if (log)
1854 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1855
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001856 return result.Succeeded();
1857}
1858
1859int
1860CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1861 int &cursor_index,
1862 int &cursor_char_position,
1863 int match_start_point,
1864 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001865 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001866 StringList &matches)
1867{
1868 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001869 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001870
1871 // For any of the command completions a unique match will be a complete word.
1872 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001873
1874 if (cursor_index == -1)
1875 {
1876 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001877 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001878 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1879 }
1880 else if (cursor_index == 0)
1881 {
1882 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001883 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001884 num_command_matches = matches.GetSize();
1885
1886 if (num_command_matches == 1
1887 && cmd_obj && cmd_obj->IsMultiwordObject()
Ed Masted78c9572014-04-20 00:31:37 +00001888 && matches.GetStringAtIndex(0) != nullptr
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001889 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1890 {
Greg Clayton765d2e22013-12-10 19:14:04 +00001891 if (parsed_line.GetArgumentCount() == 1)
1892 {
1893 word_complete = true;
1894 }
1895 else
1896 {
1897 look_for_subcommand = true;
1898 num_command_matches = 0;
1899 matches.DeleteStringAtIndex(0);
1900 parsed_line.AppendArgument ("");
1901 cursor_index++;
1902 cursor_char_position = 0;
1903 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001904 }
1905 }
1906
1907 if (cursor_index > 0 || look_for_subcommand)
1908 {
1909 // We are completing further on into a commands arguments, so find the command and tell it
1910 // to complete the command.
1911 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001912 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Ed Masted78c9572014-04-20 00:31:37 +00001913 if (command_object == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001914 {
1915 return 0;
1916 }
1917 else
1918 {
1919 parsed_line.Shift();
1920 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001921 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001922 cursor_index,
1923 cursor_char_position,
1924 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001925 max_return_elements,
1926 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001927 matches);
1928 }
1929 }
1930
1931 return num_command_matches;
1932
1933}
1934
1935int
1936CommandInterpreter::HandleCompletion (const char *current_line,
1937 const char *cursor,
1938 const char *last_char,
1939 int match_start_point,
1940 int max_return_elements,
1941 StringList &matches)
1942{
1943 // We parse the argument up to the cursor, so the last argument in parsed_line is
1944 // the one containing the cursor, and the cursor is after the last character.
1945
Pavel Labath00b7f952015-03-02 12:46:22 +00001946 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
1947 Args partial_parsed_line(llvm::StringRef(current_line, cursor - current_line));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001948
Jim Inghama5a97eb2011-07-12 03:12:18 +00001949 // Don't complete comments, and if the line we are completing is just the history repeat character,
1950 // substitute the appropriate history line.
1951 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1952 if (first_arg)
1953 {
1954 if (first_arg[0] == m_comment_char)
1955 return 0;
Enrico Granata7594f142013-06-17 22:51:50 +00001956 else if (first_arg[0] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001957 {
Enrico Granata7594f142013-06-17 22:51:50 +00001958 const char *history_string = m_command_history.FindString (first_arg);
Ed Masted78c9572014-04-20 00:31:37 +00001959 if (history_string != nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001960 {
1961 matches.Clear();
1962 matches.InsertStringAtIndex(0, history_string);
1963 return -2;
1964 }
1965 else
1966 return 0;
1967
1968 }
1969 }
1970
1971
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001972 int num_args = partial_parsed_line.GetArgumentCount();
1973 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1974 int cursor_char_position;
1975
1976 if (cursor_index == -1)
1977 cursor_char_position = 0;
1978 else
1979 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00001980
1981 if (cursor > current_line && cursor[-1] == ' ')
1982 {
1983 // We are just after a space. If we are in an argument, then we will continue
1984 // parsing, but if we are between arguments, then we have to complete whatever the next
1985 // element would be.
1986 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1987 // protected by a quote) then the space will also be in the parsed argument...
1988
1989 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1990 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1991 {
Greg Clayton765d2e22013-12-10 19:14:04 +00001992 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
Jim Inghamfe0c4252010-12-14 19:56:01 +00001993 cursor_index++;
1994 cursor_char_position = 0;
1995 }
1996 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001997
1998 int num_command_matches;
1999
2000 matches.Clear();
2001
2002 // Only max_return_elements == -1 is supported at present:
2003 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00002004 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00002005 num_command_matches = HandleCompletionMatches (parsed_line,
2006 cursor_index,
2007 cursor_char_position,
2008 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002009 max_return_elements,
2010 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002011 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002012
2013 if (num_command_matches <= 0)
2014 return num_command_matches;
2015
2016 if (num_args == 0)
2017 {
2018 // If we got an empty string, insert nothing.
2019 matches.InsertStringAtIndex(0, "");
2020 }
2021 else
2022 {
2023 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2024 // put an empty string in element 0.
2025 std::string command_partial_str;
2026 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002027 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2028 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002029
2030 std::string common_prefix;
2031 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002032 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002033
2034 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002035 // Only do this if the completer told us this was a complete word, however...
2036 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002037 {
2038 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2039 if (quote_char != '\0')
2040 common_prefix.push_back(quote_char);
2041
2042 common_prefix.push_back(' ');
2043 }
2044 common_prefix.erase (0, partial_name_len);
2045 matches.InsertStringAtIndex(0, common_prefix.c_str());
2046 }
2047 return num_command_matches;
2048}
2049
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002050
2051CommandInterpreter::~CommandInterpreter ()
2052{
2053}
2054
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002055void
Greg Clayton44d93782014-01-27 23:43:24 +00002056CommandInterpreter::UpdatePrompt (const char *new_prompt)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002057{
Greg Clayton44d93782014-01-27 23:43:24 +00002058 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2059 BroadcastEvent (prompt_change_event_sp);
2060 if (m_command_io_handler_sp)
2061 m_command_io_handler_sp->SetPrompt(new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002062}
2063
Jim Ingham97a6dc72010-10-04 19:49:29 +00002064
2065bool
2066CommandInterpreter::Confirm (const char *message, bool default_answer)
2067{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002068 // Check AutoConfirm first:
2069 if (m_debugger.GetAutoConfirm())
2070 return default_answer;
Greg Clayton44d93782014-01-27 23:43:24 +00002071
2072 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2073 message,
2074 default_answer);
2075 IOHandlerSP io_handler_sp (confirm);
2076 m_debugger.RunIOHandler (io_handler_sp);
2077 return confirm->GetResponse();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002078}
2079
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002080OptionArgVectorSP
2081CommandInterpreter::GetAliasOptions (const char *alias_name)
2082{
2083 OptionArgMap::iterator pos;
2084 OptionArgVectorSP ret_val;
2085
2086 std::string alias (alias_name);
2087
2088 if (HasAliasOptions())
2089 {
2090 pos = m_alias_options.find (alias);
2091 if (pos != m_alias_options.end())
2092 ret_val = pos->second;
2093 }
2094
2095 return ret_val;
2096}
2097
2098void
2099CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2100{
2101 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2102 if (pos != m_alias_options.end())
2103 {
2104 m_alias_options.erase (pos);
2105 }
2106}
2107
2108void
2109CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2110{
2111 m_alias_options[alias_name] = option_arg_vector_sp;
2112}
2113
2114bool
2115CommandInterpreter::HasCommands ()
2116{
2117 return (!m_command_dict.empty());
2118}
2119
2120bool
2121CommandInterpreter::HasAliases ()
2122{
2123 return (!m_alias_dict.empty());
2124}
2125
2126bool
2127CommandInterpreter::HasUserCommands ()
2128{
2129 return (!m_user_dict.empty());
2130}
2131
2132bool
2133CommandInterpreter::HasAliasOptions ()
2134{
2135 return (!m_alias_options.empty());
2136}
2137
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002138void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002139CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2140 const char *alias_name,
2141 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002142 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002143 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144{
2145 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002146
2147 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002148
Caroline Ticed9d63362010-12-07 19:58:26 +00002149 // Make sure that the alias name is the 0th element in cmd_args
2150 std::string alias_name_str = alias_name;
2151 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2152 cmd_args.Unshift (alias_name);
2153
2154 Args new_args (alias_cmd_obj->GetCommandName());
2155 if (new_args.GetArgumentCount() == 2)
2156 new_args.Shift();
2157
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002158 if (option_arg_vector_sp.get())
2159 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002160 if (wants_raw_input)
2161 {
2162 // We have a command that both has command options and takes raw input. Make *sure* it has a
2163 // " -- " in the right place in the raw_input_string.
2164 size_t pos = raw_input_string.find(" -- ");
2165 if (pos == std::string::npos)
2166 {
2167 // None found; assume it goes at the beginning of the raw input string
2168 raw_input_string.insert (0, " -- ");
2169 }
2170 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002171
2172 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002173 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002174 std::vector<bool> used (old_size + 1, false);
2175
2176 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002177
Andy Gibbsa297a972013-06-19 19:04:53 +00002178 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002179 {
2180 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002181 OptionArgValue value_pair = option_pair.second;
2182 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002183 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002184 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002185 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002186 {
2187 if (!wants_raw_input
2188 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2189 new_args.AppendArgument (value.c_str());
2190 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002191 else
2192 {
Virgile Belloe2607b52013-09-05 16:42:23 +00002193 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002194 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002195 if (value.compare ("<no-argument>") != 0)
2196 {
2197 int index = GetOptionArgumentPosition (value.c_str());
2198 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002199 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002200 // value was NOT a positional argument; must be a real value
Virgile Belloe2607b52013-09-05 16:42:23 +00002201 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002202 new_args.AppendArgument (value.c_str());
2203 else
2204 {
2205 char buffer[255];
2206 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2207 new_args.AppendArgument (buffer);
2208 }
2209
2210 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002211 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002212 {
2213 result.AppendErrorWithFormat
2214 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2215 index);
2216 result.SetStatus (eReturnStatusFailed);
2217 return;
2218 }
2219 else
2220 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002221 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2222 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2223 if (strpos != std::string::npos)
2224 {
2225 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2226 }
2227
Virgile Belloe2607b52013-09-05 16:42:23 +00002228 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002229 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2230 else
2231 {
2232 char buffer[255];
2233 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2234 cmd_args.GetArgumentAtIndex (index));
2235 new_args.AppendArgument (buffer);
2236 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002237 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002238 }
2239 }
2240 }
2241 }
2242
Andy Gibbsa297a972013-06-19 19:04:53 +00002243 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002244 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002245 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002246 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2247 }
2248
2249 cmd_args.Clear();
2250 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2251 }
2252 else
2253 {
2254 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002255 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2256 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2257 // input string.
2258 if (wants_raw_input)
2259 {
2260 cmd_args.Clear();
2261 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2262 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002263 return;
2264 }
2265
2266 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2267 return;
2268}
2269
2270
2271int
2272CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2273{
2274 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2275 // of zero.
2276
2277 char *cptr = (char *) in_string;
2278
2279 // Does it start with '%'
2280 if (cptr[0] == '%')
2281 {
2282 ++cptr;
2283
2284 // Is the rest of it entirely digits?
2285 if (isdigit (cptr[0]))
2286 {
2287 const char *start = cptr;
2288 while (isdigit (cptr[0]))
2289 ++cptr;
2290
2291 // We've gotten to the end of the digits; are we at the end of the string?
2292 if (cptr[0] == '\0')
2293 position = atoi (start);
2294 }
2295 }
2296
2297 return position;
2298}
2299
2300void
2301CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2302{
Jim Ingham16e0c682011-08-12 23:34:31 +00002303 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002304 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002305 {
Greg Clayton14a35512011-09-11 00:01:44 +00002306 // In the current working directory we don't load any program specific
2307 // .lldbinit files, we only look for a "./.lldbinit" file.
2308 if (m_skip_lldbinit_files)
2309 return;
2310
2311 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002312 }
Greg Clayton14a35512011-09-11 00:01:44 +00002313 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002314 {
Greg Clayton14a35512011-09-11 00:01:44 +00002315 // If we aren't looking in the current working directory we are looking
2316 // in the home directory. We will first see if there is an application
2317 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2318 // "-" and the name of the program. If this file doesn't exist, we fall
2319 // back to just the "~/.lldbinit" file. We also obey any requests to not
2320 // load the init files.
Zachary Turnera21fee02014-08-21 21:49:24 +00002321 llvm::SmallString<64> home_dir_path;
2322 llvm::sys::path::home_directory(home_dir_path);
2323 FileSpec profilePath(home_dir_path.c_str(), false);
Zachary Turner9e757b72014-07-28 16:45:05 +00002324 profilePath.AppendPathComponent(".lldbinit");
2325 std::string init_file_path = profilePath.GetPath();
Greg Clayton14a35512011-09-11 00:01:44 +00002326
2327 if (m_skip_app_init_files == false)
2328 {
Zachary Turnera21fee02014-08-21 21:49:24 +00002329 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
Greg Clayton14a35512011-09-11 00:01:44 +00002330 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002331
Greg Clayton14a35512011-09-11 00:01:44 +00002332 if (program_name)
2333 {
2334 char program_init_file_name[PATH_MAX];
Zachary Turner9e757b72014-07-28 16:45:05 +00002335 ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path.c_str(), program_name);
Greg Clayton14a35512011-09-11 00:01:44 +00002336 init_file.SetFile (program_init_file_name, true);
2337 if (!init_file.Exists())
2338 init_file.Clear();
2339 }
2340 }
2341
2342 if (!init_file && !m_skip_lldbinit_files)
Zachary Turner9e757b72014-07-28 16:45:05 +00002343 init_file.SetFile (init_file_path.c_str(), false);
Greg Clayton14a35512011-09-11 00:01:44 +00002344 }
2345
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002346 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2347 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2348
2349 if (init_file.Exists())
2350 {
Greg Clayton44d93782014-01-27 23:43:24 +00002351 const bool saved_batch = SetBatchCommandMode (true);
Jim Ingham26c7bf92014-10-11 00:38:27 +00002352 CommandInterpreterRunOptions options;
2353 options.SetSilent (true);
2354 options.SetStopOnError (false);
2355 options.SetStopOnContinue (true);
2356
Greg Clayton340b0302014-02-05 17:57:57 +00002357 HandleCommandsFromFile (init_file,
Ed Masted78c9572014-04-20 00:31:37 +00002358 nullptr, // Execution context
Jim Ingham26c7bf92014-10-11 00:38:27 +00002359 options,
Greg Clayton340b0302014-02-05 17:57:57 +00002360 result);
Greg Clayton44d93782014-01-27 23:43:24 +00002361 SetBatchCommandMode (saved_batch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002362 }
2363 else
2364 {
2365 // nothing to be done if the file doesn't exist
2366 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2367 }
2368}
2369
Kate Stonea487aa42015-01-15 00:52:41 +00002370const char *
2371CommandInterpreter::GetCommandPrefix()
2372{
2373 const char * prefix = GetDebugger().GetIOHandlerCommandPrefix();
2374 return prefix == NULL ? "" : prefix;
2375}
2376
Greg Clayton8b82f082011-04-12 05:54:46 +00002377PlatformSP
2378CommandInterpreter::GetPlatform (bool prefer_target_platform)
2379{
2380 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002381 if (prefer_target_platform)
2382 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002383 ExecutionContext exe_ctx(GetExecutionContext());
2384 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002385 if (target)
2386 platform_sp = target->GetPlatform();
2387 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002388
2389 if (!platform_sp)
2390 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2391 return platform_sp;
2392}
2393
Jim Inghame16c50a2011-02-18 00:54:25 +00002394void
Jim Inghambad87fe2011-03-11 01:51:49 +00002395CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham26c7bf92014-10-11 00:38:27 +00002396 ExecutionContext *override_context,
2397 CommandInterpreterRunOptions &options,
Jim Inghame16c50a2011-02-18 00:54:25 +00002398 CommandReturnObject &result)
2399{
2400 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002401
2402 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2403 // Make sure you reset this value anywhere you return from the function.
2404
2405 bool old_async_execution = m_debugger.GetAsyncExecution();
2406
2407 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2408 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2409
Ed Masted78c9572014-04-20 00:31:37 +00002410 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002411 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002412
Jim Ingham26c7bf92014-10-11 00:38:27 +00002413 if (!options.GetStopOnContinue())
Jim Inghame16c50a2011-02-18 00:54:25 +00002414 {
2415 m_debugger.SetAsyncExecution (false);
2416 }
2417
Andy Gibbsa297a972013-06-19 19:04:53 +00002418 for (size_t idx = 0; idx < num_lines; idx++)
Jim Inghame16c50a2011-02-18 00:54:25 +00002419 {
2420 const char *cmd = commands.GetStringAtIndex(idx);
2421 if (cmd[0] == '\0')
2422 continue;
2423
Jim Ingham26c7bf92014-10-11 00:38:27 +00002424 if (options.GetEchoCommands())
Jim Inghame16c50a2011-02-18 00:54:25 +00002425 {
2426 result.AppendMessageWithFormat ("%s %s\n",
Greg Clayton44d93782014-01-27 23:43:24 +00002427 m_debugger.GetPrompt(),
2428 cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002429 }
2430
Greg Clayton9d0402b2011-02-20 02:15:07 +00002431 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002432 // If override_context is not NULL, pass no_context_switching = true for
2433 // HandleCommand() since we updated our context already.
Jim Ingham076b7fc2013-05-02 23:15:37 +00002434
2435 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2436 // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here.
Jim Ingham26c7bf92014-10-11 00:38:27 +00002437 if (!options.GetAddToHistory())
Jim Ingham076b7fc2013-05-02 23:15:37 +00002438 m_command_source_depth++;
Jim Ingham26c7bf92014-10-11 00:38:27 +00002439 bool success = HandleCommand(cmd, options.m_add_to_history, tmp_result,
Ed Masted78c9572014-04-20 00:31:37 +00002440 nullptr, /* override_context */
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002441 true, /* repeat_on_empty_command */
Ed Masted78c9572014-04-20 00:31:37 +00002442 override_context != nullptr /* no_context_switching */);
Jim Ingham26c7bf92014-10-11 00:38:27 +00002443 if (!options.GetAddToHistory())
Jim Ingham076b7fc2013-05-02 23:15:37 +00002444 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002445
Jim Ingham26c7bf92014-10-11 00:38:27 +00002446 if (options.GetPrintResults())
Jim Inghame16c50a2011-02-18 00:54:25 +00002447 {
2448 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002449 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002450 }
2451
2452 if (!success || !tmp_result.Succeeded())
2453 {
Jim Inghama5038812012-04-24 02:25:07 +00002454 const char *error_msg = tmp_result.GetErrorData();
Ed Masted78c9572014-04-20 00:31:37 +00002455 if (error_msg == nullptr || error_msg[0] == '\0')
Jim Inghama5038812012-04-24 02:25:07 +00002456 error_msg = "<unknown error>.\n";
Jim Ingham26c7bf92014-10-11 00:38:27 +00002457 if (options.GetStopOnError())
Jim Inghame16c50a2011-02-18 00:54:25 +00002458 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002459 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s",
2460 (uint64_t)idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002461 result.SetStatus (eReturnStatusFailed);
2462 m_debugger.SetAsyncExecution (old_async_execution);
2463 return;
2464 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002465 else if (options.GetPrintResults())
Jim Inghame16c50a2011-02-18 00:54:25 +00002466 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002467 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s",
2468 (uint64_t)idx + 1,
Jim Inghame16c50a2011-02-18 00:54:25 +00002469 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002470 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002471 }
2472 }
2473
Caroline Tice969ed3d2011-05-02 20:41:46 +00002474 if (result.GetImmediateOutputStream())
2475 result.GetImmediateOutputStream()->Flush();
2476
2477 if (result.GetImmediateErrorStream())
2478 result.GetImmediateErrorStream()->Flush();
2479
Jim Inghame16c50a2011-02-18 00:54:25 +00002480 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2481 // could be running (for instance in Breakpoint Commands.
2482 // So we check the return value to see if it is has running in it.
2483 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2484 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2485 {
Jim Ingham26c7bf92014-10-11 00:38:27 +00002486 if (options.GetStopOnContinue())
Jim Inghame16c50a2011-02-18 00:54:25 +00002487 {
2488 // If we caused the target to proceed, and we're going to stop in that case, set the
2489 // status in our real result before returning. This is an error if the continue was not the
2490 // last command in the set of commands to be run.
2491 if (idx != num_lines - 1)
Deepak Panickal99fbc072014-03-03 15:39:47 +00002492 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n",
2493 (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002494 else
Deepak Panickal99fbc072014-03-03 15:39:47 +00002495 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002496
2497 result.SetStatus(tmp_result.GetStatus());
2498 m_debugger.SetAsyncExecution (old_async_execution);
2499
2500 return;
2501 }
2502 }
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002503
2504 // Also check for "stop on crash here:
2505 bool should_stop = false;
2506 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash())
2507 {
2508 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2509 if (target_sp)
2510 {
2511 ProcessSP process_sp (target_sp->GetProcessSP());
2512 if (process_sp)
2513 {
2514 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads())
2515 {
2516 StopReason reason = thread_sp->GetStopReason();
2517 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation)
2518 {
2519 should_stop = true;
2520 break;
2521 }
2522 }
2523 }
2524 }
2525 if (should_stop)
2526 {
2527 if (idx != num_lines - 1)
2528 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' stopped with a signal or exception.\n",
2529 (uint64_t)idx + 1, cmd);
2530 else
2531 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' stopped with a signal or exception.\n", (uint64_t)idx + 1, cmd);
2532
2533 result.SetStatus(tmp_result.GetStatus());
2534 m_debugger.SetAsyncExecution (old_async_execution);
2535
2536 return;
2537 }
2538 }
Jim Inghame16c50a2011-02-18 00:54:25 +00002539
2540 }
2541
2542 result.SetStatus (eReturnStatusSuccessFinishResult);
2543 m_debugger.SetAsyncExecution (old_async_execution);
2544
2545 return;
2546}
2547
Greg Clayton340b0302014-02-05 17:57:57 +00002548// Make flags that we can pass into the IOHandler so our delegates can do the right thing
2549enum {
2550 eHandleCommandFlagStopOnContinue = (1u << 0),
2551 eHandleCommandFlagStopOnError = (1u << 1),
2552 eHandleCommandFlagEchoCommand = (1u << 2),
Jim Ingham26c7bf92014-10-11 00:38:27 +00002553 eHandleCommandFlagPrintResult = (1u << 3),
2554 eHandleCommandFlagStopOnCrash = (1u << 4)
Greg Clayton340b0302014-02-05 17:57:57 +00002555};
2556
Jim Inghame16c50a2011-02-18 00:54:25 +00002557void
2558CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2559 ExecutionContext *context,
Jim Ingham26c7bf92014-10-11 00:38:27 +00002560 CommandInterpreterRunOptions &options,
Jim Inghame16c50a2011-02-18 00:54:25 +00002561 CommandReturnObject &result)
2562{
2563 if (cmd_file.Exists())
2564 {
Greg Clayton44d93782014-01-27 23:43:24 +00002565 StreamFileSP input_file_sp (new StreamFile());
2566
2567 std::string cmd_file_path = cmd_file.GetPath();
2568 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2569
2570 if (error.Success())
2571 {
2572 Debugger &debugger = GetDebugger();
2573
Greg Clayton340b0302014-02-05 17:57:57 +00002574 uint32_t flags = 0;
2575
Jim Ingham26c7bf92014-10-11 00:38:27 +00002576 if (options.m_stop_on_continue == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002577 {
2578 if (m_command_source_flags.empty())
2579 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002580 // Stop on continue by default
Greg Clayton340b0302014-02-05 17:57:57 +00002581 flags |= eHandleCommandFlagStopOnContinue;
2582 }
2583 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2584 {
2585 flags |= eHandleCommandFlagStopOnContinue;
2586 }
2587 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002588 else if (options.m_stop_on_continue == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002589 {
2590 flags |= eHandleCommandFlagStopOnContinue;
2591 }
2592
Jim Ingham26c7bf92014-10-11 00:38:27 +00002593 if (options.m_stop_on_error == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002594 {
2595 if (m_command_source_flags.empty())
2596 {
2597 if (GetStopCmdSourceOnError())
2598 flags |= eHandleCommandFlagStopOnError;
2599 }
2600 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2601 {
2602 flags |= eHandleCommandFlagStopOnError;
2603 }
2604 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002605 else if (options.m_stop_on_error == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002606 {
2607 flags |= eHandleCommandFlagStopOnError;
2608 }
2609
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002610 if (options.GetStopOnCrash())
2611 {
2612 if (m_command_source_flags.empty())
2613 {
2614 // Echo command by default
2615 flags |= eHandleCommandFlagStopOnCrash;
2616 }
2617 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash)
2618 {
2619 flags |= eHandleCommandFlagStopOnCrash;
2620 }
2621 }
2622
Jim Ingham26c7bf92014-10-11 00:38:27 +00002623 if (options.m_echo_commands == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002624 {
2625 if (m_command_source_flags.empty())
2626 {
2627 // Echo command by default
2628 flags |= eHandleCommandFlagEchoCommand;
2629 }
2630 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2631 {
2632 flags |= eHandleCommandFlagEchoCommand;
2633 }
2634 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002635 else if (options.m_echo_commands == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002636 {
2637 flags |= eHandleCommandFlagEchoCommand;
2638 }
2639
Jim Ingham26c7bf92014-10-11 00:38:27 +00002640 if (options.m_print_results == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002641 {
2642 if (m_command_source_flags.empty())
2643 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002644 // Print output by default
2645 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002646 }
Greg Claytone4e462c2014-02-05 21:03:22 +00002647 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
Greg Clayton340b0302014-02-05 17:57:57 +00002648 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002649 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002650 }
2651 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002652 else if (options.m_print_results == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002653 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002654 flags |= eHandleCommandFlagPrintResult;
2655 }
2656
2657 if (flags & eHandleCommandFlagPrintResult)
2658 {
Greg Clayton8ee67312014-02-05 21:46:20 +00002659 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
Greg Clayton340b0302014-02-05 17:57:57 +00002660 }
2661
2662 // Used for inheriting the right settings when "command source" might have
2663 // nested "command source" commands
Greg Claytone4e462c2014-02-05 21:03:22 +00002664 lldb::StreamFileSP empty_stream_sp;
Greg Clayton340b0302014-02-05 17:57:57 +00002665 m_command_source_flags.push_back(flags);
Greg Clayton44d93782014-01-27 23:43:24 +00002666 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00002667 IOHandler::Type::CommandInterpreter,
Greg Clayton44d93782014-01-27 23:43:24 +00002668 input_file_sp,
Greg Claytone4e462c2014-02-05 21:03:22 +00002669 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2670 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
Greg Clayton340b0302014-02-05 17:57:57 +00002671 flags,
Ed Masted78c9572014-04-20 00:31:37 +00002672 nullptr, // Pass in NULL for "editline_name" so no history is saved, or written
Greg Clayton8ee67312014-02-05 21:46:20 +00002673 debugger.GetPrompt(),
Kate Stonee30f11d2014-11-17 19:06:59 +00002674 NULL,
Greg Clayton44d93782014-01-27 23:43:24 +00002675 false, // Not multi-line
Kate Stonee30f11d2014-11-17 19:06:59 +00002676 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00002677 0,
Greg Clayton44d93782014-01-27 23:43:24 +00002678 *this));
Greg Clayton8ee67312014-02-05 21:46:20 +00002679 const bool old_async_execution = debugger.GetAsyncExecution();
2680
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002681 // Set synchronous execution if we are not stopping on continue
Greg Clayton8ee67312014-02-05 21:46:20 +00002682 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2683 debugger.SetAsyncExecution (false);
2684
Greg Clayton340b0302014-02-05 17:57:57 +00002685 m_command_source_depth++;
Greg Clayton8ee67312014-02-05 21:46:20 +00002686
2687 debugger.RunIOHandler(io_handler_sp);
Greg Clayton340b0302014-02-05 17:57:57 +00002688 if (!m_command_source_flags.empty())
2689 m_command_source_flags.pop_back();
2690 m_command_source_depth--;
Greg Clayton44d93782014-01-27 23:43:24 +00002691 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Greg Clayton8ee67312014-02-05 21:46:20 +00002692 debugger.SetAsyncExecution (old_async_execution);
Greg Clayton44d93782014-01-27 23:43:24 +00002693 }
2694 else
2695 {
2696 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2697 result.SetStatus (eReturnStatusFailed);
2698 }
Greg Clayton8ee67312014-02-05 21:46:20 +00002699
2700
Jim Inghame16c50a2011-02-18 00:54:25 +00002701 }
2702 else
2703 {
2704 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
Jim Ingham4af59612014-12-19 19:20:44 +00002705 cmd_file.GetFilename().AsCString("<Unknown>"));
Jim Inghame16c50a2011-02-18 00:54:25 +00002706 result.SetStatus (eReturnStatusFailed);
2707 return;
2708 }
2709}
2710
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002711ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002712CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002713{
Ed Masted78c9572014-04-20 00:31:37 +00002714 if (m_script_interpreter_ap.get() != nullptr)
Enrico Granatab5887262012-10-29 21:18:03 +00002715 return m_script_interpreter_ap.get();
2716
2717 if (!can_create)
Ed Masted78c9572014-04-20 00:31:37 +00002718 return nullptr;
Enrico Granatab5887262012-10-29 21:18:03 +00002719
Enrico Granataa29bdad2012-07-10 18:23:48 +00002720 // <rdar://problem/11751427>
2721 // we need to protect the initialization of the script interpreter
2722 // otherwise we could end up with two threads both trying to create
2723 // their instance of it, and for some languages (e.g. Python)
2724 // this is a bulletproof recipe for disaster!
2725 // this needs to be a function-level static because multiple Debugger instances living in the same process
2726 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002727 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2728 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002729
Greg Clayton5160ce52013-03-27 23:08:40 +00002730 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002731 if (log)
2732 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002733
Caroline Tice2f88aad2011-01-14 00:29:16 +00002734 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2735 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002736 {
Greg Claytondce502e2011-11-04 03:34:56 +00002737 case eScriptLanguagePython:
2738#ifndef LLDB_DISABLE_PYTHON
2739 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2740 break;
2741#else
2742 // Fall through to the None case when python is disabled
2743#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002744 case eScriptLanguageNone:
2745 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2746 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002747 };
2748
2749 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002750}
2751
2752
2753
2754bool
2755CommandInterpreter::GetSynchronous ()
2756{
2757 return m_synchronous_execution;
2758}
2759
2760void
2761CommandInterpreter::SetSynchronous (bool value)
2762{
Johnny Chenc066ab42010-10-14 01:22:03 +00002763 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002764}
2765
2766void
2767CommandInterpreter::OutputFormattedHelpText (Stream &strm,
Kate Stonea487aa42015-01-15 00:52:41 +00002768 const char *prefix,
2769 const char *help_text)
2770{
2771 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2772 if (prefix == NULL)
2773 prefix = "";
2774
2775 size_t prefix_width = strlen(prefix);
2776 size_t line_width_max = max_columns - prefix_width;
2777 const char *help_text_end = help_text + strlen(help_text);
2778 const char *line_start = help_text;
2779 if (line_width_max < 16)
2780 line_width_max = help_text_end - help_text + prefix_width;
2781
2782 strm.IndentMore (prefix_width);
2783 while (line_start < help_text_end)
2784 {
2785 // Break each line at the first newline or last space/tab before
2786 // the maximum number of characters that fit on a line. Lines with no
2787 // natural break are left unbroken to wrap.
2788 const char *line_end = help_text_end;
2789 const char *line_scan = line_start;
2790 const char *line_scan_end = help_text_end;
2791 while (line_scan < line_scan_end)
2792 {
2793 char next = *line_scan;
2794 if (next == '\t' || next == ' ')
2795 {
2796 line_end = line_scan;
2797 line_scan_end = line_start + line_width_max;
2798 }
2799 else if (next == '\n' || next == '\0')
2800 {
2801 line_end = line_scan;
2802 break;
2803 }
2804 ++line_scan;
2805 }
2806
2807 // Prefix the first line, indent subsequent lines to line up
2808 if (line_start == help_text)
2809 strm.Write (prefix, prefix_width);
2810 else
2811 strm.Indent();
2812 strm.Write (line_start, line_end - line_start);
2813 strm.EOL();
2814
2815 // When a line breaks at whitespace consume it before continuing
2816 line_start = line_end;
2817 char next = *line_start;
2818 if (next == '\n')
2819 ++line_start;
2820 else while (next == ' ' || next == '\t')
2821 next = *(++line_start);
2822 }
2823 strm.IndentLess (prefix_width);
2824}
2825
2826void
2827CommandInterpreter::OutputFormattedHelpText (Stream &strm,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002828 const char *word_text,
2829 const char *separator,
2830 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002831 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002832{
Kate Stonea487aa42015-01-15 00:52:41 +00002833 StreamString prefix_stream;
2834 prefix_stream.Printf (" %-*s %s ", (int)max_word_len, word_text, separator);
2835 OutputFormattedHelpText (strm, prefix_stream.GetData(), help_text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002836}
2837
2838void
Enrico Granata82a7d982011-07-07 00:38:40 +00002839CommandInterpreter::OutputHelpText (Stream &strm,
2840 const char *word_text,
2841 const char *separator,
2842 const char *help_text,
2843 uint32_t max_word_len)
2844{
2845 int indent_size = max_word_len + strlen (separator) + 2;
2846
2847 strm.IndentMore (indent_size);
2848
2849 StreamString text_strm;
2850 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2851
2852 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002853
2854 size_t len = text_strm.GetSize();
2855 const char *text = text_strm.GetData();
2856
2857 uint32_t chars_left = max_columns;
2858
2859 for (uint32_t i = 0; i < len; i++)
2860 {
2861 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2862 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002863 chars_left = max_columns - indent_size;
2864 strm.EOL();
2865 strm.Indent();
2866 }
2867 else
2868 {
2869 strm.PutChar(text[i]);
2870 chars_left--;
2871 }
2872
2873 }
2874
2875 strm.EOL();
2876 strm.IndentLess(indent_size);
2877}
2878
2879void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
Jim Inghamaf3753e2013-05-17 01:30:37 +00002881 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002882{
2883 CommandObject::CommandMap::const_iterator pos;
2884
Jim Inghamaf3753e2013-05-17 01:30:37 +00002885 if (search_builtin_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002886 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002887 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002888 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002889 const char *command_name = pos->first.c_str();
2890 CommandObject *cmd_obj = pos->second.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002891
Jim Inghamaf3753e2013-05-17 01:30:37 +00002892 if (cmd_obj->HelpTextContainsWord (search_word))
2893 {
2894 commands_found.AppendString (command_name);
2895 commands_help.AppendString (cmd_obj->GetHelp());
2896 }
2897
2898 if (cmd_obj->IsMultiwordObject())
2899 cmd_obj->AproposAllSubCommands (command_name,
2900 search_word,
2901 commands_found,
2902 commands_help);
2903
2904 }
2905 }
2906
2907 if (search_user_commands)
2908 {
2909 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
2910 {
2911 const char *command_name = pos->first.c_str();
2912 CommandObject *cmd_obj = pos->second.get();
2913
2914 if (cmd_obj->HelpTextContainsWord (search_word))
2915 {
2916 commands_found.AppendString (command_name);
2917 commands_help.AppendString (cmd_obj->GetHelp());
2918 }
2919
2920 if (cmd_obj->IsMultiwordObject())
2921 cmd_obj->AproposAllSubCommands (command_name,
2922 search_word,
2923 commands_found,
2924 commands_help);
2925
2926 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002927 }
2928}
Greg Clayton8b82f082011-04-12 05:54:46 +00002929
Greg Clayton8b82f082011-04-12 05:54:46 +00002930void
2931CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2932{
Ed Masted78c9572014-04-20 00:31:37 +00002933 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002934 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002935 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002936 }
2937 else
2938 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002939 const bool adopt_selected = true;
2940 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002941 }
2942}
Greg Clayton44d93782014-01-27 23:43:24 +00002943
2944
2945size_t
2946CommandInterpreter::GetProcessOutput ()
2947{
2948 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2949 char stdio_buffer[1024];
2950 size_t len;
2951 size_t total_bytes = 0;
2952 Error error;
2953 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2954 if (target_sp)
2955 {
2956 ProcessSP process_sp (target_sp->GetProcessSP());
2957 if (process_sp)
2958 {
2959 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2960 {
2961 size_t bytes_written = len;
2962 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
2963 total_bytes += len;
2964 }
2965 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2966 {
2967 size_t bytes_written = len;
2968 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
2969 total_bytes += len;
2970 }
2971 }
2972 }
2973 return total_bytes;
2974}
2975
2976void
2977CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
2978{
Greg Clayton340b0302014-02-05 17:57:57 +00002979 const bool is_interactive = io_handler.GetIsInteractive();
2980 if (is_interactive == false)
2981 {
2982 // When we are not interactive, don't execute blank lines. This will happen
2983 // sourcing a commands file. We don't want blank lines to repeat the previous
2984 // command and cause any errors to occur (like redefining an alias, get an error
2985 // and stop parsing the commands file).
2986 if (line.empty())
2987 return;
2988
2989 // When using a non-interactive file handle (like when sourcing commands from a file)
2990 // we need to echo the command out so we don't just see the command output and no
2991 // command...
2992 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2993 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
2994 }
2995
Greg Clayton44d93782014-01-27 23:43:24 +00002996 lldb_private::CommandReturnObject result;
2997 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2998
Greg Clayton44d93782014-01-27 23:43:24 +00002999 // Now emit the command output text from the command we just executed
Greg Clayton340b0302014-02-05 17:57:57 +00003000 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
3001 {
3002 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3003 GetProcessOutput ();
3004
Greg Clayton8ee67312014-02-05 21:46:20 +00003005 if (!result.GetImmediateOutputStream())
3006 {
3007 const char *output = result.GetOutputData();
3008 if (output && output[0])
3009 io_handler.GetOutputStreamFile()->PutCString(output);
3010 }
Greg Clayton44d93782014-01-27 23:43:24 +00003011
Greg Clayton340b0302014-02-05 17:57:57 +00003012 // Now emit the command error text from the command we just executed
Greg Clayton8ee67312014-02-05 21:46:20 +00003013 if (!result.GetImmediateErrorStream())
3014 {
3015 const char *error = result.GetErrorData();
3016 if (error && error[0])
3017 io_handler.GetErrorStreamFile()->PutCString(error);
3018 }
Greg Clayton340b0302014-02-05 17:57:57 +00003019 }
Greg Clayton44d93782014-01-27 23:43:24 +00003020
3021 switch (result.GetStatus())
3022 {
3023 case eReturnStatusInvalid:
3024 case eReturnStatusSuccessFinishNoResult:
3025 case eReturnStatusSuccessFinishResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003026 case eReturnStatusStarted:
3027 break;
3028
Greg Clayton44d93782014-01-27 23:43:24 +00003029 case eReturnStatusSuccessContinuingNoResult:
3030 case eReturnStatusSuccessContinuingResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003031 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3032 io_handler.SetIsDone(true);
3033 break;
3034
Greg Clayton44d93782014-01-27 23:43:24 +00003035 case eReturnStatusFailed:
Jim Ingham26c7bf92014-10-11 00:38:27 +00003036 m_num_errors++;
Greg Clayton340b0302014-02-05 17:57:57 +00003037 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3038 io_handler.SetIsDone(true);
Greg Clayton44d93782014-01-27 23:43:24 +00003039 break;
3040
3041 case eReturnStatusQuit:
Jim Ingham26c7bf92014-10-11 00:38:27 +00003042 m_quit_requested = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003043 io_handler.SetIsDone(true);
3044 break;
3045 }
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003046
3047 // Finally, if we're going to stop on crash, check that here:
3048 if (!m_quit_requested
3049 && result.GetDidChangeProcessState()
3050 && io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash))
3051 {
3052 bool should_stop = false;
3053 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
3054 if (target_sp)
3055 {
3056 ProcessSP process_sp (target_sp->GetProcessSP());
3057 if (process_sp)
3058 {
3059 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads())
3060 {
3061 StopReason reason = thread_sp->GetStopReason();
3062 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation)
3063 {
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003064 should_stop = true;
3065 break;
3066 }
3067 }
3068 }
3069 }
3070 if (should_stop)
3071 {
3072 io_handler.SetIsDone(true);
3073 m_stopped_for_crash = true;
3074 }
3075 }
Greg Clayton44d93782014-01-27 23:43:24 +00003076}
3077
Greg Claytonf0066ad2014-05-02 00:45:31 +00003078bool
3079CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler)
3080{
3081 ExecutionContext exe_ctx (GetExecutionContext());
3082 Process *process = exe_ctx.GetProcessPtr();
3083
3084 if (process)
3085 {
3086 StateType state = process->GetState();
3087 if (StateIsRunningState(state))
3088 {
3089 process->Halt();
3090 return true; // Don't do any updating when we are running
3091 }
3092 }
Greg Claytone507bce2015-01-27 01:58:22 +00003093
3094 ScriptInterpreter *script_interpreter = GetScriptInterpreter (false);
3095 if (script_interpreter)
3096 {
3097 if (script_interpreter->Interrupt())
3098 return true;
3099 }
Greg Claytonf0066ad2014-05-02 00:45:31 +00003100 return false;
3101}
3102
Greg Clayton44d93782014-01-27 23:43:24 +00003103void
3104CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3105 IOHandlerDelegate &delegate,
3106 bool asynchronously,
3107 void *baton)
3108{
3109 Debugger &debugger = GetDebugger();
3110 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00003111 IOHandler::Type::CommandList,
Greg Clayton44d93782014-01-27 23:43:24 +00003112 "lldb", // Name of input reader for history
3113 prompt, // Prompt
Kate Stonee30f11d2014-11-17 19:06:59 +00003114 NULL, // Continuation prompt
Greg Clayton44d93782014-01-27 23:43:24 +00003115 true, // Get multiple lines
Kate Stonee30f11d2014-11-17 19:06:59 +00003116 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00003117 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003118 delegate)); // IOHandlerDelegate
3119
3120 if (io_handler_sp)
3121 {
3122 io_handler_sp->SetUserData (baton);
3123 if (asynchronously)
3124 debugger.PushIOHandler(io_handler_sp);
3125 else
3126 debugger.RunIOHandler(io_handler_sp);
3127 }
3128
3129}
3130
3131
3132void
3133CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3134 IOHandlerDelegate &delegate,
3135 bool asynchronously,
3136 void *baton)
3137{
3138 Debugger &debugger = GetDebugger();
3139 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00003140 IOHandler::Type::PythonCode,
Greg Clayton44d93782014-01-27 23:43:24 +00003141 "lldb-python", // Name of input reader for history
3142 prompt, // Prompt
Kate Stonee30f11d2014-11-17 19:06:59 +00003143 NULL, // Continuation prompt
Greg Clayton44d93782014-01-27 23:43:24 +00003144 true, // Get multiple lines
Kate Stonee30f11d2014-11-17 19:06:59 +00003145 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00003146 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003147 delegate)); // IOHandlerDelegate
3148
3149 if (io_handler_sp)
3150 {
3151 io_handler_sp->SetUserData (baton);
3152 if (asynchronously)
3153 debugger.PushIOHandler(io_handler_sp);
3154 else
3155 debugger.RunIOHandler(io_handler_sp);
3156 }
3157
3158}
3159
3160bool
3161CommandInterpreter::IsActive ()
3162{
3163 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3164}
3165
Kate Stonee30f11d2014-11-17 19:06:59 +00003166lldb::IOHandlerSP
3167CommandInterpreter::GetIOHandler(bool force_create, CommandInterpreterRunOptions *options)
3168{
3169 // Always re-create the IOHandlerEditline in case the input
3170 // changed. The old instance might have had a non-interactive
3171 // input and now it does or vice versa.
3172 if (force_create || !m_command_io_handler_sp)
3173 {
3174 // Always re-create the IOHandlerEditline in case the input
3175 // changed. The old instance might have had a non-interactive
3176 // input and now it does or vice versa.
3177 uint32_t flags = 0;
3178
3179 if (options)
3180 {
3181 if (options->m_stop_on_continue == eLazyBoolYes)
3182 flags |= eHandleCommandFlagStopOnContinue;
3183 if (options->m_stop_on_error == eLazyBoolYes)
3184 flags |= eHandleCommandFlagStopOnError;
3185 if (options->m_stop_on_crash == eLazyBoolYes)
3186 flags |= eHandleCommandFlagStopOnCrash;
3187 if (options->m_echo_commands != eLazyBoolNo)
3188 flags |= eHandleCommandFlagEchoCommand;
3189 if (options->m_print_results != eLazyBoolNo)
3190 flags |= eHandleCommandFlagPrintResult;
3191 }
3192 else
3193 {
3194 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
3195 }
3196
3197 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3198 IOHandler::Type::CommandInterpreter,
3199 m_debugger.GetInputFile(),
3200 m_debugger.GetOutputFile(),
3201 m_debugger.GetErrorFile(),
3202 flags,
3203 "lldb",
3204 m_debugger.GetPrompt(),
3205 NULL, // Continuation prompt
3206 false, // Don't enable multiple line input, just single line commands
3207 m_debugger.GetUseColor(),
3208 0, // Don't show line numbers
3209 *this));
3210 }
3211 return m_command_io_handler_sp;
3212}
3213
Greg Clayton44d93782014-01-27 23:43:24 +00003214void
3215CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
Jim Ingham26c7bf92014-10-11 00:38:27 +00003216 bool spawn_thread,
3217 CommandInterpreterRunOptions &options)
Greg Clayton44d93782014-01-27 23:43:24 +00003218{
Kate Stonee30f11d2014-11-17 19:06:59 +00003219 // Always re-create the command intepreter when we run it in case
3220 // any file handles have changed.
3221 bool force_create = true;
3222 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003223 m_stopped_for_crash = false;
Greg Clayton380f3d82014-07-31 19:46:19 +00003224
Greg Clayton44d93782014-01-27 23:43:24 +00003225 if (auto_handle_events)
3226 m_debugger.StartEventHandlerThread();
3227
3228 if (spawn_thread)
3229 {
3230 m_debugger.StartIOHandlerThread();
3231 }
3232 else
3233 {
Siva Chandra9aaab552015-02-26 19:26:36 +00003234 m_debugger.ExecuteIOHandlers();
Kate Stonee30f11d2014-11-17 19:06:59 +00003235
Greg Clayton44d93782014-01-27 23:43:24 +00003236 if (auto_handle_events)
3237 m_debugger.StopEventHandlerThread();
3238 }
Kate Stonee30f11d2014-11-17 19:06:59 +00003239
Greg Clayton44d93782014-01-27 23:43:24 +00003240}
3241
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003242CommandObject *
3243CommandInterpreter::ResolveCommandImpl(std::string &command_line, CommandReturnObject &result)
3244{
3245 std::string scratch_command(command_line); // working copy so we don't modify command_line unless we succeed
3246 CommandObject *cmd_obj = nullptr;
3247 StreamString revised_command_line;
3248 bool wants_raw_input = false;
3249 size_t actual_cmd_name_len = 0;
3250 std::string next_word;
3251 StringList matches;
3252 bool done = false;
3253 while (!done)
3254 {
3255 char quote_char = '\0';
3256 std::string suffix;
3257 ExtractCommand(scratch_command, next_word, suffix, quote_char);
3258 if (cmd_obj == nullptr)
3259 {
3260 std::string full_name;
3261 if (GetAliasFullName(next_word.c_str(), full_name))
3262 {
3263 std::string alias_result;
3264 cmd_obj = BuildAliasResult(full_name.c_str(), scratch_command, alias_result, result);
3265 revised_command_line.Printf("%s", alias_result.c_str());
3266 if (cmd_obj)
3267 {
3268 wants_raw_input = cmd_obj->WantsRawCommandString();
3269 actual_cmd_name_len = strlen(cmd_obj->GetCommandName());
3270 }
3271 }
3272 else
3273 {
3274 cmd_obj = GetCommandObject(next_word.c_str(), &matches);
3275 if (cmd_obj)
3276 {
3277 actual_cmd_name_len += strlen(cmd_obj->GetCommandName());
3278 revised_command_line.Printf("%s", cmd_obj->GetCommandName());
3279 wants_raw_input = cmd_obj->WantsRawCommandString();
3280 }
3281 else
3282 {
3283 revised_command_line.Printf ("%s", next_word.c_str());
3284 }
3285 }
3286 }
3287 else
3288 {
3289 if (cmd_obj->IsMultiwordObject ())
3290 {
3291 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject(next_word.c_str());
3292 if (sub_cmd_obj)
3293 {
3294 // The subcommand's name includes the parent command's name,
3295 // so restart rather than append to the revised_command_line.
3296 actual_cmd_name_len = strlen(sub_cmd_obj->GetCommandName()) + 1;
3297 revised_command_line.Clear();
3298 revised_command_line.Printf("%s", sub_cmd_obj->GetCommandName());
3299 cmd_obj = sub_cmd_obj;
3300 wants_raw_input = cmd_obj->WantsRawCommandString();
3301 }
3302 else
3303 {
3304 if (quote_char)
3305 revised_command_line.Printf(" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
3306 else
3307 revised_command_line.Printf(" %s%s", next_word.c_str(), suffix.c_str());
3308 done = true;
3309 }
3310 }
3311 else
3312 {
3313 if (quote_char)
3314 revised_command_line.Printf(" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
3315 else
3316 revised_command_line.Printf(" %s%s", next_word.c_str(), suffix.c_str());
3317 done = true;
3318 }
3319 }
3320
3321 if (cmd_obj == nullptr)
3322 {
3323 const size_t num_matches = matches.GetSize();
3324 if (matches.GetSize() > 1) {
3325 StreamString error_msg;
3326 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
3327
3328 for (uint32_t i = 0; i < num_matches; ++i) {
3329 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3330 }
3331 result.AppendRawError(error_msg.GetString().c_str());
3332 } else {
3333 // We didn't have only one match, otherwise we wouldn't get here.
3334 assert(num_matches == 0);
3335 result.AppendErrorWithFormat("'%s' is not a valid command.\n", next_word.c_str());
3336 }
3337 result.SetStatus(eReturnStatusFailed);
3338 return nullptr;
3339 }
3340
3341 if (cmd_obj->IsMultiwordObject())
3342 {
3343 if (!suffix.empty())
3344 {
3345 result.AppendErrorWithFormat("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
3346 cmd_obj->GetCommandName(),
3347 next_word.empty() ? "" : next_word.c_str(),
3348 next_word.empty() ? " -- " : " ",
3349 suffix.c_str());
3350 result.SetStatus(eReturnStatusFailed);
3351 return nullptr;
3352 }
3353 }
3354 else
3355 {
3356 // If we found a normal command, we are done
3357 done = true;
3358 if (!suffix.empty())
3359 {
3360 switch (suffix[0])
3361 {
3362 case '/':
3363 // GDB format suffixes
3364 {
3365 Options *command_options = cmd_obj->GetOptions();
3366 if (command_options && command_options->SupportsLongOption("gdb-format"))
3367 {
3368 std::string gdb_format_option("--gdb-format=");
3369 gdb_format_option += (suffix.c_str() + 1);
3370
3371 bool inserted = false;
3372 std::string &cmd = revised_command_line.GetString();
3373 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3374 if (arg_terminator_idx != std::string::npos)
3375 {
3376 // Insert the gdb format option before the "--" that terminates options
3377 gdb_format_option.append(1,' ');
3378 cmd.insert(arg_terminator_idx, gdb_format_option);
3379 inserted = true;
3380 }
3381
3382 if (!inserted)
3383 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3384
3385 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
3386 revised_command_line.PutCString(" --");
3387 }
3388 else
3389 {
3390 result.AppendErrorWithFormat("the '%s' command doesn't support the --gdb-format option\n",
3391 cmd_obj->GetCommandName());
3392 result.SetStatus(eReturnStatusFailed);
3393 return nullptr;
3394 }
3395 }
3396 break;
3397
3398 default:
3399 result.AppendErrorWithFormat("unknown command shorthand suffix: '%s'\n",
3400 suffix.c_str());
3401 result.SetStatus(eReturnStatusFailed);
3402 return nullptr;
3403 }
3404 }
3405 }
3406 if (scratch_command.empty())
3407 done = true;
3408 }
3409
3410 if (!scratch_command.empty())
3411 revised_command_line.Printf(" %s", scratch_command.c_str());
3412
3413 if (cmd_obj != NULL)
3414 command_line = revised_command_line.GetData();
3415
3416 return cmd_obj;
3417}