blob: bc55691833d3910401ab0615d620e3f9234d0c43 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000013#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000014#include <stdlib.h>
15
Greg Clayton4a33d312011-06-23 17:59:56 +000016#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000017#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000018
Eli Friedman3afb70c2010-06-13 02:17:17 +000019#include "../Commands/CommandObjectApropos.h"
20#include "../Commands/CommandObjectArgs.h"
21#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectDisassemble.h"
23#include "../Commands/CommandObjectExpression.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectFrame.h"
Greg Clayton44d93782014-01-27 23:43:24 +000025#include "../Commands/CommandObjectGUI.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000026#include "../Commands/CommandObjectHelp.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000027#include "../Commands/CommandObjectLog.h"
28#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000029#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000030#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectProcess.h"
32#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000034#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSource.h"
Jim Inghamebc09c32010-07-07 03:36:20 +000036#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000037#include "../Commands/CommandObjectSyntax.h"
38#include "../Commands/CommandObjectTarget.h"
39#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000040#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000041#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000042#include "../Commands/CommandObjectWatchpoint.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043
Greg Clayton7d2ef162013-03-29 17:03:23 +000044
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045#include "lldb/Core/Debugger.h"
Enrico Granatab5887262012-10-29 21:18:03 +000046#include "lldb/Core/Log.h"
Greg Claytonf0066ad2014-05-02 00:45:31 +000047#include "lldb/Core/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "lldb/Core/Stream.h"
Greg Clayton44d93782014-01-27 23:43:24 +000049#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050#include "lldb/Core/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000051
Todd Fialacacde7d2014-09-27 16:54:22 +000052#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000053#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000054#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000055#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000056#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000057
58#include "lldb/Interpreter/Args.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000059#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000060#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000061#include "lldb/Interpreter/CommandReturnObject.h"
Enrico Granatab5887262012-10-29 21:18:03 +000062#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000063#include "lldb/Interpreter/OptionValueProperties.h"
64#include "lldb/Interpreter/Property.h"
Enrico Granatab5887262012-10-29 21:18:03 +000065#include "lldb/Interpreter/ScriptInterpreterNone.h"
66#include "lldb/Interpreter/ScriptInterpreterPython.h"
67
68
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069#include "lldb/Target/Process.h"
70#include "lldb/Target/Thread.h"
71#include "lldb/Target/TargetList.h"
72
Enrico Granatab5887262012-10-29 21:18:03 +000073#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074
Zachary Turnera21fee02014-08-21 21:49:24 +000075#include "llvm/ADT/SmallString.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000076#include "llvm/ADT/STLExtras.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000077#include "llvm/Support/Path.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000078
Chris Lattner30fdc8d2010-06-08 16:52:24 +000079using namespace lldb;
80using namespace lldb_private;
81
Greg Clayton754a9362012-08-23 00:22:02 +000082
83static PropertyDefinition
84g_properties[] =
85{
Ed Masted78c9572014-04-20 00:31:37 +000086 { "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." },
87 { "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." },
88 { "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." },
89 { nullptr , OptionValue::eTypeInvalid, true, 0 , nullptr, nullptr, nullptr }
Greg Clayton754a9362012-08-23 00:22:02 +000090};
91
92enum
93{
Enrico Granatabcba2b22013-01-17 21:36:19 +000094 ePropertyExpandRegexAliases = 0,
Enrico Granata012d4fc2013-06-11 01:26:35 +000095 ePropertyPromptOnQuit = 1,
96 ePropertyStopCmdSourceOnError = 2
Greg Clayton754a9362012-08-23 00:22:02 +000097};
98
Jim Ingham4bddaeb2012-02-16 06:50:00 +000099ConstString &
100CommandInterpreter::GetStaticBroadcasterClass ()
101{
102 static ConstString class_name ("lldb.commandInterpreter");
103 return class_name;
104}
105
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000106CommandInterpreter::CommandInterpreter
107(
Greg Clayton66111032010-06-23 01:19:29 +0000108 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000109 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +0000110 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000111) :
Ilia K8a00a562015-03-17 16:54:52 +0000112 Broadcaster (&debugger, CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
Greg Clayton754a9362012-08-23 00:22:02 +0000113 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton44d93782014-01-27 23:43:24 +0000114 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand),
Greg Clayton66111032010-06-23 01:19:29 +0000115 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000116 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000117 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000118 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000119 m_script_interpreter_ap (),
Greg Clayton44d93782014-01-27 23:43:24 +0000120 m_command_io_handler_sp (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000121 m_comment_char ('#'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000122 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000123 m_truncation_warning(eNoTruncation),
Jim Ingham26c7bf92014-10-11 00:38:27 +0000124 m_command_source_depth (0),
125 m_num_errors(0),
Jim Inghamffc9f1d2014-10-14 01:20:07 +0000126 m_quit_requested(false),
127 m_stopped_for_crash(false)
Jim Ingham26c7bf92014-10-11 00:38:27 +0000128
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000129{
Greg Clayton67cc0632012-08-22 17:17:09 +0000130 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000131 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
132 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000133 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000134 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000135 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000136}
137
Greg Clayton754a9362012-08-23 00:22:02 +0000138bool
139CommandInterpreter::GetExpandRegexAliases () const
140{
141 const uint32_t idx = ePropertyExpandRegexAliases;
Ed Masted78c9572014-04-20 00:31:37 +0000142 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000143}
144
Enrico Granatabcba2b22013-01-17 21:36:19 +0000145bool
146CommandInterpreter::GetPromptOnQuit () const
147{
148 const uint32_t idx = ePropertyPromptOnQuit;
Ed Masted78c9572014-04-20 00:31:37 +0000149 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000150}
Greg Clayton754a9362012-08-23 00:22:02 +0000151
Ilia Kacf28be2015-03-23 22:45:13 +0000152void
153CommandInterpreter::SetPromptOnQuit (bool b)
154{
155 const uint32_t idx = ePropertyPromptOnQuit;
156 m_collection_sp->SetPropertyAtIndexAsBoolean (nullptr, idx, b);
157}
158
Enrico Granata012d4fc2013-06-11 01:26:35 +0000159bool
160CommandInterpreter::GetStopCmdSourceOnError () const
161{
162 const uint32_t idx = ePropertyStopCmdSourceOnError;
Ed Masted78c9572014-04-20 00:31:37 +0000163 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000164}
165
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000166void
167CommandInterpreter::Initialize ()
168{
169 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
170
171 CommandReturnObject result;
172
173 LoadCommandDictionary ();
174
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000175 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000176 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
177 if (cmd_obj_sp)
178 {
179 AddAlias ("q", cmd_obj_sp);
180 AddAlias ("exit", cmd_obj_sp);
181 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000182
Johnny Chen6d675242012-08-24 18:15:45 +0000183 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000184 if (cmd_obj_sp)
185 {
186 AddAlias ("attach", cmd_obj_sp);
187 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000188
Johnny Chen6d675242012-08-24 18:15:45 +0000189 cmd_obj_sp = GetCommandSPExact ("process detach",false);
190 if (cmd_obj_sp)
191 {
192 AddAlias ("detach", cmd_obj_sp);
193 }
194
Caroline Ticeca90c472011-05-06 21:37:15 +0000195 cmd_obj_sp = GetCommandSPExact ("process continue", false);
196 if (cmd_obj_sp)
197 {
198 AddAlias ("c", cmd_obj_sp);
199 AddAlias ("continue", cmd_obj_sp);
200 }
201
202 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
203 if (cmd_obj_sp)
204 AddAlias ("b", cmd_obj_sp);
205
Jim Inghamca36cd12012-10-05 19:16:31 +0000206 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
207 if (cmd_obj_sp)
208 AddAlias ("tbreak", cmd_obj_sp);
209
Caroline Ticeca90c472011-05-06 21:37:15 +0000210 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
211 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000212 {
213 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000214 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000215 }
216
217 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
218 if (cmd_obj_sp)
219 {
220 AddAlias ("nexti", cmd_obj_sp);
221 AddAlias ("ni", cmd_obj_sp);
222 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000223
224 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
225 if (cmd_obj_sp)
226 {
227 AddAlias ("s", cmd_obj_sp);
228 AddAlias ("step", cmd_obj_sp);
229 }
230
231 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
232 if (cmd_obj_sp)
233 {
234 AddAlias ("n", cmd_obj_sp);
235 AddAlias ("next", cmd_obj_sp);
236 }
237
238 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
239 if (cmd_obj_sp)
240 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000241 AddAlias ("finish", cmd_obj_sp);
242 }
243
Jim Ingham6d6d1072011-12-02 01:12:59 +0000244 cmd_obj_sp = GetCommandSPExact ("frame select", false);
245 if (cmd_obj_sp)
246 {
247 AddAlias ("f", cmd_obj_sp);
248 }
249
Jim Inghamca36cd12012-10-05 19:16:31 +0000250 cmd_obj_sp = GetCommandSPExact ("thread select", false);
251 if (cmd_obj_sp)
252 {
253 AddAlias ("t", cmd_obj_sp);
254 }
255
Richard Mittonf86248d2013-09-12 02:20:34 +0000256 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
257 if (cmd_obj_sp)
258 {
259 AddAlias ("j", cmd_obj_sp);
260 AddAlias ("jump", cmd_obj_sp);
261 }
262
Greg Clayton6bade322013-02-01 23:33:03 +0000263 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000264 if (cmd_obj_sp)
265 {
266 AddAlias ("l", cmd_obj_sp);
267 AddAlias ("list", cmd_obj_sp);
268 }
269
Greg Claytonef5651d2013-02-12 18:52:24 +0000270 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
271 if (cmd_obj_sp)
272 {
273 AddAlias ("env", cmd_obj_sp);
274 }
275
Caroline Ticeca90c472011-05-06 21:37:15 +0000276 cmd_obj_sp = GetCommandSPExact ("memory read", false);
277 if (cmd_obj_sp)
278 AddAlias ("x", cmd_obj_sp);
279
280 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
281 if (cmd_obj_sp)
282 AddAlias ("up", cmd_obj_sp);
283
284 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
285 if (cmd_obj_sp)
286 AddAlias ("down", cmd_obj_sp);
287
Jason Molenda0c8e0062011-10-25 02:11:20 +0000288 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000289 if (cmd_obj_sp)
290 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000291
292 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
293 if (cmd_obj_sp)
294 AddAlias ("dis", cmd_obj_sp);
295
296 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
297 if (cmd_obj_sp)
298 AddAlias ("di", cmd_obj_sp);
299
300
Jason Molendabc7748b2011-10-22 01:30:52 +0000301
Jason Molenda0c8e0062011-10-25 02:11:20 +0000302 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000303 if (cmd_obj_sp)
304 AddAlias ("undisplay", cmd_obj_sp);
305
Jim Ingham71bf2992012-10-10 16:51:31 +0000306 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
307 if (cmd_obj_sp)
308 AddAlias ("bt", cmd_obj_sp);
309
Caroline Ticeca90c472011-05-06 21:37:15 +0000310 cmd_obj_sp = GetCommandSPExact ("target create", false);
311 if (cmd_obj_sp)
312 AddAlias ("file", cmd_obj_sp);
313
314 cmd_obj_sp = GetCommandSPExact ("target modules", false);
315 if (cmd_obj_sp)
316 AddAlias ("image", cmd_obj_sp);
317
318
319 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000320
Caroline Ticeca90c472011-05-06 21:37:15 +0000321 cmd_obj_sp = GetCommandSPExact ("expression", false);
322 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000323 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000324 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
325 AddAlias ("p", cmd_obj_sp);
326 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000327 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000328 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
329 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000330 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000331
332 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton9e57dcd2013-05-15 01:03:08 +0000333 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000334 AddAlias ("po", cmd_obj_sp);
335 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
336 }
337
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000338 cmd_obj_sp = GetCommandSPExact ("process kill", false);
339 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000340 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000341 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000342 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000343
Caroline Ticeca90c472011-05-06 21:37:15 +0000344 cmd_obj_sp = GetCommandSPExact ("process launch", false);
345 if (cmd_obj_sp)
346 {
347 alias_arguments_vector_sp.reset (new OptionArgVector);
Todd Fiala013434e2014-07-09 01:29:05 +0000348#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Jason Molenda85da3122012-07-06 02:46:23 +0000349 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
350#else
Zachary Turner10687b02014-10-20 17:46:43 +0000351 std::string shell_option;
352 shell_option.append("--shell=");
353 shell_option.append(HostInfo::GetDefaultShell().GetPath());
354 shell_option.append(" --");
355 ProcessAliasOptionsArgs (cmd_obj_sp, shell_option.c_str(), alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000356#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000357 AddAlias ("r", cmd_obj_sp);
358 AddAlias ("run", cmd_obj_sp);
359 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
360 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
361 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000362
363 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
364 if (cmd_obj_sp)
365 {
366 AddAlias ("add-dsym", cmd_obj_sp);
367 }
Sean Callananfc732752012-05-21 18:25:19 +0000368
369 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
370 if (cmd_obj_sp)
371 {
372 alias_arguments_vector_sp.reset (new OptionArgVector);
373 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000374 AddAlias ("rbreak", cmd_obj_sp);
375 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000376 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377}
378
Greg Clayton0c4129f2014-04-25 00:35:14 +0000379void
380CommandInterpreter::Clear()
381{
382 m_command_io_handler_sp.reset();
Greg Claytoned6499f2014-04-25 23:55:12 +0000383
384 if (m_script_interpreter_ap)
385 m_script_interpreter_ap->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000386}
387
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388const char *
389CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
390{
391 // This function has not yet been implemented.
392
393 // Look for any embedded script command
394 // If found,
395 // get interpreter object from the command dictionary,
396 // call execute_one_command on it,
397 // get the results as a string,
398 // substitute that string for current stuff.
399
400 return arg;
401}
402
403
404void
405CommandInterpreter::LoadCommandDictionary ()
406{
407 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
408
Caroline Ticedaccaa92010-09-20 20:44:43 +0000409 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000410
Greg Claytona7015092010-09-18 01:14:36 +0000411 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000412 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000413 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000414 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
415 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000416 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton44d93782014-01-27 23:43:24 +0000417 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000418 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000419 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
420 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000421 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000422 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000423 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000424 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000425 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000426 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000427 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000428 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000429 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
430 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000431 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000432 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000433 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000434
Jim Inghamca36cd12012-10-05 19:16:31 +0000435 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
Greg Claytond90ac932014-12-01 22:34:03 +0000436 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000437 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000438 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000439 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000440 {"^(-.*)$", "breakpoint set %1"},
441 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000442 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Greg Clayton2d4b5122014-08-14 17:58:33 +0000443 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}};
Jim Inghamca36cd12012-10-05 19:16:31 +0000444
Saleem Abdulrasool28606952014-06-27 05:17:41 +0000445 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000446
Greg Clayton7b0992d2013-04-18 22:45:39 +0000447 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000448 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000449 "_regexp-break",
Greg Clayton910db5c2015-03-07 00:01:46 +0000450 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.\n",
451 "\n_regexp-break <filename>:<linenum> # _regexp-break main.c:12 // Break on line 12 of main.c\n"
452 "_regexp-break <linenum> # _regexp-break 12 // Break on line 12 of current file\n"
453 "_regexp-break <address> # _regexp-break 0x1234000 // Break on address 0x1234000\n"
454 "_regexp-break <name> # _regexp-break main // Break in 'main' after the prologue\n"
455 "_regexp-break &<name> # _regexp-break &main // Break on the first instruction in 'main'\n"
456 "_regexp-break <module>`<name> # _regexp-break libc.so`malloc // Break in 'malloc' only in the 'libc.so' shared library\n"
457 "_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 +0000458 2,
459 CommandCompletions::eSymbolCompletion |
Greg Claytonb5472782015-01-09 19:08:20 +0000460 CommandCompletions::eSourceFileCompletion,
461 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000462
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000463 if (break_regex_cmd_ap.get())
464 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000465 bool success = true;
466 for (size_t i = 0; i < num_regexes; i++)
467 {
468 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
469 if (!success)
470 break;
471 }
472 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
473
474 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000475 {
476 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
477 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
478 }
479 }
Jim Inghamffba2292011-03-22 02:29:32 +0000480
Greg Clayton7b0992d2013-04-18 22:45:39 +0000481 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000482 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
483 "_regexp-tbreak",
484 "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 +0000485 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
486 2,
487 CommandCompletions::eSymbolCompletion |
Greg Claytonb5472782015-01-09 19:08:20 +0000488 CommandCompletions::eSourceFileCompletion,
489 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000490
491 if (tbreak_regex_cmd_ap.get())
492 {
493 bool success = true;
494 for (size_t i = 0; i < num_regexes; i++)
495 {
496 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
497 char buffer[1024];
498 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
499 assert (num_printed < 1024);
Eric Christopher5c91d5c12014-09-09 19:26:45 +0000500 // Quiet unused variable warning for release builds.
Eric Christopher9ad83942014-09-09 08:57:33 +0000501 (void) num_printed;
Jim Inghamca36cd12012-10-05 19:16:31 +0000502 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
503 if (!success)
504 break;
505 }
506 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
507
508 if (success)
509 {
510 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
511 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
512 }
513 }
514
Greg Clayton7b0992d2013-04-18 22:45:39 +0000515 std::unique_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000516 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
517 "_regexp-attach",
518 "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 +0000519 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
Greg Claytonb5472782015-01-09 19:08:20 +0000520 2,
521 0,
522 false));
Johnny Chen6d675242012-08-24 18:15:45 +0000523 if (attach_regex_cmd_ap.get())
524 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000525 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
526 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
527 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
528 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000529 {
530 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
531 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
532 }
533 }
534
Greg Clayton7b0992d2013-04-18 22:45:39 +0000535 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000536 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000537 "_regexp-down",
538 "Go down \"n\" frames in the stack (1 frame by default).",
Greg Claytonb5472782015-01-09 19:08:20 +0000539 "_regexp-down [n]",
540 2,
541 0,
542 false));
Jim Inghamffba2292011-03-22 02:29:32 +0000543 if (down_regex_cmd_ap.get())
544 {
545 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
546 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
547 {
548 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
549 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
550 }
551 }
552
Greg Clayton7b0992d2013-04-18 22:45:39 +0000553 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000554 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000555 "_regexp-up",
556 "Go up \"n\" frames in the stack (1 frame by default).",
Greg Claytonb5472782015-01-09 19:08:20 +0000557 "_regexp-up [n]",
558 2,
559 0,
560 false));
Jim Inghamffba2292011-03-22 02:29:32 +0000561 if (up_regex_cmd_ap.get())
562 {
563 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
564 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
565 {
566 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
567 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
568 }
569 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000570
Greg Clayton7b0992d2013-04-18 22:45:39 +0000571 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000572 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000573 "_regexp-display",
574 "Add an expression evaluation stop-hook.",
Greg Claytonb5472782015-01-09 19:08:20 +0000575 "_regexp-display expression",
576 2,
577 0,
578 false));
Jason Molendabc7748b2011-10-22 01:30:52 +0000579 if (display_regex_cmd_ap.get())
580 {
581 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
582 {
583 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
584 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
585 }
586 }
587
Greg Clayton7b0992d2013-04-18 22:45:39 +0000588 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000589 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000590 "_regexp-undisplay",
591 "Remove an expression evaluation stop-hook.",
Greg Claytonb5472782015-01-09 19:08:20 +0000592 "_regexp-undisplay stop-hook-number",
593 2,
594 0,
595 false));
Jason Molendabc7748b2011-10-22 01:30:52 +0000596 if (undisplay_regex_cmd_ap.get())
597 {
598 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
599 {
600 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
601 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
602 }
603 }
604
Greg Clayton7b0992d2013-04-18 22:45:39 +0000605 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000606 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000607 "gdb-remote",
608 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
Greg Claytonb5472782015-01-09 19:08:20 +0000609 "gdb-remote [<hostname>:]<portnum>",
610 2,
611 0,
612 false));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000613 if (connect_gdb_remote_cmd_ap.get())
614 {
615 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
616 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
617 {
618 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
619 m_command_dict[command_sp->GetCommandName ()] = command_sp;
620 }
621 }
622
Greg Clayton7b0992d2013-04-18 22:45:39 +0000623 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000624 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
625 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000626 "Connect to a remote KDP server. udp port 41139 is the default port number.",
Greg Claytonb5472782015-01-09 19:08:20 +0000627 "kdp-remote <hostname>[:<portnum>]",
628 2,
629 0,
630 false));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000631 if (connect_kdp_remote_cmd_ap.get())
632 {
633 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000634 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000635 {
636 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
637 m_command_dict[command_sp->GetCommandName ()] = command_sp;
638 }
639 }
640
Greg Clayton7b0992d2013-04-18 22:45:39 +0000641 std::unique_ptr<CommandObjectRegexCommand>
Jason Molenda4cddfed2012-10-05 05:29:32 +0000642 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb5472782015-01-09 19:08:20 +0000643 "_regexp-bt",
644 "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.",
645 "bt [<digit>|all]",
646 2,
647 0,
648 false));
Jason Molenda4cddfed2012-10-05 05:29:32 +0000649 if (bt_regex_cmd_ap.get())
650 {
651 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
652 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
653 // so now "bt 3" is the preferred form, in line with gdb.
654 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
655 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
656 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
657 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
658 {
659 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
660 m_command_dict[command_sp->GetCommandName ()] = command_sp;
661 }
662 }
663
Greg Clayton7b0992d2013-04-18 22:45:39 +0000664 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton6bade322013-02-01 23:33:03 +0000665 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
666 "_regexp-list",
667 "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 +0000668 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000669 2,
Greg Claytonb5472782015-01-09 19:08:20 +0000670 CommandCompletions::eSourceFileCompletion,
671 false));
Greg Clayton6bade322013-02-01 23:33:03 +0000672 if (list_regex_cmd_ap.get())
673 {
674 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
675 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
676 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000677 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000678 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000679 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
680 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
681 {
682 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
683 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
684 }
685 }
686
Greg Clayton7b0992d2013-04-18 22:45:39 +0000687 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytonef5651d2013-02-12 18:52:24 +0000688 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000689 "_regexp-env",
690 "Implements a shortcut to viewing and setting environment variables.",
Greg Claytonb5472782015-01-09 19:08:20 +0000691 "_regexp-env\n_regexp-env FOO=BAR",
692 2,
693 0,
694 false));
Greg Claytonef5651d2013-02-12 18:52:24 +0000695 if (env_regex_cmd_ap.get())
696 {
697 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
698 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
699 {
700 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
701 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
702 }
703 }
704
Richard Mittonf86248d2013-09-12 02:20:34 +0000705 std::unique_ptr<CommandObjectRegexCommand>
706 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
707 "_regexp-jump",
708 "Sets the program counter to a new address.",
709 "_regexp-jump [<line>]\n"
710 "_regexp-jump [<+-lineoffset>]\n"
711 "_regexp-jump [<file>:<line>]\n"
Greg Claytonb5472782015-01-09 19:08:20 +0000712 "_regexp-jump [*<addr>]\n",
713 2,
714 0,
715 false));
Richard Mittonf86248d2013-09-12 02:20:34 +0000716 if (jump_regex_cmd_ap.get())
717 {
718 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
719 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
720 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
721 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
722 {
723 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
724 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
725 }
726 }
727
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000728}
729
730int
731CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
732 StringList &matches)
733{
734 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
735
736 if (include_aliases)
737 {
738 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
739 }
740
741 return matches.GetSize();
742}
743
744CommandObjectSP
745CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
746{
747 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000748 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000749
750 std::string cmd(cmd_cstr);
751
752 if (HasCommands())
753 {
754 pos = m_command_dict.find(cmd);
755 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000756 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000757 }
758
759 if (include_aliases && HasAliases())
760 {
761 pos = m_alias_dict.find(cmd);
762 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000763 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764 }
765
766 if (HasUserCommands())
767 {
768 pos = m_user_dict.find(cmd);
769 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000770 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000771 }
772
Greg Claytonc7bece562013-01-25 18:06:21 +0000773 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000775 // We will only get into here if we didn't find any exact matches.
776
777 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
778
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779 StringList local_matches;
Ed Masted78c9572014-04-20 00:31:37 +0000780 if (matches == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000781 matches = &local_matches;
782
Jim Ingham279a6c22010-07-06 22:46:59 +0000783 unsigned int num_cmd_matches = 0;
784 unsigned int num_alias_matches = 0;
785 unsigned int num_user_matches = 0;
786
787 // Look through the command dictionaries one by one, and if we get only one match from any of
788 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
789
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000790 if (HasCommands())
791 {
792 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
793 }
794
795 if (num_cmd_matches == 1)
796 {
797 cmd.assign(matches->GetStringAtIndex(0));
798 pos = m_command_dict.find(cmd);
799 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000800 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000801 }
802
Jim Ingham490ac552010-06-24 20:28:42 +0000803 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000804 {
805 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
806
807 }
808
Jim Ingham279a6c22010-07-06 22:46:59 +0000809 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000810 {
811 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
812 pos = m_alias_dict.find(cmd);
813 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000814 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000815 }
816
Jim Ingham490ac552010-06-24 20:28:42 +0000817 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000818 {
819 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
820 }
821
Jim Ingham279a6c22010-07-06 22:46:59 +0000822 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823 {
824 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
825
826 pos = m_user_dict.find (cmd);
827 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000828 user_match_sp = pos->second;
829 }
830
831 // If we got exactly one match, return that, otherwise return the match list.
832
833 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
834 {
835 if (num_cmd_matches)
836 return real_match_sp;
837 else if (num_alias_matches)
838 return alias_match_sp;
839 else
840 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000841 }
842 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000843 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000844 {
845 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000846 }
847
848
Greg Claytonc7bece562013-01-25 18:06:21 +0000849 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000850}
851
Greg Claytonde164aa2011-04-20 16:37:46 +0000852bool
853CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
854{
855 if (name && name[0])
856 {
857 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000858 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
859 if (found && !can_replace)
860 return false;
861 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000862 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000863 m_command_dict[name_sstr] = cmd_sp;
864 return true;
865 }
866 return false;
867}
868
Enrico Granata223383e2011-08-16 23:24:13 +0000869bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000870CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000871 const lldb::CommandObjectSP &cmd_sp,
872 bool can_replace)
873{
Enrico Granata0a305db2011-11-07 22:57:04 +0000874 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000875 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000876
877 const char* name_cstr = name.c_str();
878
879 // do not allow replacement of internal commands
880 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000881 {
882 if (can_replace == false)
883 return false;
884 if (m_command_dict[name]->IsRemovable() == false)
885 return false;
886 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000887
Enrico Granata21dfcd92012-09-28 23:57:51 +0000888 if (UserCommandExists(name_cstr))
889 {
890 if (can_replace == false)
891 return false;
892 if (m_user_dict[name]->IsRemovable() == false)
893 return false;
894 }
895
Enrico Granata0a305db2011-11-07 22:57:04 +0000896 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000897 return true;
898 }
899 return false;
900}
Greg Claytonde164aa2011-04-20 16:37:46 +0000901
Jim Ingham279a6c22010-07-06 22:46:59 +0000902CommandObjectSP
903CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000904{
Caroline Tice472362e2010-12-14 18:51:39 +0000905 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
906 CommandObjectSP ret_val; // Possibly empty return value.
907
Ed Masted78c9572014-04-20 00:31:37 +0000908 if (cmd_cstr == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000909 return ret_val;
910
911 if (cmd_words.GetArgumentCount() == 1)
Ed Masted78c9572014-04-20 00:31:37 +0000912 return GetCommandSP(cmd_cstr, include_aliases, true, nullptr);
Caroline Tice472362e2010-12-14 18:51:39 +0000913 else
914 {
915 // We have a multi-word command (seemingly), so we need to do more work.
916 // First, get the cmd_obj_sp for the first word in the command.
Ed Masted78c9572014-04-20 00:31:37 +0000917 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr);
918 if (cmd_obj_sp.get() != nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000919 {
920 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
921 // command name), and find the appropriate sub-command SP for each command word....
922 size_t end = cmd_words.GetArgumentCount();
923 for (size_t j= 1; j < end; ++j)
924 {
925 if (cmd_obj_sp->IsMultiwordObject())
926 {
Greg Clayton998255b2012-10-13 02:07:45 +0000927 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Ed Masted78c9572014-04-20 00:31:37 +0000928 if (cmd_obj_sp.get() == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000929 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
930 return ret_val;
931 }
932 else
933 // We have more words in the command name, but we don't have a multiword object. Fail and return
934 // empty 'ret_val'.
935 return ret_val;
936 }
937 // We successfully looped through all the command words and got valid command objects for them. Assign the
938 // last object retrieved to 'ret_val'.
939 ret_val = cmd_obj_sp;
940 }
941 }
942 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000943}
944
945CommandObject *
946CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
947{
948 return GetCommandSPExact (cmd_cstr, include_aliases).get();
949}
950
951CommandObject *
952CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
953{
954 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
955
956 // If we didn't find an exact match to the command string in the commands, look in
957 // the aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000958
959 if (command_obj)
960 return command_obj;
Jim Ingham279a6c22010-07-06 22:46:59 +0000961
Enrico Granata5342c442013-06-18 18:01:08 +0000962 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
Jim Ingham279a6c22010-07-06 22:46:59 +0000963
Enrico Granata5342c442013-06-18 18:01:08 +0000964 if (command_obj)
965 return command_obj;
966
967 // If there wasn't an exact match then look for an inexact one in just the commands
Ed Masted78c9572014-04-20 00:31:37 +0000968 command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get();
Matt Kopec038ff812013-04-23 16:17:32 +0000969
970 // Finally, if there wasn't an inexact match among the commands, look for an inexact
971 // match in both the commands and aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000972
973 if (command_obj)
974 {
975 if (matches)
976 matches->AppendString(command_obj->GetCommandName());
977 return command_obj;
978 }
979
980 return GetCommandSP(cmd_cstr, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000981}
982
983bool
984CommandInterpreter::CommandExists (const char *cmd)
985{
986 return m_command_dict.find(cmd) != m_command_dict.end();
987}
988
989bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000990CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
991 const char *options_args,
992 OptionArgVectorSP &option_arg_vector_sp)
993{
994 bool success = true;
995 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
996
997 if (!options_args || (strlen (options_args) < 1))
998 return true;
999
1000 std::string options_string (options_args);
1001 Args args (options_args);
1002 CommandReturnObject result;
1003 // Check to see if the command being aliased can take any command options.
1004 Options *options = cmd_obj_sp->GetOptions ();
1005 if (options)
1006 {
1007 // See if any options were specified as part of the alias; if so, handle them appropriately.
1008 options->NotifyOptionParsingStarting ();
1009 args.Unshift ("dummy_arg");
1010 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
1011 args.Shift ();
1012 if (result.Succeeded())
1013 options->VerifyPartialOptions (result);
1014 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
1015 {
1016 result.AppendError ("Unable to create requested alias.\n");
1017 return false;
1018 }
1019 }
1020
Greg Clayton5521f992011-10-28 21:38:01 +00001021 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +00001022 {
1023 if (cmd_obj_sp->WantsRawCommandString ())
1024 option_arg_vector->push_back (OptionArgPair ("<argument>",
1025 OptionArgValue (-1,
1026 options_string)));
1027 else
1028 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001029 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +00001030 for (size_t i = 0; i < argc; ++i)
1031 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
1032 option_arg_vector->push_back
1033 (OptionArgPair ("<argument>",
1034 OptionArgValue (-1,
1035 std::string (args.GetArgumentAtIndex (i)))));
1036 }
1037 }
1038
1039 return success;
1040}
1041
1042bool
Jim Ingham298f3782013-04-03 00:25:49 +00001043CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
1044{
1045 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1046 if (exact_match)
1047 {
1048 full_name.assign(cmd);
1049 return exact_match;
1050 }
1051 else
1052 {
1053 StringList matches;
1054 size_t num_alias_matches;
1055 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
1056 if (num_alias_matches == 1)
1057 {
1058 // Make sure this isn't shadowing a command in the regular command space:
1059 StringList regular_matches;
1060 const bool include_aliases = false;
1061 const bool exact = false;
1062 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
1063 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1064 return false;
1065 else
1066 {
1067 full_name.assign (matches.GetStringAtIndex(0));
1068 return true;
1069 }
1070 }
1071 else
1072 return false;
1073 }
1074}
1075
1076bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001077CommandInterpreter::AliasExists (const char *cmd)
1078{
1079 return m_alias_dict.find(cmd) != m_alias_dict.end();
1080}
1081
1082bool
1083CommandInterpreter::UserCommandExists (const char *cmd)
1084{
1085 return m_user_dict.find(cmd) != m_user_dict.end();
1086}
1087
1088void
1089CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1090{
Jim Ingham279a6c22010-07-06 22:46:59 +00001091 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001092 m_alias_dict[alias_name] = command_obj_sp;
1093}
1094
1095bool
1096CommandInterpreter::RemoveAlias (const char *alias_name)
1097{
1098 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1099 if (pos != m_alias_dict.end())
1100 {
1101 m_alias_dict.erase(pos);
1102 return true;
1103 }
1104 return false;
1105}
Greg Claytonb5472782015-01-09 19:08:20 +00001106
1107bool
1108CommandInterpreter::RemoveCommand (const char *cmd)
1109{
1110 auto pos = m_command_dict.find(cmd);
1111 if (pos != m_command_dict.end())
1112 {
1113 if (pos->second->IsRemovable())
1114 {
1115 // Only regular expression objects or python commands are removable
1116 m_command_dict.erase(pos);
1117 return true;
1118 }
1119 }
1120 return false;
1121}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122bool
1123CommandInterpreter::RemoveUser (const char *alias_name)
1124{
1125 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1126 if (pos != m_user_dict.end())
1127 {
1128 m_user_dict.erase(pos);
1129 return true;
1130 }
1131 return false;
1132}
1133
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134void
1135CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1136{
1137 help_string.Printf ("'%s", command_name);
1138 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1139
Sean Callanan9a028512012-08-09 00:50:26 +00001140 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001141 {
1142 OptionArgVector *options = option_arg_vector_sp.get();
Andy Gibbsa297a972013-06-19 19:04:53 +00001143 for (size_t i = 0; i < options->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001144 {
1145 OptionArgPair cur_option = (*options)[i];
1146 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001147 OptionArgValue value_pair = cur_option.second;
1148 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001149 if (opt.compare("<argument>") == 0)
1150 {
1151 help_string.Printf (" %s", value.c_str());
1152 }
1153 else
1154 {
1155 help_string.Printf (" %s", opt.c_str());
1156 if ((value.compare ("<no-argument>") != 0)
1157 && (value.compare ("<need-argument") != 0))
1158 {
1159 help_string.Printf (" %s", value.c_str());
1160 }
1161 }
1162 }
1163 }
1164
1165 help_string.Printf ("'");
1166}
1167
Greg Clayton12fc3e02010-08-26 22:05:43 +00001168size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001169CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1170{
1171 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001172 CommandObject::CommandMap::const_iterator end = dict.end();
1173 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174
Greg Clayton12fc3e02010-08-26 22:05:43 +00001175 for (pos = dict.begin(); pos != end; ++pos)
1176 {
1177 size_t len = pos->first.size();
1178 if (max_len < len)
1179 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001180 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001181 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001182}
1183
1184void
Enrico Granata223383e2011-08-16 23:24:13 +00001185CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001186 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001187{
Kate Stonea487aa42015-01-15 00:52:41 +00001188 const char * help_prologue = GetDebugger().GetIOHandlerHelpPrologue();
1189 if (help_prologue != NULL)
1190 {
1191 OutputFormattedHelpText(result.GetOutputStream(), NULL, help_prologue);
1192 }
1193
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001195 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001196
1197 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001198 {
Kate Stonea487aa42015-01-15 00:52:41 +00001199 result.AppendMessage("Debugger commands:");
Enrico Granata223383e2011-08-16 23:24:13 +00001200 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001201
Enrico Granata223383e2011-08-16 23:24:13 +00001202 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1203 {
Kate Stonea487aa42015-01-15 00:52:41 +00001204 if (!(cmd_types & eCommandTypesHidden) && (pos->first.compare(0, 1, "_") == 0))
1205 continue;
1206
Enrico Granata223383e2011-08-16 23:24:13 +00001207 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1208 max_len);
1209 }
1210 result.AppendMessage("");
1211
1212 }
1213
Greg Clayton5521f992011-10-28 21:38:01 +00001214 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001215 {
Kate Stonea487aa42015-01-15 00:52:41 +00001216 result.AppendMessageWithFormat("Current command abbreviations "
1217 "(type '%shelp command alias' for more info):\n",
1218 GetCommandPrefix());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001219 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001220 max_len = FindLongestCommandWord (m_alias_dict);
1221
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001222 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1223 {
1224 StreamString sstr;
1225 StreamString translation_and_help;
1226 std::string entry_name = pos->first;
1227 std::string second_entry = pos->second.get()->GetCommandName();
1228 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1229
1230 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1231 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1232 translation_and_help.GetData(), max_len);
1233 }
1234 result.AppendMessage("");
1235 }
1236
Greg Clayton5521f992011-10-28 21:38:01 +00001237 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001238 {
Kate Stonea487aa42015-01-15 00:52:41 +00001239 result.AppendMessage ("Current user-defined commands:");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001240 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001241 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001242 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1243 {
Enrico Granata223383e2011-08-16 23:24:13 +00001244 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1245 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001246 }
1247 result.AppendMessage("");
1248 }
1249
Kate Stonea487aa42015-01-15 00:52:41 +00001250 result.AppendMessageWithFormat("For more information on any command, type '%shelp <command-name>'.\n",
1251 GetCommandPrefix());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001252}
1253
Caroline Tice844d2302010-12-09 22:52:49 +00001254CommandObject *
1255CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001256{
Caroline Tice844d2302010-12-09 22:52:49 +00001257 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1258 // eventually be invoked by the given command line.
1259
Ed Masted78c9572014-04-20 00:31:37 +00001260 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001261 std::string white_space (" \t\v");
1262 size_t start = command_string.find_first_not_of (white_space);
1263 size_t end = 0;
1264 bool done = false;
1265 while (!done)
1266 {
1267 if (start != std::string::npos)
1268 {
1269 // Get the next word from command_string.
1270 end = command_string.find_first_of (white_space, start);
1271 if (end == std::string::npos)
1272 end = command_string.size();
1273 std::string cmd_word = command_string.substr (start, end - start);
1274
Ed Masted78c9572014-04-20 00:31:37 +00001275 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001276 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1277 // command or alias.
1278 cmd_obj = GetCommandObject (cmd_word.c_str());
1279 else if (cmd_obj->IsMultiwordObject ())
1280 {
1281 // 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 +00001282 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001283 if (sub_cmd_obj)
1284 cmd_obj = sub_cmd_obj;
1285 else // cmd_word was not a valid sub-command word, so we are donee
1286 done = true;
1287 }
1288 else
1289 // We have a cmd_obj and it is not a multi-word object, so we are done.
1290 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001291
Caroline Tice844d2302010-12-09 22:52:49 +00001292 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1293 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1294 // next word.
1295
1296 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1297 done = true;
1298 else
1299 start = command_string.find_first_not_of (white_space, end);
1300 }
1301 else
1302 // Unable to find any more words.
1303 done = true;
1304 }
1305
1306 if (end == command_string.size())
1307 command_string.clear();
1308 else
1309 command_string = command_string.substr(end);
1310
1311 return cmd_obj;
1312}
1313
Greg Clayton51964162011-10-25 00:36:27 +00001314static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001315static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001316static void
1317StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001318{
Greg Clayton51964162011-10-25 00:36:27 +00001319 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001320 {
Greg Clayton51964162011-10-25 00:36:27 +00001321 size_t pos = s.find_first_not_of (k_white_space);
1322 if (pos == std::string::npos)
1323 s.clear();
1324 else if (pos == 0)
1325 return;
1326 s.erase (0, pos);
1327 }
1328}
1329
Greg Clayton93c62e62011-11-09 23:25:03 +00001330static size_t
1331FindArgumentTerminator (const std::string &s)
1332{
Greg Clayton93c62e62011-11-09 23:25:03 +00001333 const size_t s_len = s.size();
1334 size_t offset = 0;
1335 while (offset < s_len)
1336 {
1337 size_t pos = s.find ("--", offset);
1338 if (pos == std::string::npos)
1339 break;
1340 if (pos > 0)
1341 {
1342 if (isspace(s[pos-1]))
1343 {
1344 // Check if the string ends "\s--" (where \s is a space character)
1345 // or if we have "\s--\s".
1346 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1347 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001348 return pos;
1349 }
1350 }
1351 }
1352 offset = pos + 2;
1353 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001354 return std::string::npos;
1355}
1356
Greg Clayton51964162011-10-25 00:36:27 +00001357static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001358ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001359{
Greg Clayton5521f992011-10-28 21:38:01 +00001360 command.clear();
1361 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001362 StripLeadingSpaces (command_string);
1363
1364 bool result = false;
1365 quote_char = '\0';
1366
1367 if (!command_string.empty())
1368 {
1369 const char first_char = command_string[0];
1370 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001371 {
Greg Clayton51964162011-10-25 00:36:27 +00001372 quote_char = first_char;
1373 const size_t end_quote_pos = command_string.find (quote_char, 1);
1374 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001375 {
Greg Clayton5521f992011-10-28 21:38:01 +00001376 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001377 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001378 }
1379 else
1380 {
Greg Clayton5521f992011-10-28 21:38:01 +00001381 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001382 if (end_quote_pos + 1 < command_string.size())
1383 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1384 else
1385 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001386 }
Caroline Tice844d2302010-12-09 22:52:49 +00001387 }
1388 else
1389 {
Greg Clayton51964162011-10-25 00:36:27 +00001390 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1391 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001392 {
Greg Clayton5521f992011-10-28 21:38:01 +00001393 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001394 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001395 }
1396 else
1397 {
Greg Clayton5521f992011-10-28 21:38:01 +00001398 command.assign (command_string, 0, first_space_pos);
1399 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001400 }
Caroline Tice844d2302010-12-09 22:52:49 +00001401 }
Greg Clayton51964162011-10-25 00:36:27 +00001402 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001403 }
Greg Clayton5521f992011-10-28 21:38:01 +00001404
1405
1406 if (!command.empty())
1407 {
1408 // actual commands can't start with '-' or '_'
1409 if (command[0] != '-' && command[0] != '_')
1410 {
1411 size_t pos = command.find_first_not_of(k_valid_command_chars);
1412 if (pos > 0 && pos != std::string::npos)
1413 {
1414 suffix.assign (command.begin() + pos, command.end());
1415 command.erase (pos);
1416 }
1417 }
1418 }
Greg Clayton51964162011-10-25 00:36:27 +00001419
1420 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001421}
1422
Greg Clayton5521f992011-10-28 21:38:01 +00001423CommandObject *
1424CommandInterpreter::BuildAliasResult (const char *alias_name,
1425 std::string &raw_input_string,
1426 std::string &alias_result,
1427 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001428{
Ed Masted78c9572014-04-20 00:31:37 +00001429 CommandObject *alias_cmd_obj = nullptr;
Pavel Labath00b7f952015-03-02 12:46:22 +00001430 Args cmd_args (raw_input_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001431 alias_cmd_obj = GetCommandObject (alias_name);
1432 StreamString result_str;
1433
1434 if (alias_cmd_obj)
1435 {
1436 std::string alias_name_str = alias_name;
1437 if ((cmd_args.GetArgumentCount() == 0)
1438 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1439 cmd_args.Unshift (alias_name);
1440
1441 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1442 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1443
1444 if (option_arg_vector_sp.get())
1445 {
1446 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1447
Andy Gibbsa297a972013-06-19 19:04:53 +00001448 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Caroline Tice844d2302010-12-09 22:52:49 +00001449 {
1450 OptionArgPair option_pair = (*option_arg_vector)[i];
1451 OptionArgValue value_pair = option_pair.second;
1452 int value_type = value_pair.first;
1453 std::string option = option_pair.first;
1454 std::string value = value_pair.second;
1455 if (option.compare ("<argument>") == 0)
1456 result_str.Printf (" %s", value.c_str());
1457 else
1458 {
1459 result_str.Printf (" %s", option.c_str());
Ted Woodwarde7e8e3c2015-04-06 21:55:14 +00001460 if (value_type != OptionParser::eNoArgument)
Caroline Tice844d2302010-12-09 22:52:49 +00001461 {
Ted Woodwarde7e8e3c2015-04-06 21:55:14 +00001462 if (value_type != OptionParser::eOptionalArgument)
1463 result_str.Printf (" ");
Caroline Tice844d2302010-12-09 22:52:49 +00001464 int index = GetOptionArgumentPosition (value.c_str());
1465 if (index == 0)
1466 result_str.Printf ("%s", value.c_str());
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001467 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Caroline Tice844d2302010-12-09 22:52:49 +00001468 {
1469
1470 result.AppendErrorWithFormat
1471 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1472 index);
1473 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001474 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001475 }
1476 else
1477 {
1478 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1479 if (strpos != std::string::npos)
1480 raw_input_string = raw_input_string.erase (strpos,
1481 strlen (cmd_args.GetArgumentAtIndex (index)));
1482 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1483 }
1484 }
1485 }
1486 }
1487 }
1488
1489 alias_result = result_str.GetData();
1490 }
Greg Clayton5521f992011-10-28 21:38:01 +00001491 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001492}
1493
Greg Clayton5a314712011-10-14 07:41:33 +00001494Error
1495CommandInterpreter::PreprocessCommand (std::string &command)
1496{
1497 // The command preprocessor needs to do things to the command
1498 // line before any parsing of arguments or anything else is done.
1499 // The only current stuff that gets proprocessed is anyting enclosed
1500 // in backtick ('`') characters is evaluated as an expression and
1501 // the result of the expression must be a scalar that can be substituted
1502 // into the command. An example would be:
1503 // (lldb) memory read `$rsp + 20`
1504 Error error; // Error for any expressions that might not evaluate
1505 size_t start_backtick;
1506 size_t pos = 0;
1507 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1508 {
1509 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1510 {
1511 // The backtick was preceeded by a '\' character, remove the slash
1512 // and don't treat the backtick as the start of an expression
1513 command.erase(start_backtick-1, 1);
1514 // No need to add one to start_backtick since we just deleted a char
1515 pos = start_backtick;
1516 }
1517 else
1518 {
1519 const size_t expr_content_start = start_backtick + 1;
1520 const size_t end_backtick = command.find ('`', expr_content_start);
1521 if (end_backtick == std::string::npos)
1522 return error;
1523 else if (end_backtick == expr_content_start)
1524 {
1525 // Empty expression (two backticks in a row)
1526 command.erase (start_backtick, 2);
1527 }
1528 else
1529 {
1530 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1531
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001532 ExecutionContext exe_ctx(GetExecutionContext());
1533 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001534 // Get a dummy target to allow for calculator mode while processing backticks.
1535 // This also helps break the infinite loop caused when target is null.
1536 if (!target)
Jim Ingham893c9322014-11-22 01:42:44 +00001537 target = m_debugger.GetDummyTarget();
Greg Clayton5a314712011-10-14 07:41:33 +00001538 if (target)
1539 {
Greg Clayton5a314712011-10-14 07:41:33 +00001540 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001541
Jim Ingham35e1bda2012-10-16 21:41:58 +00001542 EvaluateExpressionOptions options;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00001543 options.SetCoerceToId(false);
1544 options.SetUnwindOnError(true);
1545 options.SetIgnoreBreakpoints(true);
1546 options.SetKeepInMemory(false);
1547 options.SetTryAllThreads(true);
1548 options.SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001549
Jim Ingham1624a2d2014-05-05 02:26:40 +00001550 ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granataca0e5ad2014-10-09 23:09:40 +00001551 exe_ctx.GetFramePtr(),
1552 expr_result_valobj_sp,
1553 options);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001554
Jim Ingham8646d3c2014-05-05 02:47:44 +00001555 if (expr_result == eExpressionCompleted)
Greg Clayton5a314712011-10-14 07:41:33 +00001556 {
1557 Scalar scalar;
Enrico Granataca0e5ad2014-10-09 23:09:40 +00001558 if (expr_result_valobj_sp)
1559 expr_result_valobj_sp = expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(expr_result_valobj_sp->GetDynamicValueType(), true);
Greg Clayton5a314712011-10-14 07:41:33 +00001560 if (expr_result_valobj_sp->ResolveValue (scalar))
1561 {
1562 command.erase (start_backtick, end_backtick - start_backtick + 1);
1563 StreamString value_strm;
1564 const bool show_type = false;
1565 scalar.GetValue (&value_strm, show_type);
1566 size_t value_string_size = value_strm.GetSize();
1567 if (value_string_size)
1568 {
1569 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1570 pos = start_backtick + value_string_size;
1571 continue;
1572 }
1573 else
1574 {
1575 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1576 }
1577 }
1578 else
1579 {
1580 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1581 }
1582 }
1583 else
1584 {
1585 if (expr_result_valobj_sp)
1586 error = expr_result_valobj_sp->GetError();
1587 if (error.Success())
1588 {
1589
1590 switch (expr_result)
1591 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00001592 case eExpressionSetupError:
Greg Clayton5a314712011-10-14 07:41:33 +00001593 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1594 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001595 case eExpressionParseError:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001596 error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str());
1597 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001598 case eExpressionResultUnavailable:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001599 error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str());
Jim Ingham8646d3c2014-05-05 02:47:44 +00001600 case eExpressionCompleted:
Greg Clayton5a314712011-10-14 07:41:33 +00001601 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001602 case eExpressionDiscarded:
Greg Clayton5a314712011-10-14 07:41:33 +00001603 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1604 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001605 case eExpressionInterrupted:
Greg Clayton5a314712011-10-14 07:41:33 +00001606 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1607 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001608 case eExpressionHitBreakpoint:
Jim Ingham184e9812013-01-15 02:47:48 +00001609 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1610 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001611 case eExpressionTimedOut:
Greg Clayton5a314712011-10-14 07:41:33 +00001612 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1613 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001614 case eExpressionStoppedForDebug:
Greg Claytonc28ce782013-11-08 23:38:26 +00001615 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1616 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001617 }
1618 }
1619 }
1620 }
1621 }
1622 if (error.Fail())
1623 break;
1624 }
1625 }
1626 return error;
1627}
1628
1629
Caroline Tice844d2302010-12-09 22:52:49 +00001630bool
1631CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001632 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001633 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001634 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001635 bool repeat_on_empty_command,
1636 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001637
Caroline Tice844d2302010-12-09 22:52:49 +00001638{
Jim Inghame16c50a2011-02-18 00:54:25 +00001639
Caroline Tice844d2302010-12-09 22:52:49 +00001640 bool done = false;
Ed Masted78c9572014-04-20 00:31:37 +00001641 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001642 bool wants_raw_input = false;
1643 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001644 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001645
Greg Clayton5160ce52013-03-27 23:08:40 +00001646 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001647 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1648
1649 // Make a scoped cleanup object that will clear the crash description string
1650 // on exit of this function.
Ed Masted78c9572014-04-20 00:31:37 +00001651 lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001652
Caroline Tice844d2302010-12-09 22:52:49 +00001653 if (log)
1654 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001655
Jim Ingham30244832010-11-04 23:08:45 +00001656 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1657
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001658 if (!no_context_switching)
1659 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001660
Enrico Granata5f5ab602012-05-31 01:09:06 +00001661 bool add_to_history;
1662 if (lazy_add_to_history == eLazyBoolCalculate)
1663 add_to_history = (m_command_source_depth == 0);
1664 else
1665 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1666
Jim Inghame16c50a2011-02-18 00:54:25 +00001667 bool empty_command = false;
1668 bool comment_command = false;
1669 if (command_string.empty())
1670 empty_command = true;
1671 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001672 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001673 const char *k_space_characters = "\t\n\v\f\r ";
1674
1675 size_t non_space = command_string.find_first_not_of (k_space_characters);
1676 // Check for empty line or comment line (lines whose first
1677 // non-space character is the comment character for this interpreter)
1678 if (non_space == std::string::npos)
1679 empty_command = true;
1680 else if (command_string[non_space] == m_comment_char)
1681 comment_command = true;
Enrico Granata7594f142013-06-17 22:51:50 +00001682 else if (command_string[non_space] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001683 {
Enrico Granata7594f142013-06-17 22:51:50 +00001684 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
Ed Masted78c9572014-04-20 00:31:37 +00001685 if (history_string == nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001686 {
1687 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1688 result.SetStatus(eReturnStatusFailed);
1689 return false;
1690 }
1691 add_to_history = false;
1692 command_string = history_string;
1693 original_command_string = history_string;
1694 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001695 }
1696
1697 if (empty_command)
1698 {
1699 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001700 {
Enrico Granata7594f142013-06-17 22:51:50 +00001701 if (m_command_history.IsEmpty())
Jim Inghame16c50a2011-02-18 00:54:25 +00001702 {
1703 result.AppendError ("empty command");
1704 result.SetStatus(eReturnStatusFailed);
1705 return false;
1706 }
1707 else
1708 {
1709 command_line = m_repeat_command.c_str();
1710 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001711 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001712 if (m_repeat_command.empty())
1713 {
1714 result.AppendErrorWithFormat("No auto repeat.\n");
1715 result.SetStatus (eReturnStatusFailed);
1716 return false;
1717 }
1718 }
1719 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001720 }
1721 else
1722 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001723 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1724 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001725 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001726 }
1727 else if (comment_command)
1728 {
1729 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1730 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001731 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001732
Greg Clayton5a314712011-10-14 07:41:33 +00001733
1734 Error error (PreprocessCommand (command_string));
1735
1736 if (error.Fail())
1737 {
1738 result.AppendError (error.AsCString());
1739 result.SetStatus(eReturnStatusFailed);
1740 return false;
1741 }
Caroline Tice844d2302010-12-09 22:52:49 +00001742 // Phase 1.
1743
1744 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1745 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1746 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1747 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1748 // the translation. So this first step is plain look-up & replacement, resulting in three things: 1). the command
Greg Clayton710dd5a2011-01-08 20:28:42 +00001749 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001750 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001751
Caroline Tice844d2302010-12-09 22:52:49 +00001752 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001753 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001754 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001755 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001756 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001757 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001758 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001759 std::string suffix;
1760 ExtractCommand (command_string, next_word, suffix, quote_char);
Ed Masted78c9572014-04-20 00:31:37 +00001761 if (cmd_obj == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001762 {
Jim Ingham298f3782013-04-03 00:25:49 +00001763 std::string full_name;
1764 if (GetAliasFullName(next_word.c_str(), full_name))
Caroline Tice472362e2010-12-14 18:51:39 +00001765 {
Greg Clayton5521f992011-10-28 21:38:01 +00001766 std::string alias_result;
Jim Ingham298f3782013-04-03 00:25:49 +00001767 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
Greg Clayton5521f992011-10-28 21:38:01 +00001768 revised_command_line.Printf ("%s", alias_result.c_str());
1769 if (cmd_obj)
1770 {
1771 wants_raw_input = cmd_obj->WantsRawCommandString ();
1772 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1773 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001774 }
1775 else
1776 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001777 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001778 if (cmd_obj)
1779 {
1780 actual_cmd_name_len += next_word.length();
1781 revised_command_line.Printf ("%s", next_word.c_str());
1782 wants_raw_input = cmd_obj->WantsRawCommandString ();
1783 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001784 else
Greg Clayton5521f992011-10-28 21:38:01 +00001785 {
1786 revised_command_line.Printf ("%s", next_word.c_str());
1787 }
Caroline Tice844d2302010-12-09 22:52:49 +00001788 }
1789 }
1790 else
1791 {
Greg Clayton5521f992011-10-28 21:38:01 +00001792 if (cmd_obj->IsMultiwordObject ())
1793 {
Greg Clayton998255b2012-10-13 02:07:45 +00001794 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001795 if (sub_cmd_obj)
1796 {
1797 actual_cmd_name_len += next_word.length() + 1;
1798 revised_command_line.Printf (" %s", next_word.c_str());
1799 cmd_obj = sub_cmd_obj;
1800 wants_raw_input = cmd_obj->WantsRawCommandString ();
1801 }
1802 else
1803 {
1804 if (quote_char)
1805 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1806 else
1807 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1808 done = true;
1809 }
1810 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001811 else
Greg Clayton5521f992011-10-28 21:38:01 +00001812 {
1813 if (quote_char)
1814 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1815 else
1816 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1817 done = true;
1818 }
Caroline Tice844d2302010-12-09 22:52:49 +00001819 }
1820
Ed Masted78c9572014-04-20 00:31:37 +00001821 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001822 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001823 const size_t num_matches = matches.GetSize();
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001824 if (matches.GetSize() > 1) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001825 StreamString error_msg;
1826 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001827
1828 for (uint32_t i = 0; i < num_matches; ++i) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001829 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001830 }
Greg Claytonc7bece562013-01-25 18:06:21 +00001831 result.AppendRawError (error_msg.GetString().c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001832 } else {
1833 // We didn't have only one match, otherwise we wouldn't get here.
1834 assert(num_matches == 0);
1835 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1836 }
Caroline Tice844d2302010-12-09 22:52:49 +00001837 result.SetStatus (eReturnStatusFailed);
1838 return false;
1839 }
1840
Greg Clayton5521f992011-10-28 21:38:01 +00001841 if (cmd_obj->IsMultiwordObject ())
1842 {
1843 if (!suffix.empty())
1844 {
1845
Enrico Granataaded51d2013-06-12 00:44:43 +00001846 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1847 cmd_obj->GetCommandName(),
1848 next_word.empty() ? "" : next_word.c_str(),
1849 next_word.empty() ? " -- " : " ",
Greg Clayton5521f992011-10-28 21:38:01 +00001850 suffix.c_str());
1851 result.SetStatus (eReturnStatusFailed);
1852 return false;
1853 }
1854 }
1855 else
1856 {
1857 // If we found a normal command, we are done
1858 done = true;
1859 if (!suffix.empty())
1860 {
1861 switch (suffix[0])
1862 {
1863 case '/':
1864 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001865 {
1866 Options *command_options = cmd_obj->GetOptions();
1867 if (command_options && command_options->SupportsLongOption("gdb-format"))
1868 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001869 std::string gdb_format_option ("--gdb-format=");
1870 gdb_format_option += (suffix.c_str() + 1);
1871
1872 bool inserted = false;
1873 std::string &cmd = revised_command_line.GetString();
1874 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1875 if (arg_terminator_idx != std::string::npos)
1876 {
1877 // Insert the gdb format option before the "--" that terminates options
1878 gdb_format_option.append(1,' ');
1879 cmd.insert(arg_terminator_idx, gdb_format_option);
1880 inserted = true;
1881 }
1882
1883 if (!inserted)
1884 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1885
1886 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1887 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001888 }
1889 else
1890 {
1891 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1892 cmd_obj->GetCommandName());
1893 result.SetStatus (eReturnStatusFailed);
1894 return false;
1895 }
1896 }
Greg Clayton5521f992011-10-28 21:38:01 +00001897 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001898
1899 default:
1900 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1901 suffix.c_str());
1902 result.SetStatus (eReturnStatusFailed);
1903 return false;
1904
Greg Clayton5521f992011-10-28 21:38:01 +00001905 }
1906 }
1907 }
Caroline Tice844d2302010-12-09 22:52:49 +00001908 if (command_string.length() == 0)
1909 done = true;
1910
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001911 }
Caroline Tice844d2302010-12-09 22:52:49 +00001912
Greg Clayton5521f992011-10-28 21:38:01 +00001913 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001914 revised_command_line.Printf (" %s", command_string.c_str());
1915
1916 // End of Phase 1.
1917 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1918 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1919 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1920 // wants_raw_input specifies whether the Execute method expects raw input or not.
1921
1922
1923 if (log)
1924 {
1925 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1926 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1927 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1928 }
1929
1930 // Phase 2.
1931 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1932 // CommandObject, with the appropriate arguments.
1933
Ed Masted78c9572014-04-20 00:31:37 +00001934 if (cmd_obj != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001935 {
1936 if (add_to_history)
1937 {
1938 Args command_args (revised_command_line.GetData());
1939 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
Ed Masted78c9572014-04-20 00:31:37 +00001940 if (repeat_command != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001941 m_repeat_command.assign(repeat_command);
1942 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001943 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001944
Enrico Granata7594f142013-06-17 22:51:50 +00001945 m_command_history.AppendString (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001946 }
1947
1948 command_string = revised_command_line.GetData();
1949 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001950 std::string remainder;
1951 if (actual_cmd_name_len < command_string.length())
1952 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1953 // than cmd_obj->GetCommandName(), because name completion
1954 // allows users to enter short versions of the names,
1955 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001956
1957 // Remove any initial spaces
1958 std::string white_space (" \t\v");
1959 size_t pos = remainder.find_first_not_of (white_space);
1960 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001961 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001962
1963 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001964 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001965
Jim Ingham5a988412012-06-08 21:56:10 +00001966 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001967 }
1968 else
1969 {
1970 // We didn't find the first command object, so complete the first argument.
1971 Args command_args (revised_command_line.GetData());
1972 StringList matches;
1973 int num_matches;
1974 int cursor_index = 0;
1975 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1976 bool word_complete;
1977 num_matches = HandleCompletionMatches (command_args,
1978 cursor_index,
1979 cursor_char_position,
1980 0,
1981 -1,
1982 word_complete,
1983 matches);
1984
1985 if (num_matches > 0)
1986 {
1987 std::string error_msg;
1988 error_msg.assign ("ambiguous command '");
1989 error_msg.append(command_args.GetArgumentAtIndex(0));
1990 error_msg.append ("'.");
1991
1992 error_msg.append (" Possible completions:");
1993 for (int i = 0; i < num_matches; i++)
1994 {
1995 error_msg.append ("\n\t");
1996 error_msg.append (matches.GetStringAtIndex (i));
1997 }
1998 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001999 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00002000 }
2001 else
2002 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
2003
2004 result.SetStatus (eReturnStatusFailed);
2005 }
2006
Jason Molendabfb36ff2011-08-25 00:20:04 +00002007 if (log)
2008 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
2009
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002010 return result.Succeeded();
2011}
2012
2013int
2014CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
2015 int &cursor_index,
2016 int &cursor_char_position,
2017 int match_start_point,
2018 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00002019 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002020 StringList &matches)
2021{
2022 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002023 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00002024
2025 // For any of the command completions a unique match will be a complete word.
2026 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002027
2028 if (cursor_index == -1)
2029 {
2030 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00002031 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002032 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
2033 }
2034 else if (cursor_index == 0)
2035 {
2036 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00002037 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002038 num_command_matches = matches.GetSize();
2039
2040 if (num_command_matches == 1
2041 && cmd_obj && cmd_obj->IsMultiwordObject()
Ed Masted78c9572014-04-20 00:31:37 +00002042 && matches.GetStringAtIndex(0) != nullptr
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002043 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
2044 {
Greg Clayton765d2e22013-12-10 19:14:04 +00002045 if (parsed_line.GetArgumentCount() == 1)
2046 {
2047 word_complete = true;
2048 }
2049 else
2050 {
2051 look_for_subcommand = true;
2052 num_command_matches = 0;
2053 matches.DeleteStringAtIndex(0);
2054 parsed_line.AppendArgument ("");
2055 cursor_index++;
2056 cursor_char_position = 0;
2057 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002058 }
2059 }
2060
2061 if (cursor_index > 0 || look_for_subcommand)
2062 {
2063 // We are completing further on into a commands arguments, so find the command and tell it
2064 // to complete the command.
2065 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00002066 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Ed Masted78c9572014-04-20 00:31:37 +00002067 if (command_object == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002068 {
2069 return 0;
2070 }
2071 else
2072 {
2073 parsed_line.Shift();
2074 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00002075 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00002076 cursor_index,
2077 cursor_char_position,
2078 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002079 max_return_elements,
2080 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002081 matches);
2082 }
2083 }
2084
2085 return num_command_matches;
2086
2087}
2088
2089int
2090CommandInterpreter::HandleCompletion (const char *current_line,
2091 const char *cursor,
2092 const char *last_char,
2093 int match_start_point,
2094 int max_return_elements,
2095 StringList &matches)
2096{
2097 // We parse the argument up to the cursor, so the last argument in parsed_line is
2098 // the one containing the cursor, and the cursor is after the last character.
2099
Pavel Labath00b7f952015-03-02 12:46:22 +00002100 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
2101 Args partial_parsed_line(llvm::StringRef(current_line, cursor - current_line));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002102
Jim Inghama5a97eb2011-07-12 03:12:18 +00002103 // Don't complete comments, and if the line we are completing is just the history repeat character,
2104 // substitute the appropriate history line.
2105 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
2106 if (first_arg)
2107 {
2108 if (first_arg[0] == m_comment_char)
2109 return 0;
Enrico Granata7594f142013-06-17 22:51:50 +00002110 else if (first_arg[0] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002111 {
Enrico Granata7594f142013-06-17 22:51:50 +00002112 const char *history_string = m_command_history.FindString (first_arg);
Ed Masted78c9572014-04-20 00:31:37 +00002113 if (history_string != nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002114 {
2115 matches.Clear();
2116 matches.InsertStringAtIndex(0, history_string);
2117 return -2;
2118 }
2119 else
2120 return 0;
2121
2122 }
2123 }
2124
2125
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002126 int num_args = partial_parsed_line.GetArgumentCount();
2127 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2128 int cursor_char_position;
2129
2130 if (cursor_index == -1)
2131 cursor_char_position = 0;
2132 else
2133 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00002134
2135 if (cursor > current_line && cursor[-1] == ' ')
2136 {
2137 // We are just after a space. If we are in an argument, then we will continue
2138 // parsing, but if we are between arguments, then we have to complete whatever the next
2139 // element would be.
2140 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2141 // protected by a quote) then the space will also be in the parsed argument...
2142
2143 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2144 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2145 {
Greg Clayton765d2e22013-12-10 19:14:04 +00002146 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
Jim Inghamfe0c4252010-12-14 19:56:01 +00002147 cursor_index++;
2148 cursor_char_position = 0;
2149 }
2150 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002151
2152 int num_command_matches;
2153
2154 matches.Clear();
2155
2156 // Only max_return_elements == -1 is supported at present:
2157 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00002158 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00002159 num_command_matches = HandleCompletionMatches (parsed_line,
2160 cursor_index,
2161 cursor_char_position,
2162 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002163 max_return_elements,
2164 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002165 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002166
2167 if (num_command_matches <= 0)
2168 return num_command_matches;
2169
2170 if (num_args == 0)
2171 {
2172 // If we got an empty string, insert nothing.
2173 matches.InsertStringAtIndex(0, "");
2174 }
2175 else
2176 {
2177 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2178 // put an empty string in element 0.
2179 std::string command_partial_str;
2180 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002181 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2182 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002183
2184 std::string common_prefix;
2185 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002186 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002187
2188 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002189 // Only do this if the completer told us this was a complete word, however...
2190 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002191 {
2192 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2193 if (quote_char != '\0')
2194 common_prefix.push_back(quote_char);
2195
2196 common_prefix.push_back(' ');
2197 }
2198 common_prefix.erase (0, partial_name_len);
2199 matches.InsertStringAtIndex(0, common_prefix.c_str());
2200 }
2201 return num_command_matches;
2202}
2203
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002204
2205CommandInterpreter::~CommandInterpreter ()
2206{
2207}
2208
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002209void
Greg Clayton44d93782014-01-27 23:43:24 +00002210CommandInterpreter::UpdatePrompt (const char *new_prompt)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002211{
Greg Clayton44d93782014-01-27 23:43:24 +00002212 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2213 BroadcastEvent (prompt_change_event_sp);
2214 if (m_command_io_handler_sp)
2215 m_command_io_handler_sp->SetPrompt(new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002216}
2217
Jim Ingham97a6dc72010-10-04 19:49:29 +00002218
2219bool
2220CommandInterpreter::Confirm (const char *message, bool default_answer)
2221{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002222 // Check AutoConfirm first:
2223 if (m_debugger.GetAutoConfirm())
2224 return default_answer;
Greg Clayton44d93782014-01-27 23:43:24 +00002225
2226 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2227 message,
2228 default_answer);
2229 IOHandlerSP io_handler_sp (confirm);
2230 m_debugger.RunIOHandler (io_handler_sp);
2231 return confirm->GetResponse();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002232}
2233
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002234OptionArgVectorSP
2235CommandInterpreter::GetAliasOptions (const char *alias_name)
2236{
2237 OptionArgMap::iterator pos;
2238 OptionArgVectorSP ret_val;
2239
2240 std::string alias (alias_name);
2241
2242 if (HasAliasOptions())
2243 {
2244 pos = m_alias_options.find (alias);
2245 if (pos != m_alias_options.end())
2246 ret_val = pos->second;
2247 }
2248
2249 return ret_val;
2250}
2251
2252void
2253CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2254{
2255 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2256 if (pos != m_alias_options.end())
2257 {
2258 m_alias_options.erase (pos);
2259 }
2260}
2261
2262void
2263CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2264{
2265 m_alias_options[alias_name] = option_arg_vector_sp;
2266}
2267
2268bool
2269CommandInterpreter::HasCommands ()
2270{
2271 return (!m_command_dict.empty());
2272}
2273
2274bool
2275CommandInterpreter::HasAliases ()
2276{
2277 return (!m_alias_dict.empty());
2278}
2279
2280bool
2281CommandInterpreter::HasUserCommands ()
2282{
2283 return (!m_user_dict.empty());
2284}
2285
2286bool
2287CommandInterpreter::HasAliasOptions ()
2288{
2289 return (!m_alias_options.empty());
2290}
2291
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002292void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002293CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2294 const char *alias_name,
2295 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002296 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002297 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002298{
2299 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002300
2301 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002302
Caroline Ticed9d63362010-12-07 19:58:26 +00002303 // Make sure that the alias name is the 0th element in cmd_args
2304 std::string alias_name_str = alias_name;
2305 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2306 cmd_args.Unshift (alias_name);
2307
2308 Args new_args (alias_cmd_obj->GetCommandName());
2309 if (new_args.GetArgumentCount() == 2)
2310 new_args.Shift();
2311
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002312 if (option_arg_vector_sp.get())
2313 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002314 if (wants_raw_input)
2315 {
2316 // We have a command that both has command options and takes raw input. Make *sure* it has a
2317 // " -- " in the right place in the raw_input_string.
2318 size_t pos = raw_input_string.find(" -- ");
2319 if (pos == std::string::npos)
2320 {
2321 // None found; assume it goes at the beginning of the raw input string
2322 raw_input_string.insert (0, " -- ");
2323 }
2324 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002325
2326 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002327 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002328 std::vector<bool> used (old_size + 1, false);
2329
2330 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002331
Andy Gibbsa297a972013-06-19 19:04:53 +00002332 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002333 {
2334 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002335 OptionArgValue value_pair = option_pair.second;
2336 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002337 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002338 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002339 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002340 {
2341 if (!wants_raw_input
2342 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2343 new_args.AppendArgument (value.c_str());
2344 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002345 else
2346 {
Virgile Belloe2607b52013-09-05 16:42:23 +00002347 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002348 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002349 if (value.compare ("<no-argument>") != 0)
2350 {
2351 int index = GetOptionArgumentPosition (value.c_str());
2352 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002353 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002354 // value was NOT a positional argument; must be a real value
Virgile Belloe2607b52013-09-05 16:42:23 +00002355 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002356 new_args.AppendArgument (value.c_str());
2357 else
2358 {
2359 char buffer[255];
2360 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2361 new_args.AppendArgument (buffer);
2362 }
2363
2364 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002365 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002366 {
2367 result.AppendErrorWithFormat
2368 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2369 index);
2370 result.SetStatus (eReturnStatusFailed);
2371 return;
2372 }
2373 else
2374 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002375 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2376 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2377 if (strpos != std::string::npos)
2378 {
2379 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2380 }
2381
Virgile Belloe2607b52013-09-05 16:42:23 +00002382 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002383 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2384 else
2385 {
2386 char buffer[255];
2387 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2388 cmd_args.GetArgumentAtIndex (index));
2389 new_args.AppendArgument (buffer);
2390 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002391 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002392 }
2393 }
2394 }
2395 }
2396
Andy Gibbsa297a972013-06-19 19:04:53 +00002397 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002398 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002399 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002400 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2401 }
2402
2403 cmd_args.Clear();
2404 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2405 }
2406 else
2407 {
2408 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002409 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2410 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2411 // input string.
2412 if (wants_raw_input)
2413 {
2414 cmd_args.Clear();
2415 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2416 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002417 return;
2418 }
2419
2420 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2421 return;
2422}
2423
2424
2425int
2426CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2427{
2428 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2429 // of zero.
2430
2431 char *cptr = (char *) in_string;
2432
2433 // Does it start with '%'
2434 if (cptr[0] == '%')
2435 {
2436 ++cptr;
2437
2438 // Is the rest of it entirely digits?
2439 if (isdigit (cptr[0]))
2440 {
2441 const char *start = cptr;
2442 while (isdigit (cptr[0]))
2443 ++cptr;
2444
2445 // We've gotten to the end of the digits; are we at the end of the string?
2446 if (cptr[0] == '\0')
2447 position = atoi (start);
2448 }
2449 }
2450
2451 return position;
2452}
2453
2454void
2455CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2456{
Jim Ingham16e0c682011-08-12 23:34:31 +00002457 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002458 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002459 {
Greg Clayton14a35512011-09-11 00:01:44 +00002460 // In the current working directory we don't load any program specific
2461 // .lldbinit files, we only look for a "./.lldbinit" file.
2462 if (m_skip_lldbinit_files)
2463 return;
2464
2465 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002466 }
Greg Clayton14a35512011-09-11 00:01:44 +00002467 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002468 {
Greg Clayton14a35512011-09-11 00:01:44 +00002469 // If we aren't looking in the current working directory we are looking
2470 // in the home directory. We will first see if there is an application
2471 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2472 // "-" and the name of the program. If this file doesn't exist, we fall
2473 // back to just the "~/.lldbinit" file. We also obey any requests to not
2474 // load the init files.
Zachary Turnera21fee02014-08-21 21:49:24 +00002475 llvm::SmallString<64> home_dir_path;
2476 llvm::sys::path::home_directory(home_dir_path);
2477 FileSpec profilePath(home_dir_path.c_str(), false);
Zachary Turner9e757b72014-07-28 16:45:05 +00002478 profilePath.AppendPathComponent(".lldbinit");
2479 std::string init_file_path = profilePath.GetPath();
Greg Clayton14a35512011-09-11 00:01:44 +00002480
2481 if (m_skip_app_init_files == false)
2482 {
Zachary Turnera21fee02014-08-21 21:49:24 +00002483 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
Greg Clayton14a35512011-09-11 00:01:44 +00002484 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002485
Greg Clayton14a35512011-09-11 00:01:44 +00002486 if (program_name)
2487 {
2488 char program_init_file_name[PATH_MAX];
Zachary Turner9e757b72014-07-28 16:45:05 +00002489 ::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 +00002490 init_file.SetFile (program_init_file_name, true);
2491 if (!init_file.Exists())
2492 init_file.Clear();
2493 }
2494 }
2495
2496 if (!init_file && !m_skip_lldbinit_files)
Zachary Turner9e757b72014-07-28 16:45:05 +00002497 init_file.SetFile (init_file_path.c_str(), false);
Greg Clayton14a35512011-09-11 00:01:44 +00002498 }
2499
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002500 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2501 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2502
2503 if (init_file.Exists())
2504 {
Greg Clayton44d93782014-01-27 23:43:24 +00002505 const bool saved_batch = SetBatchCommandMode (true);
Jim Ingham26c7bf92014-10-11 00:38:27 +00002506 CommandInterpreterRunOptions options;
2507 options.SetSilent (true);
2508 options.SetStopOnError (false);
2509 options.SetStopOnContinue (true);
2510
Greg Clayton340b0302014-02-05 17:57:57 +00002511 HandleCommandsFromFile (init_file,
Ed Masted78c9572014-04-20 00:31:37 +00002512 nullptr, // Execution context
Jim Ingham26c7bf92014-10-11 00:38:27 +00002513 options,
Greg Clayton340b0302014-02-05 17:57:57 +00002514 result);
Greg Clayton44d93782014-01-27 23:43:24 +00002515 SetBatchCommandMode (saved_batch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002516 }
2517 else
2518 {
2519 // nothing to be done if the file doesn't exist
2520 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2521 }
2522}
2523
Kate Stonea487aa42015-01-15 00:52:41 +00002524const char *
2525CommandInterpreter::GetCommandPrefix()
2526{
2527 const char * prefix = GetDebugger().GetIOHandlerCommandPrefix();
2528 return prefix == NULL ? "" : prefix;
2529}
2530
Greg Clayton8b82f082011-04-12 05:54:46 +00002531PlatformSP
2532CommandInterpreter::GetPlatform (bool prefer_target_platform)
2533{
2534 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002535 if (prefer_target_platform)
2536 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002537 ExecutionContext exe_ctx(GetExecutionContext());
2538 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002539 if (target)
2540 platform_sp = target->GetPlatform();
2541 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002542
2543 if (!platform_sp)
2544 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2545 return platform_sp;
2546}
2547
Jim Inghame16c50a2011-02-18 00:54:25 +00002548void
Jim Inghambad87fe2011-03-11 01:51:49 +00002549CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham26c7bf92014-10-11 00:38:27 +00002550 ExecutionContext *override_context,
2551 CommandInterpreterRunOptions &options,
Jim Inghame16c50a2011-02-18 00:54:25 +00002552 CommandReturnObject &result)
2553{
2554 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002555
2556 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2557 // Make sure you reset this value anywhere you return from the function.
2558
2559 bool old_async_execution = m_debugger.GetAsyncExecution();
2560
2561 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2562 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2563
Ed Masted78c9572014-04-20 00:31:37 +00002564 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002565 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002566
Jim Ingham26c7bf92014-10-11 00:38:27 +00002567 if (!options.GetStopOnContinue())
Jim Inghame16c50a2011-02-18 00:54:25 +00002568 {
2569 m_debugger.SetAsyncExecution (false);
2570 }
2571
Andy Gibbsa297a972013-06-19 19:04:53 +00002572 for (size_t idx = 0; idx < num_lines; idx++)
Jim Inghame16c50a2011-02-18 00:54:25 +00002573 {
2574 const char *cmd = commands.GetStringAtIndex(idx);
2575 if (cmd[0] == '\0')
2576 continue;
2577
Jim Ingham26c7bf92014-10-11 00:38:27 +00002578 if (options.GetEchoCommands())
Jim Inghame16c50a2011-02-18 00:54:25 +00002579 {
2580 result.AppendMessageWithFormat ("%s %s\n",
Greg Clayton44d93782014-01-27 23:43:24 +00002581 m_debugger.GetPrompt(),
2582 cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002583 }
2584
Greg Clayton9d0402b2011-02-20 02:15:07 +00002585 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002586 // If override_context is not NULL, pass no_context_switching = true for
2587 // HandleCommand() since we updated our context already.
Jim Ingham076b7fc2013-05-02 23:15:37 +00002588
2589 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2590 // 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 +00002591 if (!options.GetAddToHistory())
Jim Ingham076b7fc2013-05-02 23:15:37 +00002592 m_command_source_depth++;
Jim Ingham26c7bf92014-10-11 00:38:27 +00002593 bool success = HandleCommand(cmd, options.m_add_to_history, tmp_result,
Ed Masted78c9572014-04-20 00:31:37 +00002594 nullptr, /* override_context */
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002595 true, /* repeat_on_empty_command */
Ed Masted78c9572014-04-20 00:31:37 +00002596 override_context != nullptr /* no_context_switching */);
Jim Ingham26c7bf92014-10-11 00:38:27 +00002597 if (!options.GetAddToHistory())
Jim Ingham076b7fc2013-05-02 23:15:37 +00002598 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002599
Jim Ingham26c7bf92014-10-11 00:38:27 +00002600 if (options.GetPrintResults())
Jim Inghame16c50a2011-02-18 00:54:25 +00002601 {
2602 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002603 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002604 }
2605
2606 if (!success || !tmp_result.Succeeded())
2607 {
Jim Inghama5038812012-04-24 02:25:07 +00002608 const char *error_msg = tmp_result.GetErrorData();
Ed Masted78c9572014-04-20 00:31:37 +00002609 if (error_msg == nullptr || error_msg[0] == '\0')
Jim Inghama5038812012-04-24 02:25:07 +00002610 error_msg = "<unknown error>.\n";
Jim Ingham26c7bf92014-10-11 00:38:27 +00002611 if (options.GetStopOnError())
Jim Inghame16c50a2011-02-18 00:54:25 +00002612 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002613 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s",
2614 (uint64_t)idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002615 result.SetStatus (eReturnStatusFailed);
2616 m_debugger.SetAsyncExecution (old_async_execution);
2617 return;
2618 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002619 else if (options.GetPrintResults())
Jim Inghame16c50a2011-02-18 00:54:25 +00002620 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002621 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s",
2622 (uint64_t)idx + 1,
Jim Inghame16c50a2011-02-18 00:54:25 +00002623 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002624 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002625 }
2626 }
2627
Caroline Tice969ed3d2011-05-02 20:41:46 +00002628 if (result.GetImmediateOutputStream())
2629 result.GetImmediateOutputStream()->Flush();
2630
2631 if (result.GetImmediateErrorStream())
2632 result.GetImmediateErrorStream()->Flush();
2633
Jim Inghame16c50a2011-02-18 00:54:25 +00002634 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2635 // could be running (for instance in Breakpoint Commands.
2636 // So we check the return value to see if it is has running in it.
2637 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2638 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2639 {
Jim Ingham26c7bf92014-10-11 00:38:27 +00002640 if (options.GetStopOnContinue())
Jim Inghame16c50a2011-02-18 00:54:25 +00002641 {
2642 // If we caused the target to proceed, and we're going to stop in that case, set the
2643 // status in our real result before returning. This is an error if the continue was not the
2644 // last command in the set of commands to be run.
2645 if (idx != num_lines - 1)
Deepak Panickal99fbc072014-03-03 15:39:47 +00002646 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n",
2647 (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002648 else
Deepak Panickal99fbc072014-03-03 15:39:47 +00002649 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002650
2651 result.SetStatus(tmp_result.GetStatus());
2652 m_debugger.SetAsyncExecution (old_async_execution);
2653
2654 return;
2655 }
2656 }
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002657
2658 // Also check for "stop on crash here:
2659 bool should_stop = false;
2660 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash())
2661 {
2662 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2663 if (target_sp)
2664 {
2665 ProcessSP process_sp (target_sp->GetProcessSP());
2666 if (process_sp)
2667 {
2668 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads())
2669 {
2670 StopReason reason = thread_sp->GetStopReason();
2671 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation)
2672 {
2673 should_stop = true;
2674 break;
2675 }
2676 }
2677 }
2678 }
2679 if (should_stop)
2680 {
2681 if (idx != num_lines - 1)
2682 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' stopped with a signal or exception.\n",
2683 (uint64_t)idx + 1, cmd);
2684 else
2685 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' stopped with a signal or exception.\n", (uint64_t)idx + 1, cmd);
2686
2687 result.SetStatus(tmp_result.GetStatus());
2688 m_debugger.SetAsyncExecution (old_async_execution);
2689
2690 return;
2691 }
2692 }
Jim Inghame16c50a2011-02-18 00:54:25 +00002693
2694 }
2695
2696 result.SetStatus (eReturnStatusSuccessFinishResult);
2697 m_debugger.SetAsyncExecution (old_async_execution);
2698
2699 return;
2700}
2701
Greg Clayton340b0302014-02-05 17:57:57 +00002702// Make flags that we can pass into the IOHandler so our delegates can do the right thing
2703enum {
2704 eHandleCommandFlagStopOnContinue = (1u << 0),
2705 eHandleCommandFlagStopOnError = (1u << 1),
2706 eHandleCommandFlagEchoCommand = (1u << 2),
Jim Ingham26c7bf92014-10-11 00:38:27 +00002707 eHandleCommandFlagPrintResult = (1u << 3),
2708 eHandleCommandFlagStopOnCrash = (1u << 4)
Greg Clayton340b0302014-02-05 17:57:57 +00002709};
2710
Jim Inghame16c50a2011-02-18 00:54:25 +00002711void
2712CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2713 ExecutionContext *context,
Jim Ingham26c7bf92014-10-11 00:38:27 +00002714 CommandInterpreterRunOptions &options,
Jim Inghame16c50a2011-02-18 00:54:25 +00002715 CommandReturnObject &result)
2716{
2717 if (cmd_file.Exists())
2718 {
Greg Clayton44d93782014-01-27 23:43:24 +00002719 StreamFileSP input_file_sp (new StreamFile());
2720
2721 std::string cmd_file_path = cmd_file.GetPath();
2722 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2723
2724 if (error.Success())
2725 {
2726 Debugger &debugger = GetDebugger();
2727
Greg Clayton340b0302014-02-05 17:57:57 +00002728 uint32_t flags = 0;
2729
Jim Ingham26c7bf92014-10-11 00:38:27 +00002730 if (options.m_stop_on_continue == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002731 {
2732 if (m_command_source_flags.empty())
2733 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002734 // Stop on continue by default
Greg Clayton340b0302014-02-05 17:57:57 +00002735 flags |= eHandleCommandFlagStopOnContinue;
2736 }
2737 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2738 {
2739 flags |= eHandleCommandFlagStopOnContinue;
2740 }
2741 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002742 else if (options.m_stop_on_continue == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002743 {
2744 flags |= eHandleCommandFlagStopOnContinue;
2745 }
2746
Jim Ingham26c7bf92014-10-11 00:38:27 +00002747 if (options.m_stop_on_error == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002748 {
2749 if (m_command_source_flags.empty())
2750 {
2751 if (GetStopCmdSourceOnError())
2752 flags |= eHandleCommandFlagStopOnError;
2753 }
2754 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2755 {
2756 flags |= eHandleCommandFlagStopOnError;
2757 }
2758 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002759 else if (options.m_stop_on_error == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002760 {
2761 flags |= eHandleCommandFlagStopOnError;
2762 }
2763
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002764 if (options.GetStopOnCrash())
2765 {
2766 if (m_command_source_flags.empty())
2767 {
2768 // Echo command by default
2769 flags |= eHandleCommandFlagStopOnCrash;
2770 }
2771 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash)
2772 {
2773 flags |= eHandleCommandFlagStopOnCrash;
2774 }
2775 }
2776
Jim Ingham26c7bf92014-10-11 00:38:27 +00002777 if (options.m_echo_commands == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002778 {
2779 if (m_command_source_flags.empty())
2780 {
2781 // Echo command by default
2782 flags |= eHandleCommandFlagEchoCommand;
2783 }
2784 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2785 {
2786 flags |= eHandleCommandFlagEchoCommand;
2787 }
2788 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002789 else if (options.m_echo_commands == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002790 {
2791 flags |= eHandleCommandFlagEchoCommand;
2792 }
2793
Jim Ingham26c7bf92014-10-11 00:38:27 +00002794 if (options.m_print_results == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002795 {
2796 if (m_command_source_flags.empty())
2797 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002798 // Print output by default
2799 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002800 }
Greg Claytone4e462c2014-02-05 21:03:22 +00002801 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
Greg Clayton340b0302014-02-05 17:57:57 +00002802 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002803 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002804 }
2805 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002806 else if (options.m_print_results == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002807 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002808 flags |= eHandleCommandFlagPrintResult;
2809 }
2810
2811 if (flags & eHandleCommandFlagPrintResult)
2812 {
Greg Clayton8ee67312014-02-05 21:46:20 +00002813 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
Greg Clayton340b0302014-02-05 17:57:57 +00002814 }
2815
2816 // Used for inheriting the right settings when "command source" might have
2817 // nested "command source" commands
Greg Claytone4e462c2014-02-05 21:03:22 +00002818 lldb::StreamFileSP empty_stream_sp;
Greg Clayton340b0302014-02-05 17:57:57 +00002819 m_command_source_flags.push_back(flags);
Greg Clayton44d93782014-01-27 23:43:24 +00002820 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00002821 IOHandler::Type::CommandInterpreter,
Greg Clayton44d93782014-01-27 23:43:24 +00002822 input_file_sp,
Greg Claytone4e462c2014-02-05 21:03:22 +00002823 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2824 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
Greg Clayton340b0302014-02-05 17:57:57 +00002825 flags,
Ed Masted78c9572014-04-20 00:31:37 +00002826 nullptr, // Pass in NULL for "editline_name" so no history is saved, or written
Greg Clayton8ee67312014-02-05 21:46:20 +00002827 debugger.GetPrompt(),
Kate Stonee30f11d2014-11-17 19:06:59 +00002828 NULL,
Greg Clayton44d93782014-01-27 23:43:24 +00002829 false, // Not multi-line
Kate Stonee30f11d2014-11-17 19:06:59 +00002830 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00002831 0,
Greg Clayton44d93782014-01-27 23:43:24 +00002832 *this));
Greg Clayton8ee67312014-02-05 21:46:20 +00002833 const bool old_async_execution = debugger.GetAsyncExecution();
2834
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002835 // Set synchronous execution if we are not stopping on continue
Greg Clayton8ee67312014-02-05 21:46:20 +00002836 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2837 debugger.SetAsyncExecution (false);
2838
Greg Clayton340b0302014-02-05 17:57:57 +00002839 m_command_source_depth++;
Greg Clayton8ee67312014-02-05 21:46:20 +00002840
2841 debugger.RunIOHandler(io_handler_sp);
Greg Clayton340b0302014-02-05 17:57:57 +00002842 if (!m_command_source_flags.empty())
2843 m_command_source_flags.pop_back();
2844 m_command_source_depth--;
Greg Clayton44d93782014-01-27 23:43:24 +00002845 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Greg Clayton8ee67312014-02-05 21:46:20 +00002846 debugger.SetAsyncExecution (old_async_execution);
Greg Clayton44d93782014-01-27 23:43:24 +00002847 }
2848 else
2849 {
2850 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2851 result.SetStatus (eReturnStatusFailed);
2852 }
Greg Clayton8ee67312014-02-05 21:46:20 +00002853
2854
Jim Inghame16c50a2011-02-18 00:54:25 +00002855 }
2856 else
2857 {
2858 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
Jim Ingham4af59612014-12-19 19:20:44 +00002859 cmd_file.GetFilename().AsCString("<Unknown>"));
Jim Inghame16c50a2011-02-18 00:54:25 +00002860 result.SetStatus (eReturnStatusFailed);
2861 return;
2862 }
2863}
2864
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002865ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002866CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002867{
Ed Masted78c9572014-04-20 00:31:37 +00002868 if (m_script_interpreter_ap.get() != nullptr)
Enrico Granatab5887262012-10-29 21:18:03 +00002869 return m_script_interpreter_ap.get();
2870
2871 if (!can_create)
Ed Masted78c9572014-04-20 00:31:37 +00002872 return nullptr;
Enrico Granatab5887262012-10-29 21:18:03 +00002873
Enrico Granataa29bdad2012-07-10 18:23:48 +00002874 // <rdar://problem/11751427>
2875 // we need to protect the initialization of the script interpreter
2876 // otherwise we could end up with two threads both trying to create
2877 // their instance of it, and for some languages (e.g. Python)
2878 // this is a bulletproof recipe for disaster!
2879 // this needs to be a function-level static because multiple Debugger instances living in the same process
2880 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002881 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2882 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002883
Greg Clayton5160ce52013-03-27 23:08:40 +00002884 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002885 if (log)
2886 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002887
Caroline Tice2f88aad2011-01-14 00:29:16 +00002888 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2889 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002890 {
Greg Claytondce502e2011-11-04 03:34:56 +00002891 case eScriptLanguagePython:
2892#ifndef LLDB_DISABLE_PYTHON
2893 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2894 break;
2895#else
2896 // Fall through to the None case when python is disabled
2897#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002898 case eScriptLanguageNone:
2899 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2900 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002901 };
2902
2903 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002904}
2905
2906
2907
2908bool
2909CommandInterpreter::GetSynchronous ()
2910{
2911 return m_synchronous_execution;
2912}
2913
2914void
2915CommandInterpreter::SetSynchronous (bool value)
2916{
Johnny Chenc066ab42010-10-14 01:22:03 +00002917 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002918}
2919
2920void
2921CommandInterpreter::OutputFormattedHelpText (Stream &strm,
Kate Stonea487aa42015-01-15 00:52:41 +00002922 const char *prefix,
2923 const char *help_text)
2924{
2925 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2926 if (prefix == NULL)
2927 prefix = "";
2928
2929 size_t prefix_width = strlen(prefix);
2930 size_t line_width_max = max_columns - prefix_width;
2931 const char *help_text_end = help_text + strlen(help_text);
2932 const char *line_start = help_text;
2933 if (line_width_max < 16)
2934 line_width_max = help_text_end - help_text + prefix_width;
2935
2936 strm.IndentMore (prefix_width);
2937 while (line_start < help_text_end)
2938 {
2939 // Break each line at the first newline or last space/tab before
2940 // the maximum number of characters that fit on a line. Lines with no
2941 // natural break are left unbroken to wrap.
2942 const char *line_end = help_text_end;
2943 const char *line_scan = line_start;
2944 const char *line_scan_end = help_text_end;
2945 while (line_scan < line_scan_end)
2946 {
2947 char next = *line_scan;
2948 if (next == '\t' || next == ' ')
2949 {
2950 line_end = line_scan;
2951 line_scan_end = line_start + line_width_max;
2952 }
2953 else if (next == '\n' || next == '\0')
2954 {
2955 line_end = line_scan;
2956 break;
2957 }
2958 ++line_scan;
2959 }
2960
2961 // Prefix the first line, indent subsequent lines to line up
2962 if (line_start == help_text)
2963 strm.Write (prefix, prefix_width);
2964 else
2965 strm.Indent();
2966 strm.Write (line_start, line_end - line_start);
2967 strm.EOL();
2968
2969 // When a line breaks at whitespace consume it before continuing
2970 line_start = line_end;
2971 char next = *line_start;
2972 if (next == '\n')
2973 ++line_start;
2974 else while (next == ' ' || next == '\t')
2975 next = *(++line_start);
2976 }
2977 strm.IndentLess (prefix_width);
2978}
2979
2980void
2981CommandInterpreter::OutputFormattedHelpText (Stream &strm,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002982 const char *word_text,
2983 const char *separator,
2984 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002985 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002986{
Kate Stonea487aa42015-01-15 00:52:41 +00002987 StreamString prefix_stream;
2988 prefix_stream.Printf (" %-*s %s ", (int)max_word_len, word_text, separator);
2989 OutputFormattedHelpText (strm, prefix_stream.GetData(), help_text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002990}
2991
2992void
Enrico Granata82a7d982011-07-07 00:38:40 +00002993CommandInterpreter::OutputHelpText (Stream &strm,
2994 const char *word_text,
2995 const char *separator,
2996 const char *help_text,
2997 uint32_t max_word_len)
2998{
2999 int indent_size = max_word_len + strlen (separator) + 2;
3000
3001 strm.IndentMore (indent_size);
3002
3003 StreamString text_strm;
3004 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
3005
3006 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00003007
3008 size_t len = text_strm.GetSize();
3009 const char *text = text_strm.GetData();
3010
3011 uint32_t chars_left = max_columns;
3012
3013 for (uint32_t i = 0; i < len; i++)
3014 {
3015 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
3016 {
Enrico Granata82a7d982011-07-07 00:38:40 +00003017 chars_left = max_columns - indent_size;
3018 strm.EOL();
3019 strm.Indent();
3020 }
3021 else
3022 {
3023 strm.PutChar(text[i]);
3024 chars_left--;
3025 }
3026
3027 }
3028
3029 strm.EOL();
3030 strm.IndentLess(indent_size);
3031}
3032
3033void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003034CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
Jim Inghamaf3753e2013-05-17 01:30:37 +00003035 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036{
3037 CommandObject::CommandMap::const_iterator pos;
3038
Jim Inghamaf3753e2013-05-17 01:30:37 +00003039 if (search_builtin_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003040 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00003041 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003042 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00003043 const char *command_name = pos->first.c_str();
3044 CommandObject *cmd_obj = pos->second.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045
Jim Inghamaf3753e2013-05-17 01:30:37 +00003046 if (cmd_obj->HelpTextContainsWord (search_word))
3047 {
3048 commands_found.AppendString (command_name);
3049 commands_help.AppendString (cmd_obj->GetHelp());
3050 }
3051
3052 if (cmd_obj->IsMultiwordObject())
3053 cmd_obj->AproposAllSubCommands (command_name,
3054 search_word,
3055 commands_found,
3056 commands_help);
3057
3058 }
3059 }
3060
3061 if (search_user_commands)
3062 {
3063 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
3064 {
3065 const char *command_name = pos->first.c_str();
3066 CommandObject *cmd_obj = pos->second.get();
3067
3068 if (cmd_obj->HelpTextContainsWord (search_word))
3069 {
3070 commands_found.AppendString (command_name);
3071 commands_help.AppendString (cmd_obj->GetHelp());
3072 }
3073
3074 if (cmd_obj->IsMultiwordObject())
3075 cmd_obj->AproposAllSubCommands (command_name,
3076 search_word,
3077 commands_found,
3078 commands_help);
3079
3080 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003081 }
3082}
Greg Clayton8b82f082011-04-12 05:54:46 +00003083
Greg Clayton8b82f082011-04-12 05:54:46 +00003084void
3085CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
3086{
Ed Masted78c9572014-04-20 00:31:37 +00003087 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00003088 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00003089 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00003090 }
3091 else
3092 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00003093 const bool adopt_selected = true;
3094 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00003095 }
3096}
Greg Clayton44d93782014-01-27 23:43:24 +00003097
3098
3099size_t
3100CommandInterpreter::GetProcessOutput ()
3101{
3102 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
3103 char stdio_buffer[1024];
3104 size_t len;
3105 size_t total_bytes = 0;
3106 Error error;
3107 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
3108 if (target_sp)
3109 {
3110 ProcessSP process_sp (target_sp->GetProcessSP());
3111 if (process_sp)
3112 {
3113 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
3114 {
3115 size_t bytes_written = len;
3116 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
3117 total_bytes += len;
3118 }
3119 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
3120 {
3121 size_t bytes_written = len;
3122 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
3123 total_bytes += len;
3124 }
3125 }
3126 }
3127 return total_bytes;
3128}
3129
3130void
3131CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
3132{
Greg Clayton340b0302014-02-05 17:57:57 +00003133 const bool is_interactive = io_handler.GetIsInteractive();
3134 if (is_interactive == false)
3135 {
3136 // When we are not interactive, don't execute blank lines. This will happen
3137 // sourcing a commands file. We don't want blank lines to repeat the previous
3138 // command and cause any errors to occur (like redefining an alias, get an error
3139 // and stop parsing the commands file).
3140 if (line.empty())
3141 return;
3142
3143 // When using a non-interactive file handle (like when sourcing commands from a file)
3144 // we need to echo the command out so we don't just see the command output and no
3145 // command...
3146 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
3147 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
3148 }
3149
Greg Clayton44d93782014-01-27 23:43:24 +00003150 lldb_private::CommandReturnObject result;
3151 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
3152
Greg Clayton44d93782014-01-27 23:43:24 +00003153 // Now emit the command output text from the command we just executed
Greg Clayton340b0302014-02-05 17:57:57 +00003154 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
3155 {
3156 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3157 GetProcessOutput ();
3158
Greg Clayton8ee67312014-02-05 21:46:20 +00003159 if (!result.GetImmediateOutputStream())
3160 {
3161 const char *output = result.GetOutputData();
3162 if (output && output[0])
3163 io_handler.GetOutputStreamFile()->PutCString(output);
3164 }
Greg Clayton44d93782014-01-27 23:43:24 +00003165
Greg Clayton340b0302014-02-05 17:57:57 +00003166 // Now emit the command error text from the command we just executed
Greg Clayton8ee67312014-02-05 21:46:20 +00003167 if (!result.GetImmediateErrorStream())
3168 {
3169 const char *error = result.GetErrorData();
3170 if (error && error[0])
3171 io_handler.GetErrorStreamFile()->PutCString(error);
3172 }
Greg Clayton340b0302014-02-05 17:57:57 +00003173 }
Greg Clayton44d93782014-01-27 23:43:24 +00003174
3175 switch (result.GetStatus())
3176 {
3177 case eReturnStatusInvalid:
3178 case eReturnStatusSuccessFinishNoResult:
3179 case eReturnStatusSuccessFinishResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003180 case eReturnStatusStarted:
3181 break;
3182
Greg Clayton44d93782014-01-27 23:43:24 +00003183 case eReturnStatusSuccessContinuingNoResult:
3184 case eReturnStatusSuccessContinuingResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003185 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3186 io_handler.SetIsDone(true);
3187 break;
3188
Greg Clayton44d93782014-01-27 23:43:24 +00003189 case eReturnStatusFailed:
Jim Ingham26c7bf92014-10-11 00:38:27 +00003190 m_num_errors++;
Greg Clayton340b0302014-02-05 17:57:57 +00003191 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3192 io_handler.SetIsDone(true);
Greg Clayton44d93782014-01-27 23:43:24 +00003193 break;
3194
3195 case eReturnStatusQuit:
Jim Ingham26c7bf92014-10-11 00:38:27 +00003196 m_quit_requested = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003197 io_handler.SetIsDone(true);
3198 break;
3199 }
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003200
3201 // Finally, if we're going to stop on crash, check that here:
3202 if (!m_quit_requested
3203 && result.GetDidChangeProcessState()
3204 && io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash))
3205 {
3206 bool should_stop = false;
3207 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
3208 if (target_sp)
3209 {
3210 ProcessSP process_sp (target_sp->GetProcessSP());
3211 if (process_sp)
3212 {
3213 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads())
3214 {
3215 StopReason reason = thread_sp->GetStopReason();
3216 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation)
3217 {
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003218 should_stop = true;
3219 break;
3220 }
3221 }
3222 }
3223 }
3224 if (should_stop)
3225 {
3226 io_handler.SetIsDone(true);
3227 m_stopped_for_crash = true;
3228 }
3229 }
Greg Clayton44d93782014-01-27 23:43:24 +00003230}
3231
Greg Claytonf0066ad2014-05-02 00:45:31 +00003232bool
3233CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler)
3234{
3235 ExecutionContext exe_ctx (GetExecutionContext());
3236 Process *process = exe_ctx.GetProcessPtr();
3237
3238 if (process)
3239 {
3240 StateType state = process->GetState();
3241 if (StateIsRunningState(state))
3242 {
3243 process->Halt();
3244 return true; // Don't do any updating when we are running
3245 }
3246 }
Greg Claytone507bce2015-01-27 01:58:22 +00003247
3248 ScriptInterpreter *script_interpreter = GetScriptInterpreter (false);
3249 if (script_interpreter)
3250 {
3251 if (script_interpreter->Interrupt())
3252 return true;
3253 }
Greg Claytonf0066ad2014-05-02 00:45:31 +00003254 return false;
3255}
3256
Greg Clayton44d93782014-01-27 23:43:24 +00003257void
3258CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3259 IOHandlerDelegate &delegate,
3260 bool asynchronously,
3261 void *baton)
3262{
3263 Debugger &debugger = GetDebugger();
3264 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00003265 IOHandler::Type::CommandList,
Greg Clayton44d93782014-01-27 23:43:24 +00003266 "lldb", // Name of input reader for history
3267 prompt, // Prompt
Kate Stonee30f11d2014-11-17 19:06:59 +00003268 NULL, // Continuation prompt
Greg Clayton44d93782014-01-27 23:43:24 +00003269 true, // Get multiple lines
Kate Stonee30f11d2014-11-17 19:06:59 +00003270 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00003271 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003272 delegate)); // IOHandlerDelegate
3273
3274 if (io_handler_sp)
3275 {
3276 io_handler_sp->SetUserData (baton);
3277 if (asynchronously)
3278 debugger.PushIOHandler(io_handler_sp);
3279 else
3280 debugger.RunIOHandler(io_handler_sp);
3281 }
3282
3283}
3284
3285
3286void
3287CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3288 IOHandlerDelegate &delegate,
3289 bool asynchronously,
3290 void *baton)
3291{
3292 Debugger &debugger = GetDebugger();
3293 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00003294 IOHandler::Type::PythonCode,
Greg Clayton44d93782014-01-27 23:43:24 +00003295 "lldb-python", // Name of input reader for history
3296 prompt, // Prompt
Kate Stonee30f11d2014-11-17 19:06:59 +00003297 NULL, // Continuation prompt
Greg Clayton44d93782014-01-27 23:43:24 +00003298 true, // Get multiple lines
Kate Stonee30f11d2014-11-17 19:06:59 +00003299 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00003300 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003301 delegate)); // IOHandlerDelegate
3302
3303 if (io_handler_sp)
3304 {
3305 io_handler_sp->SetUserData (baton);
3306 if (asynchronously)
3307 debugger.PushIOHandler(io_handler_sp);
3308 else
3309 debugger.RunIOHandler(io_handler_sp);
3310 }
3311
3312}
3313
3314bool
3315CommandInterpreter::IsActive ()
3316{
3317 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3318}
3319
Kate Stonee30f11d2014-11-17 19:06:59 +00003320lldb::IOHandlerSP
3321CommandInterpreter::GetIOHandler(bool force_create, CommandInterpreterRunOptions *options)
3322{
3323 // Always re-create the IOHandlerEditline in case the input
3324 // changed. The old instance might have had a non-interactive
3325 // input and now it does or vice versa.
3326 if (force_create || !m_command_io_handler_sp)
3327 {
3328 // Always re-create the IOHandlerEditline in case the input
3329 // changed. The old instance might have had a non-interactive
3330 // input and now it does or vice versa.
3331 uint32_t flags = 0;
3332
3333 if (options)
3334 {
3335 if (options->m_stop_on_continue == eLazyBoolYes)
3336 flags |= eHandleCommandFlagStopOnContinue;
3337 if (options->m_stop_on_error == eLazyBoolYes)
3338 flags |= eHandleCommandFlagStopOnError;
3339 if (options->m_stop_on_crash == eLazyBoolYes)
3340 flags |= eHandleCommandFlagStopOnCrash;
3341 if (options->m_echo_commands != eLazyBoolNo)
3342 flags |= eHandleCommandFlagEchoCommand;
3343 if (options->m_print_results != eLazyBoolNo)
3344 flags |= eHandleCommandFlagPrintResult;
3345 }
3346 else
3347 {
3348 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
3349 }
3350
3351 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3352 IOHandler::Type::CommandInterpreter,
3353 m_debugger.GetInputFile(),
3354 m_debugger.GetOutputFile(),
3355 m_debugger.GetErrorFile(),
3356 flags,
3357 "lldb",
3358 m_debugger.GetPrompt(),
3359 NULL, // Continuation prompt
3360 false, // Don't enable multiple line input, just single line commands
3361 m_debugger.GetUseColor(),
3362 0, // Don't show line numbers
3363 *this));
3364 }
3365 return m_command_io_handler_sp;
3366}
3367
Greg Clayton44d93782014-01-27 23:43:24 +00003368void
3369CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
Jim Ingham26c7bf92014-10-11 00:38:27 +00003370 bool spawn_thread,
3371 CommandInterpreterRunOptions &options)
Greg Clayton44d93782014-01-27 23:43:24 +00003372{
Kate Stonee30f11d2014-11-17 19:06:59 +00003373 // Always re-create the command intepreter when we run it in case
3374 // any file handles have changed.
3375 bool force_create = true;
3376 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003377 m_stopped_for_crash = false;
Greg Clayton380f3d82014-07-31 19:46:19 +00003378
Greg Clayton44d93782014-01-27 23:43:24 +00003379 if (auto_handle_events)
3380 m_debugger.StartEventHandlerThread();
3381
3382 if (spawn_thread)
3383 {
3384 m_debugger.StartIOHandlerThread();
3385 }
3386 else
3387 {
Siva Chandra9aaab552015-02-26 19:26:36 +00003388 m_debugger.ExecuteIOHandlers();
Kate Stonee30f11d2014-11-17 19:06:59 +00003389
Greg Clayton44d93782014-01-27 23:43:24 +00003390 if (auto_handle_events)
3391 m_debugger.StopEventHandlerThread();
3392 }
Kate Stonee30f11d2014-11-17 19:06:59 +00003393
Greg Clayton44d93782014-01-27 23:43:24 +00003394}
3395