blob: 481d69eb08a1f40f53c2bba218bc7a7ced283ea9 [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
10#include <string>
Caroline Tice4ab31c92010-10-12 21:57:09 +000011#include <vector>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include <stdlib.h>
13
Greg Clayton4a33d312011-06-23 17:59:56 +000014#include "CommandObjectScript.h"
Peter Collingbourne08405b62011-06-23 20:37:26 +000015#include "lldb/Interpreter/CommandObjectRegexCommand.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000016
Eli Friedman3afb70c2010-06-13 02:17:17 +000017#include "../Commands/CommandObjectApropos.h"
18#include "../Commands/CommandObjectArgs.h"
19#include "../Commands/CommandObjectBreakpoint.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000020#include "../Commands/CommandObjectDisassemble.h"
21#include "../Commands/CommandObjectExpression.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000022#include "../Commands/CommandObjectFrame.h"
Greg Clayton44d93782014-01-27 23:43:24 +000023#include "../Commands/CommandObjectGUI.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000024#include "../Commands/CommandObjectHelp.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000025#include "../Commands/CommandObjectLog.h"
26#include "../Commands/CommandObjectMemory.h"
Greg Claytonded470d2011-03-19 01:12:21 +000027#include "../Commands/CommandObjectPlatform.h"
Enrico Granata21dfcd92012-09-28 23:57:51 +000028#include "../Commands/CommandObjectPlugin.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000029#include "../Commands/CommandObjectProcess.h"
30#include "../Commands/CommandObjectQuit.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000031#include "../Commands/CommandObjectRegister.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000032#include "../Commands/CommandObjectSettings.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000033#include "../Commands/CommandObjectSource.h"
Jim Inghamebc09c32010-07-07 03:36:20 +000034#include "../Commands/CommandObjectCommands.h"
Eli Friedman3afb70c2010-06-13 02:17:17 +000035#include "../Commands/CommandObjectSyntax.h"
36#include "../Commands/CommandObjectTarget.h"
37#include "../Commands/CommandObjectThread.h"
Greg Clayton4a33d312011-06-23 17:59:56 +000038#include "../Commands/CommandObjectType.h"
Johnny Chen31c39da2010-12-23 20:21:44 +000039#include "../Commands/CommandObjectVersion.h"
Johnny Chenf04ee932011-09-22 18:04:58 +000040#include "../Commands/CommandObjectWatchpoint.h"
Colin Rileyc9c55a22015-05-04 18:39:38 +000041#include "../Commands/CommandObjectLanguage.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042
Greg Clayton7d2ef162013-03-29 17:03:23 +000043
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044#include "lldb/Core/Debugger.h"
Enrico Granatab5887262012-10-29 21:18:03 +000045#include "lldb/Core/Log.h"
Greg Claytonf0066ad2014-05-02 00:45:31 +000046#include "lldb/Core/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047#include "lldb/Core/Stream.h"
Greg Clayton44d93782014-01-27 23:43:24 +000048#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049#include "lldb/Core/Timer.h"
Enrico Granatab5887262012-10-29 21:18:03 +000050
Todd Fialacacde7d2014-09-27 16:54:22 +000051#ifndef LLDB_DISABLE_LIBEDIT
Greg Clayton44d93782014-01-27 23:43:24 +000052#include "lldb/Host/Editline.h"
Todd Fialacacde7d2014-09-27 16:54:22 +000053#endif
Greg Clayton7fb56d02011-02-01 01:31:41 +000054#include "lldb/Host/Host.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000055#include "lldb/Host/HostInfo.h"
Enrico Granatab5887262012-10-29 21:18:03 +000056
57#include "lldb/Interpreter/Args.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000058#include "lldb/Interpreter/CommandCompletions.h"
Enrico Granatab5887262012-10-29 21:18:03 +000059#include "lldb/Interpreter/CommandInterpreter.h"
Greg Clayton7d2ef162013-03-29 17:03:23 +000060#include "lldb/Interpreter/CommandReturnObject.h"
Enrico Granatab5887262012-10-29 21:18:03 +000061#include "lldb/Interpreter/Options.h"
Zachary Turner633a29c2015-03-04 01:58:01 +000062#include "lldb/Interpreter/OptionValueProperties.h"
63#include "lldb/Interpreter/Property.h"
Enrico Granatab5887262012-10-29 21:18:03 +000064#include "lldb/Interpreter/ScriptInterpreterNone.h"
65#include "lldb/Interpreter/ScriptInterpreterPython.h"
66
67
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068#include "lldb/Target/Process.h"
69#include "lldb/Target/Thread.h"
70#include "lldb/Target/TargetList.h"
71
Enrico Granatab5887262012-10-29 21:18:03 +000072#include "lldb/Utility/CleanUp.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000073
Zachary Turnera21fee02014-08-21 21:49:24 +000074#include "llvm/ADT/SmallString.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000075#include "llvm/ADT/STLExtras.h"
Zachary Turnera21fee02014-08-21 21:49:24 +000076#include "llvm/Support/Path.h"
Saleem Abdulrasool28606952014-06-27 05:17:41 +000077
Chris Lattner30fdc8d2010-06-08 16:52:24 +000078using namespace lldb;
79using namespace lldb_private;
80
Adrian McCarthy2304b6f2015-04-23 20:00:25 +000081static const char *k_white_space = " \t\v";
Greg Clayton754a9362012-08-23 00:22:02 +000082
83static PropertyDefinition
84g_properties[] =
85{
Ed Masted78c9572014-04-20 00:31:37 +000086 { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, regular expression alias commands will show the expanded command that will be executed. This can be used to debug new regular expression alias commands." },
87 { "prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will prompt you before quitting if there are any live processes being debugged. If false, LLDB will quit without asking in any case." },
88 { "stop-command-source-on-error", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will stop running a 'command source' script upon encountering an error." },
89 { nullptr , OptionValue::eTypeInvalid, true, 0 , nullptr, nullptr, nullptr }
Greg Clayton754a9362012-08-23 00:22:02 +000090};
91
92enum
93{
Enrico Granatabcba2b22013-01-17 21:36:19 +000094 ePropertyExpandRegexAliases = 0,
Enrico Granata012d4fc2013-06-11 01:26:35 +000095 ePropertyPromptOnQuit = 1,
96 ePropertyStopCmdSourceOnError = 2
Greg Clayton754a9362012-08-23 00:22:02 +000097};
98
Jim Ingham4bddaeb2012-02-16 06:50:00 +000099ConstString &
100CommandInterpreter::GetStaticBroadcasterClass ()
101{
102 static ConstString class_name ("lldb.commandInterpreter");
103 return class_name;
104}
105
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000106CommandInterpreter::CommandInterpreter
107(
Greg Clayton66111032010-06-23 01:19:29 +0000108 Debugger &debugger,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000109 ScriptLanguage script_language,
Greg Clayton66111032010-06-23 01:19:29 +0000110 bool synchronous_execution
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000111) :
Ilia K8a00a562015-03-17 16:54:52 +0000112 Broadcaster (&debugger, CommandInterpreter::GetStaticBroadcasterClass().AsCString()),
Greg Clayton754a9362012-08-23 00:22:02 +0000113 Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))),
Greg Clayton44d93782014-01-27 23:43:24 +0000114 IOHandlerDelegate (IOHandlerDelegate::Completion::LLDBCommand),
Greg Clayton66111032010-06-23 01:19:29 +0000115 m_debugger (debugger),
Greg Clayton6eee5aa2010-10-11 01:05:37 +0000116 m_synchronous_execution (synchronous_execution),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000117 m_skip_lldbinit_files (false),
Jim Ingham16e0c682011-08-12 23:34:31 +0000118 m_skip_app_init_files (false),
Jim Inghame16c50a2011-02-18 00:54:25 +0000119 m_script_interpreter_ap (),
Greg Clayton44d93782014-01-27 23:43:24 +0000120 m_command_io_handler_sp (),
Caroline Ticed61c10b2011-06-16 16:27:19 +0000121 m_comment_char ('#'),
Johnny Chen4ac1d9e2012-08-09 22:06:10 +0000122 m_batch_command_mode (false),
Enrico Granata5f5ab602012-05-31 01:09:06 +0000123 m_truncation_warning(eNoTruncation),
Jim Ingham26c7bf92014-10-11 00:38:27 +0000124 m_command_source_depth (0),
125 m_num_errors(0),
Jim Inghamffc9f1d2014-10-14 01:20:07 +0000126 m_quit_requested(false),
127 m_stopped_for_crash(false)
Jim Ingham26c7bf92014-10-11 00:38:27 +0000128
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000129{
Greg Clayton67cc0632012-08-22 17:17:09 +0000130 debugger.SetScriptLanguage (script_language);
Greg Claytoncfd1ace2010-10-31 03:01:06 +0000131 SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit");
132 SetEventName (eBroadcastBitResetPrompt, "reset-prompt");
Greg Clayton67cc0632012-08-22 17:17:09 +0000133 SetEventName (eBroadcastBitQuitCommandReceived, "quit");
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000134 CheckInWithManager ();
Greg Clayton754a9362012-08-23 00:22:02 +0000135 m_collection_sp->Initialize (g_properties);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000136}
137
Greg Clayton754a9362012-08-23 00:22:02 +0000138bool
139CommandInterpreter::GetExpandRegexAliases () const
140{
141 const uint32_t idx = ePropertyExpandRegexAliases;
Ed Masted78c9572014-04-20 00:31:37 +0000142 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Greg Clayton754a9362012-08-23 00:22:02 +0000143}
144
Enrico Granatabcba2b22013-01-17 21:36:19 +0000145bool
146CommandInterpreter::GetPromptOnQuit () const
147{
148 const uint32_t idx = ePropertyPromptOnQuit;
Ed Masted78c9572014-04-20 00:31:37 +0000149 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granatabcba2b22013-01-17 21:36:19 +0000150}
Greg Clayton754a9362012-08-23 00:22:02 +0000151
Ilia Kacf28be2015-03-23 22:45:13 +0000152void
153CommandInterpreter::SetPromptOnQuit (bool b)
154{
155 const uint32_t idx = ePropertyPromptOnQuit;
156 m_collection_sp->SetPropertyAtIndexAsBoolean (nullptr, idx, b);
157}
158
Adrian McCarthy2304b6f2015-04-23 20:00:25 +0000159void
160CommandInterpreter::ResolveCommand(const char *command_line, CommandReturnObject &result)
161{
162 std::string command = command_line;
163 if (ResolveCommandImpl(command, result) != nullptr) {
164 result.AppendMessageWithFormat("%s", command.c_str());
165 result.SetStatus(eReturnStatusSuccessFinishResult);
166 }
167}
168
169
Enrico Granata012d4fc2013-06-11 01:26:35 +0000170bool
171CommandInterpreter::GetStopCmdSourceOnError () const
172{
173 const uint32_t idx = ePropertyStopCmdSourceOnError;
Ed Masted78c9572014-04-20 00:31:37 +0000174 return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0);
Enrico Granata012d4fc2013-06-11 01:26:35 +0000175}
176
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000177void
178CommandInterpreter::Initialize ()
179{
180 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
181
182 CommandReturnObject result;
183
184 LoadCommandDictionary ();
185
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000186 // Set up some initial aliases.
Caroline Ticeca90c472011-05-06 21:37:15 +0000187 CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false);
188 if (cmd_obj_sp)
189 {
190 AddAlias ("q", cmd_obj_sp);
191 AddAlias ("exit", cmd_obj_sp);
192 }
Sean Callanan247e62a2012-05-04 23:15:02 +0000193
Johnny Chen6d675242012-08-24 18:15:45 +0000194 cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false);
Sean Callanan247e62a2012-05-04 23:15:02 +0000195 if (cmd_obj_sp)
196 {
197 AddAlias ("attach", cmd_obj_sp);
198 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000199
Johnny Chen6d675242012-08-24 18:15:45 +0000200 cmd_obj_sp = GetCommandSPExact ("process detach",false);
201 if (cmd_obj_sp)
202 {
203 AddAlias ("detach", cmd_obj_sp);
204 }
205
Caroline Ticeca90c472011-05-06 21:37:15 +0000206 cmd_obj_sp = GetCommandSPExact ("process continue", false);
207 if (cmd_obj_sp)
208 {
209 AddAlias ("c", cmd_obj_sp);
210 AddAlias ("continue", cmd_obj_sp);
211 }
212
213 cmd_obj_sp = GetCommandSPExact ("_regexp-break",false);
214 if (cmd_obj_sp)
215 AddAlias ("b", cmd_obj_sp);
216
Jim Inghamca36cd12012-10-05 19:16:31 +0000217 cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false);
218 if (cmd_obj_sp)
219 AddAlias ("tbreak", cmd_obj_sp);
220
Caroline Ticeca90c472011-05-06 21:37:15 +0000221 cmd_obj_sp = GetCommandSPExact ("thread step-inst", false);
222 if (cmd_obj_sp)
Jason Molendaf385f122011-10-22 00:47:41 +0000223 {
224 AddAlias ("stepi", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000225 AddAlias ("si", cmd_obj_sp);
Jason Molendaf385f122011-10-22 00:47:41 +0000226 }
227
228 cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false);
229 if (cmd_obj_sp)
230 {
231 AddAlias ("nexti", cmd_obj_sp);
232 AddAlias ("ni", cmd_obj_sp);
233 }
Caroline Ticeca90c472011-05-06 21:37:15 +0000234
235 cmd_obj_sp = GetCommandSPExact ("thread step-in", false);
236 if (cmd_obj_sp)
237 {
238 AddAlias ("s", cmd_obj_sp);
239 AddAlias ("step", cmd_obj_sp);
240 }
241
242 cmd_obj_sp = GetCommandSPExact ("thread step-over", false);
243 if (cmd_obj_sp)
244 {
245 AddAlias ("n", cmd_obj_sp);
246 AddAlias ("next", cmd_obj_sp);
247 }
248
249 cmd_obj_sp = GetCommandSPExact ("thread step-out", false);
250 if (cmd_obj_sp)
251 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000252 AddAlias ("finish", cmd_obj_sp);
253 }
254
Jim Ingham6d6d1072011-12-02 01:12:59 +0000255 cmd_obj_sp = GetCommandSPExact ("frame select", false);
256 if (cmd_obj_sp)
257 {
258 AddAlias ("f", cmd_obj_sp);
259 }
260
Jim Inghamca36cd12012-10-05 19:16:31 +0000261 cmd_obj_sp = GetCommandSPExact ("thread select", false);
262 if (cmd_obj_sp)
263 {
264 AddAlias ("t", cmd_obj_sp);
265 }
266
Richard Mittonf86248d2013-09-12 02:20:34 +0000267 cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false);
268 if (cmd_obj_sp)
269 {
270 AddAlias ("j", cmd_obj_sp);
271 AddAlias ("jump", cmd_obj_sp);
272 }
273
Greg Clayton6bade322013-02-01 23:33:03 +0000274 cmd_obj_sp = GetCommandSPExact ("_regexp-list", false);
Caroline Ticeca90c472011-05-06 21:37:15 +0000275 if (cmd_obj_sp)
276 {
277 AddAlias ("l", cmd_obj_sp);
278 AddAlias ("list", cmd_obj_sp);
279 }
280
Greg Claytonef5651d2013-02-12 18:52:24 +0000281 cmd_obj_sp = GetCommandSPExact ("_regexp-env", false);
282 if (cmd_obj_sp)
283 {
284 AddAlias ("env", cmd_obj_sp);
285 }
286
Caroline Ticeca90c472011-05-06 21:37:15 +0000287 cmd_obj_sp = GetCommandSPExact ("memory read", false);
288 if (cmd_obj_sp)
289 AddAlias ("x", cmd_obj_sp);
290
291 cmd_obj_sp = GetCommandSPExact ("_regexp-up", false);
292 if (cmd_obj_sp)
293 AddAlias ("up", cmd_obj_sp);
294
295 cmd_obj_sp = GetCommandSPExact ("_regexp-down", false);
296 if (cmd_obj_sp)
297 AddAlias ("down", cmd_obj_sp);
298
Jason Molenda0c8e0062011-10-25 02:11:20 +0000299 cmd_obj_sp = GetCommandSPExact ("_regexp-display", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000300 if (cmd_obj_sp)
301 AddAlias ("display", cmd_obj_sp);
Jim Ingham7e18e422011-10-24 18:37:00 +0000302
303 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
304 if (cmd_obj_sp)
305 AddAlias ("dis", cmd_obj_sp);
306
307 cmd_obj_sp = GetCommandSPExact ("disassemble", false);
308 if (cmd_obj_sp)
309 AddAlias ("di", cmd_obj_sp);
310
311
Jason Molendabc7748b2011-10-22 01:30:52 +0000312
Jason Molenda0c8e0062011-10-25 02:11:20 +0000313 cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false);
Jason Molendabc7748b2011-10-22 01:30:52 +0000314 if (cmd_obj_sp)
315 AddAlias ("undisplay", cmd_obj_sp);
316
Jim Ingham71bf2992012-10-10 16:51:31 +0000317 cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false);
318 if (cmd_obj_sp)
319 AddAlias ("bt", cmd_obj_sp);
320
Caroline Ticeca90c472011-05-06 21:37:15 +0000321 cmd_obj_sp = GetCommandSPExact ("target create", false);
322 if (cmd_obj_sp)
323 AddAlias ("file", cmd_obj_sp);
324
325 cmd_obj_sp = GetCommandSPExact ("target modules", false);
326 if (cmd_obj_sp)
327 AddAlias ("image", cmd_obj_sp);
328
329
330 OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector);
Jim Inghamffba2292011-03-22 02:29:32 +0000331
Caroline Ticeca90c472011-05-06 21:37:15 +0000332 cmd_obj_sp = GetCommandSPExact ("expression", false);
333 if (cmd_obj_sp)
Sean Callanan90e579f2013-04-17 17:23:58 +0000334 {
Caroline Ticeca90c472011-05-06 21:37:15 +0000335 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
336 AddAlias ("p", cmd_obj_sp);
337 AddAlias ("print", cmd_obj_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000338 AddAlias ("call", cmd_obj_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000339 AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp);
340 AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp);
Sean Callanan316d5e42012-08-08 01:30:34 +0000341 AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000342
343 alias_arguments_vector_sp.reset (new OptionArgVector);
Greg Clayton9e57dcd2013-05-15 01:03:08 +0000344 ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp);
Caroline Ticeca90c472011-05-06 21:37:15 +0000345 AddAlias ("po", cmd_obj_sp);
346 AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp);
347 }
348
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000349 cmd_obj_sp = GetCommandSPExact ("process kill", false);
350 if (cmd_obj_sp)
Greg Claytone86fd742012-09-27 00:02:27 +0000351 {
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000352 AddAlias ("kill", cmd_obj_sp);
Greg Claytone86fd742012-09-27 00:02:27 +0000353 }
Sean Callanan2e1d9ba2012-06-01 23:29:32 +0000354
Caroline Ticeca90c472011-05-06 21:37:15 +0000355 cmd_obj_sp = GetCommandSPExact ("process launch", false);
356 if (cmd_obj_sp)
357 {
358 alias_arguments_vector_sp.reset (new OptionArgVector);
Todd Fiala013434e2014-07-09 01:29:05 +0000359#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Jason Molenda85da3122012-07-06 02:46:23 +0000360 ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp);
361#else
Zachary Turner10687b02014-10-20 17:46:43 +0000362 std::string shell_option;
363 shell_option.append("--shell=");
364 shell_option.append(HostInfo::GetDefaultShell().GetPath());
365 shell_option.append(" --");
366 ProcessAliasOptionsArgs (cmd_obj_sp, shell_option.c_str(), alias_arguments_vector_sp);
Jason Molenda85da3122012-07-06 02:46:23 +0000367#endif
Caroline Ticeca90c472011-05-06 21:37:15 +0000368 AddAlias ("r", cmd_obj_sp);
369 AddAlias ("run", cmd_obj_sp);
370 AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp);
371 AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp);
372 }
Greg Clayton843d62d2012-03-29 21:47:51 +0000373
374 cmd_obj_sp = GetCommandSPExact ("target symbols add", false);
375 if (cmd_obj_sp)
376 {
377 AddAlias ("add-dsym", cmd_obj_sp);
378 }
Sean Callananfc732752012-05-21 18:25:19 +0000379
380 cmd_obj_sp = GetCommandSPExact ("breakpoint set", false);
381 if (cmd_obj_sp)
382 {
383 alias_arguments_vector_sp.reset (new OptionArgVector);
384 ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp);
Jim Ingham06d282d2012-10-18 23:24:12 +0000385 AddAlias ("rbreak", cmd_obj_sp);
386 AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp);
Sean Callananfc732752012-05-21 18:25:19 +0000387 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388}
389
Greg Clayton0c4129f2014-04-25 00:35:14 +0000390void
391CommandInterpreter::Clear()
392{
393 m_command_io_handler_sp.reset();
Greg Claytoned6499f2014-04-25 23:55:12 +0000394
395 if (m_script_interpreter_ap)
396 m_script_interpreter_ap->Clear();
Greg Clayton0c4129f2014-04-25 00:35:14 +0000397}
398
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399const char *
400CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg)
401{
402 // This function has not yet been implemented.
403
404 // Look for any embedded script command
405 // If found,
406 // get interpreter object from the command dictionary,
407 // call execute_one_command on it,
408 // get the results as a string,
409 // substitute that string for current stuff.
410
411 return arg;
412}
413
414
415void
416CommandInterpreter::LoadCommandDictionary ()
417{
418 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
419
Caroline Ticedaccaa92010-09-20 20:44:43 +0000420 lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage();
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000421
Greg Claytona7015092010-09-18 01:14:36 +0000422 m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000423 m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this));
Johnny Chenb89982d2011-04-21 00:39:18 +0000424 m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000425 m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this));
426 m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000427 m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this));
Greg Clayton44d93782014-01-27 23:43:24 +0000428 m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000429 m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000430 m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this));
431 m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this));
Greg Claytonded470d2011-03-19 01:12:21 +0000432 m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this));
Enrico Granata21dfcd92012-09-28 23:57:51 +0000433 m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000434 m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000435 m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000436 m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this));
Greg Claytona7015092010-09-18 01:14:36 +0000437 m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language));
Caroline Tice3df9a8d2010-09-04 00:03:46 +0000438 m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this));
Jim Inghamebc09c32010-07-07 03:36:20 +0000439 m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this));
Greg Clayton66111032010-06-23 01:19:29 +0000440 m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this));
441 m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this));
Enrico Granata223383e2011-08-16 23:24:13 +0000442 m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this));
Johnny Chen31c39da2010-12-23 20:21:44 +0000443 m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this));
Johnny Chenf04ee932011-09-22 18:04:58 +0000444 m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this));
Colin Rileyc9c55a22015-05-04 18:39:38 +0000445 m_command_dict["language"] = CommandObjectSP (new CommandObjectLanguage(*this));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000446
Jim Inghamca36cd12012-10-05 19:16:31 +0000447 const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"},
Greg Claytond90ac932014-12-01 22:34:03 +0000448 {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000449 {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"},
Greg Clayton722e8852013-02-08 02:54:24 +0000450 {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"},
Greg Clayton1b3815c2013-01-30 00:18:29 +0000451 {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"},
Jim Inghamca36cd12012-10-05 19:16:31 +0000452 {"^(-.*)$", "breakpoint set %1"},
453 {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"},
Greg Clayton722e8852013-02-08 02:54:24 +0000454 {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"},
Greg Clayton2d4b5122014-08-14 17:58:33 +0000455 {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}};
Jim Inghamca36cd12012-10-05 19:16:31 +0000456
Saleem Abdulrasool28606952014-06-27 05:17:41 +0000457 size_t num_regexes = llvm::array_lengthof(break_regexes);
Jim Inghamca36cd12012-10-05 19:16:31 +0000458
Greg Clayton7b0992d2013-04-18 22:45:39 +0000459 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytona7015092010-09-18 01:14:36 +0000460 break_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000461 "_regexp-break",
Greg Clayton910db5c2015-03-07 00:01:46 +0000462 "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.\n",
463 "\n_regexp-break <filename>:<linenum> # _regexp-break main.c:12 // Break on line 12 of main.c\n"
464 "_regexp-break <linenum> # _regexp-break 12 // Break on line 12 of current file\n"
465 "_regexp-break <address> # _regexp-break 0x1234000 // Break on address 0x1234000\n"
466 "_regexp-break <name> # _regexp-break main // Break in 'main' after the prologue\n"
467 "_regexp-break &<name> # _regexp-break &main // Break on the first instruction in 'main'\n"
468 "_regexp-break <module>`<name> # _regexp-break libc.so`malloc // Break in 'malloc' only in the 'libc.so' shared library\n"
469 "_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 +0000470 2,
471 CommandCompletions::eSymbolCompletion |
Greg Claytonb5472782015-01-09 19:08:20 +0000472 CommandCompletions::eSourceFileCompletion,
473 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000474
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000475 if (break_regex_cmd_ap.get())
476 {
Jim Inghamca36cd12012-10-05 19:16:31 +0000477 bool success = true;
478 for (size_t i = 0; i < num_regexes; i++)
479 {
480 success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]);
481 if (!success)
482 break;
483 }
484 success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
485
486 if (success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000487 {
488 CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release());
489 m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp;
490 }
491 }
Jim Inghamffba2292011-03-22 02:29:32 +0000492
Greg Clayton7b0992d2013-04-18 22:45:39 +0000493 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamca36cd12012-10-05 19:16:31 +0000494 tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this,
495 "_regexp-tbreak",
496 "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 +0000497 "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>",
498 2,
499 CommandCompletions::eSymbolCompletion |
Greg Claytonb5472782015-01-09 19:08:20 +0000500 CommandCompletions::eSourceFileCompletion,
501 false));
Jim Inghamca36cd12012-10-05 19:16:31 +0000502
503 if (tbreak_regex_cmd_ap.get())
504 {
505 bool success = true;
506 for (size_t i = 0; i < num_regexes; i++)
507 {
508 // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer.
509 char buffer[1024];
510 int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o");
511 assert (num_printed < 1024);
Eric Christopher5c91d5c12014-09-09 19:26:45 +0000512 // Quiet unused variable warning for release builds.
Eric Christopher9ad83942014-09-09 08:57:33 +0000513 (void) num_printed;
Jim Inghamca36cd12012-10-05 19:16:31 +0000514 success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer);
515 if (!success)
516 break;
517 }
518 success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full");
519
520 if (success)
521 {
522 CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release());
523 m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp;
524 }
525 }
526
Greg Clayton7b0992d2013-04-18 22:45:39 +0000527 std::unique_ptr<CommandObjectRegexCommand>
Johnny Chen6d675242012-08-24 18:15:45 +0000528 attach_regex_cmd_ap(new CommandObjectRegexCommand (*this,
529 "_regexp-attach",
530 "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 +0000531 "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]",
Greg Claytonb5472782015-01-09 19:08:20 +0000532 2,
533 0,
534 false));
Johnny Chen6d675242012-08-24 18:15:45 +0000535 if (attach_regex_cmd_ap.get())
536 {
Greg Clayton3cb4c7d2012-12-15 01:19:07 +0000537 if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") &&
538 attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach'
539 attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") &&
540 attach_regex_cmd_ap->AddRegexCommand("^$", "process attach"))
Johnny Chen6d675242012-08-24 18:15:45 +0000541 {
542 CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release());
543 m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp;
544 }
545 }
546
Greg Clayton7b0992d2013-04-18 22:45:39 +0000547 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000548 down_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000549 "_regexp-down",
550 "Go down \"n\" frames in the stack (1 frame by default).",
Greg Claytonb5472782015-01-09 19:08:20 +0000551 "_regexp-down [n]",
552 2,
553 0,
554 false));
Jim Inghamffba2292011-03-22 02:29:32 +0000555 if (down_regex_cmd_ap.get())
556 {
557 if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") &&
558 down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1"))
559 {
560 CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release());
561 m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp;
562 }
563 }
564
Greg Clayton7b0992d2013-04-18 22:45:39 +0000565 std::unique_ptr<CommandObjectRegexCommand>
Jim Inghamffba2292011-03-22 02:29:32 +0000566 up_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton8b82f082011-04-12 05:54:46 +0000567 "_regexp-up",
568 "Go up \"n\" frames in the stack (1 frame by default).",
Greg Claytonb5472782015-01-09 19:08:20 +0000569 "_regexp-up [n]",
570 2,
571 0,
572 false));
Jim Inghamffba2292011-03-22 02:29:32 +0000573 if (up_regex_cmd_ap.get())
574 {
575 if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") &&
576 up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1"))
577 {
578 CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release());
579 m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp;
580 }
581 }
Jason Molendabc7748b2011-10-22 01:30:52 +0000582
Greg Clayton7b0992d2013-04-18 22:45:39 +0000583 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000584 display_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000585 "_regexp-display",
586 "Add an expression evaluation stop-hook.",
Greg Claytonb5472782015-01-09 19:08:20 +0000587 "_regexp-display expression",
588 2,
589 0,
590 false));
Jason Molendabc7748b2011-10-22 01:30:52 +0000591 if (display_regex_cmd_ap.get())
592 {
593 if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\""))
594 {
595 CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release());
596 m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp;
597 }
598 }
599
Greg Clayton7b0992d2013-04-18 22:45:39 +0000600 std::unique_ptr<CommandObjectRegexCommand>
Jason Molendabc7748b2011-10-22 01:30:52 +0000601 undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000602 "_regexp-undisplay",
603 "Remove an expression evaluation stop-hook.",
Greg Claytonb5472782015-01-09 19:08:20 +0000604 "_regexp-undisplay stop-hook-number",
605 2,
606 0,
607 false));
Jason Molendabc7748b2011-10-22 01:30:52 +0000608 if (undisplay_regex_cmd_ap.get())
609 {
610 if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1"))
611 {
612 CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release());
613 m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp;
614 }
615 }
616
Greg Clayton7b0992d2013-04-18 22:45:39 +0000617 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000618 connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000619 "gdb-remote",
620 "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.",
Greg Claytonb5472782015-01-09 19:08:20 +0000621 "gdb-remote [<hostname>:]<portnum>",
622 2,
623 0,
624 false));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000625 if (connect_gdb_remote_cmd_ap.get())
626 {
627 if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") &&
628 connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1"))
629 {
630 CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release());
631 m_command_dict[command_sp->GetCommandName ()] = command_sp;
632 }
633 }
634
Greg Clayton7b0992d2013-04-18 22:45:39 +0000635 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000636 connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this,
637 "kdp-remote",
Jason Molendaa7dcb332012-10-23 03:05:16 +0000638 "Connect to a remote KDP server. udp port 41139 is the default port number.",
Greg Claytonb5472782015-01-09 19:08:20 +0000639 "kdp-remote <hostname>[:<portnum>]",
640 2,
641 0,
642 false));
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000643 if (connect_kdp_remote_cmd_ap.get())
644 {
645 if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") &&
Jason Molendac36b1842012-09-27 02:47:55 +0000646 connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139"))
Greg Clayton30c0a1c2012-09-26 22:26:47 +0000647 {
648 CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release());
649 m_command_dict[command_sp->GetCommandName ()] = command_sp;
650 }
651 }
652
Greg Clayton7b0992d2013-04-18 22:45:39 +0000653 std::unique_ptr<CommandObjectRegexCommand>
Jason Molenda4cddfed2012-10-05 05:29:32 +0000654 bt_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Claytonb5472782015-01-09 19:08:20 +0000655 "_regexp-bt",
656 "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.",
657 "bt [<digit>|all]",
658 2,
659 0,
660 false));
Jason Molenda4cddfed2012-10-05 05:29:32 +0000661 if (bt_regex_cmd_ap.get())
662 {
663 // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace
664 // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and
665 // so now "bt 3" is the preferred form, in line with gdb.
666 if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") &&
667 bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") &&
668 bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") &&
669 bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace"))
670 {
671 CommandObjectSP command_sp(bt_regex_cmd_ap.release());
672 m_command_dict[command_sp->GetCommandName ()] = command_sp;
673 }
674 }
675
Greg Clayton7b0992d2013-04-18 22:45:39 +0000676 std::unique_ptr<CommandObjectRegexCommand>
Greg Clayton6bade322013-02-01 23:33:03 +0000677 list_regex_cmd_ap(new CommandObjectRegexCommand (*this,
678 "_regexp-list",
679 "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 +0000680 "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]",
Greg Clayton7d2ef162013-03-29 17:03:23 +0000681 2,
Greg Claytonb5472782015-01-09 19:08:20 +0000682 CommandCompletions::eSourceFileCompletion,
683 false));
Greg Clayton6bade322013-02-01 23:33:03 +0000684 if (list_regex_cmd_ap.get())
685 {
686 if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") &&
687 list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") &&
688 list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") &&
Greg Claytond9010962013-02-12 18:42:05 +0000689 list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") &&
Greg Claytone4ca5152013-03-13 18:25:49 +0000690 list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") &&
Greg Clayton6bade322013-02-01 23:33:03 +0000691 list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") &&
692 list_regex_cmd_ap->AddRegexCommand("^$", "source list"))
693 {
694 CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release());
695 m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp;
696 }
697 }
698
Greg Clayton7b0992d2013-04-18 22:45:39 +0000699 std::unique_ptr<CommandObjectRegexCommand>
Greg Claytonef5651d2013-02-12 18:52:24 +0000700 env_regex_cmd_ap(new CommandObjectRegexCommand (*this,
Greg Clayton7d2ef162013-03-29 17:03:23 +0000701 "_regexp-env",
702 "Implements a shortcut to viewing and setting environment variables.",
Greg Claytonb5472782015-01-09 19:08:20 +0000703 "_regexp-env\n_regexp-env FOO=BAR",
704 2,
705 0,
706 false));
Greg Claytonef5651d2013-02-12 18:52:24 +0000707 if (env_regex_cmd_ap.get())
708 {
709 if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") &&
710 env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1"))
711 {
712 CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release());
713 m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp;
714 }
715 }
716
Richard Mittonf86248d2013-09-12 02:20:34 +0000717 std::unique_ptr<CommandObjectRegexCommand>
718 jump_regex_cmd_ap(new CommandObjectRegexCommand (*this,
719 "_regexp-jump",
720 "Sets the program counter to a new address.",
721 "_regexp-jump [<line>]\n"
722 "_regexp-jump [<+-lineoffset>]\n"
723 "_regexp-jump [<file>:<line>]\n"
Greg Claytonb5472782015-01-09 19:08:20 +0000724 "_regexp-jump [*<addr>]\n",
725 2,
726 0,
727 false));
Richard Mittonf86248d2013-09-12 02:20:34 +0000728 if (jump_regex_cmd_ap.get())
729 {
730 if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") &&
731 jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") &&
732 jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") &&
733 jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1"))
734 {
735 CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release());
736 m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp;
737 }
738 }
739
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000740}
741
742int
743CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases,
744 StringList &matches)
745{
746 CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches);
747
748 if (include_aliases)
749 {
750 CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches);
751 }
752
753 return matches.GetSize();
754}
755
756CommandObjectSP
757CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches)
758{
759 CommandObject::CommandMap::iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +0000760 CommandObjectSP command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761
762 std::string cmd(cmd_cstr);
763
764 if (HasCommands())
765 {
766 pos = m_command_dict.find(cmd);
767 if (pos != m_command_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000768 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000769 }
770
771 if (include_aliases && HasAliases())
772 {
773 pos = m_alias_dict.find(cmd);
774 if (pos != m_alias_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000775 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000776 }
777
778 if (HasUserCommands())
779 {
780 pos = m_user_dict.find(cmd);
781 if (pos != m_user_dict.end())
Greg Claytonc7bece562013-01-25 18:06:21 +0000782 command_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000783 }
784
Greg Claytonc7bece562013-01-25 18:06:21 +0000785 if (!exact && !command_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000786 {
Jim Ingham279a6c22010-07-06 22:46:59 +0000787 // We will only get into here if we didn't find any exact matches.
788
789 CommandObjectSP user_match_sp, alias_match_sp, real_match_sp;
790
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791 StringList local_matches;
Ed Masted78c9572014-04-20 00:31:37 +0000792 if (matches == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793 matches = &local_matches;
794
Jim Ingham279a6c22010-07-06 22:46:59 +0000795 unsigned int num_cmd_matches = 0;
796 unsigned int num_alias_matches = 0;
797 unsigned int num_user_matches = 0;
798
799 // Look through the command dictionaries one by one, and if we get only one match from any of
800 // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches.
801
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000802 if (HasCommands())
803 {
804 num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches);
805 }
806
807 if (num_cmd_matches == 1)
808 {
809 cmd.assign(matches->GetStringAtIndex(0));
810 pos = m_command_dict.find(cmd);
811 if (pos != m_command_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000812 real_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813 }
814
Jim Ingham490ac552010-06-24 20:28:42 +0000815 if (include_aliases && HasAliases())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816 {
817 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches);
818
819 }
820
Jim Ingham279a6c22010-07-06 22:46:59 +0000821 if (num_alias_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000822 {
823 cmd.assign(matches->GetStringAtIndex (num_cmd_matches));
824 pos = m_alias_dict.find(cmd);
825 if (pos != m_alias_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000826 alias_match_sp = pos->second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000827 }
828
Jim Ingham490ac552010-06-24 20:28:42 +0000829 if (HasUserCommands())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000830 {
831 num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches);
832 }
833
Jim Ingham279a6c22010-07-06 22:46:59 +0000834 if (num_user_matches == 1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835 {
836 cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches));
837
838 pos = m_user_dict.find (cmd);
839 if (pos != m_user_dict.end())
Jim Ingham279a6c22010-07-06 22:46:59 +0000840 user_match_sp = pos->second;
841 }
842
843 // If we got exactly one match, return that, otherwise return the match list.
844
845 if (num_user_matches + num_cmd_matches + num_alias_matches == 1)
846 {
847 if (num_cmd_matches)
848 return real_match_sp;
849 else if (num_alias_matches)
850 return alias_match_sp;
851 else
852 return user_match_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000853 }
854 }
Greg Claytonc7bece562013-01-25 18:06:21 +0000855 else if (matches && command_sp)
Jim Ingham279a6c22010-07-06 22:46:59 +0000856 {
857 matches->AppendString (cmd_cstr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000858 }
859
860
Greg Claytonc7bece562013-01-25 18:06:21 +0000861 return command_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000862}
863
Greg Claytonde164aa2011-04-20 16:37:46 +0000864bool
865CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace)
866{
867 if (name && name[0])
868 {
869 std::string name_sstr(name);
Enrico Granatae00af802012-10-01 17:19:37 +0000870 bool found = (m_command_dict.find (name_sstr) != m_command_dict.end());
871 if (found && !can_replace)
872 return false;
873 if (found && m_command_dict[name_sstr]->IsRemovable() == false)
Enrico Granata21dfcd92012-09-28 23:57:51 +0000874 return false;
Greg Claytonde164aa2011-04-20 16:37:46 +0000875 m_command_dict[name_sstr] = cmd_sp;
876 return true;
877 }
878 return false;
879}
880
Enrico Granata223383e2011-08-16 23:24:13 +0000881bool
Enrico Granata0a305db2011-11-07 22:57:04 +0000882CommandInterpreter::AddUserCommand (std::string name,
Enrico Granata223383e2011-08-16 23:24:13 +0000883 const lldb::CommandObjectSP &cmd_sp,
884 bool can_replace)
885{
Enrico Granata0a305db2011-11-07 22:57:04 +0000886 if (!name.empty())
Enrico Granata223383e2011-08-16 23:24:13 +0000887 {
Enrico Granata0a305db2011-11-07 22:57:04 +0000888
889 const char* name_cstr = name.c_str();
890
891 // do not allow replacement of internal commands
892 if (CommandExists(name_cstr))
Enrico Granata21dfcd92012-09-28 23:57:51 +0000893 {
894 if (can_replace == false)
895 return false;
896 if (m_command_dict[name]->IsRemovable() == false)
897 return false;
898 }
Enrico Granata0a305db2011-11-07 22:57:04 +0000899
Enrico Granata21dfcd92012-09-28 23:57:51 +0000900 if (UserCommandExists(name_cstr))
901 {
902 if (can_replace == false)
903 return false;
904 if (m_user_dict[name]->IsRemovable() == false)
905 return false;
906 }
907
Enrico Granata0a305db2011-11-07 22:57:04 +0000908 m_user_dict[name] = cmd_sp;
Enrico Granata223383e2011-08-16 23:24:13 +0000909 return true;
910 }
911 return false;
912}
Greg Claytonde164aa2011-04-20 16:37:46 +0000913
Jim Ingham279a6c22010-07-06 22:46:59 +0000914CommandObjectSP
915CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000916{
Caroline Tice472362e2010-12-14 18:51:39 +0000917 Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command.
918 CommandObjectSP ret_val; // Possibly empty return value.
919
Ed Masted78c9572014-04-20 00:31:37 +0000920 if (cmd_cstr == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000921 return ret_val;
922
923 if (cmd_words.GetArgumentCount() == 1)
Ed Masted78c9572014-04-20 00:31:37 +0000924 return GetCommandSP(cmd_cstr, include_aliases, true, nullptr);
Caroline Tice472362e2010-12-14 18:51:39 +0000925 else
926 {
927 // We have a multi-word command (seemingly), so we need to do more work.
928 // First, get the cmd_obj_sp for the first word in the command.
Ed Masted78c9572014-04-20 00:31:37 +0000929 CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr);
930 if (cmd_obj_sp.get() != nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000931 {
932 // Loop through the rest of the words in the command (everything passed in was supposed to be part of a
933 // command name), and find the appropriate sub-command SP for each command word....
934 size_t end = cmd_words.GetArgumentCount();
935 for (size_t j= 1; j < end; ++j)
936 {
937 if (cmd_obj_sp->IsMultiwordObject())
938 {
Greg Clayton998255b2012-10-13 02:07:45 +0000939 cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j));
Ed Masted78c9572014-04-20 00:31:37 +0000940 if (cmd_obj_sp.get() == nullptr)
Caroline Tice472362e2010-12-14 18:51:39 +0000941 // The sub-command name was invalid. Fail and return the empty 'ret_val'.
942 return ret_val;
943 }
944 else
945 // We have more words in the command name, but we don't have a multiword object. Fail and return
946 // empty 'ret_val'.
947 return ret_val;
948 }
949 // We successfully looped through all the command words and got valid command objects for them. Assign the
950 // last object retrieved to 'ret_val'.
951 ret_val = cmd_obj_sp;
952 }
953 }
954 return ret_val;
Jim Ingham279a6c22010-07-06 22:46:59 +0000955}
956
957CommandObject *
958CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases)
959{
960 return GetCommandSPExact (cmd_cstr, include_aliases).get();
961}
962
963CommandObject *
964CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches)
965{
966 CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get();
967
968 // If we didn't find an exact match to the command string in the commands, look in
969 // the aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000970
971 if (command_obj)
972 return command_obj;
Jim Ingham279a6c22010-07-06 22:46:59 +0000973
Enrico Granata5342c442013-06-18 18:01:08 +0000974 command_obj = GetCommandSP (cmd_cstr, true, true, matches).get();
Jim Ingham279a6c22010-07-06 22:46:59 +0000975
Enrico Granata5342c442013-06-18 18:01:08 +0000976 if (command_obj)
977 return command_obj;
978
979 // If there wasn't an exact match then look for an inexact one in just the commands
Ed Masted78c9572014-04-20 00:31:37 +0000980 command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get();
Matt Kopec038ff812013-04-23 16:17:32 +0000981
982 // Finally, if there wasn't an inexact match among the commands, look for an inexact
983 // match in both the commands and aliases.
Enrico Granata5342c442013-06-18 18:01:08 +0000984
985 if (command_obj)
986 {
987 if (matches)
988 matches->AppendString(command_obj->GetCommandName());
989 return command_obj;
990 }
991
992 return GetCommandSP(cmd_cstr, true, false, matches).get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993}
994
995bool
996CommandInterpreter::CommandExists (const char *cmd)
997{
998 return m_command_dict.find(cmd) != m_command_dict.end();
999}
1000
1001bool
Caroline Ticeca90c472011-05-06 21:37:15 +00001002CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp,
1003 const char *options_args,
1004 OptionArgVectorSP &option_arg_vector_sp)
1005{
1006 bool success = true;
1007 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1008
1009 if (!options_args || (strlen (options_args) < 1))
1010 return true;
1011
1012 std::string options_string (options_args);
1013 Args args (options_args);
1014 CommandReturnObject result;
1015 // Check to see if the command being aliased can take any command options.
1016 Options *options = cmd_obj_sp->GetOptions ();
1017 if (options)
1018 {
1019 // See if any options were specified as part of the alias; if so, handle them appropriately.
1020 options->NotifyOptionParsingStarting ();
1021 args.Unshift ("dummy_arg");
1022 args.ParseAliasOptions (*options, result, option_arg_vector, options_string);
1023 args.Shift ();
1024 if (result.Succeeded())
1025 options->VerifyPartialOptions (result);
1026 if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted)
1027 {
1028 result.AppendError ("Unable to create requested alias.\n");
1029 return false;
1030 }
1031 }
1032
Greg Clayton5521f992011-10-28 21:38:01 +00001033 if (!options_string.empty())
Caroline Ticeca90c472011-05-06 21:37:15 +00001034 {
1035 if (cmd_obj_sp->WantsRawCommandString ())
1036 option_arg_vector->push_back (OptionArgPair ("<argument>",
1037 OptionArgValue (-1,
1038 options_string)));
1039 else
1040 {
Greg Claytonc7bece562013-01-25 18:06:21 +00001041 const size_t argc = args.GetArgumentCount();
Caroline Ticeca90c472011-05-06 21:37:15 +00001042 for (size_t i = 0; i < argc; ++i)
1043 if (strcmp (args.GetArgumentAtIndex (i), "") != 0)
1044 option_arg_vector->push_back
1045 (OptionArgPair ("<argument>",
1046 OptionArgValue (-1,
1047 std::string (args.GetArgumentAtIndex (i)))));
1048 }
1049 }
1050
1051 return success;
1052}
1053
1054bool
Jim Ingham298f3782013-04-03 00:25:49 +00001055CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name)
1056{
1057 bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end());
1058 if (exact_match)
1059 {
1060 full_name.assign(cmd);
1061 return exact_match;
1062 }
1063 else
1064 {
1065 StringList matches;
1066 size_t num_alias_matches;
1067 num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches);
1068 if (num_alias_matches == 1)
1069 {
1070 // Make sure this isn't shadowing a command in the regular command space:
1071 StringList regular_matches;
1072 const bool include_aliases = false;
1073 const bool exact = false;
1074 CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches));
1075 if (cmd_obj_sp || regular_matches.GetSize() > 0)
1076 return false;
1077 else
1078 {
1079 full_name.assign (matches.GetStringAtIndex(0));
1080 return true;
1081 }
1082 }
1083 else
1084 return false;
1085 }
1086}
1087
1088bool
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089CommandInterpreter::AliasExists (const char *cmd)
1090{
1091 return m_alias_dict.find(cmd) != m_alias_dict.end();
1092}
1093
1094bool
1095CommandInterpreter::UserCommandExists (const char *cmd)
1096{
1097 return m_user_dict.find(cmd) != m_user_dict.end();
1098}
1099
1100void
1101CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp)
1102{
Jim Ingham279a6c22010-07-06 22:46:59 +00001103 command_obj_sp->SetIsAlias (true);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 m_alias_dict[alias_name] = command_obj_sp;
1105}
1106
1107bool
1108CommandInterpreter::RemoveAlias (const char *alias_name)
1109{
1110 CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name);
1111 if (pos != m_alias_dict.end())
1112 {
1113 m_alias_dict.erase(pos);
1114 return true;
1115 }
1116 return false;
1117}
Greg Claytonb5472782015-01-09 19:08:20 +00001118
1119bool
1120CommandInterpreter::RemoveCommand (const char *cmd)
1121{
1122 auto pos = m_command_dict.find(cmd);
1123 if (pos != m_command_dict.end())
1124 {
1125 if (pos->second->IsRemovable())
1126 {
1127 // Only regular expression objects or python commands are removable
1128 m_command_dict.erase(pos);
1129 return true;
1130 }
1131 }
1132 return false;
1133}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134bool
1135CommandInterpreter::RemoveUser (const char *alias_name)
1136{
1137 CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name);
1138 if (pos != m_user_dict.end())
1139 {
1140 m_user_dict.erase(pos);
1141 return true;
1142 }
1143 return false;
1144}
1145
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146void
1147CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string)
1148{
1149 help_string.Printf ("'%s", command_name);
1150 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1151
Sean Callanan9a028512012-08-09 00:50:26 +00001152 if (option_arg_vector_sp)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001153 {
1154 OptionArgVector *options = option_arg_vector_sp.get();
Andy Gibbsa297a972013-06-19 19:04:53 +00001155 for (size_t i = 0; i < options->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001156 {
1157 OptionArgPair cur_option = (*options)[i];
1158 std::string opt = cur_option.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00001159 OptionArgValue value_pair = cur_option.second;
1160 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001161 if (opt.compare("<argument>") == 0)
1162 {
1163 help_string.Printf (" %s", value.c_str());
1164 }
1165 else
1166 {
1167 help_string.Printf (" %s", opt.c_str());
1168 if ((value.compare ("<no-argument>") != 0)
1169 && (value.compare ("<need-argument") != 0))
1170 {
1171 help_string.Printf (" %s", value.c_str());
1172 }
1173 }
1174 }
1175 }
1176
1177 help_string.Printf ("'");
1178}
1179
Greg Clayton12fc3e02010-08-26 22:05:43 +00001180size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001181CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict)
1182{
1183 CommandObject::CommandMap::const_iterator pos;
Greg Clayton12fc3e02010-08-26 22:05:43 +00001184 CommandObject::CommandMap::const_iterator end = dict.end();
1185 size_t max_len = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001186
Greg Clayton12fc3e02010-08-26 22:05:43 +00001187 for (pos = dict.begin(); pos != end; ++pos)
1188 {
1189 size_t len = pos->first.size();
1190 if (max_len < len)
1191 max_len = len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192 }
Greg Clayton12fc3e02010-08-26 22:05:43 +00001193 return max_len;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194}
1195
1196void
Enrico Granata223383e2011-08-16 23:24:13 +00001197CommandInterpreter::GetHelp (CommandReturnObject &result,
Enrico Granata08633ee2011-09-09 17:49:36 +00001198 uint32_t cmd_types)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199{
Kate Stonea487aa42015-01-15 00:52:41 +00001200 const char * help_prologue = GetDebugger().GetIOHandlerHelpPrologue();
1201 if (help_prologue != NULL)
1202 {
1203 OutputFormattedHelpText(result.GetOutputStream(), NULL, help_prologue);
1204 }
1205
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001206 CommandObject::CommandMap::const_iterator pos;
Greg Claytonc7bece562013-01-25 18:06:21 +00001207 size_t max_len = FindLongestCommandWord (m_command_dict);
Enrico Granata223383e2011-08-16 23:24:13 +00001208
1209 if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin )
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001210 {
Kate Stonea487aa42015-01-15 00:52:41 +00001211 result.AppendMessage("Debugger commands:");
Enrico Granata223383e2011-08-16 23:24:13 +00001212 result.AppendMessage("");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001213
Enrico Granata223383e2011-08-16 23:24:13 +00001214 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
1215 {
Kate Stonea487aa42015-01-15 00:52:41 +00001216 if (!(cmd_types & eCommandTypesHidden) && (pos->first.compare(0, 1, "_") == 0))
1217 continue;
1218
Enrico Granata223383e2011-08-16 23:24:13 +00001219 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1220 max_len);
1221 }
1222 result.AppendMessage("");
1223
1224 }
1225
Greg Clayton5521f992011-10-28 21:38:01 +00001226 if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001227 {
Kate Stonea487aa42015-01-15 00:52:41 +00001228 result.AppendMessageWithFormat("Current command abbreviations "
1229 "(type '%shelp command alias' for more info):\n",
1230 GetCommandPrefix());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001231 result.AppendMessage("");
Greg Clayton12fc3e02010-08-26 22:05:43 +00001232 max_len = FindLongestCommandWord (m_alias_dict);
1233
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001234 for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos)
1235 {
1236 StreamString sstr;
1237 StreamString translation_and_help;
1238 std::string entry_name = pos->first;
1239 std::string second_entry = pos->second.get()->GetCommandName();
1240 GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr);
1241
1242 translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp());
1243 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--",
1244 translation_and_help.GetData(), max_len);
1245 }
1246 result.AppendMessage("");
1247 }
1248
Greg Clayton5521f992011-10-28 21:38:01 +00001249 if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef ))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001250 {
Kate Stonea487aa42015-01-15 00:52:41 +00001251 result.AppendMessage ("Current user-defined commands:");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001252 result.AppendMessage("");
Enrico Granata223383e2011-08-16 23:24:13 +00001253 max_len = FindLongestCommandWord (m_user_dict);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001254 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
1255 {
Enrico Granata223383e2011-08-16 23:24:13 +00001256 OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(),
1257 max_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001258 }
1259 result.AppendMessage("");
1260 }
1261
Kate Stonea487aa42015-01-15 00:52:41 +00001262 result.AppendMessageWithFormat("For more information on any command, type '%shelp <command-name>'.\n",
1263 GetCommandPrefix());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001264}
1265
Caroline Tice844d2302010-12-09 22:52:49 +00001266CommandObject *
1267CommandInterpreter::GetCommandObjectForCommand (std::string &command_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001268{
Caroline Tice844d2302010-12-09 22:52:49 +00001269 // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will
1270 // eventually be invoked by the given command line.
1271
Ed Masted78c9572014-04-20 00:31:37 +00001272 CommandObject *cmd_obj = nullptr;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001273 size_t start = command_string.find_first_not_of (k_white_space);
Caroline Tice844d2302010-12-09 22:52:49 +00001274 size_t end = 0;
1275 bool done = false;
1276 while (!done)
1277 {
1278 if (start != std::string::npos)
1279 {
1280 // Get the next word from command_string.
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001281 end = command_string.find_first_of (k_white_space, start);
Caroline Tice844d2302010-12-09 22:52:49 +00001282 if (end == std::string::npos)
1283 end = command_string.size();
1284 std::string cmd_word = command_string.substr (start, end - start);
1285
Ed Masted78c9572014-04-20 00:31:37 +00001286 if (cmd_obj == nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001287 // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid
1288 // command or alias.
1289 cmd_obj = GetCommandObject (cmd_word.c_str());
1290 else if (cmd_obj->IsMultiwordObject ())
1291 {
1292 // 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 +00001293 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001294 if (sub_cmd_obj)
1295 cmd_obj = sub_cmd_obj;
Bruce Mitchener58ef3912015-06-18 05:27:05 +00001296 else // cmd_word was not a valid sub-command word, so we are done
Caroline Tice844d2302010-12-09 22:52:49 +00001297 done = true;
1298 }
1299 else
1300 // We have a cmd_obj and it is not a multi-word object, so we are done.
1301 done = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001302
Caroline Tice844d2302010-12-09 22:52:49 +00001303 // If we didn't find a valid command object, or our command object is not a multi-word object, or
1304 // we are at the end of the command_string, then we are done. Otherwise, find the start of the
1305 // next word.
1306
1307 if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size())
1308 done = true;
1309 else
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001310 start = command_string.find_first_not_of (k_white_space, end);
Caroline Tice844d2302010-12-09 22:52:49 +00001311 }
1312 else
1313 // Unable to find any more words.
1314 done = true;
1315 }
1316
1317 if (end == command_string.size())
1318 command_string.clear();
1319 else
1320 command_string = command_string.substr(end);
1321
1322 return cmd_obj;
1323}
1324
Greg Clayton5521f992011-10-28 21:38:01 +00001325static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
Greg Clayton51964162011-10-25 00:36:27 +00001326static void
1327StripLeadingSpaces (std::string &s)
Caroline Tice844d2302010-12-09 22:52:49 +00001328{
Greg Clayton51964162011-10-25 00:36:27 +00001329 if (!s.empty())
Caroline Tice844d2302010-12-09 22:52:49 +00001330 {
Greg Clayton51964162011-10-25 00:36:27 +00001331 size_t pos = s.find_first_not_of (k_white_space);
1332 if (pos == std::string::npos)
1333 s.clear();
1334 else if (pos == 0)
1335 return;
1336 s.erase (0, pos);
1337 }
1338}
1339
Greg Clayton93c62e62011-11-09 23:25:03 +00001340static size_t
1341FindArgumentTerminator (const std::string &s)
1342{
Greg Clayton93c62e62011-11-09 23:25:03 +00001343 const size_t s_len = s.size();
1344 size_t offset = 0;
1345 while (offset < s_len)
1346 {
1347 size_t pos = s.find ("--", offset);
1348 if (pos == std::string::npos)
1349 break;
1350 if (pos > 0)
1351 {
1352 if (isspace(s[pos-1]))
1353 {
1354 // Check if the string ends "\s--" (where \s is a space character)
1355 // or if we have "\s--\s".
1356 if ((pos + 2 >= s_len) || isspace(s[pos+2]))
1357 {
Greg Clayton93c62e62011-11-09 23:25:03 +00001358 return pos;
1359 }
1360 }
1361 }
1362 offset = pos + 2;
1363 }
Greg Clayton93c62e62011-11-09 23:25:03 +00001364 return std::string::npos;
1365}
1366
Greg Clayton51964162011-10-25 00:36:27 +00001367static bool
Greg Clayton5521f992011-10-28 21:38:01 +00001368ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char)
Greg Clayton51964162011-10-25 00:36:27 +00001369{
Greg Clayton5521f992011-10-28 21:38:01 +00001370 command.clear();
1371 suffix.clear();
Greg Clayton51964162011-10-25 00:36:27 +00001372 StripLeadingSpaces (command_string);
1373
1374 bool result = false;
1375 quote_char = '\0';
1376
1377 if (!command_string.empty())
1378 {
1379 const char first_char = command_string[0];
1380 if (first_char == '\'' || first_char == '"')
Caroline Tice844d2302010-12-09 22:52:49 +00001381 {
Greg Clayton51964162011-10-25 00:36:27 +00001382 quote_char = first_char;
1383 const size_t end_quote_pos = command_string.find (quote_char, 1);
1384 if (end_quote_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, 1, end_quote_pos - 1);
Greg Clayton51964162011-10-25 00:36:27 +00001392 if (end_quote_pos + 1 < command_string.size())
1393 command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1));
1394 else
1395 command_string.erase ();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001396 }
Caroline Tice844d2302010-12-09 22:52:49 +00001397 }
1398 else
1399 {
Greg Clayton51964162011-10-25 00:36:27 +00001400 const size_t first_space_pos = command_string.find_first_of (k_white_space);
1401 if (first_space_pos == std::string::npos)
Caroline Tice2b5e8502011-05-11 16:07:06 +00001402 {
Greg Clayton5521f992011-10-28 21:38:01 +00001403 command.swap (command_string);
Greg Clayton51964162011-10-25 00:36:27 +00001404 command_string.erase();
Caroline Tice2b5e8502011-05-11 16:07:06 +00001405 }
1406 else
1407 {
Greg Clayton5521f992011-10-28 21:38:01 +00001408 command.assign (command_string, 0, first_space_pos);
1409 command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos));
Caroline Tice2b5e8502011-05-11 16:07:06 +00001410 }
Caroline Tice844d2302010-12-09 22:52:49 +00001411 }
Greg Clayton51964162011-10-25 00:36:27 +00001412 result = true;
Caroline Tice844d2302010-12-09 22:52:49 +00001413 }
Greg Clayton5521f992011-10-28 21:38:01 +00001414
1415
1416 if (!command.empty())
1417 {
1418 // actual commands can't start with '-' or '_'
1419 if (command[0] != '-' && command[0] != '_')
1420 {
1421 size_t pos = command.find_first_not_of(k_valid_command_chars);
1422 if (pos > 0 && pos != std::string::npos)
1423 {
1424 suffix.assign (command.begin() + pos, command.end());
1425 command.erase (pos);
1426 }
1427 }
1428 }
Greg Clayton51964162011-10-25 00:36:27 +00001429
1430 return result;
Caroline Tice844d2302010-12-09 22:52:49 +00001431}
1432
Greg Clayton5521f992011-10-28 21:38:01 +00001433CommandObject *
1434CommandInterpreter::BuildAliasResult (const char *alias_name,
1435 std::string &raw_input_string,
1436 std::string &alias_result,
1437 CommandReturnObject &result)
Caroline Tice844d2302010-12-09 22:52:49 +00001438{
Ed Masted78c9572014-04-20 00:31:37 +00001439 CommandObject *alias_cmd_obj = nullptr;
Pavel Labath00b7f952015-03-02 12:46:22 +00001440 Args cmd_args (raw_input_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001441 alias_cmd_obj = GetCommandObject (alias_name);
1442 StreamString result_str;
1443
1444 if (alias_cmd_obj)
1445 {
1446 std::string alias_name_str = alias_name;
1447 if ((cmd_args.GetArgumentCount() == 0)
1448 || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0))
1449 cmd_args.Unshift (alias_name);
1450
1451 result_str.Printf ("%s", alias_cmd_obj->GetCommandName ());
1452 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
1453
1454 if (option_arg_vector_sp.get())
1455 {
1456 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
1457
Andy Gibbsa297a972013-06-19 19:04:53 +00001458 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Caroline Tice844d2302010-12-09 22:52:49 +00001459 {
1460 OptionArgPair option_pair = (*option_arg_vector)[i];
1461 OptionArgValue value_pair = option_pair.second;
1462 int value_type = value_pair.first;
1463 std::string option = option_pair.first;
1464 std::string value = value_pair.second;
1465 if (option.compare ("<argument>") == 0)
1466 result_str.Printf (" %s", value.c_str());
1467 else
1468 {
1469 result_str.Printf (" %s", option.c_str());
Ted Woodwarde7e8e3c2015-04-06 21:55:14 +00001470 if (value_type != OptionParser::eNoArgument)
Caroline Tice844d2302010-12-09 22:52:49 +00001471 {
Ted Woodwarde7e8e3c2015-04-06 21:55:14 +00001472 if (value_type != OptionParser::eOptionalArgument)
1473 result_str.Printf (" ");
Caroline Tice844d2302010-12-09 22:52:49 +00001474 int index = GetOptionArgumentPosition (value.c_str());
1475 if (index == 0)
1476 result_str.Printf ("%s", value.c_str());
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001477 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Caroline Tice844d2302010-12-09 22:52:49 +00001478 {
1479
1480 result.AppendErrorWithFormat
1481 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
1482 index);
1483 result.SetStatus (eReturnStatusFailed);
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001484 return nullptr;
Caroline Tice844d2302010-12-09 22:52:49 +00001485 }
1486 else
1487 {
1488 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
1489 if (strpos != std::string::npos)
1490 raw_input_string = raw_input_string.erase (strpos,
1491 strlen (cmd_args.GetArgumentAtIndex (index)));
1492 result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index));
1493 }
1494 }
1495 }
1496 }
1497 }
1498
1499 alias_result = result_str.GetData();
1500 }
Greg Clayton5521f992011-10-28 21:38:01 +00001501 return alias_cmd_obj;
Caroline Tice844d2302010-12-09 22:52:49 +00001502}
1503
Greg Clayton5a314712011-10-14 07:41:33 +00001504Error
1505CommandInterpreter::PreprocessCommand (std::string &command)
1506{
1507 // The command preprocessor needs to do things to the command
1508 // line before any parsing of arguments or anything else is done.
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001509 // The only current stuff that gets preprocessed is anything enclosed
Greg Clayton5a314712011-10-14 07:41:33 +00001510 // in backtick ('`') characters is evaluated as an expression and
1511 // the result of the expression must be a scalar that can be substituted
1512 // into the command. An example would be:
1513 // (lldb) memory read `$rsp + 20`
1514 Error error; // Error for any expressions that might not evaluate
1515 size_t start_backtick;
1516 size_t pos = 0;
1517 while ((start_backtick = command.find ('`', pos)) != std::string::npos)
1518 {
1519 if (start_backtick > 0 && command[start_backtick-1] == '\\')
1520 {
Bruce Mitchener58ef3912015-06-18 05:27:05 +00001521 // The backtick was preceded by a '\' character, remove the slash
Greg Clayton5a314712011-10-14 07:41:33 +00001522 // and don't treat the backtick as the start of an expression
1523 command.erase(start_backtick-1, 1);
1524 // No need to add one to start_backtick since we just deleted a char
1525 pos = start_backtick;
1526 }
1527 else
1528 {
1529 const size_t expr_content_start = start_backtick + 1;
1530 const size_t end_backtick = command.find ('`', expr_content_start);
1531 if (end_backtick == std::string::npos)
1532 return error;
1533 else if (end_backtick == expr_content_start)
1534 {
1535 // Empty expression (two backticks in a row)
1536 command.erase (start_backtick, 2);
1537 }
1538 else
1539 {
1540 std::string expr_str (command, expr_content_start, end_backtick - expr_content_start);
1541
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00001542 ExecutionContext exe_ctx(GetExecutionContext());
1543 Target *target = exe_ctx.GetTargetPtr();
Johnny Chen51ea0ad2011-10-29 00:21:50 +00001544 // Get a dummy target to allow for calculator mode while processing backticks.
1545 // This also helps break the infinite loop caused when target is null.
1546 if (!target)
Jim Ingham893c9322014-11-22 01:42:44 +00001547 target = m_debugger.GetDummyTarget();
Greg Clayton5a314712011-10-14 07:41:33 +00001548 if (target)
1549 {
Greg Clayton5a314712011-10-14 07:41:33 +00001550 ValueObjectSP expr_result_valobj_sp;
Enrico Granatad4439aa2012-09-05 20:41:26 +00001551
Jim Ingham35e1bda2012-10-16 21:41:58 +00001552 EvaluateExpressionOptions options;
Jim Ingham6fbc48b2013-11-07 00:11:47 +00001553 options.SetCoerceToId(false);
1554 options.SetUnwindOnError(true);
1555 options.SetIgnoreBreakpoints(true);
1556 options.SetKeepInMemory(false);
1557 options.SetTryAllThreads(true);
1558 options.SetTimeoutUsec(0);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001559
Jim Ingham1624a2d2014-05-05 02:26:40 +00001560 ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(),
Enrico Granataca0e5ad2014-10-09 23:09:40 +00001561 exe_ctx.GetFramePtr(),
1562 expr_result_valobj_sp,
1563 options);
Enrico Granatad4439aa2012-09-05 20:41:26 +00001564
Jim Ingham8646d3c2014-05-05 02:47:44 +00001565 if (expr_result == eExpressionCompleted)
Greg Clayton5a314712011-10-14 07:41:33 +00001566 {
1567 Scalar scalar;
Enrico Granataca0e5ad2014-10-09 23:09:40 +00001568 if (expr_result_valobj_sp)
1569 expr_result_valobj_sp = expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(expr_result_valobj_sp->GetDynamicValueType(), true);
Greg Clayton5a314712011-10-14 07:41:33 +00001570 if (expr_result_valobj_sp->ResolveValue (scalar))
1571 {
1572 command.erase (start_backtick, end_backtick - start_backtick + 1);
1573 StreamString value_strm;
1574 const bool show_type = false;
1575 scalar.GetValue (&value_strm, show_type);
1576 size_t value_string_size = value_strm.GetSize();
1577 if (value_string_size)
1578 {
1579 command.insert (start_backtick, value_strm.GetData(), value_string_size);
1580 pos = start_backtick + value_string_size;
1581 continue;
1582 }
1583 else
1584 {
1585 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1586 }
1587 }
1588 else
1589 {
1590 error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str());
1591 }
1592 }
1593 else
1594 {
1595 if (expr_result_valobj_sp)
1596 error = expr_result_valobj_sp->GetError();
1597 if (error.Success())
1598 {
1599
1600 switch (expr_result)
1601 {
Jim Ingham8646d3c2014-05-05 02:47:44 +00001602 case eExpressionSetupError:
Greg Clayton5a314712011-10-14 07:41:33 +00001603 error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str());
1604 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001605 case eExpressionParseError:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001606 error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str());
1607 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001608 case eExpressionResultUnavailable:
Jim Ingham1624a2d2014-05-05 02:26:40 +00001609 error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str());
Jim Ingham8646d3c2014-05-05 02:47:44 +00001610 case eExpressionCompleted:
Greg Clayton5a314712011-10-14 07:41:33 +00001611 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001612 case eExpressionDiscarded:
Greg Clayton5a314712011-10-14 07:41:33 +00001613 error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str());
1614 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001615 case eExpressionInterrupted:
Greg Clayton5a314712011-10-14 07:41:33 +00001616 error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str());
1617 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001618 case eExpressionHitBreakpoint:
Jim Ingham184e9812013-01-15 02:47:48 +00001619 error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str());
1620 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001621 case eExpressionTimedOut:
Greg Clayton5a314712011-10-14 07:41:33 +00001622 error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str());
1623 break;
Jim Ingham8646d3c2014-05-05 02:47:44 +00001624 case eExpressionStoppedForDebug:
Greg Claytonc28ce782013-11-08 23:38:26 +00001625 error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str());
1626 break;
Greg Clayton5a314712011-10-14 07:41:33 +00001627 }
1628 }
1629 }
1630 }
1631 }
1632 if (error.Fail())
1633 break;
1634 }
1635 }
1636 return error;
1637}
1638
1639
Caroline Tice844d2302010-12-09 22:52:49 +00001640bool
1641CommandInterpreter::HandleCommand (const char *command_line,
Enrico Granata5f5ab602012-05-31 01:09:06 +00001642 LazyBool lazy_add_to_history,
Caroline Tice844d2302010-12-09 22:52:49 +00001643 CommandReturnObject &result,
Jim Inghame16c50a2011-02-18 00:54:25 +00001644 ExecutionContext *override_context,
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001645 bool repeat_on_empty_command,
1646 bool no_context_switching)
Jim Inghame16c50a2011-02-18 00:54:25 +00001647
Caroline Tice844d2302010-12-09 22:52:49 +00001648{
Jim Inghame16c50a2011-02-18 00:54:25 +00001649
Caroline Tice844d2302010-12-09 22:52:49 +00001650 std::string command_string (command_line);
Jim Inghama5a97eb2011-07-12 03:12:18 +00001651 std::string original_command_string (command_line);
Caroline Tice844d2302010-12-09 22:52:49 +00001652
Greg Clayton5160ce52013-03-27 23:08:40 +00001653 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS));
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001654 Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line);
1655
1656 // Make a scoped cleanup object that will clear the crash description string
1657 // on exit of this function.
Ed Masted78c9572014-04-20 00:31:37 +00001658 lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription);
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001659
Caroline Tice844d2302010-12-09 22:52:49 +00001660 if (log)
1661 log->Printf ("Processing command: %s", command_line);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001662
Jim Ingham30244832010-11-04 23:08:45 +00001663 Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line);
1664
Johnny Chen80fdd7c2011-10-05 00:42:59 +00001665 if (!no_context_switching)
1666 UpdateExecutionContext (override_context);
Enrico Granata5f5ab602012-05-31 01:09:06 +00001667
Enrico Granata5f5ab602012-05-31 01:09:06 +00001668 bool add_to_history;
1669 if (lazy_add_to_history == eLazyBoolCalculate)
1670 add_to_history = (m_command_source_depth == 0);
1671 else
1672 add_to_history = (lazy_add_to_history == eLazyBoolYes);
1673
Jim Inghame16c50a2011-02-18 00:54:25 +00001674 bool empty_command = false;
1675 bool comment_command = false;
1676 if (command_string.empty())
1677 empty_command = true;
1678 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001679 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001680 const char *k_space_characters = "\t\n\v\f\r ";
1681
1682 size_t non_space = command_string.find_first_not_of (k_space_characters);
1683 // Check for empty line or comment line (lines whose first
1684 // non-space character is the comment character for this interpreter)
1685 if (non_space == std::string::npos)
1686 empty_command = true;
1687 else if (command_string[non_space] == m_comment_char)
1688 comment_command = true;
Enrico Granata7594f142013-06-17 22:51:50 +00001689 else if (command_string[non_space] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001690 {
Enrico Granata7594f142013-06-17 22:51:50 +00001691 const char *history_string = m_command_history.FindString(command_string.c_str() + non_space);
Ed Masted78c9572014-04-20 00:31:37 +00001692 if (history_string == nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001693 {
1694 result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str());
1695 result.SetStatus(eReturnStatusFailed);
1696 return false;
1697 }
1698 add_to_history = false;
1699 command_string = history_string;
1700 original_command_string = history_string;
1701 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001702 }
1703
1704 if (empty_command)
1705 {
1706 if (repeat_on_empty_command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001707 {
Enrico Granata7594f142013-06-17 22:51:50 +00001708 if (m_command_history.IsEmpty())
Jim Inghame16c50a2011-02-18 00:54:25 +00001709 {
1710 result.AppendError ("empty command");
1711 result.SetStatus(eReturnStatusFailed);
1712 return false;
1713 }
1714 else
1715 {
1716 command_line = m_repeat_command.c_str();
1717 command_string = command_line;
Jim Inghama5a97eb2011-07-12 03:12:18 +00001718 original_command_string = command_line;
Jim Inghame16c50a2011-02-18 00:54:25 +00001719 if (m_repeat_command.empty())
1720 {
1721 result.AppendErrorWithFormat("No auto repeat.\n");
1722 result.SetStatus (eReturnStatusFailed);
1723 return false;
1724 }
1725 }
1726 add_to_history = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001727 }
1728 else
1729 {
Jim Inghame16c50a2011-02-18 00:54:25 +00001730 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1731 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001732 }
Jim Inghame16c50a2011-02-18 00:54:25 +00001733 }
1734 else if (comment_command)
1735 {
1736 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1737 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001738 }
Caroline Tice2b5e8502011-05-11 16:07:06 +00001739
Greg Clayton5a314712011-10-14 07:41:33 +00001740
1741 Error error (PreprocessCommand (command_string));
1742
1743 if (error.Fail())
1744 {
1745 result.AppendError (error.AsCString());
1746 result.SetStatus(eReturnStatusFailed);
1747 return false;
1748 }
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001749
Caroline Tice844d2302010-12-09 22:52:49 +00001750 // Phase 1.
1751
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001752 // Before we do ANY kind of argument processing, we need to figure out what
1753 // the real/final command object is for the specified command. This gets
1754 // complicated by the fact that the user could have specified an alias, and,
1755 // in translating the alias, there may also be command options and/or even
1756 // data (including raw text strings) that need to be found and inserted into
1757 // the command line as part of the translation. So this first step is plain
1758 // look-up and replacement, resulting in:
1759 // 1. the command object whose Execute method will actually be called
1760 // 2. a revised command string, with all substitutions and replacements
1761 // taken care of
1762 // From 1 above, we can determine whether the Execute function wants raw
1763 // input or not.
Caroline Ticed9d63362010-12-07 19:58:26 +00001764
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001765 CommandObject *cmd_obj = ResolveCommandImpl(command_string, result);
Caroline Tice844d2302010-12-09 22:52:49 +00001766
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001767 // Although the user may have abbreviated the command, the command_string now
1768 // has the command expanded to the full name. For example, if the input
1769 // was "br s -n main", command_string is now "breakpoint set -n main".
Filipe Cabecinhasaf1537f2012-05-16 23:25:54 +00001770
Caroline Tice844d2302010-12-09 22:52:49 +00001771 if (log)
1772 {
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001773 log->Printf("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>");
1774 log->Printf("HandleCommand, (revised) command_string: '%s'", command_string.c_str());
1775 const bool wants_raw_input = (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false;
1776 log->Printf("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False");
Caroline Tice844d2302010-12-09 22:52:49 +00001777 }
1778
1779 // Phase 2.
1780 // Take care of things like setting up the history command & calling the appropriate Execute method on the
1781 // CommandObject, with the appropriate arguments.
1782
Ed Masted78c9572014-04-20 00:31:37 +00001783 if (cmd_obj != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001784 {
1785 if (add_to_history)
1786 {
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001787 Args command_args (command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001788 const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0);
Ed Masted78c9572014-04-20 00:31:37 +00001789 if (repeat_command != nullptr)
Caroline Tice844d2302010-12-09 22:52:49 +00001790 m_repeat_command.assign(repeat_command);
1791 else
Jim Inghama5a97eb2011-07-12 03:12:18 +00001792 m_repeat_command.assign(original_command_string.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001793
Enrico Granata7594f142013-06-17 22:51:50 +00001794 m_command_history.AppendString (original_command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001795 }
1796
Caroline Tice01274c02010-12-11 08:16:56 +00001797 std::string remainder;
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001798 const std::size_t actual_cmd_name_len = strlen (cmd_obj->GetCommandName());
Caroline Tice01274c02010-12-11 08:16:56 +00001799 if (actual_cmd_name_len < command_string.length())
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001800 remainder = command_string.substr (actual_cmd_name_len);
Caroline Tice844d2302010-12-09 22:52:49 +00001801
1802 // Remove any initial spaces
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001803 size_t pos = remainder.find_first_not_of (k_white_space);
Caroline Tice844d2302010-12-09 22:52:49 +00001804 if (pos != 0 && pos != std::string::npos)
Greg Claytona3482592011-04-22 20:58:45 +00001805 remainder.erase(0, pos);
Caroline Tice844d2302010-12-09 22:52:49 +00001806
1807 if (log)
Jason Molendabfb36ff2011-08-25 00:20:04 +00001808 log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001809
Jim Ingham5a988412012-06-08 21:56:10 +00001810 cmd_obj->Execute (remainder.c_str(), result);
Caroline Tice844d2302010-12-09 22:52:49 +00001811 }
1812 else
1813 {
1814 // We didn't find the first command object, so complete the first argument.
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00001815 Args command_args (command_string);
Caroline Tice844d2302010-12-09 22:52:49 +00001816 StringList matches;
1817 int num_matches;
1818 int cursor_index = 0;
1819 int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0));
1820 bool word_complete;
1821 num_matches = HandleCompletionMatches (command_args,
1822 cursor_index,
1823 cursor_char_position,
1824 0,
1825 -1,
1826 word_complete,
1827 matches);
1828
1829 if (num_matches > 0)
1830 {
1831 std::string error_msg;
1832 error_msg.assign ("ambiguous command '");
1833 error_msg.append(command_args.GetArgumentAtIndex(0));
1834 error_msg.append ("'.");
1835
1836 error_msg.append (" Possible completions:");
1837 for (int i = 0; i < num_matches; i++)
1838 {
1839 error_msg.append ("\n\t");
1840 error_msg.append (matches.GetStringAtIndex (i));
1841 }
1842 error_msg.append ("\n");
Greg Claytonc7bece562013-01-25 18:06:21 +00001843 result.AppendRawError (error_msg.c_str());
Caroline Tice844d2302010-12-09 22:52:49 +00001844 }
1845 else
1846 result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0));
1847
1848 result.SetStatus (eReturnStatusFailed);
1849 }
1850
Jason Molendabfb36ff2011-08-25 00:20:04 +00001851 if (log)
1852 log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed"));
1853
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001854 return result.Succeeded();
1855}
1856
1857int
1858CommandInterpreter::HandleCompletionMatches (Args &parsed_line,
1859 int &cursor_index,
1860 int &cursor_char_position,
1861 int match_start_point,
1862 int max_return_elements,
Jim Ingham558ce122010-06-30 05:02:46 +00001863 bool &word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001864 StringList &matches)
1865{
1866 int num_command_matches = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001867 bool look_for_subcommand = false;
Jim Ingham558ce122010-06-30 05:02:46 +00001868
1869 // For any of the command completions a unique match will be a complete word.
1870 word_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001871
1872 if (cursor_index == -1)
1873 {
1874 // We got nothing on the command line, so return the list of commands
Jim Ingham279a6c22010-07-06 22:46:59 +00001875 bool include_aliases = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001876 num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches);
1877 }
1878 else if (cursor_index == 0)
1879 {
1880 // The cursor is in the first argument, so just do a lookup in the dictionary.
Jim Ingham279a6c22010-07-06 22:46:59 +00001881 CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001882 num_command_matches = matches.GetSize();
1883
1884 if (num_command_matches == 1
1885 && cmd_obj && cmd_obj->IsMultiwordObject()
Ed Masted78c9572014-04-20 00:31:37 +00001886 && matches.GetStringAtIndex(0) != nullptr
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001887 && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0)
1888 {
Greg Clayton765d2e22013-12-10 19:14:04 +00001889 if (parsed_line.GetArgumentCount() == 1)
1890 {
1891 word_complete = true;
1892 }
1893 else
1894 {
1895 look_for_subcommand = true;
1896 num_command_matches = 0;
1897 matches.DeleteStringAtIndex(0);
1898 parsed_line.AppendArgument ("");
1899 cursor_index++;
1900 cursor_char_position = 0;
1901 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001902 }
1903 }
1904
1905 if (cursor_index > 0 || look_for_subcommand)
1906 {
1907 // We are completing further on into a commands arguments, so find the command and tell it
1908 // to complete the command.
1909 // First see if there is a matching initial command:
Jim Ingham279a6c22010-07-06 22:46:59 +00001910 CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0));
Ed Masted78c9572014-04-20 00:31:37 +00001911 if (command_object == nullptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001912 {
1913 return 0;
1914 }
1915 else
1916 {
1917 parsed_line.Shift();
1918 cursor_index--;
Greg Claytona7015092010-09-18 01:14:36 +00001919 num_command_matches = command_object->HandleCompletion (parsed_line,
Greg Clayton66111032010-06-23 01:19:29 +00001920 cursor_index,
1921 cursor_char_position,
1922 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00001923 max_return_elements,
1924 word_complete,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001925 matches);
1926 }
1927 }
1928
1929 return num_command_matches;
1930
1931}
1932
1933int
1934CommandInterpreter::HandleCompletion (const char *current_line,
1935 const char *cursor,
1936 const char *last_char,
1937 int match_start_point,
1938 int max_return_elements,
1939 StringList &matches)
1940{
1941 // We parse the argument up to the cursor, so the last argument in parsed_line is
1942 // the one containing the cursor, and the cursor is after the last character.
1943
Pavel Labath00b7f952015-03-02 12:46:22 +00001944 Args parsed_line(llvm::StringRef(current_line, last_char - current_line));
1945 Args partial_parsed_line(llvm::StringRef(current_line, cursor - current_line));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001946
Jim Inghama5a97eb2011-07-12 03:12:18 +00001947 // Don't complete comments, and if the line we are completing is just the history repeat character,
1948 // substitute the appropriate history line.
1949 const char *first_arg = parsed_line.GetArgumentAtIndex(0);
1950 if (first_arg)
1951 {
1952 if (first_arg[0] == m_comment_char)
1953 return 0;
Enrico Granata7594f142013-06-17 22:51:50 +00001954 else if (first_arg[0] == CommandHistory::g_repeat_char)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001955 {
Enrico Granata7594f142013-06-17 22:51:50 +00001956 const char *history_string = m_command_history.FindString (first_arg);
Ed Masted78c9572014-04-20 00:31:37 +00001957 if (history_string != nullptr)
Jim Inghama5a97eb2011-07-12 03:12:18 +00001958 {
1959 matches.Clear();
1960 matches.InsertStringAtIndex(0, history_string);
1961 return -2;
1962 }
1963 else
1964 return 0;
1965
1966 }
1967 }
1968
1969
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001970 int num_args = partial_parsed_line.GetArgumentCount();
1971 int cursor_index = partial_parsed_line.GetArgumentCount() - 1;
1972 int cursor_char_position;
1973
1974 if (cursor_index == -1)
1975 cursor_char_position = 0;
1976 else
1977 cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index));
Jim Inghamfe0c4252010-12-14 19:56:01 +00001978
1979 if (cursor > current_line && cursor[-1] == ' ')
1980 {
1981 // We are just after a space. If we are in an argument, then we will continue
1982 // parsing, but if we are between arguments, then we have to complete whatever the next
1983 // element would be.
1984 // We can distinguish the two cases because if we are in an argument (e.g. because the space is
1985 // protected by a quote) then the space will also be in the parsed argument...
1986
1987 const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index);
1988 if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ')
1989 {
Greg Clayton765d2e22013-12-10 19:14:04 +00001990 parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0');
Jim Inghamfe0c4252010-12-14 19:56:01 +00001991 cursor_index++;
1992 cursor_char_position = 0;
1993 }
1994 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001995
1996 int num_command_matches;
1997
1998 matches.Clear();
1999
2000 // Only max_return_elements == -1 is supported at present:
2001 assert (max_return_elements == -1);
Jim Ingham558ce122010-06-30 05:02:46 +00002002 bool word_complete;
Greg Clayton66111032010-06-23 01:19:29 +00002003 num_command_matches = HandleCompletionMatches (parsed_line,
2004 cursor_index,
2005 cursor_char_position,
2006 match_start_point,
Jim Ingham558ce122010-06-30 05:02:46 +00002007 max_return_elements,
2008 word_complete,
Greg Clayton66111032010-06-23 01:19:29 +00002009 matches);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002010
2011 if (num_command_matches <= 0)
2012 return num_command_matches;
2013
2014 if (num_args == 0)
2015 {
2016 // If we got an empty string, insert nothing.
2017 matches.InsertStringAtIndex(0, "");
2018 }
2019 else
2020 {
2021 // Now figure out if there is a common substring, and if so put that in element 0, otherwise
2022 // put an empty string in element 0.
2023 std::string command_partial_str;
2024 if (cursor_index >= 0)
Jim Ingham49e80a12010-10-22 18:47:16 +00002025 command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index),
2026 parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002027
2028 std::string common_prefix;
2029 matches.LongestCommonPrefix (common_prefix);
Greg Claytonc7bece562013-01-25 18:06:21 +00002030 const size_t partial_name_len = command_partial_str.size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002031
2032 // If we matched a unique single command, add a space...
Jim Ingham558ce122010-06-30 05:02:46 +00002033 // Only do this if the completer told us this was a complete word, however...
2034 if (num_command_matches == 1 && word_complete)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002035 {
2036 char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index);
2037 if (quote_char != '\0')
2038 common_prefix.push_back(quote_char);
2039
2040 common_prefix.push_back(' ');
2041 }
2042 common_prefix.erase (0, partial_name_len);
2043 matches.InsertStringAtIndex(0, common_prefix.c_str());
2044 }
2045 return num_command_matches;
2046}
2047
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002048
2049CommandInterpreter::~CommandInterpreter ()
2050{
2051}
2052
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002053void
Greg Clayton44d93782014-01-27 23:43:24 +00002054CommandInterpreter::UpdatePrompt (const char *new_prompt)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002055{
Greg Clayton44d93782014-01-27 23:43:24 +00002056 EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));;
2057 BroadcastEvent (prompt_change_event_sp);
2058 if (m_command_io_handler_sp)
2059 m_command_io_handler_sp->SetPrompt(new_prompt);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002060}
2061
Jim Ingham97a6dc72010-10-04 19:49:29 +00002062
2063bool
2064CommandInterpreter::Confirm (const char *message, bool default_answer)
2065{
Jim Ingham3bcdb292010-10-04 22:44:14 +00002066 // Check AutoConfirm first:
2067 if (m_debugger.GetAutoConfirm())
2068 return default_answer;
Greg Clayton44d93782014-01-27 23:43:24 +00002069
2070 IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger,
2071 message,
2072 default_answer);
2073 IOHandlerSP io_handler_sp (confirm);
2074 m_debugger.RunIOHandler (io_handler_sp);
2075 return confirm->GetResponse();
Jim Ingham97a6dc72010-10-04 19:49:29 +00002076}
2077
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002078OptionArgVectorSP
2079CommandInterpreter::GetAliasOptions (const char *alias_name)
2080{
2081 OptionArgMap::iterator pos;
2082 OptionArgVectorSP ret_val;
2083
2084 std::string alias (alias_name);
2085
2086 if (HasAliasOptions())
2087 {
2088 pos = m_alias_options.find (alias);
2089 if (pos != m_alias_options.end())
2090 ret_val = pos->second;
2091 }
2092
2093 return ret_val;
2094}
2095
2096void
2097CommandInterpreter::RemoveAliasOptions (const char *alias_name)
2098{
2099 OptionArgMap::iterator pos = m_alias_options.find(alias_name);
2100 if (pos != m_alias_options.end())
2101 {
2102 m_alias_options.erase (pos);
2103 }
2104}
2105
2106void
2107CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp)
2108{
2109 m_alias_options[alias_name] = option_arg_vector_sp;
2110}
2111
2112bool
2113CommandInterpreter::HasCommands ()
2114{
2115 return (!m_command_dict.empty());
2116}
2117
2118bool
2119CommandInterpreter::HasAliases ()
2120{
2121 return (!m_alias_dict.empty());
2122}
2123
2124bool
2125CommandInterpreter::HasUserCommands ()
2126{
2127 return (!m_user_dict.empty());
2128}
2129
2130bool
2131CommandInterpreter::HasAliasOptions ()
2132{
2133 return (!m_alias_options.empty());
2134}
2135
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002136void
Caroline Tice4ab31c92010-10-12 21:57:09 +00002137CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj,
2138 const char *alias_name,
2139 Args &cmd_args,
Caroline Ticed9d63362010-12-07 19:58:26 +00002140 std::string &raw_input_string,
Caroline Tice4ab31c92010-10-12 21:57:09 +00002141 CommandReturnObject &result)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002142{
2143 OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name);
Caroline Ticed9d63362010-12-07 19:58:26 +00002144
2145 bool wants_raw_input = alias_cmd_obj->WantsRawCommandString();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002146
Caroline Ticed9d63362010-12-07 19:58:26 +00002147 // Make sure that the alias name is the 0th element in cmd_args
2148 std::string alias_name_str = alias_name;
2149 if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)
2150 cmd_args.Unshift (alias_name);
2151
2152 Args new_args (alias_cmd_obj->GetCommandName());
2153 if (new_args.GetArgumentCount() == 2)
2154 new_args.Shift();
2155
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002156 if (option_arg_vector_sp.get())
2157 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002158 if (wants_raw_input)
2159 {
2160 // We have a command that both has command options and takes raw input. Make *sure* it has a
2161 // " -- " in the right place in the raw_input_string.
2162 size_t pos = raw_input_string.find(" -- ");
2163 if (pos == std::string::npos)
2164 {
2165 // None found; assume it goes at the beginning of the raw input string
2166 raw_input_string.insert (0, " -- ");
2167 }
2168 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002169
2170 OptionArgVector *option_arg_vector = option_arg_vector_sp.get();
Greg Claytonc7bece562013-01-25 18:06:21 +00002171 const size_t old_size = cmd_args.GetArgumentCount();
Caroline Tice4ab31c92010-10-12 21:57:09 +00002172 std::vector<bool> used (old_size + 1, false);
2173
2174 used[0] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002175
Andy Gibbsa297a972013-06-19 19:04:53 +00002176 for (size_t i = 0; i < option_arg_vector->size(); ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002177 {
2178 OptionArgPair option_pair = (*option_arg_vector)[i];
Caroline Ticed9d63362010-12-07 19:58:26 +00002179 OptionArgValue value_pair = option_pair.second;
2180 int value_type = value_pair.first;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002181 std::string option = option_pair.first;
Caroline Ticed9d63362010-12-07 19:58:26 +00002182 std::string value = value_pair.second;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002183 if (option.compare ("<argument>") == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002184 {
2185 if (!wants_raw_input
2186 || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice
2187 new_args.AppendArgument (value.c_str());
2188 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002189 else
2190 {
Virgile Belloe2607b52013-09-05 16:42:23 +00002191 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002192 new_args.AppendArgument (option.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002193 if (value.compare ("<no-argument>") != 0)
2194 {
2195 int index = GetOptionArgumentPosition (value.c_str());
2196 if (index == 0)
Caroline Ticed9d63362010-12-07 19:58:26 +00002197 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002198 // value was NOT a positional argument; must be a real value
Virgile Belloe2607b52013-09-05 16:42:23 +00002199 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002200 new_args.AppendArgument (value.c_str());
2201 else
2202 {
2203 char buffer[255];
2204 ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str());
2205 new_args.AppendArgument (buffer);
2206 }
2207
2208 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002209 else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002210 {
2211 result.AppendErrorWithFormat
2212 ("Not enough arguments provided; you need at least %d arguments to use this alias.\n",
2213 index);
2214 result.SetStatus (eReturnStatusFailed);
2215 return;
2216 }
2217 else
2218 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002219 // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string
2220 size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index));
2221 if (strpos != std::string::npos)
2222 {
2223 raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index)));
2224 }
2225
Virgile Belloe2607b52013-09-05 16:42:23 +00002226 if (value_type != OptionParser::eOptionalArgument)
Caroline Ticed9d63362010-12-07 19:58:26 +00002227 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index));
2228 else
2229 {
2230 char buffer[255];
2231 ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(),
2232 cmd_args.GetArgumentAtIndex (index));
2233 new_args.AppendArgument (buffer);
2234 }
Caroline Tice4ab31c92010-10-12 21:57:09 +00002235 used[index] = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002236 }
2237 }
2238 }
2239 }
2240
Andy Gibbsa297a972013-06-19 19:04:53 +00002241 for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002242 {
Caroline Ticed9d63362010-12-07 19:58:26 +00002243 if (!used[j] && !wants_raw_input)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002244 new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j));
2245 }
2246
2247 cmd_args.Clear();
Vince Harrond7e6a4f2015-05-13 00:25:54 +00002248 cmd_args.SetArguments (new_args.GetArgumentCount(), new_args.GetConstArgumentVector());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002249 }
2250 else
2251 {
2252 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Caroline Ticed9d63362010-12-07 19:58:26 +00002253 // This alias was not created with any options; nothing further needs to be done, unless it is a command that
2254 // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw
2255 // input string.
2256 if (wants_raw_input)
2257 {
2258 cmd_args.Clear();
Vince Harrond7e6a4f2015-05-13 00:25:54 +00002259 cmd_args.SetArguments (new_args.GetArgumentCount(), new_args.GetConstArgumentVector());
Caroline Ticed9d63362010-12-07 19:58:26 +00002260 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002261 return;
2262 }
2263
2264 result.SetStatus (eReturnStatusSuccessFinishNoResult);
2265 return;
2266}
2267
2268
2269int
2270CommandInterpreter::GetOptionArgumentPosition (const char *in_string)
2271{
2272 int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position
2273 // of zero.
2274
Vince Harrond7e6a4f2015-05-13 00:25:54 +00002275 const char *cptr = in_string;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002276
2277 // Does it start with '%'
2278 if (cptr[0] == '%')
2279 {
2280 ++cptr;
2281
2282 // Is the rest of it entirely digits?
2283 if (isdigit (cptr[0]))
2284 {
2285 const char *start = cptr;
2286 while (isdigit (cptr[0]))
2287 ++cptr;
2288
2289 // We've gotten to the end of the digits; are we at the end of the string?
2290 if (cptr[0] == '\0')
2291 position = atoi (start);
2292 }
2293 }
2294
2295 return position;
2296}
2297
2298void
2299CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result)
2300{
Jim Ingham16e0c682011-08-12 23:34:31 +00002301 FileSpec init_file;
Greg Clayton14a35512011-09-11 00:01:44 +00002302 if (in_cwd)
Jim Ingham16e0c682011-08-12 23:34:31 +00002303 {
Greg Clayton14a35512011-09-11 00:01:44 +00002304 // In the current working directory we don't load any program specific
2305 // .lldbinit files, we only look for a "./.lldbinit" file.
2306 if (m_skip_lldbinit_files)
2307 return;
2308
2309 init_file.SetFile ("./.lldbinit", true);
Jim Ingham16e0c682011-08-12 23:34:31 +00002310 }
Greg Clayton14a35512011-09-11 00:01:44 +00002311 else
Jim Ingham16e0c682011-08-12 23:34:31 +00002312 {
Greg Clayton14a35512011-09-11 00:01:44 +00002313 // If we aren't looking in the current working directory we are looking
2314 // in the home directory. We will first see if there is an application
2315 // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a
2316 // "-" and the name of the program. If this file doesn't exist, we fall
2317 // back to just the "~/.lldbinit" file. We also obey any requests to not
2318 // load the init files.
Zachary Turnera21fee02014-08-21 21:49:24 +00002319 llvm::SmallString<64> home_dir_path;
2320 llvm::sys::path::home_directory(home_dir_path);
2321 FileSpec profilePath(home_dir_path.c_str(), false);
Zachary Turner9e757b72014-07-28 16:45:05 +00002322 profilePath.AppendPathComponent(".lldbinit");
2323 std::string init_file_path = profilePath.GetPath();
Greg Clayton14a35512011-09-11 00:01:44 +00002324
2325 if (m_skip_app_init_files == false)
2326 {
Zachary Turnera21fee02014-08-21 21:49:24 +00002327 FileSpec program_file_spec(HostInfo::GetProgramFileSpec());
Greg Clayton14a35512011-09-11 00:01:44 +00002328 const char *program_name = program_file_spec.GetFilename().AsCString();
Jim Ingham16e0c682011-08-12 23:34:31 +00002329
Greg Clayton14a35512011-09-11 00:01:44 +00002330 if (program_name)
2331 {
2332 char program_init_file_name[PATH_MAX];
Zachary Turner9e757b72014-07-28 16:45:05 +00002333 ::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 +00002334 init_file.SetFile (program_init_file_name, true);
2335 if (!init_file.Exists())
2336 init_file.Clear();
2337 }
2338 }
2339
2340 if (!init_file && !m_skip_lldbinit_files)
Zachary Turner9e757b72014-07-28 16:45:05 +00002341 init_file.SetFile (init_file_path.c_str(), false);
Greg Clayton14a35512011-09-11 00:01:44 +00002342 }
2343
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002344 // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting
2345 // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details).
2346
2347 if (init_file.Exists())
2348 {
Greg Clayton44d93782014-01-27 23:43:24 +00002349 const bool saved_batch = SetBatchCommandMode (true);
Jim Ingham26c7bf92014-10-11 00:38:27 +00002350 CommandInterpreterRunOptions options;
2351 options.SetSilent (true);
2352 options.SetStopOnError (false);
2353 options.SetStopOnContinue (true);
2354
Greg Clayton340b0302014-02-05 17:57:57 +00002355 HandleCommandsFromFile (init_file,
Ed Masted78c9572014-04-20 00:31:37 +00002356 nullptr, // Execution context
Jim Ingham26c7bf92014-10-11 00:38:27 +00002357 options,
Greg Clayton340b0302014-02-05 17:57:57 +00002358 result);
Greg Clayton44d93782014-01-27 23:43:24 +00002359 SetBatchCommandMode (saved_batch);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002360 }
2361 else
2362 {
2363 // nothing to be done if the file doesn't exist
2364 result.SetStatus(eReturnStatusSuccessFinishNoResult);
2365 }
2366}
2367
Kate Stonea487aa42015-01-15 00:52:41 +00002368const char *
2369CommandInterpreter::GetCommandPrefix()
2370{
2371 const char * prefix = GetDebugger().GetIOHandlerCommandPrefix();
2372 return prefix == NULL ? "" : prefix;
2373}
2374
Greg Clayton8b82f082011-04-12 05:54:46 +00002375PlatformSP
2376CommandInterpreter::GetPlatform (bool prefer_target_platform)
2377{
2378 PlatformSP platform_sp;
Greg Claytonc14ee322011-09-22 04:58:26 +00002379 if (prefer_target_platform)
2380 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002381 ExecutionContext exe_ctx(GetExecutionContext());
2382 Target *target = exe_ctx.GetTargetPtr();
Greg Claytonc14ee322011-09-22 04:58:26 +00002383 if (target)
2384 platform_sp = target->GetPlatform();
2385 }
Greg Clayton8b82f082011-04-12 05:54:46 +00002386
2387 if (!platform_sp)
2388 platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform();
2389 return platform_sp;
2390}
2391
Jim Inghame16c50a2011-02-18 00:54:25 +00002392void
Jim Inghambad87fe2011-03-11 01:51:49 +00002393CommandInterpreter::HandleCommands (const StringList &commands,
Jim Ingham26c7bf92014-10-11 00:38:27 +00002394 ExecutionContext *override_context,
2395 CommandInterpreterRunOptions &options,
Jim Inghame16c50a2011-02-18 00:54:25 +00002396 CommandReturnObject &result)
2397{
2398 size_t num_lines = commands.GetSize();
Jim Inghame16c50a2011-02-18 00:54:25 +00002399
2400 // If we are going to continue past a "continue" then we need to run the commands synchronously.
2401 // Make sure you reset this value anywhere you return from the function.
2402
2403 bool old_async_execution = m_debugger.GetAsyncExecution();
2404
2405 // If we've been given an execution context, set it at the start, but don't keep resetting it or we will
2406 // cause series of commands that change the context, then do an operation that relies on that context to fail.
2407
Ed Masted78c9572014-04-20 00:31:37 +00002408 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002409 UpdateExecutionContext (override_context);
Jim Inghame16c50a2011-02-18 00:54:25 +00002410
Jim Ingham26c7bf92014-10-11 00:38:27 +00002411 if (!options.GetStopOnContinue())
Jim Inghame16c50a2011-02-18 00:54:25 +00002412 {
2413 m_debugger.SetAsyncExecution (false);
2414 }
2415
Andy Gibbsa297a972013-06-19 19:04:53 +00002416 for (size_t idx = 0; idx < num_lines; idx++)
Jim Inghame16c50a2011-02-18 00:54:25 +00002417 {
2418 const char *cmd = commands.GetStringAtIndex(idx);
2419 if (cmd[0] == '\0')
2420 continue;
2421
Jim Ingham26c7bf92014-10-11 00:38:27 +00002422 if (options.GetEchoCommands())
Jim Inghame16c50a2011-02-18 00:54:25 +00002423 {
2424 result.AppendMessageWithFormat ("%s %s\n",
Greg Clayton44d93782014-01-27 23:43:24 +00002425 m_debugger.GetPrompt(),
2426 cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002427 }
2428
Greg Clayton9d0402b2011-02-20 02:15:07 +00002429 CommandReturnObject tmp_result;
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002430 // If override_context is not NULL, pass no_context_switching = true for
2431 // HandleCommand() since we updated our context already.
Jim Ingham076b7fc2013-05-02 23:15:37 +00002432
2433 // We might call into a regex or alias command, in which case the add_to_history will get lost. This
2434 // 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 +00002435 if (!options.GetAddToHistory())
Jim Ingham076b7fc2013-05-02 23:15:37 +00002436 m_command_source_depth++;
Jim Ingham26c7bf92014-10-11 00:38:27 +00002437 bool success = HandleCommand(cmd, options.m_add_to_history, tmp_result,
Ed Masted78c9572014-04-20 00:31:37 +00002438 nullptr, /* override_context */
Johnny Chen80fdd7c2011-10-05 00:42:59 +00002439 true, /* repeat_on_empty_command */
Ed Masted78c9572014-04-20 00:31:37 +00002440 override_context != nullptr /* no_context_switching */);
Jim Ingham26c7bf92014-10-11 00:38:27 +00002441 if (!options.GetAddToHistory())
Jim Ingham076b7fc2013-05-02 23:15:37 +00002442 m_command_source_depth--;
Jim Inghame16c50a2011-02-18 00:54:25 +00002443
Jim Ingham26c7bf92014-10-11 00:38:27 +00002444 if (options.GetPrintResults())
Jim Inghame16c50a2011-02-18 00:54:25 +00002445 {
2446 if (tmp_result.Succeeded())
Jim Ingham85e8b812011-02-19 02:53:09 +00002447 result.AppendMessageWithFormat("%s", tmp_result.GetOutputData());
Jim Inghame16c50a2011-02-18 00:54:25 +00002448 }
2449
2450 if (!success || !tmp_result.Succeeded())
2451 {
Jim Inghama5038812012-04-24 02:25:07 +00002452 const char *error_msg = tmp_result.GetErrorData();
Ed Masted78c9572014-04-20 00:31:37 +00002453 if (error_msg == nullptr || error_msg[0] == '\0')
Jim Inghama5038812012-04-24 02:25:07 +00002454 error_msg = "<unknown error>.\n";
Jim Ingham26c7bf92014-10-11 00:38:27 +00002455 if (options.GetStopOnError())
Jim Inghame16c50a2011-02-18 00:54:25 +00002456 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002457 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s",
2458 (uint64_t)idx, cmd, error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002459 result.SetStatus (eReturnStatusFailed);
2460 m_debugger.SetAsyncExecution (old_async_execution);
2461 return;
2462 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002463 else if (options.GetPrintResults())
Jim Inghame16c50a2011-02-18 00:54:25 +00002464 {
Deepak Panickal99fbc072014-03-03 15:39:47 +00002465 result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s",
2466 (uint64_t)idx + 1,
Jim Inghame16c50a2011-02-18 00:54:25 +00002467 cmd,
Jim Inghama5038812012-04-24 02:25:07 +00002468 error_msg);
Jim Inghame16c50a2011-02-18 00:54:25 +00002469 }
2470 }
2471
Caroline Tice969ed3d2011-05-02 20:41:46 +00002472 if (result.GetImmediateOutputStream())
2473 result.GetImmediateOutputStream()->Flush();
2474
2475 if (result.GetImmediateErrorStream())
2476 result.GetImmediateErrorStream()->Flush();
2477
Jim Inghame16c50a2011-02-18 00:54:25 +00002478 // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution
2479 // could be running (for instance in Breakpoint Commands.
2480 // So we check the return value to see if it is has running in it.
2481 if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult)
2482 || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult))
2483 {
Jim Ingham26c7bf92014-10-11 00:38:27 +00002484 if (options.GetStopOnContinue())
Jim Inghame16c50a2011-02-18 00:54:25 +00002485 {
2486 // If we caused the target to proceed, and we're going to stop in that case, set the
2487 // status in our real result before returning. This is an error if the continue was not the
2488 // last command in the set of commands to be run.
2489 if (idx != num_lines - 1)
Deepak Panickal99fbc072014-03-03 15:39:47 +00002490 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n",
2491 (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002492 else
Deepak Panickal99fbc072014-03-03 15:39:47 +00002493 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd);
Jim Inghame16c50a2011-02-18 00:54:25 +00002494
2495 result.SetStatus(tmp_result.GetStatus());
2496 m_debugger.SetAsyncExecution (old_async_execution);
2497
2498 return;
2499 }
2500 }
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002501
2502 // Also check for "stop on crash here:
2503 bool should_stop = false;
2504 if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash())
2505 {
2506 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2507 if (target_sp)
2508 {
2509 ProcessSP process_sp (target_sp->GetProcessSP());
2510 if (process_sp)
2511 {
2512 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads())
2513 {
2514 StopReason reason = thread_sp->GetStopReason();
2515 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation)
2516 {
2517 should_stop = true;
2518 break;
2519 }
2520 }
2521 }
2522 }
2523 if (should_stop)
2524 {
2525 if (idx != num_lines - 1)
2526 result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' stopped with a signal or exception.\n",
2527 (uint64_t)idx + 1, cmd);
2528 else
2529 result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' stopped with a signal or exception.\n", (uint64_t)idx + 1, cmd);
2530
2531 result.SetStatus(tmp_result.GetStatus());
2532 m_debugger.SetAsyncExecution (old_async_execution);
2533
2534 return;
2535 }
2536 }
Jim Inghame16c50a2011-02-18 00:54:25 +00002537
2538 }
2539
2540 result.SetStatus (eReturnStatusSuccessFinishResult);
2541 m_debugger.SetAsyncExecution (old_async_execution);
2542
2543 return;
2544}
2545
Greg Clayton340b0302014-02-05 17:57:57 +00002546// Make flags that we can pass into the IOHandler so our delegates can do the right thing
2547enum {
2548 eHandleCommandFlagStopOnContinue = (1u << 0),
2549 eHandleCommandFlagStopOnError = (1u << 1),
2550 eHandleCommandFlagEchoCommand = (1u << 2),
Jim Ingham26c7bf92014-10-11 00:38:27 +00002551 eHandleCommandFlagPrintResult = (1u << 3),
2552 eHandleCommandFlagStopOnCrash = (1u << 4)
Greg Clayton340b0302014-02-05 17:57:57 +00002553};
2554
Jim Inghame16c50a2011-02-18 00:54:25 +00002555void
2556CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file,
2557 ExecutionContext *context,
Jim Ingham26c7bf92014-10-11 00:38:27 +00002558 CommandInterpreterRunOptions &options,
Jim Inghame16c50a2011-02-18 00:54:25 +00002559 CommandReturnObject &result)
2560{
2561 if (cmd_file.Exists())
2562 {
Greg Clayton44d93782014-01-27 23:43:24 +00002563 StreamFileSP input_file_sp (new StreamFile());
2564
2565 std::string cmd_file_path = cmd_file.GetPath();
2566 Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead);
2567
2568 if (error.Success())
2569 {
2570 Debugger &debugger = GetDebugger();
2571
Greg Clayton340b0302014-02-05 17:57:57 +00002572 uint32_t flags = 0;
2573
Jim Ingham26c7bf92014-10-11 00:38:27 +00002574 if (options.m_stop_on_continue == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002575 {
2576 if (m_command_source_flags.empty())
2577 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002578 // Stop on continue by default
Greg Clayton340b0302014-02-05 17:57:57 +00002579 flags |= eHandleCommandFlagStopOnContinue;
2580 }
2581 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue)
2582 {
2583 flags |= eHandleCommandFlagStopOnContinue;
2584 }
2585 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002586 else if (options.m_stop_on_continue == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002587 {
2588 flags |= eHandleCommandFlagStopOnContinue;
2589 }
2590
Jim Ingham26c7bf92014-10-11 00:38:27 +00002591 if (options.m_stop_on_error == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002592 {
2593 if (m_command_source_flags.empty())
2594 {
2595 if (GetStopCmdSourceOnError())
2596 flags |= eHandleCommandFlagStopOnError;
2597 }
2598 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError)
2599 {
2600 flags |= eHandleCommandFlagStopOnError;
2601 }
2602 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002603 else if (options.m_stop_on_error == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002604 {
2605 flags |= eHandleCommandFlagStopOnError;
2606 }
2607
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002608 if (options.GetStopOnCrash())
2609 {
2610 if (m_command_source_flags.empty())
2611 {
2612 // Echo command by default
2613 flags |= eHandleCommandFlagStopOnCrash;
2614 }
2615 else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash)
2616 {
2617 flags |= eHandleCommandFlagStopOnCrash;
2618 }
2619 }
2620
Jim Ingham26c7bf92014-10-11 00:38:27 +00002621 if (options.m_echo_commands == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002622 {
2623 if (m_command_source_flags.empty())
2624 {
2625 // Echo command by default
2626 flags |= eHandleCommandFlagEchoCommand;
2627 }
2628 else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand)
2629 {
2630 flags |= eHandleCommandFlagEchoCommand;
2631 }
2632 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002633 else if (options.m_echo_commands == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002634 {
2635 flags |= eHandleCommandFlagEchoCommand;
2636 }
2637
Jim Ingham26c7bf92014-10-11 00:38:27 +00002638 if (options.m_print_results == eLazyBoolCalculate)
Greg Clayton340b0302014-02-05 17:57:57 +00002639 {
2640 if (m_command_source_flags.empty())
2641 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002642 // Print output by default
2643 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002644 }
Greg Claytone4e462c2014-02-05 21:03:22 +00002645 else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult)
Greg Clayton340b0302014-02-05 17:57:57 +00002646 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002647 flags |= eHandleCommandFlagPrintResult;
Greg Clayton340b0302014-02-05 17:57:57 +00002648 }
2649 }
Jim Ingham26c7bf92014-10-11 00:38:27 +00002650 else if (options.m_print_results == eLazyBoolYes)
Greg Clayton340b0302014-02-05 17:57:57 +00002651 {
Greg Claytone4e462c2014-02-05 21:03:22 +00002652 flags |= eHandleCommandFlagPrintResult;
2653 }
2654
2655 if (flags & eHandleCommandFlagPrintResult)
2656 {
Greg Clayton8ee67312014-02-05 21:46:20 +00002657 debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str());
Greg Clayton340b0302014-02-05 17:57:57 +00002658 }
2659
2660 // Used for inheriting the right settings when "command source" might have
2661 // nested "command source" commands
Greg Claytone4e462c2014-02-05 21:03:22 +00002662 lldb::StreamFileSP empty_stream_sp;
Greg Clayton340b0302014-02-05 17:57:57 +00002663 m_command_source_flags.push_back(flags);
Greg Clayton44d93782014-01-27 23:43:24 +00002664 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00002665 IOHandler::Type::CommandInterpreter,
Greg Clayton44d93782014-01-27 23:43:24 +00002666 input_file_sp,
Greg Claytone4e462c2014-02-05 21:03:22 +00002667 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream
2668 empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream
Greg Clayton340b0302014-02-05 17:57:57 +00002669 flags,
Ed Masted78c9572014-04-20 00:31:37 +00002670 nullptr, // Pass in NULL for "editline_name" so no history is saved, or written
Greg Clayton8ee67312014-02-05 21:46:20 +00002671 debugger.GetPrompt(),
Kate Stonee30f11d2014-11-17 19:06:59 +00002672 NULL,
Greg Clayton44d93782014-01-27 23:43:24 +00002673 false, // Not multi-line
Kate Stonee30f11d2014-11-17 19:06:59 +00002674 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00002675 0,
Greg Clayton44d93782014-01-27 23:43:24 +00002676 *this));
Greg Clayton8ee67312014-02-05 21:46:20 +00002677 const bool old_async_execution = debugger.GetAsyncExecution();
2678
Jim Inghamffc9f1d2014-10-14 01:20:07 +00002679 // Set synchronous execution if we are not stopping on continue
Greg Clayton8ee67312014-02-05 21:46:20 +00002680 if ((flags & eHandleCommandFlagStopOnContinue) == 0)
2681 debugger.SetAsyncExecution (false);
2682
Greg Clayton340b0302014-02-05 17:57:57 +00002683 m_command_source_depth++;
Greg Clayton8ee67312014-02-05 21:46:20 +00002684
2685 debugger.RunIOHandler(io_handler_sp);
Greg Clayton340b0302014-02-05 17:57:57 +00002686 if (!m_command_source_flags.empty())
2687 m_command_source_flags.pop_back();
2688 m_command_source_depth--;
Greg Clayton44d93782014-01-27 23:43:24 +00002689 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Greg Clayton8ee67312014-02-05 21:46:20 +00002690 debugger.SetAsyncExecution (old_async_execution);
Greg Clayton44d93782014-01-27 23:43:24 +00002691 }
2692 else
2693 {
2694 result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString());
2695 result.SetStatus (eReturnStatusFailed);
2696 }
Greg Clayton8ee67312014-02-05 21:46:20 +00002697
2698
Jim Inghame16c50a2011-02-18 00:54:25 +00002699 }
2700 else
2701 {
2702 result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n",
Jim Ingham4af59612014-12-19 19:20:44 +00002703 cmd_file.GetFilename().AsCString("<Unknown>"));
Jim Inghame16c50a2011-02-18 00:54:25 +00002704 result.SetStatus (eReturnStatusFailed);
2705 return;
2706 }
2707}
2708
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002709ScriptInterpreter *
Enrico Granatab5887262012-10-29 21:18:03 +00002710CommandInterpreter::GetScriptInterpreter (bool can_create)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002711{
Ed Masted78c9572014-04-20 00:31:37 +00002712 if (m_script_interpreter_ap.get() != nullptr)
Enrico Granatab5887262012-10-29 21:18:03 +00002713 return m_script_interpreter_ap.get();
2714
2715 if (!can_create)
Ed Masted78c9572014-04-20 00:31:37 +00002716 return nullptr;
Enrico Granatab5887262012-10-29 21:18:03 +00002717
Enrico Granataa29bdad2012-07-10 18:23:48 +00002718 // <rdar://problem/11751427>
2719 // we need to protect the initialization of the script interpreter
2720 // otherwise we could end up with two threads both trying to create
2721 // their instance of it, and for some languages (e.g. Python)
2722 // this is a bulletproof recipe for disaster!
2723 // this needs to be a function-level static because multiple Debugger instances living in the same process
2724 // still need to be isolated and not try to initialize Python concurrently
Enrico Granata8b95df22012-07-10 19:04:14 +00002725 static Mutex g_interpreter_mutex(Mutex::eMutexTypeRecursive);
2726 Mutex::Locker interpreter_lock(g_interpreter_mutex);
Enrico Granataa29bdad2012-07-10 18:23:48 +00002727
Greg Clayton5160ce52013-03-27 23:08:40 +00002728 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
Enrico Granatab5887262012-10-29 21:18:03 +00002729 if (log)
2730 log->Printf("Initializing the ScriptInterpreter now\n");
Greg Clayton66111032010-06-23 01:19:29 +00002731
Caroline Tice2f88aad2011-01-14 00:29:16 +00002732 lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage();
2733 switch (script_lang)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002734 {
Greg Claytondce502e2011-11-04 03:34:56 +00002735 case eScriptLanguagePython:
2736#ifndef LLDB_DISABLE_PYTHON
2737 m_script_interpreter_ap.reset (new ScriptInterpreterPython (*this));
2738 break;
2739#else
2740 // Fall through to the None case when python is disabled
2741#endif
Caroline Tice2f88aad2011-01-14 00:29:16 +00002742 case eScriptLanguageNone:
2743 m_script_interpreter_ap.reset (new ScriptInterpreterNone (*this));
2744 break;
Caroline Tice2f88aad2011-01-14 00:29:16 +00002745 };
2746
2747 return m_script_interpreter_ap.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002748}
2749
2750
2751
2752bool
2753CommandInterpreter::GetSynchronous ()
2754{
2755 return m_synchronous_execution;
2756}
2757
2758void
2759CommandInterpreter::SetSynchronous (bool value)
2760{
Johnny Chenc066ab42010-10-14 01:22:03 +00002761 m_synchronous_execution = value;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002762}
2763
2764void
2765CommandInterpreter::OutputFormattedHelpText (Stream &strm,
Kate Stonea487aa42015-01-15 00:52:41 +00002766 const char *prefix,
2767 const char *help_text)
2768{
2769 const uint32_t max_columns = m_debugger.GetTerminalWidth();
2770 if (prefix == NULL)
2771 prefix = "";
2772
2773 size_t prefix_width = strlen(prefix);
2774 size_t line_width_max = max_columns - prefix_width;
2775 const char *help_text_end = help_text + strlen(help_text);
2776 const char *line_start = help_text;
2777 if (line_width_max < 16)
2778 line_width_max = help_text_end - help_text + prefix_width;
2779
2780 strm.IndentMore (prefix_width);
2781 while (line_start < help_text_end)
2782 {
2783 // Break each line at the first newline or last space/tab before
2784 // the maximum number of characters that fit on a line. Lines with no
2785 // natural break are left unbroken to wrap.
2786 const char *line_end = help_text_end;
2787 const char *line_scan = line_start;
2788 const char *line_scan_end = help_text_end;
2789 while (line_scan < line_scan_end)
2790 {
2791 char next = *line_scan;
2792 if (next == '\t' || next == ' ')
2793 {
2794 line_end = line_scan;
2795 line_scan_end = line_start + line_width_max;
2796 }
2797 else if (next == '\n' || next == '\0')
2798 {
2799 line_end = line_scan;
2800 break;
2801 }
2802 ++line_scan;
2803 }
2804
2805 // Prefix the first line, indent subsequent lines to line up
2806 if (line_start == help_text)
2807 strm.Write (prefix, prefix_width);
2808 else
2809 strm.Indent();
2810 strm.Write (line_start, line_end - line_start);
2811 strm.EOL();
2812
2813 // When a line breaks at whitespace consume it before continuing
2814 line_start = line_end;
2815 char next = *line_start;
2816 if (next == '\n')
2817 ++line_start;
2818 else while (next == ' ' || next == '\t')
2819 next = *(++line_start);
2820 }
2821 strm.IndentLess (prefix_width);
2822}
2823
2824void
2825CommandInterpreter::OutputFormattedHelpText (Stream &strm,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002826 const char *word_text,
2827 const char *separator,
2828 const char *help_text,
Greg Claytonc7bece562013-01-25 18:06:21 +00002829 size_t max_word_len)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002830{
Kate Stonea487aa42015-01-15 00:52:41 +00002831 StreamString prefix_stream;
2832 prefix_stream.Printf (" %-*s %s ", (int)max_word_len, word_text, separator);
2833 OutputFormattedHelpText (strm, prefix_stream.GetData(), help_text);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002834}
2835
2836void
Enrico Granata82a7d982011-07-07 00:38:40 +00002837CommandInterpreter::OutputHelpText (Stream &strm,
2838 const char *word_text,
2839 const char *separator,
2840 const char *help_text,
2841 uint32_t max_word_len)
2842{
2843 int indent_size = max_word_len + strlen (separator) + 2;
2844
2845 strm.IndentMore (indent_size);
2846
2847 StreamString text_strm;
2848 text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text);
2849
2850 const uint32_t max_columns = m_debugger.GetTerminalWidth();
Enrico Granata82a7d982011-07-07 00:38:40 +00002851
2852 size_t len = text_strm.GetSize();
2853 const char *text = text_strm.GetData();
2854
2855 uint32_t chars_left = max_columns;
2856
2857 for (uint32_t i = 0; i < len; i++)
2858 {
2859 if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n')
2860 {
Enrico Granata82a7d982011-07-07 00:38:40 +00002861 chars_left = max_columns - indent_size;
2862 strm.EOL();
2863 strm.Indent();
2864 }
2865 else
2866 {
2867 strm.PutChar(text[i]);
2868 chars_left--;
2869 }
2870
2871 }
2872
2873 strm.EOL();
2874 strm.IndentLess(indent_size);
2875}
2876
2877void
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002878CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found,
Jim Inghamaf3753e2013-05-17 01:30:37 +00002879 StringList &commands_help, bool search_builtin_commands, bool search_user_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002880{
2881 CommandObject::CommandMap::const_iterator pos;
2882
Jim Inghamaf3753e2013-05-17 01:30:37 +00002883 if (search_builtin_commands)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002884 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002885 for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002886 {
Jim Inghamaf3753e2013-05-17 01:30:37 +00002887 const char *command_name = pos->first.c_str();
2888 CommandObject *cmd_obj = pos->second.get();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002889
Jim Inghamaf3753e2013-05-17 01:30:37 +00002890 if (cmd_obj->HelpTextContainsWord (search_word))
2891 {
2892 commands_found.AppendString (command_name);
2893 commands_help.AppendString (cmd_obj->GetHelp());
2894 }
2895
2896 if (cmd_obj->IsMultiwordObject())
2897 cmd_obj->AproposAllSubCommands (command_name,
2898 search_word,
2899 commands_found,
2900 commands_help);
2901
2902 }
2903 }
2904
2905 if (search_user_commands)
2906 {
2907 for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos)
2908 {
2909 const char *command_name = pos->first.c_str();
2910 CommandObject *cmd_obj = pos->second.get();
2911
2912 if (cmd_obj->HelpTextContainsWord (search_word))
2913 {
2914 commands_found.AppendString (command_name);
2915 commands_help.AppendString (cmd_obj->GetHelp());
2916 }
2917
2918 if (cmd_obj->IsMultiwordObject())
2919 cmd_obj->AproposAllSubCommands (command_name,
2920 search_word,
2921 commands_found,
2922 commands_help);
2923
2924 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002925 }
2926}
Greg Clayton8b82f082011-04-12 05:54:46 +00002927
Greg Clayton8b82f082011-04-12 05:54:46 +00002928void
2929CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context)
2930{
Ed Masted78c9572014-04-20 00:31:37 +00002931 if (override_context != nullptr)
Greg Clayton8b82f082011-04-12 05:54:46 +00002932 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002933 m_exe_ctx_ref = *override_context;
Greg Clayton8b82f082011-04-12 05:54:46 +00002934 }
2935 else
2936 {
Greg Clayton4e0fe8a2012-07-12 20:32:19 +00002937 const bool adopt_selected = true;
2938 m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected);
Greg Clayton8b82f082011-04-12 05:54:46 +00002939 }
2940}
Greg Clayton44d93782014-01-27 23:43:24 +00002941
2942
2943size_t
2944CommandInterpreter::GetProcessOutput ()
2945{
2946 // The process has stuff waiting for stderr; get it and write it out to the appropriate place.
2947 char stdio_buffer[1024];
2948 size_t len;
2949 size_t total_bytes = 0;
2950 Error error;
2951 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
2952 if (target_sp)
2953 {
2954 ProcessSP process_sp (target_sp->GetProcessSP());
2955 if (process_sp)
2956 {
2957 while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2958 {
2959 size_t bytes_written = len;
2960 m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written);
2961 total_bytes += len;
2962 }
2963 while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0)
2964 {
2965 size_t bytes_written = len;
2966 m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written);
2967 total_bytes += len;
2968 }
2969 }
2970 }
2971 return total_bytes;
2972}
2973
2974void
2975CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line)
2976{
Greg Clayton340b0302014-02-05 17:57:57 +00002977 const bool is_interactive = io_handler.GetIsInteractive();
2978 if (is_interactive == false)
2979 {
2980 // When we are not interactive, don't execute blank lines. This will happen
2981 // sourcing a commands file. We don't want blank lines to repeat the previous
2982 // command and cause any errors to occur (like redefining an alias, get an error
2983 // and stop parsing the commands file).
2984 if (line.empty())
2985 return;
2986
2987 // When using a non-interactive file handle (like when sourcing commands from a file)
2988 // we need to echo the command out so we don't just see the command output and no
2989 // command...
2990 if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand))
2991 io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str());
2992 }
2993
Greg Clayton44d93782014-01-27 23:43:24 +00002994 lldb_private::CommandReturnObject result;
2995 HandleCommand(line.c_str(), eLazyBoolCalculate, result);
2996
Greg Clayton44d93782014-01-27 23:43:24 +00002997 // Now emit the command output text from the command we just executed
Greg Clayton340b0302014-02-05 17:57:57 +00002998 if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult))
2999 {
3000 // Display any STDOUT/STDERR _prior_ to emitting the command result text
3001 GetProcessOutput ();
3002
Greg Clayton8ee67312014-02-05 21:46:20 +00003003 if (!result.GetImmediateOutputStream())
3004 {
3005 const char *output = result.GetOutputData();
3006 if (output && output[0])
3007 io_handler.GetOutputStreamFile()->PutCString(output);
3008 }
Greg Clayton44d93782014-01-27 23:43:24 +00003009
Greg Clayton340b0302014-02-05 17:57:57 +00003010 // Now emit the command error text from the command we just executed
Greg Clayton8ee67312014-02-05 21:46:20 +00003011 if (!result.GetImmediateErrorStream())
3012 {
3013 const char *error = result.GetErrorData();
3014 if (error && error[0])
3015 io_handler.GetErrorStreamFile()->PutCString(error);
3016 }
Greg Clayton340b0302014-02-05 17:57:57 +00003017 }
Greg Clayton44d93782014-01-27 23:43:24 +00003018
3019 switch (result.GetStatus())
3020 {
3021 case eReturnStatusInvalid:
3022 case eReturnStatusSuccessFinishNoResult:
3023 case eReturnStatusSuccessFinishResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003024 case eReturnStatusStarted:
3025 break;
3026
Greg Clayton44d93782014-01-27 23:43:24 +00003027 case eReturnStatusSuccessContinuingNoResult:
3028 case eReturnStatusSuccessContinuingResult:
Greg Clayton340b0302014-02-05 17:57:57 +00003029 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue))
3030 io_handler.SetIsDone(true);
3031 break;
3032
Greg Clayton44d93782014-01-27 23:43:24 +00003033 case eReturnStatusFailed:
Jim Ingham26c7bf92014-10-11 00:38:27 +00003034 m_num_errors++;
Greg Clayton340b0302014-02-05 17:57:57 +00003035 if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError))
3036 io_handler.SetIsDone(true);
Greg Clayton44d93782014-01-27 23:43:24 +00003037 break;
3038
3039 case eReturnStatusQuit:
Jim Ingham26c7bf92014-10-11 00:38:27 +00003040 m_quit_requested = true;
Greg Clayton44d93782014-01-27 23:43:24 +00003041 io_handler.SetIsDone(true);
3042 break;
3043 }
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003044
3045 // Finally, if we're going to stop on crash, check that here:
3046 if (!m_quit_requested
3047 && result.GetDidChangeProcessState()
3048 && io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash))
3049 {
3050 bool should_stop = false;
3051 TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget());
3052 if (target_sp)
3053 {
3054 ProcessSP process_sp (target_sp->GetProcessSP());
3055 if (process_sp)
3056 {
3057 for (ThreadSP thread_sp : process_sp->GetThreadList().Threads())
3058 {
3059 StopReason reason = thread_sp->GetStopReason();
3060 if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation)
3061 {
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003062 should_stop = true;
3063 break;
3064 }
3065 }
3066 }
3067 }
3068 if (should_stop)
3069 {
3070 io_handler.SetIsDone(true);
3071 m_stopped_for_crash = true;
3072 }
3073 }
Greg Clayton44d93782014-01-27 23:43:24 +00003074}
3075
Greg Claytonf0066ad2014-05-02 00:45:31 +00003076bool
3077CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler)
3078{
3079 ExecutionContext exe_ctx (GetExecutionContext());
3080 Process *process = exe_ctx.GetProcessPtr();
3081
3082 if (process)
3083 {
3084 StateType state = process->GetState();
3085 if (StateIsRunningState(state))
3086 {
3087 process->Halt();
3088 return true; // Don't do any updating when we are running
3089 }
3090 }
Greg Claytone507bce2015-01-27 01:58:22 +00003091
3092 ScriptInterpreter *script_interpreter = GetScriptInterpreter (false);
3093 if (script_interpreter)
3094 {
3095 if (script_interpreter->Interrupt())
3096 return true;
3097 }
Greg Claytonf0066ad2014-05-02 00:45:31 +00003098 return false;
3099}
3100
Greg Clayton44d93782014-01-27 23:43:24 +00003101void
3102CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt,
3103 IOHandlerDelegate &delegate,
3104 bool asynchronously,
3105 void *baton)
3106{
3107 Debugger &debugger = GetDebugger();
3108 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00003109 IOHandler::Type::CommandList,
Greg Clayton44d93782014-01-27 23:43:24 +00003110 "lldb", // Name of input reader for history
3111 prompt, // Prompt
Kate Stonee30f11d2014-11-17 19:06:59 +00003112 NULL, // Continuation prompt
Greg Clayton44d93782014-01-27 23:43:24 +00003113 true, // Get multiple lines
Kate Stonee30f11d2014-11-17 19:06:59 +00003114 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00003115 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003116 delegate)); // IOHandlerDelegate
3117
3118 if (io_handler_sp)
3119 {
3120 io_handler_sp->SetUserData (baton);
3121 if (asynchronously)
3122 debugger.PushIOHandler(io_handler_sp);
3123 else
3124 debugger.RunIOHandler(io_handler_sp);
3125 }
3126
3127}
3128
3129
3130void
3131CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt,
3132 IOHandlerDelegate &delegate,
3133 bool asynchronously,
3134 void *baton)
3135{
3136 Debugger &debugger = GetDebugger();
3137 IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger,
Kate Stonee30f11d2014-11-17 19:06:59 +00003138 IOHandler::Type::PythonCode,
Greg Clayton44d93782014-01-27 23:43:24 +00003139 "lldb-python", // Name of input reader for history
3140 prompt, // Prompt
Kate Stonee30f11d2014-11-17 19:06:59 +00003141 NULL, // Continuation prompt
Greg Clayton44d93782014-01-27 23:43:24 +00003142 true, // Get multiple lines
Kate Stonee30f11d2014-11-17 19:06:59 +00003143 debugger.GetUseColor(),
Greg Claytonf6913cd2014-03-07 00:53:24 +00003144 0, // Don't show line numbers
Greg Clayton44d93782014-01-27 23:43:24 +00003145 delegate)); // IOHandlerDelegate
3146
3147 if (io_handler_sp)
3148 {
3149 io_handler_sp->SetUserData (baton);
3150 if (asynchronously)
3151 debugger.PushIOHandler(io_handler_sp);
3152 else
3153 debugger.RunIOHandler(io_handler_sp);
3154 }
3155
3156}
3157
3158bool
3159CommandInterpreter::IsActive ()
3160{
3161 return m_debugger.IsTopIOHandler (m_command_io_handler_sp);
3162}
3163
Kate Stonee30f11d2014-11-17 19:06:59 +00003164lldb::IOHandlerSP
3165CommandInterpreter::GetIOHandler(bool force_create, CommandInterpreterRunOptions *options)
3166{
3167 // Always re-create the IOHandlerEditline in case the input
3168 // changed. The old instance might have had a non-interactive
3169 // input and now it does or vice versa.
3170 if (force_create || !m_command_io_handler_sp)
3171 {
3172 // Always re-create the IOHandlerEditline in case the input
3173 // changed. The old instance might have had a non-interactive
3174 // input and now it does or vice versa.
3175 uint32_t flags = 0;
3176
3177 if (options)
3178 {
3179 if (options->m_stop_on_continue == eLazyBoolYes)
3180 flags |= eHandleCommandFlagStopOnContinue;
3181 if (options->m_stop_on_error == eLazyBoolYes)
3182 flags |= eHandleCommandFlagStopOnError;
3183 if (options->m_stop_on_crash == eLazyBoolYes)
3184 flags |= eHandleCommandFlagStopOnCrash;
3185 if (options->m_echo_commands != eLazyBoolNo)
3186 flags |= eHandleCommandFlagEchoCommand;
3187 if (options->m_print_results != eLazyBoolNo)
3188 flags |= eHandleCommandFlagPrintResult;
3189 }
3190 else
3191 {
3192 flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult;
3193 }
3194
3195 m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger,
3196 IOHandler::Type::CommandInterpreter,
3197 m_debugger.GetInputFile(),
3198 m_debugger.GetOutputFile(),
3199 m_debugger.GetErrorFile(),
3200 flags,
3201 "lldb",
3202 m_debugger.GetPrompt(),
3203 NULL, // Continuation prompt
3204 false, // Don't enable multiple line input, just single line commands
3205 m_debugger.GetUseColor(),
3206 0, // Don't show line numbers
3207 *this));
3208 }
3209 return m_command_io_handler_sp;
3210}
3211
Greg Clayton44d93782014-01-27 23:43:24 +00003212void
3213CommandInterpreter::RunCommandInterpreter(bool auto_handle_events,
Jim Ingham26c7bf92014-10-11 00:38:27 +00003214 bool spawn_thread,
3215 CommandInterpreterRunOptions &options)
Greg Clayton44d93782014-01-27 23:43:24 +00003216{
Bruce Mitchener58ef3912015-06-18 05:27:05 +00003217 // Always re-create the command interpreter when we run it in case
Kate Stonee30f11d2014-11-17 19:06:59 +00003218 // any file handles have changed.
3219 bool force_create = true;
3220 m_debugger.PushIOHandler(GetIOHandler(force_create, &options));
Jim Inghamffc9f1d2014-10-14 01:20:07 +00003221 m_stopped_for_crash = false;
Greg Clayton380f3d82014-07-31 19:46:19 +00003222
Greg Clayton44d93782014-01-27 23:43:24 +00003223 if (auto_handle_events)
3224 m_debugger.StartEventHandlerThread();
3225
3226 if (spawn_thread)
3227 {
3228 m_debugger.StartIOHandlerThread();
3229 }
3230 else
3231 {
Siva Chandra9aaab552015-02-26 19:26:36 +00003232 m_debugger.ExecuteIOHandlers();
Kate Stonee30f11d2014-11-17 19:06:59 +00003233
Greg Clayton44d93782014-01-27 23:43:24 +00003234 if (auto_handle_events)
3235 m_debugger.StopEventHandlerThread();
3236 }
Kate Stonee30f11d2014-11-17 19:06:59 +00003237
Greg Clayton44d93782014-01-27 23:43:24 +00003238}
3239
Adrian McCarthy2304b6f2015-04-23 20:00:25 +00003240CommandObject *
3241CommandInterpreter::ResolveCommandImpl(std::string &command_line, CommandReturnObject &result)
3242{
3243 std::string scratch_command(command_line); // working copy so we don't modify command_line unless we succeed
3244 CommandObject *cmd_obj = nullptr;
3245 StreamString revised_command_line;
3246 bool wants_raw_input = false;
3247 size_t actual_cmd_name_len = 0;
3248 std::string next_word;
3249 StringList matches;
3250 bool done = false;
3251 while (!done)
3252 {
3253 char quote_char = '\0';
3254 std::string suffix;
3255 ExtractCommand(scratch_command, next_word, suffix, quote_char);
3256 if (cmd_obj == nullptr)
3257 {
3258 std::string full_name;
3259 if (GetAliasFullName(next_word.c_str(), full_name))
3260 {
3261 std::string alias_result;
3262 cmd_obj = BuildAliasResult(full_name.c_str(), scratch_command, alias_result, result);
3263 revised_command_line.Printf("%s", alias_result.c_str());
3264 if (cmd_obj)
3265 {
3266 wants_raw_input = cmd_obj->WantsRawCommandString();
3267 actual_cmd_name_len = strlen(cmd_obj->GetCommandName());
3268 }
3269 }
3270 else
3271 {
3272 cmd_obj = GetCommandObject(next_word.c_str(), &matches);
3273 if (cmd_obj)
3274 {
3275 actual_cmd_name_len += strlen(cmd_obj->GetCommandName());
3276 revised_command_line.Printf("%s", cmd_obj->GetCommandName());
3277 wants_raw_input = cmd_obj->WantsRawCommandString();
3278 }
3279 else
3280 {
3281 revised_command_line.Printf ("%s", next_word.c_str());
3282 }
3283 }
3284 }
3285 else
3286 {
3287 if (cmd_obj->IsMultiwordObject ())
3288 {
3289 CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject(next_word.c_str());
3290 if (sub_cmd_obj)
3291 {
3292 // The subcommand's name includes the parent command's name,
3293 // so restart rather than append to the revised_command_line.
3294 actual_cmd_name_len = strlen(sub_cmd_obj->GetCommandName()) + 1;
3295 revised_command_line.Clear();
3296 revised_command_line.Printf("%s", sub_cmd_obj->GetCommandName());
3297 cmd_obj = sub_cmd_obj;
3298 wants_raw_input = cmd_obj->WantsRawCommandString();
3299 }
3300 else
3301 {
3302 if (quote_char)
3303 revised_command_line.Printf(" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
3304 else
3305 revised_command_line.Printf(" %s%s", next_word.c_str(), suffix.c_str());
3306 done = true;
3307 }
3308 }
3309 else
3310 {
3311 if (quote_char)
3312 revised_command_line.Printf(" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char);
3313 else
3314 revised_command_line.Printf(" %s%s", next_word.c_str(), suffix.c_str());
3315 done = true;
3316 }
3317 }
3318
3319 if (cmd_obj == nullptr)
3320 {
3321 const size_t num_matches = matches.GetSize();
3322 if (matches.GetSize() > 1) {
3323 StreamString error_msg;
3324 error_msg.Printf("Ambiguous command '%s'. Possible matches:\n", next_word.c_str());
3325
3326 for (uint32_t i = 0; i < num_matches; ++i) {
3327 error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i));
3328 }
3329 result.AppendRawError(error_msg.GetString().c_str());
3330 } else {
3331 // We didn't have only one match, otherwise we wouldn't get here.
3332 assert(num_matches == 0);
3333 result.AppendErrorWithFormat("'%s' is not a valid command.\n", next_word.c_str());
3334 }
3335 result.SetStatus(eReturnStatusFailed);
3336 return nullptr;
3337 }
3338
3339 if (cmd_obj->IsMultiwordObject())
3340 {
3341 if (!suffix.empty())
3342 {
3343 result.AppendErrorWithFormat("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n",
3344 cmd_obj->GetCommandName(),
3345 next_word.empty() ? "" : next_word.c_str(),
3346 next_word.empty() ? " -- " : " ",
3347 suffix.c_str());
3348 result.SetStatus(eReturnStatusFailed);
3349 return nullptr;
3350 }
3351 }
3352 else
3353 {
3354 // If we found a normal command, we are done
3355 done = true;
3356 if (!suffix.empty())
3357 {
3358 switch (suffix[0])
3359 {
3360 case '/':
3361 // GDB format suffixes
3362 {
3363 Options *command_options = cmd_obj->GetOptions();
3364 if (command_options && command_options->SupportsLongOption("gdb-format"))
3365 {
3366 std::string gdb_format_option("--gdb-format=");
3367 gdb_format_option += (suffix.c_str() + 1);
3368
3369 bool inserted = false;
3370 std::string &cmd = revised_command_line.GetString();
3371 size_t arg_terminator_idx = FindArgumentTerminator(cmd);
3372 if (arg_terminator_idx != std::string::npos)
3373 {
3374 // Insert the gdb format option before the "--" that terminates options
3375 gdb_format_option.append(1,' ');
3376 cmd.insert(arg_terminator_idx, gdb_format_option);
3377 inserted = true;
3378 }
3379
3380 if (!inserted)
3381 revised_command_line.Printf(" %s", gdb_format_option.c_str());
3382
3383 if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos)
3384 revised_command_line.PutCString(" --");
3385 }
3386 else
3387 {
3388 result.AppendErrorWithFormat("the '%s' command doesn't support the --gdb-format option\n",
3389 cmd_obj->GetCommandName());
3390 result.SetStatus(eReturnStatusFailed);
3391 return nullptr;
3392 }
3393 }
3394 break;
3395
3396 default:
3397 result.AppendErrorWithFormat("unknown command shorthand suffix: '%s'\n",
3398 suffix.c_str());
3399 result.SetStatus(eReturnStatusFailed);
3400 return nullptr;
3401 }
3402 }
3403 }
3404 if (scratch_command.empty())
3405 done = true;
3406 }
3407
3408 if (!scratch_command.empty())
3409 revised_command_line.Printf(" %s", scratch_command.c_str());
3410
3411 if (cmd_obj != NULL)
3412 command_line = revised_command_line.GetData();
3413
3414 return cmd_obj;
3415}