blob: eaa21adc13918cf7e525102cd998764d497ee4a6 [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
Enrico Granata012d4fc2013-06-11 01:26:35 +0000152bool
153CommandInterpreter::GetStopCmdSourceOnError () const
154{
155 const uint32_t idx = ePropertyStopCmdSourceOnError;
Ed Masted78c9572014-04-20 00:31:37 +0000156 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000157}
158
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000159void
160CommandInterpreter::Initialize ()
161{
162 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
163
164 CommandReturnObject result;
165
166 LoadCommandDictionary ();
167
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000168 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000169 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
170 if (cmd_obj_sp)
171 {
172 AddAlias ("q", cmd_obj_sp);
173 AddAlias ("exit", cmd_obj_sp);
174 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000175
Johnny Chen6d675242012-08-24 18:15:45 +0000176 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000177 if (cmd_obj_sp)
178 {
179 AddAlias ("attach", cmd_obj_sp);
180 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000181
Johnny Chen6d675242012-08-24 18:15:45 +0000182 cmd_obj_sp = GetCommandSPExact ("process detach",false);
183 if (cmd_obj_sp)
184 {
185 AddAlias ("detach", cmd_obj_sp);
186 }
187
Caroline Ticeca90c472011-05-06 21:37:15 +0000188 cmd_obj_sp = GetCommandSPExact ("process continue", false);
189 if (cmd_obj_sp)
190 {
191 AddAlias ("c", cmd_obj_sp);
192 AddAlias ("continue", cmd_obj_sp);
193 }
194
195 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
196 if (cmd_obj_sp)
197 AddAlias ("b", cmd_obj_sp);
198
Jim Inghamca36cd12012-10-05 19:16:31 +0000199 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
200 if (cmd_obj_sp)
201 AddAlias ("tbreak", cmd_obj_sp);
202
Caroline Ticeca90c472011-05-06 21:37:15 +0000203 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
204 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000205 {
206 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000207 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000208 }
209
210 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
211 if (cmd_obj_sp)
212 {
213 AddAlias ("nexti", cmd_obj_sp);
214 AddAlias ("ni", cmd_obj_sp);
215 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000216
217 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
218 if (cmd_obj_sp)
219 {
220 AddAlias ("s", cmd_obj_sp);
221 AddAlias ("step", cmd_obj_sp);
222 }
223
224 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
225 if (cmd_obj_sp)
226 {
227 AddAlias ("n", cmd_obj_sp);
228 AddAlias ("next", cmd_obj_sp);
229 }
230
231 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
232 if (cmd_obj_sp)
233 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000234 AddAlias ("finish", cmd_obj_sp);
235 }
236
Jim Ingham6d6d1072011-12-02 01:12:59 +0000237 cmd_obj_sp = GetCommandSPExact ("frame select", false);
238 if (cmd_obj_sp)
239 {
240 AddAlias ("f", cmd_obj_sp);
241 }
242
Jim Inghamca36cd12012-10-05 19:16:31 +0000243 cmd_obj_sp = GetCommandSPExact ("thread select", false);
244 if (cmd_obj_sp)
245 {
246 AddAlias ("t", cmd_obj_sp);
247 }
248
Richard Mittonf86248d2013-09-12 02:20:34 +0000249 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
250 if (cmd_obj_sp)
251 {
252 AddAlias ("j", cmd_obj_sp);
253 AddAlias ("jump", cmd_obj_sp);
254 }
255
Greg Clayton6bade322013-02-01 23:33:03 +0000256 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000257 if (cmd_obj_sp)
258 {
259 AddAlias ("l", cmd_obj_sp);
260 AddAlias ("list", cmd_obj_sp);
261 }
262
Greg Claytonef5651d2013-02-12 18:52:24 +0000263 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
264 if (cmd_obj_sp)
265 {
266 AddAlias ("env", cmd_obj_sp);
267 }
268
Caroline Ticeca90c472011-05-06 21:37:15 +0000269 cmd_obj_sp = GetCommandSPExact ("memory read", false);
270 if (cmd_obj_sp)
271 AddAlias ("x", cmd_obj_sp);
272
273 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
274 if (cmd_obj_sp)
275 AddAlias ("up", cmd_obj_sp);
276
277 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
278 if (cmd_obj_sp)
279 AddAlias ("down", cmd_obj_sp);
280
Jason Molenda0c8e0062011-10-25 02:11:20 +0000281 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000282 if (cmd_obj_sp)
283 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000284
285 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
286 if (cmd_obj_sp)
287 AddAlias ("dis", cmd_obj_sp);
288
289 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
290 if (cmd_obj_sp)
291 AddAlias ("di", cmd_obj_sp);
292
293
Jason Molendabc7748b2011-10-22 01:30:52 +0000294
Jason Molenda0c8e0062011-10-25 02:11:20 +0000295 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000296 if (cmd_obj_sp)
297 AddAlias ("undisplay", cmd_obj_sp);
298
Jim Ingham71bf2992012-10-10 16:51:31 +0000299 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
300 if (cmd_obj_sp)
301 AddAlias ("bt", cmd_obj_sp);
302
Caroline Ticeca90c472011-05-06 21:37:15 +0000303 cmd_obj_sp = GetCommandSPExact ("target create", false);
304 if (cmd_obj_sp)
305 AddAlias ("file", cmd_obj_sp);
306
307 cmd_obj_sp = GetCommandSPExact ("target modules", false);
308 if (cmd_obj_sp)
309 AddAlias ("image", cmd_obj_sp);
310
311
312 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000313
Caroline Ticeca90c472011-05-06 21:37:15 +0000314 cmd_obj_sp = GetCommandSPExact ("expression", false);
315 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000316 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000317 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
318 AddAlias ("p", cmd_obj_sp);
319 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000320 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000321 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
322 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000323 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000324
325 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton9e57dcd2013-05-15 01:03:08 +0000326 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000327 AddAlias ("po", cmd_obj_sp);
328 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
329 }
330
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000331 cmd_obj_sp = GetCommandSPExact ("process kill", false);
332 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000333 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000334 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000335 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000336
Caroline Ticeca90c472011-05-06 21:37:15 +0000337 cmd_obj_sp = GetCommandSPExact ("process launch", false);
338 if (cmd_obj_sp)
339 {
340 alias_arguments_vector_sp.reset (new OptionArgVector);
Todd Fiala013434e2014-07-09 01:29:05 +0000341#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Jason Molenda85da3122012-07-06 02:46:23 +0000342 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
343#else
Zachary Turner10687b02014-10-20 17:46:43 +0000344 std::string shell_option;
345 shell_option.append("--shell=");
346 shell_option.append(HostInfo::GetDefaultShell().GetPath());
347 shell_option.append(" --");
348 ProcessAliasOptionsArgs (cmd_obj_sp, shell_option.c_str(), alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000349#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000350 AddAlias ("r", cmd_obj_sp);
351 AddAlias ("run", cmd_obj_sp);
352 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
353 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
354 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000355
356 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
357 if (cmd_obj_sp)
358 {
359 AddAlias ("add-dsym", cmd_obj_sp);
360 }
Sean Callananfc732752012-05-21 18:25:19 +0000361
362 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
363 if (cmd_obj_sp)
364 {
365 alias_arguments_vector_sp.reset (new OptionArgVector);
366 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000367 AddAlias ("rbreak", cmd_obj_sp);
368 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000369 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000370}
371
Greg Clayton0c4129f2014-04-25 00:35:14 +0000372void
373CommandInterpreter::Clear()
374{
375 m_command_io_handler_sp.reset();
Greg Claytoned6499f2014-04-25 23:55:12 +0000376
377 if (m_script_interpreter_ap)
378 m_script_interpreter_ap->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000379}
380
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000381const char *
382CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
383{
384 // This function has not yet been implemented.
385
386 // Look for any embedded script command
387 // If found,
388 // get interpreter object from the command dictionary,
389 // call execute_one_command on it,
390 // get the results as a string,
391 // substitute that string for current stuff.
392
393 return arg;
394}
395
396
397void
398CommandInterpreter::LoadCommandDictionary ()
399{
400 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
401
Caroline Ticedaccaa92010-09-20 20:44:43 +0000402 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000403
Greg Claytona7015092010-09-18 01:14:36 +0000404 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000405 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000406 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000407 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
408 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000409 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton44d93782014-01-27 23:43:24 +0000410 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000411 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000412 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
413 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000414 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000415 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000416 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000417 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000418 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000419 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000420 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000421 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000422 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
423 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000424 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000425 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000426 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000427
Jim Inghamca36cd12012-10-05 19:16:31 +0000428 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
Greg Claytond90ac932014-12-01 22:34:03 +0000429 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000430 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000431 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000432 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000433 {"^(-.*)$", "breakpoint set %1"},
434 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000435 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Greg Clayton2d4b5122014-08-14 17:58:33 +0000436 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}};
Jim Inghamca36cd12012-10-05 19:16:31 +0000437
Saleem Abdulrasool28606952014-06-27 05:17:41 +0000438 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000439
Greg Clayton7b0992d2013-04-18 22:45:39 +0000440 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000441 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000442 "_regexp-break",
Greg Clayton910db5c2015-03-07 00:01:46 +0000443 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.\n",
444 "\n_regexp-break <filename>:<linenum> # _regexp-break main.c:12 // Break on line 12 of main.c\n"
445 "_regexp-break <linenum> # _regexp-break 12 // Break on line 12 of current file\n"
446 "_regexp-break <address> # _regexp-break 0x1234000 // Break on address 0x1234000\n"
447 "_regexp-break <name> # _regexp-break main // Break in 'main' after the prologue\n"
448 "_regexp-break &<name> # _regexp-break &main // Break on the first instruction in 'main'\n"
449 "_regexp-break <module>`<name> # _regexp-break libc.so`malloc // Break in 'malloc' only in the 'libc.so' shared library\n"
450 "_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 +0000451 2,
452 CommandCompletions::eSymbolCompletion |
Greg Claytonb5472782015-01-09 19:08:20 +0000453 CommandCompletions::eSourceFileCompletion,
454 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000455
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000456 if (break_regex_cmd_ap.get())
457 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000458 bool success = true;
459 for (size_t i = 0; i < num_regexes; i++)
460 {
461 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
462 if (!success)
463 break;
464 }
465 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
466
467 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000468 {
469 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
470 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
471 }
472 }
Jim Inghamffba2292011-03-22 02:29:32 +0000473
Greg Clayton7b0992d2013-04-18 22:45:39 +0000474 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000475 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
476 "_regexp-tbreak",
477 "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 +0000478 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
479 2,
480 CommandCompletions::eSymbolCompletion |
Greg Claytonb5472782015-01-09 19:08:20 +0000481 CommandCompletions::eSourceFileCompletion,
482 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000483
484 if (tbreak_regex_cmd_ap.get())
485 {
486 bool success = true;
487 for (size_t i = 0; i < num_regexes; i++)
488 {
489 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
490 char buffer[1024];
491 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
492 assert (num_printed < 1024);
Eric Christopher5c91d5c12014-09-09 19:26:45 +0000493 // Quiet unused variable warning for release builds.
Eric Christopher9ad83942014-09-09 08:57:33 +0000494 (void) num_printed;
Jim Inghamca36cd12012-10-05 19:16:31 +0000495 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
496 if (!success)
497 break;
498 }
499 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
500
501 if (success)
502 {
503 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
504 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
505 }
506 }
507
Greg Clayton7b0992d2013-04-18 22:45:39 +0000508 std::unique_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000509 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
510 "_regexp-attach",
511 "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 +0000512 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
Greg Claytonb5472782015-01-09 19:08:20 +0000513 2,
514 0,
515 false));
Johnny Chen6d675242012-08-24 18:15:45 +0000516 if (attach_regex_cmd_ap.get())
517 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000518 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
519 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
520 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
521 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000522 {
523 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
524 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
525 }
526 }
527
Greg Clayton7b0992d2013-04-18 22:45:39 +0000528 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000529 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000530 "_regexp-down",
531 "Go down \"n\" frames in the stack (1 frame by default).",
Greg Claytonb5472782015-01-09 19:08:20 +0000532 "_regexp-down [n]",
533 2,
534 0,
535 false));
Jim Inghamffba2292011-03-22 02:29:32 +0000536 if (down_regex_cmd_ap.get())
537 {
538 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
539 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
540 {
541 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
542 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
543 }
544 }
545
Greg Clayton7b0992d2013-04-18 22:45:39 +0000546 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000547 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000548 "_regexp-up",
549 "Go up \"n\" frames in the stack (1 frame by default).",
Greg Claytonb5472782015-01-09 19:08:20 +0000550 "_regexp-up [n]",
551 2,
552 0,
553 false));
Jim Inghamffba2292011-03-22 02:29:32 +0000554 if (up_regex_cmd_ap.get())
555 {
556 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
557 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
558 {
559 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
560 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
561 }
562 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000563
Greg Clayton7b0992d2013-04-18 22:45:39 +0000564 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000565 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000566 "_regexp-display",
567 "Add an expression evaluation stop-hook.",
Greg Claytonb5472782015-01-09 19:08:20 +0000568 "_regexp-display expression",
569 2,
570 0,
571 false));
Jason Molendabc7748b2011-10-22 01:30:52 +0000572 if (display_regex_cmd_ap.get())
573 {
574 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
575 {
576 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
577 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
578 }
579 }
580
Greg Clayton7b0992d2013-04-18 22:45:39 +0000581 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000582 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000583 "_regexp-undisplay",
584 "Remove an expression evaluation stop-hook.",
Greg Claytonb5472782015-01-09 19:08:20 +0000585 "_regexp-undisplay stop-hook-number",
586 2,
587 0,
588 false));
Jason Molendabc7748b2011-10-22 01:30:52 +0000589 if (undisplay_regex_cmd_ap.get())
590 {
591 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
592 {
593 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
594 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
595 }
596 }
597
Greg Clayton7b0992d2013-04-18 22:45:39 +0000598 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000599 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000600 "gdb-remote",
601 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
Greg Claytonb5472782015-01-09 19:08:20 +0000602 "gdb-remote [<hostname>:]<portnum>",
603 2,
604 0,
605 false));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000606 if (connect_gdb_remote_cmd_ap.get())
607 {
608 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
609 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
610 {
611 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
612 m_command_dict[command_sp->GetCommandName ()] = command_sp;
613 }
614 }
615
Greg Clayton7b0992d2013-04-18 22:45:39 +0000616 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000617 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
618 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000619 "Connect to a remote KDP server. udp port 41139 is the default port number.",
Greg Claytonb5472782015-01-09 19:08:20 +0000620 "kdp-remote <hostname>[:<portnum>]",
621 2,
622 0,
623 false));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000624 if (connect_kdp_remote_cmd_ap.get())
625 {
626 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000627 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000628 {
629 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
630 m_command_dict[command_sp->GetCommandName ()] = command_sp;
631 }
632 }
633
Greg Clayton7b0992d2013-04-18 22:45:39 +0000634 std::unique_ptr<CommandObjectRegexCommand>
Jason Molenda4cddfed2012-10-05 05:29:32 +0000635 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb5472782015-01-09 19:08:20 +0000636 "_regexp-bt",
637 "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.",
638 "bt [<digit>|all]",
639 2,
640 0,
641 false));
Jason Molenda4cddfed2012-10-05 05:29:32 +0000642 if (bt_regex_cmd_ap.get())
643 {
644 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
645 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
646 // so now "bt 3" is the preferred form, in line with gdb.
647 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
648 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
649 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
650 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
651 {
652 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
653 m_command_dict[command_sp->GetCommandName ()] = command_sp;
654 }
655 }
656
Greg Clayton7b0992d2013-04-18 22:45:39 +0000657 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton6bade322013-02-01 23:33:03 +0000658 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
659 "_regexp-list",
660 "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 +0000661 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000662 2,
Greg Claytonb5472782015-01-09 19:08:20 +0000663 CommandCompletions::eSourceFileCompletion,
664 false));
Greg Clayton6bade322013-02-01 23:33:03 +0000665 if (list_regex_cmd_ap.get())
666 {
667 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
668 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
669 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000670 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000671 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000672 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
673 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
674 {
675 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
676 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
677 }
678 }
679
Greg Clayton7b0992d2013-04-18 22:45:39 +0000680 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytonef5651d2013-02-12 18:52:24 +0000681 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000682 "_regexp-env",
683 "Implements a shortcut to viewing and setting environment variables.",
Greg Claytonb5472782015-01-09 19:08:20 +0000684 "_regexp-env\n_regexp-env FOO=BAR",
685 2,
686 0,
687 false));
Greg Claytonef5651d2013-02-12 18:52:24 +0000688 if (env_regex_cmd_ap.get())
689 {
690 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
691 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
692 {
693 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
694 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
695 }
696 }
697
Richard Mittonf86248d2013-09-12 02:20:34 +0000698 std::unique_ptr<CommandObjectRegexCommand>
699 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
700 "_regexp-jump",
701 "Sets the program counter to a new address.",
702 "_regexp-jump [<line>]\n"
703 "_regexp-jump [<+-lineoffset>]\n"
704 "_regexp-jump [<file>:<line>]\n"
Greg Claytonb5472782015-01-09 19:08:20 +0000705 "_regexp-jump [*<addr>]\n",
706 2,
707 0,
708 false));
Richard Mittonf86248d2013-09-12 02:20:34 +0000709 if (jump_regex_cmd_ap.get())
710 {
711 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
712 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
713 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
714 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
715 {
716 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
717 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
718 }
719 }
720
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000721}
722
723int
724CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
725 StringList &matches)
726{
727 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
728
729 if (include_aliases)
730 {
731 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
732 }
733
734 return matches.GetSize();
735}
736
737CommandObjectSP
738CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
739{
740 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000741 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742
743 std::string cmd(cmd_cstr);
744
745 if (HasCommands())
746 {
747 pos = m_command_dict.find(cmd);
748 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000749 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750 }
751
752 if (include_aliases && HasAliases())
753 {
754 pos = m_alias_dict.find(cmd);
755 if (pos != m_alias_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 (HasUserCommands())
760 {
761 pos = m_user_dict.find(cmd);
762 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000763 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000764 }
765
Greg Claytonc7bece562013-01-25 18:06:21 +0000766 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000767 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000768 // We will only get into here if we didn't find any exact matches.
769
770 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
771
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000772 StringList local_matches;
Ed Masted78c9572014-04-20 00:31:37 +0000773 if (matches == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774 matches = &local_matches;
775
Jim Ingham279a6c22010-07-06 22:46:59 +0000776 unsigned int num_cmd_matches = 0;
777 unsigned int num_alias_matches = 0;
778 unsigned int num_user_matches = 0;
779
780 // Look through the command dictionaries one by one, and if we get only one match from any of
781 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
782
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000783 if (HasCommands())
784 {
785 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
786 }
787
788 if (num_cmd_matches == 1)
789 {
790 cmd.assign(matches->GetStringAtIndex(0));
791 pos = m_command_dict.find(cmd);
792 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000793 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794 }
795
Jim Ingham490ac552010-06-24 20:28:42 +0000796 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000797 {
798 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
799
800 }
801
Jim Ingham279a6c22010-07-06 22:46:59 +0000802 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000803 {
804 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
805 pos = m_alias_dict.find(cmd);
806 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000807 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000808 }
809
Jim Ingham490ac552010-06-24 20:28:42 +0000810 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000811 {
812 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
813 }
814
Jim Ingham279a6c22010-07-06 22:46:59 +0000815 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816 {
817 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
818
819 pos = m_user_dict.find (cmd);
820 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000821 user_match_sp = pos->second;
822 }
823
824 // If we got exactly one match, return that, otherwise return the match list.
825
826 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
827 {
828 if (num_cmd_matches)
829 return real_match_sp;
830 else if (num_alias_matches)
831 return alias_match_sp;
832 else
833 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000834 }
835 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000836 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000837 {
838 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000839 }
840
841
Greg Claytonc7bece562013-01-25 18:06:21 +0000842 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000843}
844
Greg Claytonde164aa2011-04-20 16:37:46 +0000845bool
846CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
847{
848 if (name && name[0])
849 {
850 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000851 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
852 if (found && !can_replace)
853 return false;
854 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000855 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000856 m_command_dict[name_sstr] = cmd_sp;
857 return true;
858 }
859 return false;
860}
861
Enrico Granata223383e2011-08-16 23:24:13 +0000862bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000863CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000864 const lldb::CommandObjectSP &cmd_sp,
865 bool can_replace)
866{
Enrico Granata0a305db2011-11-07 22:57:04 +0000867 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000868 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000869
870 const char* name_cstr = name.c_str();
871
872 // do not allow replacement of internal commands
873 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000874 {
875 if (can_replace == false)
876 return false;
877 if (m_command_dict[name]->IsRemovable() == false)
878 return false;
879 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000880
Enrico Granata21dfcd92012-09-28 23:57:51 +0000881 if (UserCommandExists(name_cstr))
882 {
883 if (can_replace == false)
884 return false;
885 if (m_user_dict[name]->IsRemovable() == false)
886 return false;
887 }
888
Enrico Granata0a305db2011-11-07 22:57:04 +0000889 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000890 return true;
891 }
892 return false;
893}
Greg Claytonde164aa2011-04-20 16:37:46 +0000894
Jim Ingham279a6c22010-07-06 22:46:59 +0000895CommandObjectSP
896CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000897{
Caroline Tice472362e2010-12-14 18:51:39 +0000898 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
899 CommandObjectSP ret_val; // Possibly empty return value.
900
Ed Masted78c9572014-04-20 00:31:37 +0000901 if (cmd_cstr == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000902 return ret_val;
903
904 if (cmd_words.GetArgumentCount() == 1)
Ed Masted78c9572014-04-20 00:31:37 +0000905 return GetCommandSP(cmd_cstr, include_aliases, true, nullptr);
Caroline Tice472362e2010-12-14 18:51:39 +0000906 else
907 {
908 // We have a multi-word command (seemingly), so we need to do more work.
909 // First, get the cmd_obj_sp for the first word in the command.
Ed Masted78c9572014-04-20 00:31:37 +0000910 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr);
911 if (cmd_obj_sp.get() != nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000912 {
913 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
914 // command name), and find the appropriate sub-command SP for each command word....
915 size_t end = cmd_words.GetArgumentCount();
916 for (size_t j= 1; j < end; ++j)
917 {
918 if (cmd_obj_sp->IsMultiwordObject())
919 {
Greg Clayton998255b2012-10-13 02:07:45 +0000920 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Ed Masted78c9572014-04-20 00:31:37 +0000921 if (cmd_obj_sp.get() == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000922 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
923 return ret_val;
924 }
925 else
926 // We have more words in the command name, but we don't have a multiword object. Fail and return
927 // empty 'ret_val'.
928 return ret_val;
929 }
930 // We successfully looped through all the command words and got valid command objects for them. Assign the
931 // last object retrieved to 'ret_val'.
932 ret_val = cmd_obj_sp;
933 }
934 }
935 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000936}
937
938CommandObject *
939CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
940{
941 return GetCommandSPExact (cmd_cstr, include_aliases).get();
942}
943
944CommandObject *
945CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
946{
947 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
948
949 // If we didn't find an exact match to the command string in the commands, look in
950 // the aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000951
952 if (command_obj)
953 return command_obj;
Jim Ingham279a6c22010-07-06 22:46:59 +0000954
Enrico Granata5342c442013-06-18 18:01:08 +0000955 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
Jim Ingham279a6c22010-07-06 22:46:59 +0000956
Enrico Granata5342c442013-06-18 18:01:08 +0000957 if (command_obj)
958 return command_obj;
959
960 // If there wasn't an exact match then look for an inexact one in just the commands
Ed Masted78c9572014-04-20 00:31:37 +0000961 command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get();
Matt Kopec038ff812013-04-23 16:17:32 +0000962
963 // Finally, if there wasn't an inexact match among the commands, look for an inexact
964 // match in both the commands and aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000965
966 if (command_obj)
967 {
968 if (matches)
969 matches->AppendString(command_obj->GetCommandName());
970 return command_obj;
971 }
972
973 return GetCommandSP(cmd_cstr, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000974}
975
976bool
977CommandInterpreter::CommandExists (const char *cmd)
978{
979 return m_command_dict.find(cmd) != m_command_dict.end();
980}
981
982bool
Caroline Ticeca90c472011-05-06 21:37:15 +0000983CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
984 const char *options_args,
985 OptionArgVectorSP &option_arg_vector_sp)
986{
987 bool success = true;
988 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
989
990 if (!options_args || (strlen (options_args) < 1))
991 return true;
992
993 std::string options_string (options_args);
994 Args args (options_args);
995 CommandReturnObject result;
996 // Check to see if the command being aliased can take any command options.
997 Options *options = cmd_obj_sp->GetOptions ();
998 if (options)
999 {
1000 // See if any options were specified as part of the alias; if so, handle them appropriately.
1001 options->NotifyOptionParsingStarting ();
1002 args.Unshift ("dummy_arg");
1003 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
1004 args.Shift ();
1005 if (result.Succeeded())
1006 options->VerifyPartialOptions (result);
1007 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
1008 {
1009 result.AppendError ("Unable to create requested alias.\n");
1010 return false;
1011 }
1012 }
1013
Greg Clayton5521f992011-10-28 21:38:01 +00001014 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +00001015 {
1016 if (cmd_obj_sp->WantsRawCommandString ())
1017 option_arg_vector->push_back (OptionArgPair ("<argument>",
1018 OptionArgValue (-1,
1019 options_string)));
1020 else
1021 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001022 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +00001023 for (size_t i = 0; i < argc; ++i)
1024 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
1025 option_arg_vector->push_back
1026 (OptionArgPair ("<argument>",
1027 OptionArgValue (-1,
1028 std::string (args.GetArgumentAtIndex (i)))));
1029 }
1030 }
1031
1032 return success;
1033}
1034
1035bool
Jim Ingham298f3782013-04-03 00:25:49 +00001036CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
1037{
1038 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1039 if (exact_match)
1040 {
1041 full_name.assign(cmd);
1042 return exact_match;
1043 }
1044 else
1045 {
1046 StringList matches;
1047 size_t num_alias_matches;
1048 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
1049 if (num_alias_matches == 1)
1050 {
1051 // Make sure this isn't shadowing a command in the regular command space:
1052 StringList regular_matches;
1053 const bool include_aliases = false;
1054 const bool exact = false;
1055 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
1056 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1057 return false;
1058 else
1059 {
1060 full_name.assign (matches.GetStringAtIndex(0));
1061 return true;
1062 }
1063 }
1064 else
1065 return false;
1066 }
1067}
1068
1069bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001070CommandInterpreter::AliasExists (const char *cmd)
1071{
1072 return m_alias_dict.find(cmd) != m_alias_dict.end();
1073}
1074
1075bool
1076CommandInterpreter::UserCommandExists (const char *cmd)
1077{
1078 return m_user_dict.find(cmd) != m_user_dict.end();
1079}
1080
1081void
1082CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1083{
Jim Ingham279a6c22010-07-06 22:46:59 +00001084 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001085 m_alias_dict[alias_name] = command_obj_sp;
1086}
1087
1088bool
1089CommandInterpreter::RemoveAlias (const char *alias_name)
1090{
1091 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1092 if (pos != m_alias_dict.end())
1093 {
1094 m_alias_dict.erase(pos);
1095 return true;
1096 }
1097 return false;
1098}
Greg Claytonb5472782015-01-09 19:08:20 +00001099
1100bool
1101CommandInterpreter::RemoveCommand (const char *cmd)
1102{
1103 auto pos = m_command_dict.find(cmd);
1104 if (pos != m_command_dict.end())
1105 {
1106 if (pos->second->IsRemovable())
1107 {
1108 // Only regular expression objects or python commands are removable
1109 m_command_dict.erase(pos);
1110 return true;
1111 }
1112 }
1113 return false;
1114}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115bool
1116CommandInterpreter::RemoveUser (const char *alias_name)
1117{
1118 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1119 if (pos != m_user_dict.end())
1120 {
1121 m_user_dict.erase(pos);
1122 return true;
1123 }
1124 return false;
1125}
1126
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001127void
1128CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1129{
1130 help_string.Printf ("'%s", command_name);
1131 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1132
Sean Callanan9a028512012-08-09 00:50:26 +00001133 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134 {
1135 OptionArgVector *options = option_arg_vector_sp.get();
Andy Gibbsa297a972013-06-19 19:04:53 +00001136 for (size_t i = 0; i < options->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001137 {
1138 OptionArgPair cur_option = (*options)[i];
1139 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001140 OptionArgValue value_pair = cur_option.second;
1141 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142 if (opt.compare("<argument>") == 0)
1143 {
1144 help_string.Printf (" %s", value.c_str());
1145 }
1146 else
1147 {
1148 help_string.Printf (" %s", opt.c_str());
1149 if ((value.compare ("<no-argument>") != 0)
1150 && (value.compare ("<need-argument") != 0))
1151 {
1152 help_string.Printf (" %s", value.c_str());
1153 }
1154 }
1155 }
1156 }
1157
1158 help_string.Printf ("'");
1159}
1160
Greg Clayton12fc3e02010-08-26 22:05:43 +00001161size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001162CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1163{
1164 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001165 CommandObject::CommandMap::const_iterator end = dict.end();
1166 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001167
Greg Clayton12fc3e02010-08-26 22:05:43 +00001168 for (pos = dict.begin(); pos != end; ++pos)
1169 {
1170 size_t len = pos->first.size();
1171 if (max_len < len)
1172 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001173 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001174 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001175}
1176
1177void
Enrico Granata223383e2011-08-16 23:24:13 +00001178CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001179 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001180{
Kate Stonea487aa42015-01-15 00:52:41 +00001181 const char * help_prologue = GetDebugger().GetIOHandlerHelpPrologue();
1182 if (help_prologue != NULL)
1183 {
1184 OutputFormattedHelpText(result.GetOutputStream(), NULL, help_prologue);
1185 }
1186
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001187 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001188 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001189
1190 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001191 {
Kate Stonea487aa42015-01-15 00:52:41 +00001192 result.AppendMessage("Debugger commands:");
Enrico Granata223383e2011-08-16 23:24:13 +00001193 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194
Enrico Granata223383e2011-08-16 23:24:13 +00001195 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1196 {
Kate Stonea487aa42015-01-15 00:52:41 +00001197 if (!(cmd_types & eCommandTypesHidden) && (pos->first.compare(0, 1, "_") == 0))
1198 continue;
1199
Enrico Granata223383e2011-08-16 23:24:13 +00001200 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1201 max_len);
1202 }
1203 result.AppendMessage("");
1204
1205 }
1206
Greg Clayton5521f992011-10-28 21:38:01 +00001207 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001208 {
Kate Stonea487aa42015-01-15 00:52:41 +00001209 result.AppendMessageWithFormat("Current command abbreviations "
1210 "(type '%shelp command alias' for more info):\n",
1211 GetCommandPrefix());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001212 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001213 max_len = FindLongestCommandWord (m_alias_dict);
1214
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001215 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1216 {
1217 StreamString sstr;
1218 StreamString translation_and_help;
1219 std::string entry_name = pos->first;
1220 std::string second_entry = pos->second.get()->GetCommandName();
1221 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1222
1223 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1224 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1225 translation_and_help.GetData(), max_len);
1226 }
1227 result.AppendMessage("");
1228 }
1229
Greg Clayton5521f992011-10-28 21:38:01 +00001230 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001231 {
Kate Stonea487aa42015-01-15 00:52:41 +00001232 result.AppendMessage ("Current user-defined commands:");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001233 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001234 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001235 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1236 {
Enrico Granata223383e2011-08-16 23:24:13 +00001237 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1238 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001239 }
1240 result.AppendMessage("");
1241 }
1242
Kate Stonea487aa42015-01-15 00:52:41 +00001243 result.AppendMessageWithFormat("For more information on any command, type '%shelp <command-name>'.\n",
1244 GetCommandPrefix());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001245}
1246
Caroline Tice844d2302010-12-09 22:52:49 +00001247CommandObject *
1248CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001249{
Caroline Tice844d2302010-12-09 22:52:49 +00001250 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1251 // eventually be invoked by the given command line.
1252
Ed Masted78c9572014-04-20 00:31:37 +00001253 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001254 std::string white_space (" \t\v");
1255 size_t start = command_string.find_first_not_of (white_space);
1256 size_t end = 0;
1257 bool done = false;
1258 while (!done)
1259 {
1260 if (start != std::string::npos)
1261 {
1262 // Get the next word from command_string.
1263 end = command_string.find_first_of (white_space, start);
1264 if (end == std::string::npos)
1265 end = command_string.size();
1266 std::string cmd_word = command_string.substr (start, end - start);
1267
Ed Masted78c9572014-04-20 00:31:37 +00001268 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001269 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1270 // command or alias.
1271 cmd_obj = GetCommandObject (cmd_word.c_str());
1272 else if (cmd_obj->IsMultiwordObject ())
1273 {
1274 // 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 +00001275 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001276 if (sub_cmd_obj)
1277 cmd_obj = sub_cmd_obj;
1278 else // cmd_word was not a valid sub-command word, so we are donee
1279 done = true;
1280 }
1281 else
1282 // We have a cmd_obj and it is not a multi-word object, so we are done.
1283 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001284
Caroline Tice844d2302010-12-09 22:52:49 +00001285 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1286 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1287 // next word.
1288
1289 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1290 done = true;
1291 else
1292 start = command_string.find_first_not_of (white_space, end);
1293 }
1294 else
1295 // Unable to find any more words.
1296 done = true;
1297 }
1298
1299 if (end == command_string.size())
1300 command_string.clear();
1301 else
1302 command_string = command_string.substr(end);
1303
1304 return cmd_obj;
1305}
1306
Greg Clayton51964162011-10-25 00:36:27 +00001307static const char *k_white_space = " \t\v";
Greg Clayton5521f992011-10-28 21:38:01 +00001308static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001309static void
1310StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001311{
Greg Clayton51964162011-10-25 00:36:27 +00001312 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001313 {
Greg Clayton51964162011-10-25 00:36:27 +00001314 size_t pos = s.find_first_not_of (k_white_space);
1315 if (pos == std::string::npos)
1316 s.clear();
1317 else if (pos == 0)
1318 return;
1319 s.erase (0, pos);
1320 }
1321}
1322
Greg Clayton93c62e62011-11-09 23:25:03 +00001323static size_t
1324FindArgumentTerminator (const std::string &s)
1325{
Greg Clayton93c62e62011-11-09 23:25:03 +00001326 const size_t s_len = s.size();
1327 size_t offset = 0;
1328 while (offset < s_len)
1329 {
1330 size_t pos = s.find ("--", offset);
1331 if (pos == std::string::npos)
1332 break;
1333 if (pos > 0)
1334 {
1335 if (isspace(s[pos-1]))
1336 {
1337 // Check if the string ends "\s--" (where \s is a space character)
1338 // or if we have "\s--\s".
1339 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1340 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001341 return pos;
1342 }
1343 }
1344 }
1345 offset = pos + 2;
1346 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001347 return std::string::npos;
1348}
1349
Greg Clayton51964162011-10-25 00:36:27 +00001350static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001351ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001352{
Greg Clayton5521f992011-10-28 21:38:01 +00001353 command.clear();
1354 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001355 StripLeadingSpaces (command_string);
1356
1357 bool result = false;
1358 quote_char = '\0';
1359
1360 if (!command_string.empty())
1361 {
1362 const char first_char = command_string[0];
1363 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001364 {
Greg Clayton51964162011-10-25 00:36:27 +00001365 quote_char = first_char;
1366 const size_t end_quote_pos = command_string.find (quote_char, 1);
1367 if (end_quote_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001368 {
Greg Clayton5521f992011-10-28 21:38:01 +00001369 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001370 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001371 }
1372 else
1373 {
Greg Clayton5521f992011-10-28 21:38:01 +00001374 command.assign (command_string, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001375 if (end_quote_pos + 1 < command_string.size())
1376 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1377 else
1378 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001379 }
Caroline Tice844d2302010-12-09 22:52:49 +00001380 }
1381 else
1382 {
Greg Clayton51964162011-10-25 00:36:27 +00001383 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1384 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001385 {
Greg Clayton5521f992011-10-28 21:38:01 +00001386 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001387 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001388 }
1389 else
1390 {
Greg Clayton5521f992011-10-28 21:38:01 +00001391 command.assign (command_string, 0, first_space_pos);
1392 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001393 }
Caroline Tice844d2302010-12-09 22:52:49 +00001394 }
Greg Clayton51964162011-10-25 00:36:27 +00001395 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001396 }
Greg Clayton5521f992011-10-28 21:38:01 +00001397
1398
1399 if (!command.empty())
1400 {
1401 // actual commands can't start with '-' or '_'
1402 if (command[0] != '-' && command[0] != '_')
1403 {
1404 size_t pos = command.find_first_not_of(k_valid_command_chars);
1405 if (pos > 0 && pos != std::string::npos)
1406 {
1407 suffix.assign (command.begin() + pos, command.end());
1408 command.erase (pos);
1409 }
1410 }
1411 }
Greg Clayton51964162011-10-25 00:36:27 +00001412
1413 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001414}
1415
Greg Clayton5521f992011-10-28 21:38:01 +00001416CommandObject *
1417CommandInterpreter::BuildAliasResult (const char *alias_name,
1418 std::string &raw_input_string,
1419 std::string &alias_result,
1420 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001421{
Ed Masted78c9572014-04-20 00:31:37 +00001422 CommandObject *alias_cmd_obj = nullptr;
Pavel Labath00b7f952015-03-02 12:46:22 +00001423 Args cmd_args (raw_input_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001424 alias_cmd_obj = GetCommandObject (alias_name);
1425 StreamString result_str;
1426
1427 if (alias_cmd_obj)
1428 {
1429 std::string alias_name_str = alias_name;
1430 if ((cmd_args.GetArgumentCount() == 0)
1431 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1432 cmd_args.Unshift (alias_name);
1433
1434 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1435 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1436
1437 if (option_arg_vector_sp.get())
1438 {
1439 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1440
Andy Gibbsa297a972013-06-19 19:04:53 +00001441 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Caroline Tice844d2302010-12-09 22:52:49 +00001442 {
1443 OptionArgPair option_pair = (*option_arg_vector)[i];
1444 OptionArgValue value_pair = option_pair.second;
1445 int value_type = value_pair.first;
1446 std::string option = option_pair.first;
1447 std::string value = value_pair.second;
1448 if (option.compare ("<argument>") == 0)
1449 result_str.Printf (" %s", value.c_str());
1450 else
1451 {
1452 result_str.Printf (" %s", option.c_str());
Virgile Belloe2607b52013-09-05 16:42:23 +00001453 if (value_type != OptionParser::eOptionalArgument)
Caroline Tice844d2302010-12-09 22:52:49 +00001454 result_str.Printf (" ");
Virgile Belloe2607b52013-09-05 16:42:23 +00001455 if (value.compare ("<OptionParser::eNoArgument>") != 0)
Caroline Tice844d2302010-12-09 22:52:49 +00001456 {
1457 int index = GetOptionArgumentPosition (value.c_str());
1458 if (index == 0)
1459 result_str.Printf ("%s", value.c_str());
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001460 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Caroline Tice844d2302010-12-09 22:52:49 +00001461 {
1462
1463 result.AppendErrorWithFormat
1464 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1465 index);
1466 result.SetStatus (eReturnStatusFailed);
Greg Clayton5521f992011-10-28 21:38:01 +00001467 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001468 }
1469 else
1470 {
1471 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1472 if (strpos != std::string::npos)
1473 raw_input_string = raw_input_string.erase (strpos,
1474 strlen (cmd_args.GetArgumentAtIndex (index)));
1475 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1476 }
1477 }
1478 }
1479 }
1480 }
1481
1482 alias_result = result_str.GetData();
1483 }
Greg Clayton5521f992011-10-28 21:38:01 +00001484 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001485}
1486
Greg Clayton5a314712011-10-14 07:41:33 +00001487Error
1488CommandInterpreter::PreprocessCommand (std::string &command)
1489{
1490 // The command preprocessor needs to do things to the command
1491 // line before any parsing of arguments or anything else is done.
1492 // The only current stuff that gets proprocessed is anyting enclosed
1493 // in backtick ('`') characters is evaluated as an expression and
1494 // the result of the expression must be a scalar that can be substituted
1495 // into the command. An example would be:
1496 // (lldb) memory read `$rsp + 20`
1497 Error error; // Error for any expressions that might not evaluate
1498 size_t start_backtick;
1499 size_t pos = 0;
1500 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1501 {
1502 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1503 {
1504 // The backtick was preceeded by a '\' character, remove the slash
1505 // and don't treat the backtick as the start of an expression
1506 command.erase(start_backtick-1, 1);
1507 // No need to add one to start_backtick since we just deleted a char
1508 pos = start_backtick;
1509 }
1510 else
1511 {
1512 const size_t expr_content_start = start_backtick + 1;
1513 const size_t end_backtick = command.find ('`', expr_content_start);
1514 if (end_backtick == std::string::npos)
1515 return error;
1516 else if (end_backtick == expr_content_start)
1517 {
1518 // Empty expression (two backticks in a row)
1519 command.erase (start_backtick, 2);
1520 }
1521 else
1522 {
1523 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1524
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001525 ExecutionContext exe_ctx(GetExecutionContext());
1526 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001527 // Get a dummy target to allow for calculator mode while processing backticks.
1528 // This also helps break the infinite loop caused when target is null.
1529 if (!target)
Jim Ingham893c9322014-11-22 01:42:44 +00001530 target = m_debugger.GetDummyTarget();
Greg Clayton5a314712011-10-14 07:41:33 +00001531 if (target)
1532 {
Greg Clayton5a314712011-10-14 07:41:33 +00001533 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001534
Jim Ingham35e1bda2012-10-16 21:41:58 +00001535 EvaluateExpressionOptions options;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00001536 options.SetCoerceToId(false);
1537 options.SetUnwindOnError(true);
1538 options.SetIgnoreBreakpoints(true);
1539 options.SetKeepInMemory(false);
1540 options.SetTryAllThreads(true);
1541 options.SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001542
Jim Ingham1624a2d2014-05-05 02:26:40 +00001543 ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granataca0e5ad2014-10-09 23:09:40 +00001544 exe_ctx.GetFramePtr(),
1545 expr_result_valobj_sp,
1546 options);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001547
Jim Ingham8646d3c2014-05-05 02:47:44 +00001548 if (expr_result == eExpressionCompleted)
Greg Clayton5a314712011-10-14 07:41:33 +00001549 {
1550 Scalar scalar;
Enrico Granataca0e5ad2014-10-09 23:09:40 +00001551 if (expr_result_valobj_sp)
1552 expr_result_valobj_sp = expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(expr_result_valobj_sp->GetDynamicValueType(), true);
Greg Clayton5a314712011-10-14 07:41:33 +00001553 if (expr_result_valobj_sp->ResolveValue (scalar))
1554 {
1555 command.erase (start_backtick, end_backtick - start_backtick + 1);
1556 StreamString value_strm;
1557 const bool show_type = false;
1558 scalar.GetValue (&value_strm, show_type);
1559 size_t value_string_size = value_strm.GetSize();
1560 if (value_string_size)
1561 {
1562 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1563 pos = start_backtick + value_string_size;
1564 continue;
1565 }
1566 else
1567 {
1568 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1569 }
1570 }
1571 else
1572 {
1573 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1574 }
1575 }
1576 else
1577 {
1578 if (expr_result_valobj_sp)
1579 error = expr_result_valobj_sp->GetError();
1580 if (error.Success())
1581 {
1582
1583 switch (expr_result)
1584 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00001585 case eExpressionSetupError:
Greg Clayton5a314712011-10-14 07:41:33 +00001586 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1587 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001588 case eExpressionParseError:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001589 error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str());
1590 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001591 case eExpressionResultUnavailable:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001592 error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str());
Jim Ingham8646d3c2014-05-05 02:47:44 +00001593 case eExpressionCompleted:
Greg Clayton5a314712011-10-14 07:41:33 +00001594 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001595 case eExpressionDiscarded:
Greg Clayton5a314712011-10-14 07:41:33 +00001596 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1597 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001598 case eExpressionInterrupted:
Greg Clayton5a314712011-10-14 07:41:33 +00001599 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1600 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001601 case eExpressionHitBreakpoint:
Jim Ingham184e9812013-01-15 02:47:48 +00001602 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1603 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001604 case eExpressionTimedOut:
Greg Clayton5a314712011-10-14 07:41:33 +00001605 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1606 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001607 case eExpressionStoppedForDebug:
Greg Claytonc28ce782013-11-08 23:38:26 +00001608 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1609 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001610 }
1611 }
1612 }
1613 }
1614 }
1615 if (error.Fail())
1616 break;
1617 }
1618 }
1619 return error;
1620}
1621
1622
Caroline Tice844d2302010-12-09 22:52:49 +00001623bool
1624CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001625 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001626 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001627 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001628 bool repeat_on_empty_command,
1629 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001630
Caroline Tice844d2302010-12-09 22:52:49 +00001631{
Jim Inghame16c50a2011-02-18 00:54:25 +00001632
Caroline Tice844d2302010-12-09 22:52:49 +00001633 bool done = false;
Ed Masted78c9572014-04-20 00:31:37 +00001634 CommandObject *cmd_obj = nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001635 bool wants_raw_input = false;
1636 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001637 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001638
Greg Clayton5160ce52013-03-27 23:08:40 +00001639 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001640 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1641
1642 // Make a scoped cleanup object that will clear the crash description string
1643 // on exit of this function.
Ed Masted78c9572014-04-20 00:31:37 +00001644 lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001645
Caroline Tice844d2302010-12-09 22:52:49 +00001646 if (log)
1647 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001648
Jim Ingham30244832010-11-04 23:08:45 +00001649 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1650
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001651 if (!no_context_switching)
1652 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001653
Enrico Granata5f5ab602012-05-31 01:09:06 +00001654 bool add_to_history;
1655 if (lazy_add_to_history == eLazyBoolCalculate)
1656 add_to_history = (m_command_source_depth == 0);
1657 else
1658 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1659
Jim Inghame16c50a2011-02-18 00:54:25 +00001660 bool empty_command = false;
1661 bool comment_command = false;
1662 if (command_string.empty())
1663 empty_command = true;
1664 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001665 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001666 const char *k_space_characters = "\t\n\v\f\r ";
1667
1668 size_t non_space = command_string.find_first_not_of (k_space_characters);
1669 // Check for empty line or comment line (lines whose first
1670 // non-space character is the comment character for this interpreter)
1671 if (non_space == std::string::npos)
1672 empty_command = true;
1673 else if (command_string[non_space] == m_comment_char)
1674 comment_command = true;
Enrico Granata7594f142013-06-17 22:51:50 +00001675 else if (command_string[non_space] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001676 {
Enrico Granata7594f142013-06-17 22:51:50 +00001677 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
Ed Masted78c9572014-04-20 00:31:37 +00001678 if (history_string == nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001679 {
1680 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1681 result.SetStatus(eReturnStatusFailed);
1682 return false;
1683 }
1684 add_to_history = false;
1685 command_string = history_string;
1686 original_command_string = history_string;
1687 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001688 }
1689
1690 if (empty_command)
1691 {
1692 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001693 {
Enrico Granata7594f142013-06-17 22:51:50 +00001694 if (m_command_history.IsEmpty())
Jim Inghame16c50a2011-02-18 00:54:25 +00001695 {
1696 result.AppendError ("empty command");
1697 result.SetStatus(eReturnStatusFailed);
1698 return false;
1699 }
1700 else
1701 {
1702 command_line = m_repeat_command.c_str();
1703 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001704 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001705 if (m_repeat_command.empty())
1706 {
1707 result.AppendErrorWithFormat("No auto repeat.\n");
1708 result.SetStatus (eReturnStatusFailed);
1709 return false;
1710 }
1711 }
1712 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001713 }
1714 else
1715 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001716 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1717 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001718 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001719 }
1720 else if (comment_command)
1721 {
1722 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1723 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001724 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001725
Greg Clayton5a314712011-10-14 07:41:33 +00001726
1727 Error error (PreprocessCommand (command_string));
1728
1729 if (error.Fail())
1730 {
1731 result.AppendError (error.AsCString());
1732 result.SetStatus(eReturnStatusFailed);
1733 return false;
1734 }
Caroline Tice844d2302010-12-09 22:52:49 +00001735 // Phase 1.
1736
1737 // Before we do ANY kind of argument processing, etc. we need to figure out what the real/final command object
1738 // is for the specified command, and whether or not it wants raw input. This gets complicated by the fact that
1739 // the user could have specified an alias, and in translating the alias there may also be command options and/or
1740 // even data (including raw text strings) that need to be found and inserted into the command line as part of
1741 // 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 +00001742 // object whose Execute method will actually be called; 2). a revised command string, with all substitutions &
Caroline Tice844d2302010-12-09 22:52:49 +00001743 // replacements taken care of; 3). whether or not the Execute function wants raw input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001744
Caroline Tice844d2302010-12-09 22:52:49 +00001745 StreamString revised_command_line;
Caroline Tice01274c02010-12-11 08:16:56 +00001746 size_t actual_cmd_name_len = 0;
Greg Clayton5521f992011-10-28 21:38:01 +00001747 std::string next_word;
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001748 StringList matches;
Caroline Tice844d2302010-12-09 22:52:49 +00001749 while (!done)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001750 {
Caroline Tice2b5e8502011-05-11 16:07:06 +00001751 char quote_char = '\0';
Greg Clayton5521f992011-10-28 21:38:01 +00001752 std::string suffix;
1753 ExtractCommand (command_string, next_word, suffix, quote_char);
Ed Masted78c9572014-04-20 00:31:37 +00001754 if (cmd_obj == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001755 {
Jim Ingham298f3782013-04-03 00:25:49 +00001756 std::string full_name;
1757 if (GetAliasFullName(next_word.c_str(), full_name))
Caroline Tice472362e2010-12-14 18:51:39 +00001758 {
Greg Clayton5521f992011-10-28 21:38:01 +00001759 std::string alias_result;
Jim Ingham298f3782013-04-03 00:25:49 +00001760 cmd_obj = BuildAliasResult (full_name.c_str(), command_string, alias_result, result);
Greg Clayton5521f992011-10-28 21:38:01 +00001761 revised_command_line.Printf ("%s", alias_result.c_str());
1762 if (cmd_obj)
1763 {
1764 wants_raw_input = cmd_obj->WantsRawCommandString ();
1765 actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
1766 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001767 }
1768 else
1769 {
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001770 cmd_obj = GetCommandObject (next_word.c_str(), &matches);
Greg Clayton5521f992011-10-28 21:38:01 +00001771 if (cmd_obj)
1772 {
1773 actual_cmd_name_len += next_word.length();
1774 revised_command_line.Printf ("%s", next_word.c_str());
1775 wants_raw_input = cmd_obj->WantsRawCommandString ();
1776 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001777 else
Greg Clayton5521f992011-10-28 21:38:01 +00001778 {
1779 revised_command_line.Printf ("%s", next_word.c_str());
1780 }
Caroline Tice844d2302010-12-09 22:52:49 +00001781 }
1782 }
1783 else
1784 {
Greg Clayton5521f992011-10-28 21:38:01 +00001785 if (cmd_obj->IsMultiwordObject ())
1786 {
Greg Clayton998255b2012-10-13 02:07:45 +00001787 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (next_word.c_str());
Greg Clayton5521f992011-10-28 21:38:01 +00001788 if (sub_cmd_obj)
1789 {
1790 actual_cmd_name_len += next_word.length() + 1;
1791 revised_command_line.Printf (" %s", next_word.c_str());
1792 cmd_obj = sub_cmd_obj;
1793 wants_raw_input = cmd_obj->WantsRawCommandString ();
1794 }
1795 else
1796 {
1797 if (quote_char)
1798 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1799 else
1800 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1801 done = true;
1802 }
1803 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001804 else
Greg Clayton5521f992011-10-28 21:38:01 +00001805 {
1806 if (quote_char)
1807 revised_command_line.Printf (" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
1808 else
1809 revised_command_line.Printf (" %s%s", next_word.c_str(), suffix.c_str());
1810 done = true;
1811 }
Caroline Tice844d2302010-12-09 22:52:49 +00001812 }
1813
Ed Masted78c9572014-04-20 00:31:37 +00001814 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001815 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001816 const size_t num_matches = matches.GetSize();
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001817 if (matches.GetSize() > 1) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001818 StreamString error_msg;
1819 error_msg.Printf ("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001820
1821 for (uint32_t i = 0; i < num_matches; ++i) {
Greg Claytonc7bece562013-01-25 18:06:21 +00001822 error_msg.Printf ("\t%s\n", matches.GetStringAtIndex(i));
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001823 }
Greg Claytonc7bece562013-01-25 18:06:21 +00001824 result.AppendRawError (error_msg.GetString().c_str());
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001825 } else {
1826 // We didn't have only one match, otherwise we wouldn't get here.
1827 assert(num_matches == 0);
1828 result.AppendErrorWithFormat ("'%s' is not a valid command.\n", next_word.c_str());
1829 }
Caroline Tice844d2302010-12-09 22:52:49 +00001830 result.SetStatus (eReturnStatusFailed);
1831 return false;
1832 }
1833
Greg Clayton5521f992011-10-28 21:38:01 +00001834 if (cmd_obj->IsMultiwordObject ())
1835 {
1836 if (!suffix.empty())
1837 {
1838
Enrico Granataaded51d2013-06-12 00:44:43 +00001839 result.AppendErrorWithFormat ("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
1840 cmd_obj->GetCommandName(),
1841 next_word.empty() ? "" : next_word.c_str(),
1842 next_word.empty() ? " -- " : " ",
Greg Clayton5521f992011-10-28 21:38:01 +00001843 suffix.c_str());
1844 result.SetStatus (eReturnStatusFailed);
1845 return false;
1846 }
1847 }
1848 else
1849 {
1850 // If we found a normal command, we are done
1851 done = true;
1852 if (!suffix.empty())
1853 {
1854 switch (suffix[0])
1855 {
1856 case '/':
1857 // GDB format suffixes
Greg Clayton52ec56c2011-10-29 00:57:28 +00001858 {
1859 Options *command_options = cmd_obj->GetOptions();
1860 if (command_options && command_options->SupportsLongOption("gdb-format"))
1861 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001862 std::string gdb_format_option ("--gdb-format=");
1863 gdb_format_option += (suffix.c_str() + 1);
1864
1865 bool inserted = false;
1866 std::string &cmd = revised_command_line.GetString();
1867 size_t arg_terminator_idx = FindArgumentTerminator (cmd);
1868 if (arg_terminator_idx != std::string::npos)
1869 {
1870 // Insert the gdb format option before the "--" that terminates options
1871 gdb_format_option.append(1,' ');
1872 cmd.insert(arg_terminator_idx, gdb_format_option);
1873 inserted = true;
1874 }
1875
1876 if (!inserted)
1877 revised_command_line.Printf (" %s", gdb_format_option.c_str());
1878
1879 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
1880 revised_command_line.PutCString (" --");
Greg Clayton52ec56c2011-10-29 00:57:28 +00001881 }
1882 else
1883 {
1884 result.AppendErrorWithFormat ("the '%s' command doesn't support the --gdb-format option\n",
1885 cmd_obj->GetCommandName());
1886 result.SetStatus (eReturnStatusFailed);
1887 return false;
1888 }
1889 }
Greg Clayton5521f992011-10-28 21:38:01 +00001890 break;
Johnny Chen8e9383d2011-10-31 22:22:06 +00001891
1892 default:
1893 result.AppendErrorWithFormat ("unknown command shorthand suffix: '%s'\n",
1894 suffix.c_str());
1895 result.SetStatus (eReturnStatusFailed);
1896 return false;
1897
Greg Clayton5521f992011-10-28 21:38:01 +00001898 }
1899 }
1900 }
Caroline Tice844d2302010-12-09 22:52:49 +00001901 if (command_string.length() == 0)
1902 done = true;
1903
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001904 }
Caroline Tice844d2302010-12-09 22:52:49 +00001905
Greg Clayton5521f992011-10-28 21:38:01 +00001906 if (!command_string.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001907 revised_command_line.Printf (" %s", command_string.c_str());
1908
1909 // End of Phase 1.
1910 // At this point cmd_obj should contain the CommandObject whose Execute method will be called, if the command
1911 // specified was valid; revised_command_line contains the complete command line (including command name(s)),
1912 // fully translated with all substitutions & translations taken care of (still in raw text format); and
1913 // wants_raw_input specifies whether the Execute method expects raw input or not.
1914
1915
1916 if (log)
1917 {
1918 log->Printf ("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1919 log->Printf ("HandleCommand, revised_command_line: '%s'", revised_command_line.GetData());
1920 log->Printf ("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
1921 }
1922
1923 // Phase 2.
1924 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1925 // CommandObject, with the appropriate arguments.
1926
Ed Masted78c9572014-04-20 00:31:37 +00001927 if (cmd_obj != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001928 {
1929 if (add_to_history)
1930 {
1931 Args command_args (revised_command_line.GetData());
1932 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
Ed Masted78c9572014-04-20 00:31:37 +00001933 if (repeat_command != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001934 m_repeat_command.assign(repeat_command);
1935 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001936 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001937
Enrico Granata7594f142013-06-17 22:51:50 +00001938 m_command_history.AppendString (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001939 }
1940
1941 command_string = revised_command_line.GetData();
1942 std::string command_name (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001943 std::string remainder;
1944 if (actual_cmd_name_len < command_string.length())
1945 remainder = command_string.substr (actual_cmd_name_len); // Note: 'actual_cmd_name_len' may be considerably shorter
1946 // than cmd_obj->GetCommandName(), because name completion
1947 // allows users to enter short versions of the names,
1948 // e.g. 'br s' for 'breakpoint set'.
Caroline Tice844d2302010-12-09 22:52:49 +00001949
1950 // Remove any initial spaces
1951 std::string white_space (" \t\v");
1952 size_t pos = remainder.find_first_not_of (white_space);
1953 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001954 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001955
1956 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001957 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001958
Jim Ingham5a988412012-06-08 21:56:10 +00001959 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001960 }
1961 else
1962 {
1963 // We didn't find the first command object, so complete the first argument.
1964 Args command_args (revised_command_line.GetData());
1965 StringList matches;
1966 int num_matches;
1967 int cursor_index = 0;
1968 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1969 bool word_complete;
1970 num_matches = HandleCompletionMatches (command_args,
1971 cursor_index,
1972 cursor_char_position,
1973 0,
1974 -1,
1975 word_complete,
1976 matches);
1977
1978 if (num_matches > 0)
1979 {
1980 std::string error_msg;
1981 error_msg.assign ("ambiguous command '");
1982 error_msg.append(command_args.GetArgumentAtIndex(0));
1983 error_msg.append ("'.");
1984
1985 error_msg.append (" Possible completions:");
1986 for (int i = 0; i < num_matches; i++)
1987 {
1988 error_msg.append ("\n\t");
1989 error_msg.append (matches.GetStringAtIndex (i));
1990 }
1991 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001992 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001993 }
1994 else
1995 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1996
1997 result.SetStatus (eReturnStatusFailed);
1998 }
1999
Jason Molendabfb36ff2011-08-25 00:20:04 +00002000 if (log)
2001 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
2002
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002003 return result.Succeeded();
2004}
2005
2006int
2007CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
2008 int &cursor_index,
2009 int &cursor_char_position,
2010 int match_start_point,
2011 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00002012 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002013 StringList &matches)
2014{
2015 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002016 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00002017
2018 // For any of the command completions a unique match will be a complete word.
2019 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002020
2021 if (cursor_index == -1)
2022 {
2023 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00002024 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002025 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
2026 }
2027 else if (cursor_index == 0)
2028 {
2029 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00002030 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002031 num_command_matches = matches.GetSize();
2032
2033 if (num_command_matches == 1
2034 && cmd_obj && cmd_obj->IsMultiwordObject()
Ed Masted78c9572014-04-20 00:31:37 +00002035 && matches.GetStringAtIndex(0) != nullptr
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002036 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
2037 {
Greg Clayton765d2e22013-12-10 19:14:04 +00002038 if (parsed_line.GetArgumentCount() == 1)
2039 {
2040 word_complete = true;
2041 }
2042 else
2043 {
2044 look_for_subcommand = true;
2045 num_command_matches = 0;
2046 matches.DeleteStringAtIndex(0);
2047 parsed_line.AppendArgument ("");
2048 cursor_index++;
2049 cursor_char_position = 0;
2050 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002051 }
2052 }
2053
2054 if (cursor_index > 0 || look_for_subcommand)
2055 {
2056 // We are completing further on into a commands arguments, so find the command and tell it
2057 // to complete the command.
2058 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00002059 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Ed Masted78c9572014-04-20 00:31:37 +00002060 if (command_object == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002061 {
2062 return 0;
2063 }
2064 else
2065 {
2066 parsed_line.Shift();
2067 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00002068 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00002069 cursor_index,
2070 cursor_char_position,
2071 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002072 max_return_elements,
2073 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002074 matches);
2075 }
2076 }
2077
2078 return num_command_matches;
2079
2080}
2081
2082int
2083CommandInterpreter::HandleCompletion (const char *current_line,
2084 const char *cursor,
2085 const char *last_char,
2086 int match_start_point,
2087 int max_return_elements,
2088 StringList &matches)
2089{
2090 // We parse the argument up to the cursor, so the last argument in parsed_line is
2091 // the one containing the cursor, and the cursor is after the last character.
2092
Pavel Labath00b7f952015-03-02 12:46:22 +00002093 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
2094 Args partial_parsed_line(llvm::StringRef(current_line, cursor - current_line));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002095
Jim Inghama5a97eb2011-07-12 03:12:18 +00002096 // Don't complete comments, and if the line we are completing is just the history repeat character,
2097 // substitute the appropriate history line.
2098 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
2099 if (first_arg)
2100 {
2101 if (first_arg[0] == m_comment_char)
2102 return 0;
Enrico Granata7594f142013-06-17 22:51:50 +00002103 else if (first_arg[0] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002104 {
Enrico Granata7594f142013-06-17 22:51:50 +00002105 const char *history_string = m_command_history.FindString (first_arg);
Ed Masted78c9572014-04-20 00:31:37 +00002106 if (history_string != nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00002107 {
2108 matches.Clear();
2109 matches.InsertStringAtIndex(0, history_string);
2110 return -2;
2111 }
2112 else
2113 return 0;
2114
2115 }
2116 }
2117
2118
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002119 int num_args = partial_parsed_line.GetArgumentCount();
2120 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
2121 int cursor_char_position;
2122
2123 if (cursor_index == -1)
2124 cursor_char_position = 0;
2125 else
2126 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00002127
2128 if (cursor > current_line && cursor[-1] == ' ')
2129 {
2130 // We are just after a space. If we are in an argument, then we will continue
2131 // parsing, but if we are between arguments, then we have to complete whatever the next
2132 // element would be.
2133 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
2134 // protected by a quote) then the space will also be in the parsed argument...
2135
2136 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
2137 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
2138 {
Greg Clayton765d2e22013-12-10 19:14:04 +00002139 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
Jim Inghamfe0c4252010-12-14 19:56:01 +00002140 cursor_index++;
2141 cursor_char_position = 0;
2142 }
2143 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002144
2145 int num_command_matches;
2146
2147 matches.Clear();
2148
2149 // Only max_return_elements == -1 is supported at present:
2150 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00002151 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00002152 num_command_matches = HandleCompletionMatches (parsed_line,
2153 cursor_index,
2154 cursor_char_position,
2155 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002156 max_return_elements,
2157 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002158 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002159
2160 if (num_command_matches <= 0)
2161 return num_command_matches;
2162
2163 if (num_args == 0)
2164 {
2165 // If we got an empty string, insert nothing.
2166 matches.InsertStringAtIndex(0, "");
2167 }
2168 else
2169 {
2170 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2171 // put an empty string in element 0.
2172 std::string command_partial_str;
2173 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002174 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2175 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002176
2177 std::string common_prefix;
2178 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002179 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002180
2181 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002182 // Only do this if the completer told us this was a complete word, however...
2183 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002184 {
2185 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2186 if (quote_char != '\0')
2187 common_prefix.push_back(quote_char);
2188
2189 common_prefix.push_back(' ');
2190 }
2191 common_prefix.erase (0, partial_name_len);
2192 matches.InsertStringAtIndex(0, common_prefix.c_str());
2193 }
2194 return num_command_matches;
2195}
2196
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002197
2198CommandInterpreter::~CommandInterpreter ()
2199{
2200}
2201
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002202void
Greg Clayton44d93782014-01-27 23:43:24 +00002203CommandInterpreter::UpdatePrompt (const char *new_prompt)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002204{
Greg Clayton44d93782014-01-27 23:43:24 +00002205 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2206 BroadcastEvent (prompt_change_event_sp);
2207 if (m_command_io_handler_sp)
2208 m_command_io_handler_sp->SetPrompt(new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002209}
2210
Jim Ingham97a6dc72010-10-04 19:49:29 +00002211
2212bool
2213CommandInterpreter::Confirm (const char *message, bool default_answer)
2214{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002215 // Check AutoConfirm first:
2216 if (m_debugger.GetAutoConfirm())
2217 return default_answer;
Greg Clayton44d93782014-01-27 23:43:24 +00002218
2219 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2220 message,
2221 default_answer);
2222 IOHandlerSP io_handler_sp (confirm);
2223 m_debugger.RunIOHandler (io_handler_sp);
2224 return confirm->GetResponse();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002225}
2226
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002227OptionArgVectorSP
2228CommandInterpreter::GetAliasOptions (const char *alias_name)
2229{
2230 OptionArgMap::iterator pos;
2231 OptionArgVectorSP ret_val;
2232
2233 std::string alias (alias_name);
2234
2235 if (HasAliasOptions())
2236 {
2237 pos = m_alias_options.find (alias);
2238 if (pos != m_alias_options.end())
2239 ret_val = pos->second;
2240 }
2241
2242 return ret_val;
2243}
2244
2245void
2246CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2247{
2248 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2249 if (pos != m_alias_options.end())
2250 {
2251 m_alias_options.erase (pos);
2252 }
2253}
2254
2255void
2256CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2257{
2258 m_alias_options[alias_name] = option_arg_vector_sp;
2259}
2260
2261bool
2262CommandInterpreter::HasCommands ()
2263{
2264 return (!m_command_dict.empty());
2265}
2266
2267bool
2268CommandInterpreter::HasAliases ()
2269{
2270 return (!m_alias_dict.empty());
2271}
2272
2273bool
2274CommandInterpreter::HasUserCommands ()
2275{
2276 return (!m_user_dict.empty());
2277}
2278
2279bool
2280CommandInterpreter::HasAliasOptions ()
2281{
2282 return (!m_alias_options.empty());
2283}
2284
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002285void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002286CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2287 const char *alias_name,
2288 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002289 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002290 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002291{
2292 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002293
2294 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002295
Caroline Ticed9d63362010-12-07 19:58:26 +00002296 // Make sure that the alias name is the 0th element in cmd_args
2297 std::string alias_name_str = alias_name;
2298 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2299 cmd_args.Unshift (alias_name);
2300
2301 Args new_args (alias_cmd_obj->GetCommandName());
2302 if (new_args.GetArgumentCount() == 2)
2303 new_args.Shift();
2304
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002305 if (option_arg_vector_sp.get())
2306 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002307 if (wants_raw_input)
2308 {
2309 // We have a command that both has command options and takes raw input. Make *sure* it has a
2310 // " -- " in the right place in the raw_input_string.
2311 size_t pos = raw_input_string.find(" -- ");
2312 if (pos == std::string::npos)
2313 {
2314 // None found; assume it goes at the beginning of the raw input string
2315 raw_input_string.insert (0, " -- ");
2316 }
2317 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002318
2319 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002320 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002321 std::vector<bool> used (old_size + 1, false);
2322
2323 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002324
Andy Gibbsa297a972013-06-19 19:04:53 +00002325 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002326 {
2327 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002328 OptionArgValue value_pair = option_pair.second;
2329 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002330 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002331 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002332 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002333 {
2334 if (!wants_raw_input
2335 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2336 new_args.AppendArgument (value.c_str());
2337 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002338 else
2339 {
Virgile Belloe2607b52013-09-05 16:42:23 +00002340 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002341 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002342 if (value.compare ("<no-argument>") != 0)
2343 {
2344 int index = GetOptionArgumentPosition (value.c_str());
2345 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002346 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002347 // value was NOT a positional argument; must be a real value
Virgile Belloe2607b52013-09-05 16:42:23 +00002348 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002349 new_args.AppendArgument (value.c_str());
2350 else
2351 {
2352 char buffer[255];
2353 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2354 new_args.AppendArgument (buffer);
2355 }
2356
2357 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002358 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002359 {
2360 result.AppendErrorWithFormat
2361 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2362 index);
2363 result.SetStatus (eReturnStatusFailed);
2364 return;
2365 }
2366 else
2367 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002368 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2369 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2370 if (strpos != std::string::npos)
2371 {
2372 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2373 }
2374
Virgile Belloe2607b52013-09-05 16:42:23 +00002375 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002376 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2377 else
2378 {
2379 char buffer[255];
2380 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2381 cmd_args.GetArgumentAtIndex (index));
2382 new_args.AppendArgument (buffer);
2383 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002384 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002385 }
2386 }
2387 }
2388 }
2389
Andy Gibbsa297a972013-06-19 19:04:53 +00002390 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002391 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002392 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002393 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2394 }
2395
2396 cmd_args.Clear();
2397 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2398 }
2399 else
2400 {
2401 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002402 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2403 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2404 // input string.
2405 if (wants_raw_input)
2406 {
2407 cmd_args.Clear();
2408 cmd_args.SetArguments (new_args.GetArgumentCount(), (const char **) new_args.GetArgumentVector());
2409 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002410 return;
2411 }
2412
2413 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2414 return;
2415}
2416
2417
2418int
2419CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2420{
2421 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2422 // of zero.
2423
2424 char *cptr = (char *) in_string;
2425
2426 // Does it start with '%'
2427 if (cptr[0] == '%')
2428 {
2429 ++cptr;
2430
2431 // Is the rest of it entirely digits?
2432 if (isdigit (cptr[0]))
2433 {
2434 const char *start = cptr;
2435 while (isdigit (cptr[0]))
2436 ++cptr;
2437
2438 // We've gotten to the end of the digits; are we at the end of the string?
2439 if (cptr[0] == '\0')
2440 position = atoi (start);
2441 }
2442 }
2443
2444 return position;
2445}
2446
2447void
2448CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2449{
Jim Ingham16e0c682011-08-12 23:34:31 +00002450 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002451 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002452 {
Greg Clayton14a35512011-09-11 00:01:44 +00002453 // In the current working directory we don't load any program specific
2454 // .lldbinit files, we only look for a "./.lldbinit" file.
2455 if (m_skip_lldbinit_files)
2456 return;
2457
2458 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002459 }
Greg Clayton14a35512011-09-11 00:01:44 +00002460 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002461 {
Greg Clayton14a35512011-09-11 00:01:44 +00002462 // If we aren't looking in the current working directory we are looking
2463 // in the home directory. We will first see if there is an application
2464 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2465 // "-" and the name of the program. If this file doesn't exist, we fall
2466 // back to just the "~/.lldbinit" file. We also obey any requests to not
2467 // load the init files.
Zachary Turnera21fee02014-08-21 21:49:24 +00002468 llvm::SmallString<64> home_dir_path;
2469 llvm::sys::path::home_directory(home_dir_path);
2470 FileSpec profilePath(home_dir_path.c_str(), false);
Zachary Turner9e757b72014-07-28 16:45:05 +00002471 profilePath.AppendPathComponent(".lldbinit");
2472 std::string init_file_path = profilePath.GetPath();
Greg Clayton14a35512011-09-11 00:01:44 +00002473
2474 if (m_skip_app_init_files == false)
2475 {
Zachary Turnera21fee02014-08-21 21:49:24 +00002476 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
Greg Clayton14a35512011-09-11 00:01:44 +00002477 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002478
Greg Clayton14a35512011-09-11 00:01:44 +00002479 if (program_name)
2480 {
2481 char program_init_file_name[PATH_MAX];
Zachary Turner9e757b72014-07-28 16:45:05 +00002482 ::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 +00002483 init_file.SetFile (program_init_file_name, true);
2484 if (!init_file.Exists())
2485 init_file.Clear();
2486 }
2487 }
2488
2489 if (!init_file && !m_skip_lldbinit_files)
Zachary Turner9e757b72014-07-28 16:45:05 +00002490 init_file.SetFile (init_file_path.c_str(), false);
Greg Clayton14a35512011-09-11 00:01:44 +00002491 }
2492
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002493 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2494 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2495
2496 if (init_file.Exists())
2497 {
Greg Clayton44d93782014-01-27 23:43:24 +00002498 const bool saved_batch = SetBatchCommandMode (true);
Jim Ingham26c7bf92014-10-11 00:38:27 +00002499 CommandInterpreterRunOptions options;
2500 options.SetSilent (true);
2501 options.SetStopOnError (false);
2502 options.SetStopOnContinue (true);
2503
Greg Clayton340b0302014-02-05 17:57:57 +00002504 HandleCommandsFromFile (init_file,
Ed Masted78c9572014-04-20 00:31:37 +00002505 nullptr, // Execution context
Jim Ingham26c7bf92014-10-11 00:38:27 +00002506 options,
Greg Clayton340b0302014-02-05 17:57:57 +00002507 result);
Greg Clayton44d93782014-01-27 23:43:24 +00002508 SetBatchCommandMode (saved_batch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002509 }
2510 else
2511 {
2512 // nothing to be done if the file doesn't exist
2513 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2514 }
2515}
2516
Kate Stonea487aa42015-01-15 00:52:41 +00002517const char *
2518CommandInterpreter::GetCommandPrefix()
2519{
2520 const char * prefix = GetDebugger().GetIOHandlerCommandPrefix();
2521 return prefix == NULL ? "" : prefix;
2522}
2523
Greg Clayton8b82f082011-04-12 05:54:46 +00002524PlatformSP
2525CommandInterpreter::GetPlatform (bool prefer_target_platform)
2526{
2527 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002528 if (prefer_target_platform)
2529 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002530 ExecutionContext exe_ctx(GetExecutionContext());
2531 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002532 if (target)
2533 platform_sp = target->GetPlatform();
2534 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002535
2536 if (!platform_sp)
2537 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2538 return platform_sp;
2539}
2540
Jim Inghame16c50a2011-02-18 00:54:25 +00002541void
Jim Inghambad87fe2011-03-11 01:51:49 +00002542CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham26c7bf92014-10-11 00:38:27 +00002543 ExecutionContext *override_context,
2544 CommandInterpreterRunOptions &options,
Jim Inghame16c50a2011-02-18 00:54:25 +00002545 CommandReturnObject &result)
2546{
2547 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002548
2549 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2550 // Make sure you reset this value anywhere you return from the function.
2551
2552 bool old_async_execution = m_debugger.GetAsyncExecution();
2553
2554 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2555 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2556
Ed Masted78c9572014-04-20 00:31:37 +00002557 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002558 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002559
Jim Ingham26c7bf92014-10-11 00:38:27 +00002560 if (!options.GetStopOnContinue())
Jim Inghame16c50a2011-02-18 00:54:25 +00002561 {
2562 m_debugger.SetAsyncExecution (false);
2563 }
2564
Andy Gibbsa297a972013-06-19 19:04:53 +00002565 for (size_t idx = 0; idx < num_lines; idx++)
Jim Inghame16c50a2011-02-18 00:54:25 +00002566 {
2567 const char *cmd = commands.GetStringAtIndex(idx);
2568 if (cmd[0] == '\0')
2569 continue;
2570
Jim Ingham26c7bf92014-10-11 00:38:27 +00002571 if (options.GetEchoCommands())
Jim Inghame16c50a2011-02-18 00:54:25 +00002572 {
2573 result.AppendMessageWithFormat ("%s %s\n",
Greg Clayton44d93782014-01-27 23:43:24 +00002574 m_debugger.GetPrompt(),
2575 cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002576 }
2577
Greg Clayton9d0402b2011-02-20 02:15:07 +00002578 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002579 // If override_context is not NULL, pass no_context_switching = true for
2580 // HandleCommand() since we updated our context already.
Jim Ingham076b7fc2013-05-02 23:15:37 +00002581
2582 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2583 // 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 +00002584 if (!options.GetAddToHistory())
Jim Ingham076b7fc2013-05-02 23:15:37 +00002585 m_command_source_depth++;
Jim Ingham26c7bf92014-10-11 00:38:27 +00002586 bool success = HandleCommand(cmd, options.m_add_to_history, tmp_result,
Ed Masted78c9572014-04-20 00:31:37 +00002587 nullptr, /* override_context */
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002588 true, /* repeat_on_empty_command */
Ed Masted78c9572014-04-20 00:31:37 +00002589 override_context != nullptr /* no_context_switching */);
Jim Ingham26c7bf92014-10-11 00:38:27 +00002590 if (!options.GetAddToHistory())
Jim Ingham076b7fc2013-05-02 23:15:37 +00002591 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002592
Jim Ingham26c7bf92014-10-11 00:38:27 +00002593 if (options.GetPrintResults())
Jim Inghame16c50a2011-02-18 00:54:25 +00002594 {
2595 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002596 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002597 }
2598
2599 if (!success || !tmp_result.Succeeded())
2600 {
Jim Inghama5038812012-04-24 02:25:07 +00002601 const char *error_msg = tmp_result.GetErrorData();
Ed Masted78c9572014-04-20 00:31:37 +00002602 if (error_msg == nullptr || error_msg[0] == '\0')
Jim Inghama5038812012-04-24 02:25:07 +00002603 error_msg = "<unknown error>.\n";
Jim Ingham26c7bf92014-10-11 00:38:27 +00002604 if (options.GetStopOnError())
Jim Inghame16c50a2011-02-18 00:54:25 +00002605 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002606 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s",
2607 (uint64_t)idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002608 result.SetStatus (eReturnStatusFailed);
2609 m_debugger.SetAsyncExecution (old_async_execution);
2610 return;
2611 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002612 else if (options.GetPrintResults())
Jim Inghame16c50a2011-02-18 00:54:25 +00002613 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002614 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s",
2615 (uint64_t)idx + 1,
Jim Inghame16c50a2011-02-18 00:54:25 +00002616 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002617 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002618 }
2619 }
2620
Caroline Tice969ed3d2011-05-02 20:41:46 +00002621 if (result.GetImmediateOutputStream())
2622 result.GetImmediateOutputStream()->Flush();
2623
2624 if (result.GetImmediateErrorStream())
2625 result.GetImmediateErrorStream()->Flush();
2626
Jim Inghame16c50a2011-02-18 00:54:25 +00002627 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2628 // could be running (for instance in Breakpoint Commands.
2629 // So we check the return value to see if it is has running in it.
2630 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2631 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2632 {
Jim Ingham26c7bf92014-10-11 00:38:27 +00002633 if (options.GetStopOnContinue())
Jim Inghame16c50a2011-02-18 00:54:25 +00002634 {
2635 // If we caused the target to proceed, and we're going to stop in that case, set the
2636 // status in our real result before returning. This is an error if the continue was not the
2637 // last command in the set of commands to be run.
2638 if (idx != num_lines - 1)
Deepak Panickal99fbc072014-03-03 15:39:47 +00002639 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n",
2640 (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002641 else
Deepak Panickal99fbc072014-03-03 15:39:47 +00002642 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002643
2644 result.SetStatus(tmp_result.GetStatus());
2645 m_debugger.SetAsyncExecution (old_async_execution);
2646
2647 return;
2648 }
2649 }
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002650
2651 // Also check for "stop on crash here:
2652 bool should_stop = false;
2653 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash())
2654 {
2655 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2656 if (target_sp)
2657 {
2658 ProcessSP process_sp (target_sp->GetProcessSP());
2659 if (process_sp)
2660 {
2661 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads())
2662 {
2663 StopReason reason = thread_sp->GetStopReason();
2664 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation)
2665 {
2666 should_stop = true;
2667 break;
2668 }
2669 }
2670 }
2671 }
2672 if (should_stop)
2673 {
2674 if (idx != num_lines - 1)
2675 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' stopped with a signal or exception.\n",
2676 (uint64_t)idx + 1, cmd);
2677 else
2678 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' stopped with a signal or exception.\n", (uint64_t)idx + 1, cmd);
2679
2680 result.SetStatus(tmp_result.GetStatus());
2681 m_debugger.SetAsyncExecution (old_async_execution);
2682
2683 return;
2684 }
2685 }
Jim Inghame16c50a2011-02-18 00:54:25 +00002686
2687 }
2688
2689 result.SetStatus (eReturnStatusSuccessFinishResult);
2690 m_debugger.SetAsyncExecution (old_async_execution);
2691
2692 return;
2693}
2694
Greg Clayton340b0302014-02-05 17:57:57 +00002695// Make flags that we can pass into the IOHandler so our delegates can do the right thing
2696enum {
2697 eHandleCommandFlagStopOnContinue = (1u << 0),
2698 eHandleCommandFlagStopOnError = (1u << 1),
2699 eHandleCommandFlagEchoCommand = (1u << 2),
Jim Ingham26c7bf92014-10-11 00:38:27 +00002700 eHandleCommandFlagPrintResult = (1u << 3),
2701 eHandleCommandFlagStopOnCrash = (1u << 4)
Greg Clayton340b0302014-02-05 17:57:57 +00002702};
2703
Jim Inghame16c50a2011-02-18 00:54:25 +00002704void
2705CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2706 ExecutionContext *context,
Jim Ingham26c7bf92014-10-11 00:38:27 +00002707 CommandInterpreterRunOptions &options,
Jim Inghame16c50a2011-02-18 00:54:25 +00002708 CommandReturnObject &result)
2709{
2710 if (cmd_file.Exists())
2711 {
Greg Clayton44d93782014-01-27 23:43:24 +00002712 StreamFileSP input_file_sp (new StreamFile());
2713
2714 std::string cmd_file_path = cmd_file.GetPath();
2715 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2716
2717 if (error.Success())
2718 {
2719 Debugger &debugger = GetDebugger();
2720
Greg Clayton340b0302014-02-05 17:57:57 +00002721 uint32_t flags = 0;
2722
Jim Ingham26c7bf92014-10-11 00:38:27 +00002723 if (options.m_stop_on_continue == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002724 {
2725 if (m_command_source_flags.empty())
2726 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002727 // Stop on continue by default
Greg Clayton340b0302014-02-05 17:57:57 +00002728 flags |= eHandleCommandFlagStopOnContinue;
2729 }
2730 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2731 {
2732 flags |= eHandleCommandFlagStopOnContinue;
2733 }
2734 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002735 else if (options.m_stop_on_continue == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002736 {
2737 flags |= eHandleCommandFlagStopOnContinue;
2738 }
2739
Jim Ingham26c7bf92014-10-11 00:38:27 +00002740 if (options.m_stop_on_error == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002741 {
2742 if (m_command_source_flags.empty())
2743 {
2744 if (GetStopCmdSourceOnError())
2745 flags |= eHandleCommandFlagStopOnError;
2746 }
2747 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2748 {
2749 flags |= eHandleCommandFlagStopOnError;
2750 }
2751 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002752 else if (options.m_stop_on_error == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002753 {
2754 flags |= eHandleCommandFlagStopOnError;
2755 }
2756
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002757 if (options.GetStopOnCrash())
2758 {
2759 if (m_command_source_flags.empty())
2760 {
2761 // Echo command by default
2762 flags |= eHandleCommandFlagStopOnCrash;
2763 }
2764 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash)
2765 {
2766 flags |= eHandleCommandFlagStopOnCrash;
2767 }
2768 }
2769
Jim Ingham26c7bf92014-10-11 00:38:27 +00002770 if (options.m_echo_commands == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002771 {
2772 if (m_command_source_flags.empty())
2773 {
2774 // Echo command by default
2775 flags |= eHandleCommandFlagEchoCommand;
2776 }
2777 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2778 {
2779 flags |= eHandleCommandFlagEchoCommand;
2780 }
2781 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002782 else if (options.m_echo_commands == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002783 {
2784 flags |= eHandleCommandFlagEchoCommand;
2785 }
2786
Jim Ingham26c7bf92014-10-11 00:38:27 +00002787 if (options.m_print_results == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002788 {
2789 if (m_command_source_flags.empty())
2790 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002791 // Print output by default
2792 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002793 }
Greg Claytone4e462c2014-02-05 21:03:22 +00002794 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
Greg Clayton340b0302014-02-05 17:57:57 +00002795 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002796 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002797 }
2798 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002799 else if (options.m_print_results == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002800 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002801 flags |= eHandleCommandFlagPrintResult;
2802 }
2803
2804 if (flags & eHandleCommandFlagPrintResult)
2805 {
Greg Clayton8ee67312014-02-05 21:46:20 +00002806 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
Greg Clayton340b0302014-02-05 17:57:57 +00002807 }
2808
2809 // Used for inheriting the right settings when "command source" might have
2810 // nested "command source" commands
Greg Claytone4e462c2014-02-05 21:03:22 +00002811 lldb::StreamFileSP empty_stream_sp;
Greg Clayton340b0302014-02-05 17:57:57 +00002812 m_command_source_flags.push_back(flags);
Greg Clayton44d93782014-01-27 23:43:24 +00002813 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00002814 IOHandler::Type::CommandInterpreter,
Greg Clayton44d93782014-01-27 23:43:24 +00002815 input_file_sp,
Greg Claytone4e462c2014-02-05 21:03:22 +00002816 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2817 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
Greg Clayton340b0302014-02-05 17:57:57 +00002818 flags,
Ed Masted78c9572014-04-20 00:31:37 +00002819 nullptr, // Pass in NULL for "editline_name" so no history is saved, or written
Greg Clayton8ee67312014-02-05 21:46:20 +00002820 debugger.GetPrompt(),
Kate Stonee30f11d2014-11-17 19:06:59 +00002821 NULL,
Greg Clayton44d93782014-01-27 23:43:24 +00002822 false, // Not multi-line
Kate Stonee30f11d2014-11-17 19:06:59 +00002823 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00002824 0,
Greg Clayton44d93782014-01-27 23:43:24 +00002825 *this));
Greg Clayton8ee67312014-02-05 21:46:20 +00002826 const bool old_async_execution = debugger.GetAsyncExecution();
2827
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002828 // Set synchronous execution if we are not stopping on continue
Greg Clayton8ee67312014-02-05 21:46:20 +00002829 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2830 debugger.SetAsyncExecution (false);
2831
Greg Clayton340b0302014-02-05 17:57:57 +00002832 m_command_source_depth++;
Greg Clayton8ee67312014-02-05 21:46:20 +00002833
2834 debugger.RunIOHandler(io_handler_sp);
Greg Clayton340b0302014-02-05 17:57:57 +00002835 if (!m_command_source_flags.empty())
2836 m_command_source_flags.pop_back();
2837 m_command_source_depth--;
Greg Clayton44d93782014-01-27 23:43:24 +00002838 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Greg Clayton8ee67312014-02-05 21:46:20 +00002839 debugger.SetAsyncExecution (old_async_execution);
Greg Clayton44d93782014-01-27 23:43:24 +00002840 }
2841 else
2842 {
2843 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2844 result.SetStatus (eReturnStatusFailed);
2845 }
Greg Clayton8ee67312014-02-05 21:46:20 +00002846
2847
Jim Inghame16c50a2011-02-18 00:54:25 +00002848 }
2849 else
2850 {
2851 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
Jim Ingham4af59612014-12-19 19:20:44 +00002852 cmd_file.GetFilename().AsCString("<Unknown>"));
Jim Inghame16c50a2011-02-18 00:54:25 +00002853 result.SetStatus (eReturnStatusFailed);
2854 return;
2855 }
2856}
2857
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002858ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002859CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002860{
Ed Masted78c9572014-04-20 00:31:37 +00002861 if (m_script_interpreter_ap.get() != nullptr)
Enrico Granatab5887262012-10-29 21:18:03 +00002862 return m_script_interpreter_ap.get();
2863
2864 if (!can_create)
Ed Masted78c9572014-04-20 00:31:37 +00002865 return nullptr;
Enrico Granatab5887262012-10-29 21:18:03 +00002866
Enrico Granataa29bdad2012-07-10 18:23:48 +00002867 // <rdar://problem/11751427>
2868 // we need to protect the initialization of the script interpreter
2869 // otherwise we could end up with two threads both trying to create
2870 // their instance of it, and for some languages (e.g. Python)
2871 // this is a bulletproof recipe for disaster!
2872 // this needs to be a function-level static because multiple Debugger instances living in the same process
2873 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002874 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2875 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002876
Greg Clayton5160ce52013-03-27 23:08:40 +00002877 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002878 if (log)
2879 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002880
Caroline Tice2f88aad2011-01-14 00:29:16 +00002881 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2882 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002883 {
Greg Claytondce502e2011-11-04 03:34:56 +00002884 case eScriptLanguagePython:
2885#ifndef LLDB_DISABLE_PYTHON
2886 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2887 break;
2888#else
2889 // Fall through to the None case when python is disabled
2890#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002891 case eScriptLanguageNone:
2892 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2893 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002894 };
2895
2896 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002897}
2898
2899
2900
2901bool
2902CommandInterpreter::GetSynchronous ()
2903{
2904 return m_synchronous_execution;
2905}
2906
2907void
2908CommandInterpreter::SetSynchronous (bool value)
2909{
Johnny Chenc066ab42010-10-14 01:22:03 +00002910 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002911}
2912
2913void
2914CommandInterpreter::OutputFormattedHelpText (Stream &strm,
Kate Stonea487aa42015-01-15 00:52:41 +00002915 const char *prefix,
2916 const char *help_text)
2917{
2918 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2919 if (prefix == NULL)
2920 prefix = "";
2921
2922 size_t prefix_width = strlen(prefix);
2923 size_t line_width_max = max_columns - prefix_width;
2924 const char *help_text_end = help_text + strlen(help_text);
2925 const char *line_start = help_text;
2926 if (line_width_max < 16)
2927 line_width_max = help_text_end - help_text + prefix_width;
2928
2929 strm.IndentMore (prefix_width);
2930 while (line_start < help_text_end)
2931 {
2932 // Break each line at the first newline or last space/tab before
2933 // the maximum number of characters that fit on a line. Lines with no
2934 // natural break are left unbroken to wrap.
2935 const char *line_end = help_text_end;
2936 const char *line_scan = line_start;
2937 const char *line_scan_end = help_text_end;
2938 while (line_scan < line_scan_end)
2939 {
2940 char next = *line_scan;
2941 if (next == '\t' || next == ' ')
2942 {
2943 line_end = line_scan;
2944 line_scan_end = line_start + line_width_max;
2945 }
2946 else if (next == '\n' || next == '\0')
2947 {
2948 line_end = line_scan;
2949 break;
2950 }
2951 ++line_scan;
2952 }
2953
2954 // Prefix the first line, indent subsequent lines to line up
2955 if (line_start == help_text)
2956 strm.Write (prefix, prefix_width);
2957 else
2958 strm.Indent();
2959 strm.Write (line_start, line_end - line_start);
2960 strm.EOL();
2961
2962 // When a line breaks at whitespace consume it before continuing
2963 line_start = line_end;
2964 char next = *line_start;
2965 if (next == '\n')
2966 ++line_start;
2967 else while (next == ' ' || next == '\t')
2968 next = *(++line_start);
2969 }
2970 strm.IndentLess (prefix_width);
2971}
2972
2973void
2974CommandInterpreter::OutputFormattedHelpText (Stream &strm,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002975 const char *word_text,
2976 const char *separator,
2977 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002978 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002979{
Kate Stonea487aa42015-01-15 00:52:41 +00002980 StreamString prefix_stream;
2981 prefix_stream.Printf (" %-*s %s ", (int)max_word_len, word_text, separator);
2982 OutputFormattedHelpText (strm, prefix_stream.GetData(), help_text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002983}
2984
2985void
Enrico Granata82a7d982011-07-07 00:38:40 +00002986CommandInterpreter::OutputHelpText (Stream &strm,
2987 const char *word_text,
2988 const char *separator,
2989 const char *help_text,
2990 uint32_t max_word_len)
2991{
2992 int indent_size = max_word_len + strlen (separator) + 2;
2993
2994 strm.IndentMore (indent_size);
2995
2996 StreamString text_strm;
2997 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2998
2999 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00003000
3001 size_t len = text_strm.GetSize();
3002 const char *text = text_strm.GetData();
3003
3004 uint32_t chars_left = max_columns;
3005
3006 for (uint32_t i = 0; i < len; i++)
3007 {
3008 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
3009 {
Enrico Granata82a7d982011-07-07 00:38:40 +00003010 chars_left = max_columns - indent_size;
3011 strm.EOL();
3012 strm.Indent();
3013 }
3014 else
3015 {
3016 strm.PutChar(text[i]);
3017 chars_left--;
3018 }
3019
3020 }
3021
3022 strm.EOL();
3023 strm.IndentLess(indent_size);
3024}
3025
3026void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003027CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
Jim Inghamaf3753e2013-05-17 01:30:37 +00003028 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003029{
3030 CommandObject::CommandMap::const_iterator pos;
3031
Jim Inghamaf3753e2013-05-17 01:30:37 +00003032 if (search_builtin_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003033 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00003034 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003035 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00003036 const char *command_name = pos->first.c_str();
3037 CommandObject *cmd_obj = pos->second.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003038
Jim Inghamaf3753e2013-05-17 01:30:37 +00003039 if (cmd_obj->HelpTextContainsWord (search_word))
3040 {
3041 commands_found.AppendString (command_name);
3042 commands_help.AppendString (cmd_obj->GetHelp());
3043 }
3044
3045 if (cmd_obj->IsMultiwordObject())
3046 cmd_obj->AproposAllSubCommands (command_name,
3047 search_word,
3048 commands_found,
3049 commands_help);
3050
3051 }
3052 }
3053
3054 if (search_user_commands)
3055 {
3056 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
3057 {
3058 const char *command_name = pos->first.c_str();
3059 CommandObject *cmd_obj = pos->second.get();
3060
3061 if (cmd_obj->HelpTextContainsWord (search_word))
3062 {
3063 commands_found.AppendString (command_name);
3064 commands_help.AppendString (cmd_obj->GetHelp());
3065 }
3066
3067 if (cmd_obj->IsMultiwordObject())
3068 cmd_obj->AproposAllSubCommands (command_name,
3069 search_word,
3070 commands_found,
3071 commands_help);
3072
3073 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003074 }
3075}
Greg Clayton8b82f082011-04-12 05:54:46 +00003076
Greg Clayton8b82f082011-04-12 05:54:46 +00003077void
3078CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
3079{
Ed Masted78c9572014-04-20 00:31:37 +00003080 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00003081 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00003082 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00003083 }
3084 else
3085 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00003086 const bool adopt_selected = true;
3087 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00003088 }
3089}
Greg Clayton44d93782014-01-27 23:43:24 +00003090
3091
3092size_t
3093CommandInterpreter::GetProcessOutput ()
3094{
3095 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
3096 char stdio_buffer[1024];
3097 size_t len;
3098 size_t total_bytes = 0;
3099 Error error;
3100 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
3101 if (target_sp)
3102 {
3103 ProcessSP process_sp (target_sp->GetProcessSP());
3104 if (process_sp)
3105 {
3106 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
3107 {
3108 size_t bytes_written = len;
3109 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
3110 total_bytes += len;
3111 }
3112 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
3113 {
3114 size_t bytes_written = len;
3115 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
3116 total_bytes += len;
3117 }
3118 }
3119 }
3120 return total_bytes;
3121}
3122
3123void
3124CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
3125{
Greg Clayton340b0302014-02-05 17:57:57 +00003126 const bool is_interactive = io_handler.GetIsInteractive();
3127 if (is_interactive == false)
3128 {
3129 // When we are not interactive, don't execute blank lines. This will happen
3130 // sourcing a commands file. We don't want blank lines to repeat the previous
3131 // command and cause any errors to occur (like redefining an alias, get an error
3132 // and stop parsing the commands file).
3133 if (line.empty())
3134 return;
3135
3136 // When using a non-interactive file handle (like when sourcing commands from a file)
3137 // we need to echo the command out so we don't just see the command output and no
3138 // command...
3139 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
3140 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
3141 }
3142
Greg Clayton44d93782014-01-27 23:43:24 +00003143 lldb_private::CommandReturnObject result;
3144 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
3145
Greg Clayton44d93782014-01-27 23:43:24 +00003146 // Now emit the command output text from the command we just executed
Greg Clayton340b0302014-02-05 17:57:57 +00003147 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
3148 {
3149 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3150 GetProcessOutput ();
3151
Greg Clayton8ee67312014-02-05 21:46:20 +00003152 if (!result.GetImmediateOutputStream())
3153 {
3154 const char *output = result.GetOutputData();
3155 if (output && output[0])
3156 io_handler.GetOutputStreamFile()->PutCString(output);
3157 }
Greg Clayton44d93782014-01-27 23:43:24 +00003158
Greg Clayton340b0302014-02-05 17:57:57 +00003159 // Now emit the command error text from the command we just executed
Greg Clayton8ee67312014-02-05 21:46:20 +00003160 if (!result.GetImmediateErrorStream())
3161 {
3162 const char *error = result.GetErrorData();
3163 if (error && error[0])
3164 io_handler.GetErrorStreamFile()->PutCString(error);
3165 }
Greg Clayton340b0302014-02-05 17:57:57 +00003166 }
Greg Clayton44d93782014-01-27 23:43:24 +00003167
3168 switch (result.GetStatus())
3169 {
3170 case eReturnStatusInvalid:
3171 case eReturnStatusSuccessFinishNoResult:
3172 case eReturnStatusSuccessFinishResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003173 case eReturnStatusStarted:
3174 break;
3175
Greg Clayton44d93782014-01-27 23:43:24 +00003176 case eReturnStatusSuccessContinuingNoResult:
3177 case eReturnStatusSuccessContinuingResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003178 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3179 io_handler.SetIsDone(true);
3180 break;
3181
Greg Clayton44d93782014-01-27 23:43:24 +00003182 case eReturnStatusFailed:
Jim Ingham26c7bf92014-10-11 00:38:27 +00003183 m_num_errors++;
Greg Clayton340b0302014-02-05 17:57:57 +00003184 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3185 io_handler.SetIsDone(true);
Greg Clayton44d93782014-01-27 23:43:24 +00003186 break;
3187
3188 case eReturnStatusQuit:
Jim Ingham26c7bf92014-10-11 00:38:27 +00003189 m_quit_requested = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003190 io_handler.SetIsDone(true);
3191 break;
3192 }
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003193
3194 // Finally, if we're going to stop on crash, check that here:
3195 if (!m_quit_requested
3196 && result.GetDidChangeProcessState()
3197 && io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash))
3198 {
3199 bool should_stop = false;
3200 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
3201 if (target_sp)
3202 {
3203 ProcessSP process_sp (target_sp->GetProcessSP());
3204 if (process_sp)
3205 {
3206 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads())
3207 {
3208 StopReason reason = thread_sp->GetStopReason();
3209 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation)
3210 {
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003211 should_stop = true;
3212 break;
3213 }
3214 }
3215 }
3216 }
3217 if (should_stop)
3218 {
3219 io_handler.SetIsDone(true);
3220 m_stopped_for_crash = true;
3221 }
3222 }
Greg Clayton44d93782014-01-27 23:43:24 +00003223}
3224
Greg Claytonf0066ad2014-05-02 00:45:31 +00003225bool
3226CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler)
3227{
3228 ExecutionContext exe_ctx (GetExecutionContext());
3229 Process *process = exe_ctx.GetProcessPtr();
3230
3231 if (process)
3232 {
3233 StateType state = process->GetState();
3234 if (StateIsRunningState(state))
3235 {
3236 process->Halt();
3237 return true; // Don't do any updating when we are running
3238 }
3239 }
Greg Claytone507bce2015-01-27 01:58:22 +00003240
3241 ScriptInterpreter *script_interpreter = GetScriptInterpreter (false);
3242 if (script_interpreter)
3243 {
3244 if (script_interpreter->Interrupt())
3245 return true;
3246 }
Greg Claytonf0066ad2014-05-02 00:45:31 +00003247 return false;
3248}
3249
Greg Clayton44d93782014-01-27 23:43:24 +00003250void
3251CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3252 IOHandlerDelegate &delegate,
3253 bool asynchronously,
3254 void *baton)
3255{
3256 Debugger &debugger = GetDebugger();
3257 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00003258 IOHandler::Type::CommandList,
Greg Clayton44d93782014-01-27 23:43:24 +00003259 "lldb", // Name of input reader for history
3260 prompt, // Prompt
Kate Stonee30f11d2014-11-17 19:06:59 +00003261 NULL, // Continuation prompt
Greg Clayton44d93782014-01-27 23:43:24 +00003262 true, // Get multiple lines
Kate Stonee30f11d2014-11-17 19:06:59 +00003263 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00003264 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003265 delegate)); // IOHandlerDelegate
3266
3267 if (io_handler_sp)
3268 {
3269 io_handler_sp->SetUserData (baton);
3270 if (asynchronously)
3271 debugger.PushIOHandler(io_handler_sp);
3272 else
3273 debugger.RunIOHandler(io_handler_sp);
3274 }
3275
3276}
3277
3278
3279void
3280CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3281 IOHandlerDelegate &delegate,
3282 bool asynchronously,
3283 void *baton)
3284{
3285 Debugger &debugger = GetDebugger();
3286 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00003287 IOHandler::Type::PythonCode,
Greg Clayton44d93782014-01-27 23:43:24 +00003288 "lldb-python", // Name of input reader for history
3289 prompt, // Prompt
Kate Stonee30f11d2014-11-17 19:06:59 +00003290 NULL, // Continuation prompt
Greg Clayton44d93782014-01-27 23:43:24 +00003291 true, // Get multiple lines
Kate Stonee30f11d2014-11-17 19:06:59 +00003292 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00003293 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003294 delegate)); // IOHandlerDelegate
3295
3296 if (io_handler_sp)
3297 {
3298 io_handler_sp->SetUserData (baton);
3299 if (asynchronously)
3300 debugger.PushIOHandler(io_handler_sp);
3301 else
3302 debugger.RunIOHandler(io_handler_sp);
3303 }
3304
3305}
3306
3307bool
3308CommandInterpreter::IsActive ()
3309{
3310 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3311}
3312
Kate Stonee30f11d2014-11-17 19:06:59 +00003313lldb::IOHandlerSP
3314CommandInterpreter::GetIOHandler(bool force_create, CommandInterpreterRunOptions *options)
3315{
3316 // Always re-create the IOHandlerEditline in case the input
3317 // changed. The old instance might have had a non-interactive
3318 // input and now it does or vice versa.
3319 if (force_create || !m_command_io_handler_sp)
3320 {
3321 // Always re-create the IOHandlerEditline in case the input
3322 // changed. The old instance might have had a non-interactive
3323 // input and now it does or vice versa.
3324 uint32_t flags = 0;
3325
3326 if (options)
3327 {
3328 if (options->m_stop_on_continue == eLazyBoolYes)
3329 flags |= eHandleCommandFlagStopOnContinue;
3330 if (options->m_stop_on_error == eLazyBoolYes)
3331 flags |= eHandleCommandFlagStopOnError;
3332 if (options->m_stop_on_crash == eLazyBoolYes)
3333 flags |= eHandleCommandFlagStopOnCrash;
3334 if (options->m_echo_commands != eLazyBoolNo)
3335 flags |= eHandleCommandFlagEchoCommand;
3336 if (options->m_print_results != eLazyBoolNo)
3337 flags |= eHandleCommandFlagPrintResult;
3338 }
3339 else
3340 {
3341 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
3342 }
3343
3344 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3345 IOHandler::Type::CommandInterpreter,
3346 m_debugger.GetInputFile(),
3347 m_debugger.GetOutputFile(),
3348 m_debugger.GetErrorFile(),
3349 flags,
3350 "lldb",
3351 m_debugger.GetPrompt(),
3352 NULL, // Continuation prompt
3353 false, // Don't enable multiple line input, just single line commands
3354 m_debugger.GetUseColor(),
3355 0, // Don't show line numbers
3356 *this));
3357 }
3358 return m_command_io_handler_sp;
3359}
3360
Greg Clayton44d93782014-01-27 23:43:24 +00003361void
3362CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
Jim Ingham26c7bf92014-10-11 00:38:27 +00003363 bool spawn_thread,
3364 CommandInterpreterRunOptions &options)
Greg Clayton44d93782014-01-27 23:43:24 +00003365{
Kate Stonee30f11d2014-11-17 19:06:59 +00003366 // Always re-create the command intepreter when we run it in case
3367 // any file handles have changed.
3368 bool force_create = true;
3369 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003370 m_stopped_for_crash = false;
Greg Clayton380f3d82014-07-31 19:46:19 +00003371
Greg Clayton44d93782014-01-27 23:43:24 +00003372 if (auto_handle_events)
3373 m_debugger.StartEventHandlerThread();
3374
3375 if (spawn_thread)
3376 {
3377 m_debugger.StartIOHandlerThread();
3378 }
3379 else
3380 {
Siva Chandra9aaab552015-02-26 19:26:36 +00003381 m_debugger.ExecuteIOHandlers();
Kate Stonee30f11d2014-11-17 19:06:59 +00003382
Greg Clayton44d93782014-01-27 23:43:24 +00003383 if (auto_handle_events)
3384 m_debugger.StopEventHandlerThread();
3385 }
Kate Stonee30f11d2014-11-17 19:06:59 +00003386
Greg Clayton44d93782014-01-27 23:43:24 +00003387}
3388