blob: cc38959e03cabc3aaa7b6c509035b011ef3fca9a [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandObjectProcess.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
Chris Lattner30fdc8d2010-06-08 16:52:24 +000010// C Includes
11// C++ Includes
12// Other libraries and framework includes
13// Project includes
Eugene Zelenko49bcfd82016-02-23 01:43:44 +000014#include "CommandObjectProcess.h"
Jim Ingham0e410842012-08-11 01:27:55 +000015#include "lldb/Breakpoint/Breakpoint.h"
16#include "lldb/Breakpoint/BreakpointLocation.h"
17#include "lldb/Breakpoint/BreakpointSite.h"
Greg Clayton1f746072012-08-29 21:13:06 +000018#include "lldb/Core/Module.h"
Greg Claytona2715cf2014-06-13 00:54:12 +000019#include "lldb/Core/PluginManager.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000020#include "lldb/Core/State.h"
Greg Clayton7260f622011-04-18 08:33:37 +000021#include "lldb/Host/Host.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000022#include "lldb/Host/StringConvert.h"
Jim Ingham0e410842012-08-11 01:27:55 +000023#include "lldb/Interpreter/Args.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Interpreter/CommandInterpreter.h"
25#include "lldb/Interpreter/CommandReturnObject.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000026#include "lldb/Interpreter/Options.h"
Greg Claytone996fd32011-03-08 22:40:15 +000027#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000028#include "lldb/Target/Process.h"
Jim Ingham0e410842012-08-11 01:27:55 +000029#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "lldb/Target/Target.h"
31#include "lldb/Target/Thread.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000032#include "lldb/Target/UnixSignals.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000033
34using namespace lldb;
35using namespace lldb_private;
36
Kate Stoneb9c1b512016-09-06 20:57:50 +000037class CommandObjectProcessLaunchOrAttach : public CommandObjectParsed {
Jim Inghamdcb1d852013-03-29 00:56:30 +000038public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000039 CommandObjectProcessLaunchOrAttach(CommandInterpreter &interpreter,
40 const char *name, const char *help,
41 const char *syntax, uint32_t flags,
42 const char *new_process_action)
43 : CommandObjectParsed(interpreter, name, help, syntax, flags),
44 m_new_process_action(new_process_action) {}
Eugene Zelenko49bcfd82016-02-23 01:43:44 +000045
Kate Stoneb9c1b512016-09-06 20:57:50 +000046 ~CommandObjectProcessLaunchOrAttach() override = default;
Eugene Zelenko49bcfd82016-02-23 01:43:44 +000047
Jim Inghamdcb1d852013-03-29 00:56:30 +000048protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +000049 bool StopProcessIfNecessary(Process *process, StateType &state,
50 CommandReturnObject &result) {
51 state = eStateInvalid;
52 if (process) {
53 state = process->GetState();
Eugene Zelenko49bcfd82016-02-23 01:43:44 +000054
Kate Stoneb9c1b512016-09-06 20:57:50 +000055 if (process->IsAlive() && state != eStateConnected) {
56 char message[1024];
57 if (process->GetState() == eStateAttaching)
58 ::snprintf(message, sizeof(message),
59 "There is a pending attach, abort it and %s?",
60 m_new_process_action.c_str());
61 else if (process->GetShouldDetach())
62 ::snprintf(message, sizeof(message),
63 "There is a running process, detach from it and %s?",
64 m_new_process_action.c_str());
65 else
66 ::snprintf(message, sizeof(message),
67 "There is a running process, kill it and %s?",
68 m_new_process_action.c_str());
69
70 if (!m_interpreter.Confirm(message, true)) {
71 result.SetStatus(eReturnStatusFailed);
72 return false;
73 } else {
74 if (process->GetShouldDetach()) {
75 bool keep_stopped = false;
76 Error detach_error(process->Detach(keep_stopped));
77 if (detach_error.Success()) {
78 result.SetStatus(eReturnStatusSuccessFinishResult);
79 process = nullptr;
80 } else {
81 result.AppendErrorWithFormat(
82 "Failed to detach from process: %s\n",
83 detach_error.AsCString());
84 result.SetStatus(eReturnStatusFailed);
85 }
86 } else {
87 Error destroy_error(process->Destroy(false));
88 if (destroy_error.Success()) {
89 result.SetStatus(eReturnStatusSuccessFinishResult);
90 process = nullptr;
91 } else {
92 result.AppendErrorWithFormat("Failed to kill process: %s\n",
93 destroy_error.AsCString());
94 result.SetStatus(eReturnStatusFailed);
95 }
96 }
97 }
98 }
99 }
100 return result.Succeeded();
101 }
102
103 std::string m_new_process_action;
Jim Inghamdcb1d852013-03-29 00:56:30 +0000104};
Eugene Zelenko49bcfd82016-02-23 01:43:44 +0000105
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000106//-------------------------------------------------------------------------
107// CommandObjectProcessLaunch
108//-------------------------------------------------------------------------
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000109#pragma mark CommandObjectProcessLaunch
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000111public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 CommandObjectProcessLaunch(CommandInterpreter &interpreter)
113 : CommandObjectProcessLaunchOrAttach(
114 interpreter, "process launch",
115 "Launch the executable in the debugger.", nullptr,
116 eCommandRequiresTarget, "restart"),
117 m_options() {
118 CommandArgumentEntry arg;
119 CommandArgumentData run_args_arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000120
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121 // Define the first (and only) variant of this arg.
122 run_args_arg.arg_type = eArgTypeRunArgs;
123 run_args_arg.arg_repetition = eArgRepeatOptional;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 // There is only one variant this argument could be; put it into the
126 // argument entry.
127 arg.push_back(run_args_arg);
Todd Fialae1cfbc72016-08-11 23:51:28 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 // Push the data for the first argument into the m_arguments vector.
130 m_arguments.push_back(arg);
131 }
Jim Inghame9ce62b2012-08-10 21:48:41 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 ~CommandObjectProcessLaunch() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 int HandleArgumentCompletion(Args &input, int &cursor_index,
136 int &cursor_char_position,
137 OptionElementVector &opt_element_vector,
138 int match_start_point, int max_return_elements,
139 bool &word_complete,
140 StringList &matches) override {
141 std::string completion_str(input.GetArgumentAtIndex(cursor_index));
142 completion_str.erase(cursor_char_position);
143
144 CommandCompletions::InvokeCommonCompletionCallbacks(
145 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
146 completion_str.c_str(), match_start_point, max_return_elements, nullptr,
147 word_complete, matches);
148 return matches.GetSize();
149 }
150
151 Options *GetOptions() override { return &m_options; }
152
153 const char *GetRepeatCommand(Args &current_command_args,
154 uint32_t index) override {
155 // No repeat for "process launch"...
156 return "";
157 }
Jim Ingham5a988412012-06-08 21:56:10 +0000158
159protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160 bool DoExecute(Args &launch_args, CommandReturnObject &result) override {
161 Debugger &debugger = m_interpreter.GetDebugger();
162 Target *target = debugger.GetSelectedTarget().get();
163 // If our listener is nullptr, users aren't allows to launch
164 ModuleSP exe_module_sp = target->GetExecutableModule();
Greg Clayton71337622011-02-24 22:24:29 +0000165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166 if (exe_module_sp == nullptr) {
167 result.AppendError("no file in target, create a debug target using the "
168 "'target create' command");
169 result.SetStatus(eReturnStatusFailed);
170 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000171 }
172
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173 StateType state = eStateInvalid;
174
175 if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result))
176 return false;
177
178 const char *target_settings_argv0 = target->GetArg0();
179
180 // Determine whether we will disable ASLR or leave it in the default state
181 // (i.e. enabled if the platform supports it).
182 // First check if the process launch options explicitly turn on/off
183 // disabling ASLR. If so, use that setting;
184 // otherwise, use the 'settings target.disable-aslr' setting.
185 bool disable_aslr = false;
186 if (m_options.disable_aslr != eLazyBoolCalculate) {
187 // The user specified an explicit setting on the process launch line. Use
188 // it.
189 disable_aslr = (m_options.disable_aslr == eLazyBoolYes);
190 } else {
191 // The user did not explicitly specify whether to disable ASLR. Fall back
192 // to the target.disable-aslr setting.
193 disable_aslr = target->GetDisableASLR();
194 }
195
196 if (disable_aslr)
197 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
198 else
199 m_options.launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
200
201 if (target->GetDetachOnError())
202 m_options.launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
203
204 if (target->GetDisableSTDIO())
205 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO);
206
207 Args environment;
208 target->GetEnvironmentAsArgs(environment);
209 if (environment.GetArgumentCount() > 0)
210 m_options.launch_info.GetEnvironmentEntries().AppendArguments(
211 environment);
212
213 if (target_settings_argv0) {
214 m_options.launch_info.GetArguments().AppendArgument(
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000215 llvm::StringRef(target_settings_argv0));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216 m_options.launch_info.SetExecutableFile(
217 exe_module_sp->GetPlatformFileSpec(), false);
218 } else {
219 m_options.launch_info.SetExecutableFile(
220 exe_module_sp->GetPlatformFileSpec(), true);
221 }
222
223 if (launch_args.GetArgumentCount() == 0) {
224 m_options.launch_info.GetArguments().AppendArguments(
225 target->GetProcessLaunchInfo().GetArguments());
226 } else {
227 m_options.launch_info.GetArguments().AppendArguments(launch_args);
228 // Save the arguments for subsequent runs in the current target.
229 target->SetRunArguments(launch_args);
230 }
231
232 StreamString stream;
233 Error error = target->Launch(m_options.launch_info, &stream);
234
235 if (error.Success()) {
236 ProcessSP process_sp(target->GetProcessSP());
237 if (process_sp) {
238 // There is a race condition where this thread will return up the call
239 // stack to the main command
240 // handler and show an (lldb) prompt before HandlePrivateEvent (from
241 // PrivateStateThread) has
242 // a chance to call PushProcessIOHandler().
243 process_sp->SyncIOHandler(0, 2000);
244
245 const char *data = stream.GetData();
246 if (data && strlen(data) > 0)
247 result.AppendMessage(stream.GetData());
248 const char *archname =
249 exe_module_sp->GetArchitecture().GetArchitectureName();
250 result.AppendMessageWithFormat(
251 "Process %" PRIu64 " launched: '%s' (%s)\n", process_sp->GetID(),
252 exe_module_sp->GetFileSpec().GetPath().c_str(), archname);
253 result.SetStatus(eReturnStatusSuccessFinishResult);
254 result.SetDidChangeProcessState(true);
255 } else {
256 result.AppendError(
257 "no error returned from Target::Launch, and target has no process");
258 result.SetStatus(eReturnStatusFailed);
259 }
260 } else {
261 result.AppendError(error.AsCString());
262 result.SetStatus(eReturnStatusFailed);
263 }
264 return result.Succeeded();
265 }
266
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000267protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 ProcessLaunchCommandOptions m_options;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000269};
270
Greg Clayton982c9762011-11-03 21:22:33 +0000271//#define SET1 LLDB_OPT_SET_1
272//#define SET2 LLDB_OPT_SET_2
273//#define SET3 LLDB_OPT_SET_3
274//
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275// OptionDefinition
276// CommandObjectProcessLaunch::CommandOptions::g_option_table[] =
Greg Clayton982c9762011-11-03 21:22:33 +0000277//{
Kate Stoneac9c3a62016-08-26 23:28:47 +0000278// // clang-format off
Kate Stoneb9c1b512016-09-06 20:57:50 +0000279// {SET1 | SET2 | SET3, false, "stop-at-entry", 's', OptionParser::eNoArgument,
280// nullptr, 0, eArgTypeNone, "Stop at the entry point of the program
281// when launching a process."},
282// {SET1, false, "stdin", 'i',
283// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName,
284// "Redirect stdin for the process to <path>."},
285// {SET1, false, "stdout", 'o',
286// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName,
287// "Redirect stdout for the process to <path>."},
288// {SET1, false, "stderr", 'e',
289// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName,
290// "Redirect stderr for the process to <path>."},
291// {SET1 | SET2 | SET3, false, "plugin", 'p',
292// OptionParser::eRequiredArgument, nullptr, 0, eArgTypePlugin, "Name of
293// the process plugin you want to use."},
294// { SET2, false, "tty", 't',
295// OptionParser::eOptionalArgument, nullptr, 0, eArgTypeDirectoryName, "Start
296// the process in a terminal. If <path> is specified, look for a terminal whose
297// name contains <path>, else start the process in a new terminal."},
298// { SET3, false, "no-stdio", 'n', OptionParser::eNoArgument,
299// nullptr, 0, eArgTypeNone, "Do not set up for terminal I/O to go to
300// running process."},
301// {SET1 | SET2 | SET3, false, "working-dir", 'w',
302// OptionParser::eRequiredArgument, nullptr, 0, eArgTypeDirectoryName, "Set the
303// current working directory to <path> when running the inferior."},
Kate Stoneac9c3a62016-08-26 23:28:47 +0000304// {0, false, nullptr, 0, 0, nullptr, 0, eArgTypeNone, nullptr}
305// // clang-format on
Greg Clayton982c9762011-11-03 21:22:33 +0000306//};
307//
308//#undef SET1
309//#undef SET2
310//#undef SET3
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000311
312//-------------------------------------------------------------------------
313// CommandObjectProcessAttach
314//-------------------------------------------------------------------------
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000315
316static OptionDefinition g_process_attach_options[] = {
317 // clang-format off
318 { LLDB_OPT_SET_ALL, false, "continue", 'c', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Immediately continue the process once attached." },
319 { LLDB_OPT_SET_ALL, false, "plugin", 'P', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePlugin, "Name of the process plugin you want to use." },
320 { LLDB_OPT_SET_1, false, "pid", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePid, "The process ID of an existing process to attach to." },
321 { LLDB_OPT_SET_2, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "The name of the process to attach to." },
322 { LLDB_OPT_SET_2, false, "include-existing", 'i', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Include existing processes when doing attach -w." },
323 { LLDB_OPT_SET_2, false, "waitfor", 'w', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Wait for the process with <process-name> to launch." },
324 // clang-format on
325};
326
Jim Inghambb9caf72010-12-09 18:58:16 +0000327#pragma mark CommandObjectProcessAttach
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000329public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 class CommandOptions : public Options {
331 public:
332 CommandOptions() : Options() {
333 // Keep default values of all options in one place: OptionParsingStarting
334 // ()
335 OptionParsingStarting(nullptr);
Jim Ingham5aee1622010-08-09 23:31:02 +0000336 }
337
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 ~CommandOptions() override = default;
Jim Ingham5aee1622010-08-09 23:31:02 +0000339
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 Error SetOptionValue(uint32_t option_idx, const char *option_arg,
341 ExecutionContext *execution_context) override {
342 Error error;
343 const int short_option = m_getopt_table[option_idx].val;
344 bool success = false;
345 switch (short_option) {
346 case 'c':
347 attach_info.SetContinueOnceAttached(true);
348 break;
349
350 case 'p': {
351 lldb::pid_t pid = StringConvert::ToUInt32(
352 option_arg, LLDB_INVALID_PROCESS_ID, 0, &success);
353 if (!success || pid == LLDB_INVALID_PROCESS_ID) {
354 error.SetErrorStringWithFormat("invalid process ID '%s'", option_arg);
355 } else {
356 attach_info.SetProcessID(pid);
357 }
358 } break;
359
360 case 'P':
361 attach_info.SetProcessPluginName(option_arg);
362 break;
363
364 case 'n':
365 attach_info.GetExecutableFile().SetFile(option_arg, false);
366 break;
367
368 case 'w':
369 attach_info.SetWaitForLaunch(true);
370 break;
371
372 case 'i':
373 attach_info.SetIgnoreExisting(false);
374 break;
375
376 default:
377 error.SetErrorStringWithFormat("invalid short option character '%c'",
378 short_option);
379 break;
380 }
381 return error;
Jim Ingham5a988412012-06-08 21:56:10 +0000382 }
383
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 void OptionParsingStarting(ExecutionContext *execution_context) override {
385 attach_info.Clear();
386 }
387
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000388 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +0000389 return llvm::makeArrayRef(g_process_attach_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000390 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391
392 bool HandleOptionArgumentCompletion(
393 Args &input, int cursor_index, int char_pos,
394 OptionElementVector &opt_element_vector, int opt_element_index,
395 int match_start_point, int max_return_elements,
396 CommandInterpreter &interpreter, bool &word_complete,
397 StringList &matches) override {
398 int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos;
399 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
400
401 // We are only completing the name option for now...
402
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000403 if (GetDefinitions()[opt_defs_index].short_option == 'n') {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 // Are we in the name?
405
406 // Look to see if there is a -P argument provided, and if so use that
407 // plugin, otherwise
408 // use the default plugin.
409
410 const char *partial_name = nullptr;
411 partial_name = input.GetArgumentAtIndex(opt_arg_pos);
412
413 PlatformSP platform_sp(interpreter.GetPlatform(true));
414 if (platform_sp) {
415 ProcessInstanceInfoList process_infos;
416 ProcessInstanceInfoMatch match_info;
417 if (partial_name) {
418 match_info.GetProcessInfo().GetExecutableFile().SetFile(
419 partial_name, false);
420 match_info.SetNameMatchType(eNameMatchStartsWith);
421 }
422 platform_sp->FindProcesses(match_info, process_infos);
423 const size_t num_matches = process_infos.GetSize();
424 if (num_matches > 0) {
425 for (size_t i = 0; i < num_matches; ++i) {
426 matches.AppendString(
427 process_infos.GetProcessNameAtIndex(i),
428 process_infos.GetProcessNameLengthAtIndex(i));
429 }
430 }
431 }
432 }
433
434 return false;
435 }
436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 // Instance variables to hold the values for command options.
438
439 ProcessAttachInfo attach_info;
440 };
441
442 CommandObjectProcessAttach(CommandInterpreter &interpreter)
443 : CommandObjectProcessLaunchOrAttach(
444 interpreter, "process attach", "Attach to a process.",
445 "process attach <cmd-options>", 0, "attach"),
446 m_options() {}
447
448 ~CommandObjectProcessAttach() override = default;
449
450 Options *GetOptions() override { return &m_options; }
451
Jim Ingham5a988412012-06-08 21:56:10 +0000452protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 bool DoExecute(Args &command, CommandReturnObject &result) override {
454 PlatformSP platform_sp(
455 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
Oleksiy Vyalov926af0c2015-02-03 00:04:35 +0000456
Kate Stoneb9c1b512016-09-06 20:57:50 +0000457 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
458 // N.B. The attach should be synchronous. It doesn't help much to get the
459 // prompt back between initiating the attach
460 // and the target actually stopping. So even if the interpreter is set to
461 // be asynchronous, we wait for the stop
462 // ourselves here.
Jim Ingham5aee1622010-08-09 23:31:02 +0000463
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464 StateType state = eStateInvalid;
465 Process *process = m_exe_ctx.GetProcessPtr();
Oleksiy Vyalov926af0c2015-02-03 00:04:35 +0000466
Kate Stoneb9c1b512016-09-06 20:57:50 +0000467 if (!StopProcessIfNecessary(process, state, result))
468 return false;
Oleksiy Vyalov926af0c2015-02-03 00:04:35 +0000469
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470 if (target == nullptr) {
471 // If there isn't a current target create one.
472 TargetSP new_target_sp;
473 Error error;
Oleksiy Vyalov926af0c2015-02-03 00:04:35 +0000474
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475 error = m_interpreter.GetDebugger().GetTargetList().CreateTarget(
476 m_interpreter.GetDebugger(), nullptr, nullptr, false,
477 nullptr, // No platform options
478 new_target_sp);
479 target = new_target_sp.get();
480 if (target == nullptr || error.Fail()) {
481 result.AppendError(error.AsCString("Error creating target"));
482 return false;
483 }
484 m_interpreter.GetDebugger().GetTargetList().SetSelectedTarget(target);
Jim Ingham5aee1622010-08-09 23:31:02 +0000485 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486
487 // Record the old executable module, we want to issue a warning if the
488 // process of attaching changed the
489 // current executable (like somebody said "file foo" then attached to a PID
490 // whose executable was bar.)
491
492 ModuleSP old_exec_module_sp = target->GetExecutableModule();
493 ArchSpec old_arch_spec = target->GetArchitecture();
494
495 if (command.GetArgumentCount()) {
496 result.AppendErrorWithFormat("Invalid arguments for '%s'.\nUsage: %s\n",
497 m_cmd_name.c_str(), m_cmd_syntax.c_str());
498 result.SetStatus(eReturnStatusFailed);
499 return false;
500 }
501
502 m_interpreter.UpdateExecutionContext(nullptr);
503 StreamString stream;
504 const auto error = target->Attach(m_options.attach_info, &stream);
505 if (error.Success()) {
506 ProcessSP process_sp(target->GetProcessSP());
507 if (process_sp) {
508 if (stream.GetData())
509 result.AppendMessage(stream.GetData());
510 result.SetStatus(eReturnStatusSuccessFinishNoResult);
511 result.SetDidChangeProcessState(true);
512 result.SetAbnormalStopWasExpected(true);
513 } else {
514 result.AppendError(
515 "no error returned from Target::Attach, and target has no process");
516 result.SetStatus(eReturnStatusFailed);
517 }
518 } else {
519 result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString());
520 result.SetStatus(eReturnStatusFailed);
521 }
522
523 if (!result.Succeeded())
524 return false;
525
526 // Okay, we're done. Last step is to warn if the executable module has
527 // changed:
528 char new_path[PATH_MAX];
529 ModuleSP new_exec_module_sp(target->GetExecutableModule());
530 if (!old_exec_module_sp) {
531 // We might not have a module if we attached to a raw pid...
532 if (new_exec_module_sp) {
533 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
534 result.AppendMessageWithFormat("Executable module set to \"%s\".\n",
535 new_path);
536 }
537 } else if (old_exec_module_sp->GetFileSpec() !=
538 new_exec_module_sp->GetFileSpec()) {
539 char old_path[PATH_MAX];
540
541 old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX);
542 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
543
544 result.AppendWarningWithFormat(
545 "Executable module changed from \"%s\" to \"%s\".\n", old_path,
546 new_path);
547 }
548
549 if (!old_arch_spec.IsValid()) {
550 result.AppendMessageWithFormat(
551 "Architecture set to: %s.\n",
552 target->GetArchitecture().GetTriple().getTriple().c_str());
553 } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) {
554 result.AppendWarningWithFormat(
555 "Architecture changed from %s to %s.\n",
556 old_arch_spec.GetTriple().getTriple().c_str(),
557 target->GetArchitecture().GetTriple().getTriple().c_str());
558 }
559
560 // This supports the use-case scenario of immediately continuing the process
561 // once attached.
562 if (m_options.attach_info.GetContinueOnceAttached())
563 m_interpreter.HandleCommand("process continue", eLazyBoolNo, result);
564
565 return result.Succeeded();
566 }
567
568 CommandOptions m_options;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000569};
570
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000571//-------------------------------------------------------------------------
572// CommandObjectProcessContinue
573//-------------------------------------------------------------------------
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000574
575static OptionDefinition g_process_continue_options[] = {
576 // clang-format off
577 { LLDB_OPT_SET_ALL, false, "ignore-count",'i', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Ignore <N> crossings of the breakpoint (if it exists) for the currently selected thread." }
578 // clang-format on
579};
580
Jim Inghambb9caf72010-12-09 18:58:16 +0000581#pragma mark CommandObjectProcessContinue
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583class CommandObjectProcessContinue : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000584public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585 CommandObjectProcessContinue(CommandInterpreter &interpreter)
586 : CommandObjectParsed(
587 interpreter, "process continue",
588 "Continue execution of all threads in the current process.",
589 "process continue",
590 eCommandRequiresProcess | eCommandTryTargetAPILock |
591 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
592 m_options() {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000593
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594 ~CommandObjectProcessContinue() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000595
Jim Ingham5a988412012-06-08 21:56:10 +0000596protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 class CommandOptions : public Options {
598 public:
599 CommandOptions() : Options() {
600 // Keep default values of all options in one place: OptionParsingStarting
601 // ()
602 OptionParsingStarting(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000603 }
Jim Ingham0e410842012-08-11 01:27:55 +0000604
Kate Stoneb9c1b512016-09-06 20:57:50 +0000605 ~CommandOptions() override = default;
606
607 Error SetOptionValue(uint32_t option_idx, const char *option_arg,
608 ExecutionContext *execution_context) override {
609 Error error;
610 const int short_option = m_getopt_table[option_idx].val;
611 bool success = false;
612 switch (short_option) {
613 case 'i':
614 m_ignore = StringConvert::ToUInt32(option_arg, 0, 0, &success);
615 if (!success)
616 error.SetErrorStringWithFormat(
617 "invalid value for ignore option: \"%s\", should be a number.",
618 option_arg);
619 break;
620
621 default:
622 error.SetErrorStringWithFormat("invalid short option character '%c'",
623 short_option);
624 break;
625 }
626 return error;
Jim Ingham0e410842012-08-11 01:27:55 +0000627 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628
629 void OptionParsingStarting(ExecutionContext *execution_context) override {
630 m_ignore = 0;
631 }
632
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000633 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +0000634 return llvm::makeArrayRef(g_process_continue_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000635 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636
637 uint32_t m_ignore;
638 };
639
640 bool DoExecute(Args &command, CommandReturnObject &result) override {
641 Process *process = m_exe_ctx.GetProcessPtr();
642 bool synchronous_execution = m_interpreter.GetSynchronous();
643 StateType state = process->GetState();
644 if (state == eStateStopped) {
645 if (command.GetArgumentCount() != 0) {
646 result.AppendErrorWithFormat(
647 "The '%s' command does not take any arguments.\n",
648 m_cmd_name.c_str());
649 result.SetStatus(eReturnStatusFailed);
650 return false;
651 }
652
653 if (m_options.m_ignore > 0) {
654 ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this());
655 if (sel_thread_sp) {
656 StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo();
657 if (stop_info_sp &&
658 stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
659 lldb::break_id_t bp_site_id =
660 (lldb::break_id_t)stop_info_sp->GetValue();
661 BreakpointSiteSP bp_site_sp(
662 process->GetBreakpointSiteList().FindByID(bp_site_id));
663 if (bp_site_sp) {
664 const size_t num_owners = bp_site_sp->GetNumberOfOwners();
665 for (size_t i = 0; i < num_owners; i++) {
666 Breakpoint &bp_ref =
667 bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
668 if (!bp_ref.IsInternal()) {
669 bp_ref.SetIgnoreCount(m_options.m_ignore);
670 }
671 }
672 }
673 }
674 }
675 }
676
677 { // Scope for thread list mutex:
678 std::lock_guard<std::recursive_mutex> guard(
679 process->GetThreadList().GetMutex());
680 const uint32_t num_threads = process->GetThreadList().GetSize();
681
682 // Set the actions that the threads should each take when resuming
683 for (uint32_t idx = 0; idx < num_threads; ++idx) {
684 const bool override_suspend = false;
685 process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState(
686 eStateRunning, override_suspend);
687 }
688 }
689
690 const uint32_t iohandler_id = process->GetIOHandlerID();
691
692 StreamString stream;
693 Error error;
694 if (synchronous_execution)
695 error = process->ResumeSynchronous(&stream);
696 else
697 error = process->Resume();
698
699 if (error.Success()) {
700 // There is a race condition where this thread will return up the call
701 // stack to the main command
702 // handler and show an (lldb) prompt before HandlePrivateEvent (from
703 // PrivateStateThread) has
704 // a chance to call PushProcessIOHandler().
705 process->SyncIOHandler(iohandler_id, 2000);
706
707 result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
708 process->GetID());
709 if (synchronous_execution) {
710 // If any state changed events had anything to say, add that to the
711 // result
712 if (stream.GetData())
713 result.AppendMessage(stream.GetData());
714
715 result.SetDidChangeProcessState(true);
716 result.SetStatus(eReturnStatusSuccessFinishNoResult);
717 } else {
718 result.SetStatus(eReturnStatusSuccessContinuingNoResult);
719 }
720 } else {
721 result.AppendErrorWithFormat("Failed to resume process: %s.\n",
722 error.AsCString());
723 result.SetStatus(eReturnStatusFailed);
724 }
725 } else {
726 result.AppendErrorWithFormat(
727 "Process cannot be continued from its current state (%s).\n",
728 StateAsCString(state));
729 result.SetStatus(eReturnStatusFailed);
730 }
731 return result.Succeeded();
732 }
733
734 Options *GetOptions() override { return &m_options; }
735
736 CommandOptions m_options;
Jim Ingham0e410842012-08-11 01:27:55 +0000737};
738
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000739//-------------------------------------------------------------------------
740// CommandObjectProcessDetach
741//-------------------------------------------------------------------------
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000742static OptionDefinition g_process_detach_options[] = {
743 // clang-format off
744 { LLDB_OPT_SET_1, false, "keep-stopped", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Whether or not the process should be kept stopped on detach (if possible)." },
745 // clang-format on
746};
747
Jim Inghambb9caf72010-12-09 18:58:16 +0000748#pragma mark CommandObjectProcessDetach
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000749
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750class CommandObjectProcessDetach : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000751public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 class CommandOptions : public Options {
753 public:
754 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
755
756 ~CommandOptions() override = default;
757
758 Error SetOptionValue(uint32_t option_idx, const char *option_arg,
759 ExecutionContext *execution_context) override {
760 Error error;
761 const int short_option = m_getopt_table[option_idx].val;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000762 auto option_strref = llvm::StringRef::withNullAsEmpty(option_arg);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763
764 switch (short_option) {
765 case 's':
766 bool tmp_result;
767 bool success;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000768 tmp_result = Args::StringToBoolean(option_strref, false, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769 if (!success)
770 error.SetErrorStringWithFormat("invalid boolean option: \"%s\"",
771 option_arg);
772 else {
773 if (tmp_result)
774 m_keep_stopped = eLazyBoolYes;
775 else
776 m_keep_stopped = eLazyBoolNo;
Jim Inghamacff8952013-05-02 00:27:30 +0000777 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000778 break;
779 default:
780 error.SetErrorStringWithFormat("invalid short option character '%c'",
781 short_option);
782 break;
783 }
784 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785 }
786
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787 void OptionParsingStarting(ExecutionContext *execution_context) override {
788 m_keep_stopped = eLazyBoolCalculate;
Jim Inghamacff8952013-05-02 00:27:30 +0000789 }
790
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000791 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +0000792 return llvm::makeArrayRef(g_process_detach_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000793 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794
795 // Instance variables to hold the values for command options.
796 LazyBool m_keep_stopped;
797 };
798
799 CommandObjectProcessDetach(CommandInterpreter &interpreter)
800 : CommandObjectParsed(interpreter, "process detach",
801 "Detach from the current target process.",
802 "process detach",
803 eCommandRequiresProcess | eCommandTryTargetAPILock |
804 eCommandProcessMustBeLaunched),
805 m_options() {}
806
807 ~CommandObjectProcessDetach() override = default;
808
809 Options *GetOptions() override { return &m_options; }
810
Jim Ingham5a988412012-06-08 21:56:10 +0000811protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812 bool DoExecute(Args &command, CommandReturnObject &result) override {
813 Process *process = m_exe_ctx.GetProcessPtr();
814 // FIXME: This will be a Command Option:
815 bool keep_stopped;
816 if (m_options.m_keep_stopped == eLazyBoolCalculate) {
817 // Check the process default:
818 keep_stopped = process->GetDetachKeepsStopped();
819 } else if (m_options.m_keep_stopped == eLazyBoolYes)
820 keep_stopped = true;
821 else
822 keep_stopped = false;
Jim Inghamacff8952013-05-02 00:27:30 +0000823
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824 Error error(process->Detach(keep_stopped));
825 if (error.Success()) {
826 result.SetStatus(eReturnStatusSuccessFinishResult);
827 } else {
828 result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString());
829 result.SetStatus(eReturnStatusFailed);
830 return false;
831 }
832 return result.Succeeded();
833 }
834
835 CommandOptions m_options;
Jim Inghamacff8952013-05-02 00:27:30 +0000836};
837
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000838//-------------------------------------------------------------------------
Greg Claytonb766a732011-02-04 01:58:07 +0000839// CommandObjectProcessConnect
840//-------------------------------------------------------------------------
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000841
842static OptionDefinition g_process_connect_options[] = {
843 // clang-format off
844 { LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePlugin, "Name of the process plugin you want to use." },
845 // clang-format on
846};
847
Greg Claytonb766a732011-02-04 01:58:07 +0000848#pragma mark CommandObjectProcessConnect
849
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850class CommandObjectProcessConnect : public CommandObjectParsed {
Greg Claytonb766a732011-02-04 01:58:07 +0000851public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 class CommandOptions : public Options {
853 public:
854 CommandOptions() : Options() {
855 // Keep default values of all options in one place: OptionParsingStarting
856 // ()
857 OptionParsingStarting(nullptr);
Greg Claytonb766a732011-02-04 01:58:07 +0000858 }
Greg Claytonb766a732011-02-04 01:58:07 +0000859
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 ~CommandOptions() override = default;
Eugene Zelenko49bcfd82016-02-23 01:43:44 +0000861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 Error SetOptionValue(uint32_t option_idx, const char *option_arg,
863 ExecutionContext *execution_context) override {
864 Error error;
865 const int short_option = m_getopt_table[option_idx].val;
866
867 switch (short_option) {
868 case 'p':
869 plugin_name.assign(option_arg);
870 break;
871
872 default:
873 error.SetErrorStringWithFormat("invalid short option character '%c'",
874 short_option);
875 break;
876 }
877 return error;
Jim Ingham5a988412012-06-08 21:56:10 +0000878 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879
880 void OptionParsingStarting(ExecutionContext *execution_context) override {
881 plugin_name.clear();
882 }
883
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000884 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +0000885 return llvm::makeArrayRef(g_process_connect_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000886 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887
888 // Instance variables to hold the values for command options.
889
890 std::string plugin_name;
891 };
892
893 CommandObjectProcessConnect(CommandInterpreter &interpreter)
894 : CommandObjectParsed(interpreter, "process connect",
895 "Connect to a remote debug service.",
896 "process connect <remote-url>", 0),
897 m_options() {}
898
899 ~CommandObjectProcessConnect() override = default;
900
901 Options *GetOptions() override { return &m_options; }
902
Jim Ingham5a988412012-06-08 21:56:10 +0000903protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 bool DoExecute(Args &command, CommandReturnObject &result) override {
905 if (command.GetArgumentCount() != 1) {
906 result.AppendErrorWithFormat(
907 "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(),
908 m_cmd_syntax.c_str());
909 result.SetStatus(eReturnStatusFailed);
910 return false;
Greg Claytonb766a732011-02-04 01:58:07 +0000911 }
Tamas Berghammerccd6cff2015-12-08 14:08:19 +0000912
Kate Stoneb9c1b512016-09-06 20:57:50 +0000913 Process *process = m_exe_ctx.GetProcessPtr();
914 if (process && process->IsAlive()) {
915 result.AppendErrorWithFormat(
916 "Process %" PRIu64
917 " is currently being debugged, kill the process before connecting.\n",
918 process->GetID());
919 result.SetStatus(eReturnStatusFailed);
920 return false;
921 }
922
923 const char *plugin_name = nullptr;
924 if (!m_options.plugin_name.empty())
925 plugin_name = m_options.plugin_name.c_str();
926
927 Error error;
928 Debugger &debugger = m_interpreter.GetDebugger();
929 PlatformSP platform_sp = m_interpreter.GetPlatform(true);
930 ProcessSP process_sp = platform_sp->ConnectProcess(
931 command.GetArgumentAtIndex(0), plugin_name, debugger,
932 debugger.GetSelectedTarget().get(), error);
933 if (error.Fail() || process_sp == nullptr) {
934 result.AppendError(error.AsCString("Error connecting to the process"));
935 result.SetStatus(eReturnStatusFailed);
936 return false;
937 }
938 return true;
939 }
940
941 CommandOptions m_options;
Greg Claytonb766a732011-02-04 01:58:07 +0000942};
943
Greg Claytonb766a732011-02-04 01:58:07 +0000944//-------------------------------------------------------------------------
Greg Clayton998255b2012-10-13 02:07:45 +0000945// CommandObjectProcessPlugin
946//-------------------------------------------------------------------------
947#pragma mark CommandObjectProcessPlugin
948
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949class CommandObjectProcessPlugin : public CommandObjectProxy {
Greg Clayton998255b2012-10-13 02:07:45 +0000950public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 CommandObjectProcessPlugin(CommandInterpreter &interpreter)
952 : CommandObjectProxy(
953 interpreter, "process plugin",
954 "Send a custom command to the current target process plug-in.",
955 "process plugin <args>", 0) {}
Eugene Zelenko49bcfd82016-02-23 01:43:44 +0000956
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 ~CommandObjectProcessPlugin() override = default;
Greg Clayton998255b2012-10-13 02:07:45 +0000958
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959 CommandObject *GetProxyCommandObject() override {
960 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
961 if (process)
962 return process->GetPluginCommandObject();
963 return nullptr;
964 }
Greg Clayton998255b2012-10-13 02:07:45 +0000965};
966
Greg Clayton998255b2012-10-13 02:07:45 +0000967//-------------------------------------------------------------------------
Greg Clayton8f343b02010-11-04 01:54:29 +0000968// CommandObjectProcessLoad
969//-------------------------------------------------------------------------
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000970
971static OptionDefinition g_process_load_options[] = {
972 // clang-format off
973 { LLDB_OPT_SET_ALL, false, "install", 'i', OptionParser::eOptionalArgument, nullptr, nullptr, 0, eArgTypePath, "Install the shared library to the target. If specified without an argument then the library will installed in the current working directory." },
974 // clang-format on
975};
976
Jim Inghambb9caf72010-12-09 18:58:16 +0000977#pragma mark CommandObjectProcessLoad
Greg Clayton8f343b02010-11-04 01:54:29 +0000978
Kate Stoneb9c1b512016-09-06 20:57:50 +0000979class CommandObjectProcessLoad : public CommandObjectParsed {
Greg Clayton8f343b02010-11-04 01:54:29 +0000980public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 class CommandOptions : public Options {
982 public:
983 CommandOptions() : Options() {
984 // Keep default values of all options in one place: OptionParsingStarting
985 // ()
986 OptionParsingStarting(nullptr);
Greg Clayton8f343b02010-11-04 01:54:29 +0000987 }
988
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 ~CommandOptions() override = default;
Tamas Berghammer4fbd67a2015-12-08 13:43:59 +0000990
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 Error SetOptionValue(uint32_t option_idx, const char *option_arg,
992 ExecutionContext *execution_context) override {
993 Error error;
994 const int short_option = m_getopt_table[option_idx].val;
995 switch (short_option) {
996 case 'i':
997 do_install = true;
998 if (option_arg && option_arg[0])
999 install_path.SetFile(option_arg, false);
1000 break;
1001 default:
1002 error.SetErrorStringWithFormat("invalid short option character '%c'",
1003 short_option);
1004 break;
1005 }
1006 return error;
Greg Clayton8f343b02010-11-04 01:54:29 +00001007 }
1008
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 void OptionParsingStarting(ExecutionContext *execution_context) override {
1010 do_install = false;
1011 install_path.Clear();
1012 }
1013
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001014 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +00001015 return llvm::makeArrayRef(g_process_load_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001016 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017
1018 // Instance variables to hold the values for command options.
1019 bool do_install;
1020 FileSpec install_path;
1021 };
1022
1023 CommandObjectProcessLoad(CommandInterpreter &interpreter)
1024 : CommandObjectParsed(interpreter, "process load",
1025 "Load a shared library into the current process.",
1026 "process load <filename> [<filename> ...]",
1027 eCommandRequiresProcess | eCommandTryTargetAPILock |
1028 eCommandProcessMustBeLaunched |
1029 eCommandProcessMustBePaused),
1030 m_options() {}
1031
1032 ~CommandObjectProcessLoad() override = default;
1033
1034 Options *GetOptions() override { return &m_options; }
1035
Jim Ingham5a988412012-06-08 21:56:10 +00001036protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037 bool DoExecute(Args &command, CommandReturnObject &result) override {
1038 Process *process = m_exe_ctx.GetProcessPtr();
Greg Clayton8f343b02010-11-04 01:54:29 +00001039
Zachary Turner97d2c402016-10-05 23:40:23 +00001040 for (auto &entry : command.entries()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001041 Error error;
1042 PlatformSP platform = process->GetTarget().GetPlatform();
Zachary Turner97d2c402016-10-05 23:40:23 +00001043 llvm::StringRef image_path = entry.ref;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer4fbd67a2015-12-08 13:43:59 +00001045
Kate Stoneb9c1b512016-09-06 20:57:50 +00001046 if (!m_options.do_install) {
1047 FileSpec image_spec(image_path, false);
1048 platform->ResolveRemotePath(image_spec, image_spec);
1049 image_token =
1050 platform->LoadImage(process, FileSpec(), image_spec, error);
1051 } else if (m_options.install_path) {
1052 FileSpec image_spec(image_path, true);
1053 platform->ResolveRemotePath(m_options.install_path,
1054 m_options.install_path);
1055 image_token = platform->LoadImage(process, image_spec,
1056 m_options.install_path, error);
1057 } else {
1058 FileSpec image_spec(image_path, true);
1059 image_token =
1060 platform->LoadImage(process, image_spec, FileSpec(), error);
1061 }
Tamas Berghammer4fbd67a2015-12-08 13:43:59 +00001062
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063 if (image_token != LLDB_INVALID_IMAGE_TOKEN) {
1064 result.AppendMessageWithFormat(
Zachary Turner97d2c402016-10-05 23:40:23 +00001065 "Loading \"%s\"...ok\nImage %u loaded.\n", image_path.str().c_str(),
1066 image_token);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067 result.SetStatus(eReturnStatusSuccessFinishResult);
1068 } else {
Zachary Turner97d2c402016-10-05 23:40:23 +00001069 result.AppendErrorWithFormat("failed to load '%s': %s",
1070 image_path.str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001071 error.AsCString());
1072 result.SetStatus(eReturnStatusFailed);
1073 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001074 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 return result.Succeeded();
1076 }
1077
1078 CommandOptions m_options;
Greg Clayton8f343b02010-11-04 01:54:29 +00001079};
1080
Greg Clayton8f343b02010-11-04 01:54:29 +00001081//-------------------------------------------------------------------------
1082// CommandObjectProcessUnload
1083//-------------------------------------------------------------------------
Jim Inghambb9caf72010-12-09 18:58:16 +00001084#pragma mark CommandObjectProcessUnload
Greg Clayton8f343b02010-11-04 01:54:29 +00001085
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086class CommandObjectProcessUnload : public CommandObjectParsed {
Greg Clayton8f343b02010-11-04 01:54:29 +00001087public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 CommandObjectProcessUnload(CommandInterpreter &interpreter)
1089 : CommandObjectParsed(
1090 interpreter, "process unload",
1091 "Unload a shared library from the current process using the index "
1092 "returned by a previous call to \"process load\".",
1093 "process unload <index>",
1094 eCommandRequiresProcess | eCommandTryTargetAPILock |
1095 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
Greg Clayton8f343b02010-11-04 01:54:29 +00001096
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097 ~CommandObjectProcessUnload() override = default;
Greg Clayton8f343b02010-11-04 01:54:29 +00001098
Jim Ingham5a988412012-06-08 21:56:10 +00001099protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 bool DoExecute(Args &command, CommandReturnObject &result) override {
1101 Process *process = m_exe_ctx.GetProcessPtr();
Greg Clayton8f343b02010-11-04 01:54:29 +00001102
Zachary Turner97d2c402016-10-05 23:40:23 +00001103 for (auto &entry : command.entries()) {
1104 uint32_t image_token;
1105 if (entry.ref.getAsInteger(0, image_token)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 result.AppendErrorWithFormat("invalid image index argument '%s'",
Zachary Turner97d2c402016-10-05 23:40:23 +00001107 entry.ref.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108 result.SetStatus(eReturnStatusFailed);
1109 break;
1110 } else {
1111 Error error(process->GetTarget().GetPlatform()->UnloadImage(
1112 process, image_token));
1113 if (error.Success()) {
1114 result.AppendMessageWithFormat(
1115 "Unloading shared library with index %u...ok\n", image_token);
1116 result.SetStatus(eReturnStatusSuccessFinishResult);
1117 } else {
1118 result.AppendErrorWithFormat("failed to unload image: %s",
1119 error.AsCString());
1120 result.SetStatus(eReturnStatusFailed);
1121 break;
Greg Clayton8f343b02010-11-04 01:54:29 +00001122 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001124 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 return result.Succeeded();
1126 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001127};
1128
1129//-------------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001130// CommandObjectProcessSignal
1131//-------------------------------------------------------------------------
Jim Inghambb9caf72010-12-09 18:58:16 +00001132#pragma mark CommandObjectProcessSignal
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001133
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134class CommandObjectProcessSignal : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001135public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136 CommandObjectProcessSignal(CommandInterpreter &interpreter)
1137 : CommandObjectParsed(interpreter, "process signal",
1138 "Send a UNIX signal to the current target process.",
1139 nullptr, eCommandRequiresProcess |
1140 eCommandTryTargetAPILock) {
1141 CommandArgumentEntry arg;
1142 CommandArgumentData signal_arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 // Define the first (and only) variant of this arg.
1145 signal_arg.arg_type = eArgTypeUnixSignal;
1146 signal_arg.arg_repetition = eArgRepeatPlain;
1147
1148 // There is only one variant this argument could be; put it into the
1149 // argument entry.
1150 arg.push_back(signal_arg);
1151
1152 // Push the data for the first argument into the m_arguments vector.
1153 m_arguments.push_back(arg);
1154 }
1155
1156 ~CommandObjectProcessSignal() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157
Jim Ingham5a988412012-06-08 21:56:10 +00001158protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 bool DoExecute(Args &command, CommandReturnObject &result) override {
1160 Process *process = m_exe_ctx.GetProcessPtr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001161
Kate Stoneb9c1b512016-09-06 20:57:50 +00001162 if (command.GetArgumentCount() == 1) {
1163 int signo = LLDB_INVALID_SIGNAL_NUMBER;
1164
1165 const char *signal_name = command.GetArgumentAtIndex(0);
1166 if (::isxdigit(signal_name[0]))
1167 signo =
1168 StringConvert::ToSInt32(signal_name, LLDB_INVALID_SIGNAL_NUMBER, 0);
1169 else
1170 signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name);
1171
1172 if (signo == LLDB_INVALID_SIGNAL_NUMBER) {
1173 result.AppendErrorWithFormat("Invalid signal argument '%s'.\n",
1174 command.GetArgumentAtIndex(0));
1175 result.SetStatus(eReturnStatusFailed);
1176 } else {
1177 Error error(process->Signal(signo));
1178 if (error.Success()) {
1179 result.SetStatus(eReturnStatusSuccessFinishResult);
1180 } else {
1181 result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo,
1182 error.AsCString());
1183 result.SetStatus(eReturnStatusFailed);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001184 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185 }
1186 } else {
1187 result.AppendErrorWithFormat(
1188 "'%s' takes exactly one signal number argument:\nUsage: %s\n",
1189 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1190 result.SetStatus(eReturnStatusFailed);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001191 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 return result.Succeeded();
1193 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001194};
1195
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001196//-------------------------------------------------------------------------
1197// CommandObjectProcessInterrupt
1198//-------------------------------------------------------------------------
Jim Inghambb9caf72010-12-09 18:58:16 +00001199#pragma mark CommandObjectProcessInterrupt
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001200
Kate Stoneb9c1b512016-09-06 20:57:50 +00001201class CommandObjectProcessInterrupt : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001202public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 CommandObjectProcessInterrupt(CommandInterpreter &interpreter)
1204 : CommandObjectParsed(interpreter, "process interrupt",
1205 "Interrupt the current target process.",
1206 "process interrupt",
1207 eCommandRequiresProcess | eCommandTryTargetAPILock |
1208 eCommandProcessMustBeLaunched) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001209
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 ~CommandObjectProcessInterrupt() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001211
Jim Ingham5a988412012-06-08 21:56:10 +00001212protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 bool DoExecute(Args &command, CommandReturnObject &result) override {
1214 Process *process = m_exe_ctx.GetProcessPtr();
1215 if (process == nullptr) {
1216 result.AppendError("no process to halt");
1217 result.SetStatus(eReturnStatusFailed);
1218 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001219 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220
1221 if (command.GetArgumentCount() == 0) {
1222 bool clear_thread_plans = true;
1223 Error error(process->Halt(clear_thread_plans));
1224 if (error.Success()) {
1225 result.SetStatus(eReturnStatusSuccessFinishResult);
1226 } else {
1227 result.AppendErrorWithFormat("Failed to halt process: %s\n",
1228 error.AsCString());
1229 result.SetStatus(eReturnStatusFailed);
1230 }
1231 } else {
1232 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n",
1233 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1234 result.SetStatus(eReturnStatusFailed);
1235 }
1236 return result.Succeeded();
1237 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001238};
1239
1240//-------------------------------------------------------------------------
1241// CommandObjectProcessKill
1242//-------------------------------------------------------------------------
Jim Inghambb9caf72010-12-09 18:58:16 +00001243#pragma mark CommandObjectProcessKill
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001244
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245class CommandObjectProcessKill : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001246public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 CommandObjectProcessKill(CommandInterpreter &interpreter)
1248 : CommandObjectParsed(interpreter, "process kill",
1249 "Terminate the current target process.",
1250 "process kill",
1251 eCommandRequiresProcess | eCommandTryTargetAPILock |
1252 eCommandProcessMustBeLaunched) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001253
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254 ~CommandObjectProcessKill() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001255
Jim Ingham5a988412012-06-08 21:56:10 +00001256protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 bool DoExecute(Args &command, CommandReturnObject &result) override {
1258 Process *process = m_exe_ctx.GetProcessPtr();
1259 if (process == nullptr) {
1260 result.AppendError("no process to kill");
1261 result.SetStatus(eReturnStatusFailed);
1262 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001263 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264
1265 if (command.GetArgumentCount() == 0) {
1266 Error error(process->Destroy(true));
1267 if (error.Success()) {
1268 result.SetStatus(eReturnStatusSuccessFinishResult);
1269 } else {
1270 result.AppendErrorWithFormat("Failed to kill process: %s\n",
1271 error.AsCString());
1272 result.SetStatus(eReturnStatusFailed);
1273 }
1274 } else {
1275 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n",
1276 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1277 result.SetStatus(eReturnStatusFailed);
1278 }
1279 return result.Succeeded();
1280 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001281};
1282
1283//-------------------------------------------------------------------------
Greg Claytona2715cf2014-06-13 00:54:12 +00001284// CommandObjectProcessSaveCore
1285//-------------------------------------------------------------------------
1286#pragma mark CommandObjectProcessSaveCore
1287
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288class CommandObjectProcessSaveCore : public CommandObjectParsed {
Greg Claytona2715cf2014-06-13 00:54:12 +00001289public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001290 CommandObjectProcessSaveCore(CommandInterpreter &interpreter)
1291 : CommandObjectParsed(interpreter, "process save-core",
1292 "Save the current process as a core file using an "
1293 "appropriate file type.",
1294 "process save-core FILE",
1295 eCommandRequiresProcess | eCommandTryTargetAPILock |
1296 eCommandProcessMustBeLaunched) {}
Eugene Zelenko49bcfd82016-02-23 01:43:44 +00001297
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 ~CommandObjectProcessSaveCore() override = default;
Eugene Zelenko49bcfd82016-02-23 01:43:44 +00001299
Greg Claytona2715cf2014-06-13 00:54:12 +00001300protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 bool DoExecute(Args &command, CommandReturnObject &result) override {
1302 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1303 if (process_sp) {
1304 if (command.GetArgumentCount() == 1) {
1305 FileSpec output_file(command.GetArgumentAtIndex(0), false);
1306 Error error = PluginManager::SaveCore(process_sp, output_file);
1307 if (error.Success()) {
1308 result.SetStatus(eReturnStatusSuccessFinishResult);
1309 } else {
1310 result.AppendErrorWithFormat(
1311 "Failed to save core file for process: %s\n", error.AsCString());
1312 result.SetStatus(eReturnStatusFailed);
Greg Claytona2715cf2014-06-13 00:54:12 +00001313 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001314 } else {
1315 result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n",
1316 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1317 result.SetStatus(eReturnStatusFailed);
1318 }
1319 } else {
1320 result.AppendError("invalid process");
1321 result.SetStatus(eReturnStatusFailed);
1322 return false;
Greg Claytona2715cf2014-06-13 00:54:12 +00001323 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324
1325 return result.Succeeded();
1326 }
Greg Claytona2715cf2014-06-13 00:54:12 +00001327};
1328
1329//-------------------------------------------------------------------------
Jim Ingham4b9bea82010-06-18 01:23:09 +00001330// CommandObjectProcessStatus
1331//-------------------------------------------------------------------------
Jim Inghambb9caf72010-12-09 18:58:16 +00001332#pragma mark CommandObjectProcessStatus
1333
Kate Stoneb9c1b512016-09-06 20:57:50 +00001334class CommandObjectProcessStatus : public CommandObjectParsed {
Jim Ingham4b9bea82010-06-18 01:23:09 +00001335public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 CommandObjectProcessStatus(CommandInterpreter &interpreter)
1337 : CommandObjectParsed(
1338 interpreter, "process status",
1339 "Show status and stop location for the current target process.",
1340 "process status",
1341 eCommandRequiresProcess | eCommandTryTargetAPILock) {}
Jim Ingham4b9bea82010-06-18 01:23:09 +00001342
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343 ~CommandObjectProcessStatus() override = default;
Jim Ingham4b9bea82010-06-18 01:23:09 +00001344
Kate Stoneb9c1b512016-09-06 20:57:50 +00001345 bool DoExecute(Args &command, CommandReturnObject &result) override {
1346 Stream &strm = result.GetOutputStream();
1347 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1348 // No need to check "process" for validity as eCommandRequiresProcess
1349 // ensures it is valid
1350 Process *process = m_exe_ctx.GetProcessPtr();
1351 const bool only_threads_with_stop_reason = true;
1352 const uint32_t start_frame = 0;
1353 const uint32_t num_frames = 1;
1354 const uint32_t num_frames_with_source = 1;
1355 process->GetStatus(strm);
1356 process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1357 num_frames, num_frames_with_source);
1358 return result.Succeeded();
1359 }
Jim Ingham4b9bea82010-06-18 01:23:09 +00001360};
1361
1362//-------------------------------------------------------------------------
Caroline Tice35731352010-10-13 20:44:39 +00001363// CommandObjectProcessHandle
1364//-------------------------------------------------------------------------
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001365
1366static OptionDefinition g_process_handle_options[] = {
1367 // clang-format off
1368 { LLDB_OPT_SET_1, false, "stop", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Whether or not the process should be stopped if the signal is received." },
1369 { LLDB_OPT_SET_1, false, "notify", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Whether or not the debugger should notify the user if the signal is received." },
1370 { LLDB_OPT_SET_1, false, "pass", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Whether or not the signal should be passed to the process." }
1371 // clang-format on
1372};
1373
Jim Inghambb9caf72010-12-09 18:58:16 +00001374#pragma mark CommandObjectProcessHandle
Caroline Tice35731352010-10-13 20:44:39 +00001375
Kate Stoneb9c1b512016-09-06 20:57:50 +00001376class CommandObjectProcessHandle : public CommandObjectParsed {
Caroline Tice35731352010-10-13 20:44:39 +00001377public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378 class CommandOptions : public Options {
1379 public:
1380 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
Caroline Tice35731352010-10-13 20:44:39 +00001381
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 ~CommandOptions() override = default;
Caroline Tice35731352010-10-13 20:44:39 +00001383
Kate Stoneb9c1b512016-09-06 20:57:50 +00001384 Error SetOptionValue(uint32_t option_idx, const char *option_arg,
1385 ExecutionContext *execution_context) override {
1386 Error error;
1387 const int short_option = m_getopt_table[option_idx].val;
Caroline Tice35731352010-10-13 20:44:39 +00001388
Kate Stoneb9c1b512016-09-06 20:57:50 +00001389 switch (short_option) {
1390 case 's':
1391 stop = option_arg;
1392 break;
1393 case 'n':
1394 notify = option_arg;
1395 break;
1396 case 'p':
1397 pass = option_arg;
1398 break;
1399 default:
1400 error.SetErrorStringWithFormat("invalid short option character '%c'",
1401 short_option);
1402 break;
1403 }
1404 return error;
Caroline Tice35731352010-10-13 20:44:39 +00001405 }
1406
Kate Stoneb9c1b512016-09-06 20:57:50 +00001407 void OptionParsingStarting(ExecutionContext *execution_context) override {
1408 stop.clear();
1409 notify.clear();
1410 pass.clear();
Caroline Tice35731352010-10-13 20:44:39 +00001411 }
1412
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001413 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +00001414 return llvm::makeArrayRef(g_process_handle_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001415 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001416
1417 // Instance variables to hold the values for command options.
1418
1419 std::string stop;
1420 std::string notify;
1421 std::string pass;
1422 };
1423
1424 CommandObjectProcessHandle(CommandInterpreter &interpreter)
1425 : CommandObjectParsed(interpreter, "process handle",
1426 "Manage LLDB handling of OS signals for the "
1427 "current target process. Defaults to showing "
1428 "current policy.",
1429 nullptr),
1430 m_options() {
1431 SetHelpLong("\nIf no signals are specified, update them all. If no update "
1432 "option is specified, list the current values.");
1433 CommandArgumentEntry arg;
1434 CommandArgumentData signal_arg;
1435
1436 signal_arg.arg_type = eArgTypeUnixSignal;
1437 signal_arg.arg_repetition = eArgRepeatStar;
1438
1439 arg.push_back(signal_arg);
1440
1441 m_arguments.push_back(arg);
1442 }
1443
1444 ~CommandObjectProcessHandle() override = default;
1445
1446 Options *GetOptions() override { return &m_options; }
1447
1448 bool VerifyCommandOptionValue(const std::string &option, int &real_value) {
1449 bool okay = true;
1450 bool success = false;
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001451 bool tmp_value = Args::StringToBoolean(option, false, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001452
1453 if (success && tmp_value)
1454 real_value = 1;
1455 else if (success && !tmp_value)
1456 real_value = 0;
1457 else {
1458 // If the value isn't 'true' or 'false', it had better be 0 or 1.
1459 real_value = StringConvert::ToUInt32(option.c_str(), 3);
1460 if (real_value != 0 && real_value != 1)
1461 okay = false;
Caroline Tice35731352010-10-13 20:44:39 +00001462 }
1463
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464 return okay;
1465 }
Caroline Tice10ad7992010-10-14 21:31:13 +00001466
Kate Stoneb9c1b512016-09-06 20:57:50 +00001467 void PrintSignalHeader(Stream &str) {
1468 str.Printf("NAME PASS STOP NOTIFY\n");
1469 str.Printf("=========== ===== ===== ======\n");
1470 }
Caroline Tice10ad7992010-10-14 21:31:13 +00001471
Kate Stoneb9c1b512016-09-06 20:57:50 +00001472 void PrintSignal(Stream &str, int32_t signo, const char *sig_name,
1473 const UnixSignalsSP &signals_sp) {
1474 bool stop;
1475 bool suppress;
1476 bool notify;
1477
1478 str.Printf("%-11s ", sig_name);
1479 if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) {
1480 bool pass = !suppress;
1481 str.Printf("%s %s %s", (pass ? "true " : "false"),
1482 (stop ? "true " : "false"), (notify ? "true " : "false"));
Caroline Tice10ad7992010-10-14 21:31:13 +00001483 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484 str.Printf("\n");
1485 }
Caroline Tice10ad7992010-10-14 21:31:13 +00001486
Kate Stoneb9c1b512016-09-06 20:57:50 +00001487 void PrintSignalInformation(Stream &str, Args &signal_args,
1488 int num_valid_signals,
1489 const UnixSignalsSP &signals_sp) {
1490 PrintSignalHeader(str);
1491
1492 if (num_valid_signals > 0) {
1493 size_t num_args = signal_args.GetArgumentCount();
1494 for (size_t i = 0; i < num_args; ++i) {
1495 int32_t signo = signals_sp->GetSignalNumberFromName(
1496 signal_args.GetArgumentAtIndex(i));
1497 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
1498 PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i),
1499 signals_sp);
1500 }
1501 } else // Print info for ALL signals
Caroline Tice10ad7992010-10-14 21:31:13 +00001502 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001503 int32_t signo = signals_sp->GetFirstSignalNumber();
1504 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1505 PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo),
1506 signals_sp);
1507 signo = signals_sp->GetNextSignalNumber(signo);
1508 }
Caroline Tice10ad7992010-10-14 21:31:13 +00001509 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001510 }
Caroline Tice10ad7992010-10-14 21:31:13 +00001511
Jim Ingham5a988412012-06-08 21:56:10 +00001512protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001513 bool DoExecute(Args &signal_args, CommandReturnObject &result) override {
1514 TargetSP target_sp = m_interpreter.GetDebugger().GetSelectedTarget();
Caroline Tice35731352010-10-13 20:44:39 +00001515
Kate Stoneb9c1b512016-09-06 20:57:50 +00001516 if (!target_sp) {
1517 result.AppendError("No current target;"
1518 " cannot handle signals until you have a valid target "
1519 "and process.\n");
1520 result.SetStatus(eReturnStatusFailed);
1521 return false;
Caroline Tice35731352010-10-13 20:44:39 +00001522 }
1523
Kate Stoneb9c1b512016-09-06 20:57:50 +00001524 ProcessSP process_sp = target_sp->GetProcessSP();
1525
1526 if (!process_sp) {
1527 result.AppendError("No current process; cannot handle signals until you "
1528 "have a valid process.\n");
1529 result.SetStatus(eReturnStatusFailed);
1530 return false;
1531 }
1532
1533 int stop_action = -1; // -1 means leave the current setting alone
1534 int pass_action = -1; // -1 means leave the current setting alone
1535 int notify_action = -1; // -1 means leave the current setting alone
1536
1537 if (!m_options.stop.empty() &&
1538 !VerifyCommandOptionValue(m_options.stop, stop_action)) {
1539 result.AppendError("Invalid argument for command option --stop; must be "
1540 "true or false.\n");
1541 result.SetStatus(eReturnStatusFailed);
1542 return false;
1543 }
1544
1545 if (!m_options.notify.empty() &&
1546 !VerifyCommandOptionValue(m_options.notify, notify_action)) {
1547 result.AppendError("Invalid argument for command option --notify; must "
1548 "be true or false.\n");
1549 result.SetStatus(eReturnStatusFailed);
1550 return false;
1551 }
1552
1553 if (!m_options.pass.empty() &&
1554 !VerifyCommandOptionValue(m_options.pass, pass_action)) {
1555 result.AppendError("Invalid argument for command option --pass; must be "
1556 "true or false.\n");
1557 result.SetStatus(eReturnStatusFailed);
1558 return false;
1559 }
1560
1561 size_t num_args = signal_args.GetArgumentCount();
1562 UnixSignalsSP signals_sp = process_sp->GetUnixSignals();
1563 int num_signals_set = 0;
1564
1565 if (num_args > 0) {
1566 for (size_t i = 0; i < num_args; ++i) {
1567 int32_t signo = signals_sp->GetSignalNumberFromName(
1568 signal_args.GetArgumentAtIndex(i));
1569 if (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1570 // Casting the actions as bools here should be okay, because
1571 // VerifyCommandOptionValue guarantees
1572 // the value is either 0 or 1.
1573 if (stop_action != -1)
1574 signals_sp->SetShouldStop(signo, stop_action);
1575 if (pass_action != -1) {
1576 bool suppress = !pass_action;
1577 signals_sp->SetShouldSuppress(signo, suppress);
1578 }
1579 if (notify_action != -1)
1580 signals_sp->SetShouldNotify(signo, notify_action);
1581 ++num_signals_set;
1582 } else {
1583 result.AppendErrorWithFormat("Invalid signal name '%s'\n",
1584 signal_args.GetArgumentAtIndex(i));
1585 }
1586 }
1587 } else {
1588 // No signal specified, if any command options were specified, update ALL
1589 // signals.
1590 if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) {
1591 if (m_interpreter.Confirm(
1592 "Do you really want to update all the signals?", false)) {
1593 int32_t signo = signals_sp->GetFirstSignalNumber();
1594 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1595 if (notify_action != -1)
1596 signals_sp->SetShouldNotify(signo, notify_action);
1597 if (stop_action != -1)
1598 signals_sp->SetShouldStop(signo, stop_action);
1599 if (pass_action != -1) {
1600 bool suppress = !pass_action;
1601 signals_sp->SetShouldSuppress(signo, suppress);
1602 }
1603 signo = signals_sp->GetNextSignalNumber(signo);
1604 }
1605 }
1606 }
1607 }
1608
1609 PrintSignalInformation(result.GetOutputStream(), signal_args,
1610 num_signals_set, signals_sp);
1611
1612 if (num_signals_set > 0)
1613 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1614 else
1615 result.SetStatus(eReturnStatusFailed);
1616
1617 return result.Succeeded();
1618 }
1619
1620 CommandOptions m_options;
Caroline Tice35731352010-10-13 20:44:39 +00001621};
1622
Caroline Tice35731352010-10-13 20:44:39 +00001623//-------------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001624// CommandObjectMultiwordProcess
1625//-------------------------------------------------------------------------
1626
Kate Stoneb9c1b512016-09-06 20:57:50 +00001627CommandObjectMultiwordProcess::CommandObjectMultiwordProcess(
1628 CommandInterpreter &interpreter)
1629 : CommandObjectMultiword(
1630 interpreter, "process",
1631 "Commands for interacting with processes on the current platform.",
1632 "process <subcommand> [<subcommand-options>]") {
1633 LoadSubCommand("attach",
1634 CommandObjectSP(new CommandObjectProcessAttach(interpreter)));
1635 LoadSubCommand("launch",
1636 CommandObjectSP(new CommandObjectProcessLaunch(interpreter)));
1637 LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue(
1638 interpreter)));
1639 LoadSubCommand("connect",
1640 CommandObjectSP(new CommandObjectProcessConnect(interpreter)));
1641 LoadSubCommand("detach",
1642 CommandObjectSP(new CommandObjectProcessDetach(interpreter)));
1643 LoadSubCommand("load",
1644 CommandObjectSP(new CommandObjectProcessLoad(interpreter)));
1645 LoadSubCommand("unload",
1646 CommandObjectSP(new CommandObjectProcessUnload(interpreter)));
1647 LoadSubCommand("signal",
1648 CommandObjectSP(new CommandObjectProcessSignal(interpreter)));
1649 LoadSubCommand("handle",
1650 CommandObjectSP(new CommandObjectProcessHandle(interpreter)));
1651 LoadSubCommand("status",
1652 CommandObjectSP(new CommandObjectProcessStatus(interpreter)));
1653 LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt(
1654 interpreter)));
1655 LoadSubCommand("kill",
1656 CommandObjectSP(new CommandObjectProcessKill(interpreter)));
1657 LoadSubCommand("plugin",
1658 CommandObjectSP(new CommandObjectProcessPlugin(interpreter)));
1659 LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore(
1660 interpreter)));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001661}
1662
Eugene Zelenko49bcfd82016-02-23 01:43:44 +00001663CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default;