blob: 1cc0b0b43c78a85ffd0362b05e85c3c71bbadd0f [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- CommandObjectProcess.cpp --------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Eugene Zelenko49bcfd82016-02-23 01:43:44 +00009#include "CommandObjectProcess.h"
Jim Ingham0e410842012-08-11 01:27:55 +000010#include "lldb/Breakpoint/Breakpoint.h"
11#include "lldb/Breakpoint/BreakpointLocation.h"
12#include "lldb/Breakpoint/BreakpointSite.h"
Greg Clayton1f746072012-08-29 21:13:06 +000013#include "lldb/Core/Module.h"
Greg Claytona2715cf2014-06-13 00:54:12 +000014#include "lldb/Core/PluginManager.h"
Greg Clayton7260f622011-04-18 08:33:37 +000015#include "lldb/Host/Host.h"
Zachary Turner3eb2b442017-03-22 23:33:16 +000016#include "lldb/Host/OptionParser.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000017#include "lldb/Host/StringConvert.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Interpreter/CommandInterpreter.h"
19#include "lldb/Interpreter/CommandReturnObject.h"
Pavel Labath47cbf4a2018-04-10 09:03:59 +000020#include "lldb/Interpreter/OptionArgParser.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include "lldb/Interpreter/Options.h"
Greg Claytone996fd32011-03-08 22:40:15 +000022#include "lldb/Target/Platform.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include "lldb/Target/Process.h"
Jim Ingham0e410842012-08-11 01:27:55 +000024#include "lldb/Target/StopInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000025#include "lldb/Target/Target.h"
26#include "lldb/Target/Thread.h"
Zachary Turner93749ab2015-03-03 21:51:25 +000027#include "lldb/Target/UnixSignals.h"
Pavel Labath145d95c2018-04-17 18:53:35 +000028#include "lldb/Utility/Args.h"
Pavel Labathd821c992018-08-07 11:07:21 +000029#include "lldb/Utility/State.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030
31using namespace lldb;
32using namespace lldb_private;
33
Kate Stoneb9c1b512016-09-06 20:57:50 +000034class CommandObjectProcessLaunchOrAttach : public CommandObjectParsed {
Jim Inghamdcb1d852013-03-29 00:56:30 +000035public:
Kate Stoneb9c1b512016-09-06 20:57:50 +000036 CommandObjectProcessLaunchOrAttach(CommandInterpreter &interpreter,
37 const char *name, const char *help,
38 const char *syntax, uint32_t flags,
39 const char *new_process_action)
40 : CommandObjectParsed(interpreter, name, help, syntax, flags),
41 m_new_process_action(new_process_action) {}
Eugene Zelenko49bcfd82016-02-23 01:43:44 +000042
Kate Stoneb9c1b512016-09-06 20:57:50 +000043 ~CommandObjectProcessLaunchOrAttach() override = default;
Eugene Zelenko49bcfd82016-02-23 01:43:44 +000044
Jim Inghamdcb1d852013-03-29 00:56:30 +000045protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +000046 bool StopProcessIfNecessary(Process *process, StateType &state,
47 CommandReturnObject &result) {
48 state = eStateInvalid;
49 if (process) {
50 state = process->GetState();
Eugene Zelenko49bcfd82016-02-23 01:43:44 +000051
Kate Stoneb9c1b512016-09-06 20:57:50 +000052 if (process->IsAlive() && state != eStateConnected) {
53 char message[1024];
54 if (process->GetState() == eStateAttaching)
55 ::snprintf(message, sizeof(message),
56 "There is a pending attach, abort it and %s?",
57 m_new_process_action.c_str());
58 else if (process->GetShouldDetach())
59 ::snprintf(message, sizeof(message),
60 "There is a running process, detach from it and %s?",
61 m_new_process_action.c_str());
62 else
63 ::snprintf(message, sizeof(message),
64 "There is a running process, kill it and %s?",
65 m_new_process_action.c_str());
66
67 if (!m_interpreter.Confirm(message, true)) {
68 result.SetStatus(eReturnStatusFailed);
69 return false;
70 } else {
71 if (process->GetShouldDetach()) {
72 bool keep_stopped = false;
Zachary Turner97206d52017-05-12 04:51:55 +000073 Status detach_error(process->Detach(keep_stopped));
Kate Stoneb9c1b512016-09-06 20:57:50 +000074 if (detach_error.Success()) {
75 result.SetStatus(eReturnStatusSuccessFinishResult);
76 process = nullptr;
77 } else {
78 result.AppendErrorWithFormat(
79 "Failed to detach from process: %s\n",
80 detach_error.AsCString());
81 result.SetStatus(eReturnStatusFailed);
82 }
83 } else {
Zachary Turner97206d52017-05-12 04:51:55 +000084 Status destroy_error(process->Destroy(false));
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 if (destroy_error.Success()) {
86 result.SetStatus(eReturnStatusSuccessFinishResult);
87 process = nullptr;
88 } else {
89 result.AppendErrorWithFormat("Failed to kill process: %s\n",
90 destroy_error.AsCString());
91 result.SetStatus(eReturnStatusFailed);
92 }
93 }
94 }
95 }
96 }
97 return result.Succeeded();
98 }
99
100 std::string m_new_process_action;
Jim Inghamdcb1d852013-03-29 00:56:30 +0000101};
Eugene Zelenko49bcfd82016-02-23 01:43:44 +0000102
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000103// CommandObjectProcessLaunch
Jim Ingham4bddaeb2012-02-16 06:50:00 +0000104#pragma mark CommandObjectProcessLaunch
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000106public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107 CommandObjectProcessLaunch(CommandInterpreter &interpreter)
108 : CommandObjectProcessLaunchOrAttach(
109 interpreter, "process launch",
110 "Launch the executable in the debugger.", nullptr,
111 eCommandRequiresTarget, "restart"),
112 m_options() {
113 CommandArgumentEntry arg;
114 CommandArgumentData run_args_arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000115
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 // Define the first (and only) variant of this arg.
117 run_args_arg.arg_type = eArgTypeRunArgs;
118 run_args_arg.arg_repetition = eArgRepeatOptional;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000119
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 // There is only one variant this argument could be; put it into the
121 // argument entry.
122 arg.push_back(run_args_arg);
Todd Fialae1cfbc72016-08-11 23:51:28 +0000123
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124 // Push the data for the first argument into the m_arguments vector.
125 m_arguments.push_back(arg);
126 }
Jim Inghame9ce62b2012-08-10 21:48:41 +0000127
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 ~CommandObjectProcessLaunch() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000129
Raphael Isemann2443bbd2018-07-02 21:29:56 +0000130 int HandleArgumentCompletion(
131 CompletionRequest &request,
132 OptionElementVector &opt_element_vector) override {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133
134 CommandCompletions::InvokeCommonCompletionCallbacks(
135 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000136 request, nullptr);
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +0000137 return request.GetNumberOfMatches();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000138 }
139
140 Options *GetOptions() override { return &m_options; }
141
142 const char *GetRepeatCommand(Args &current_command_args,
143 uint32_t index) override {
144 // No repeat for "process launch"...
145 return "";
146 }
Jim Ingham5a988412012-06-08 21:56:10 +0000147
148protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 bool DoExecute(Args &launch_args, CommandReturnObject &result) override {
Jonas Devlieghere57179862019-04-27 06:19:42 +0000150 Debugger &debugger = GetDebugger();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 Target *target = debugger.GetSelectedTarget().get();
152 // If our listener is nullptr, users aren't allows to launch
153 ModuleSP exe_module_sp = target->GetExecutableModule();
Greg Clayton71337622011-02-24 22:24:29 +0000154
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 if (exe_module_sp == nullptr) {
156 result.AppendError("no file in target, create a debug target using the "
157 "'target create' command");
158 result.SetStatus(eReturnStatusFailed);
159 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000160 }
161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 StateType state = eStateInvalid;
163
164 if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result))
165 return false;
166
Zachary Turner31d97a52016-11-17 18:08:12 +0000167 llvm::StringRef target_settings_argv0 = target->GetArg0();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168
169 // Determine whether we will disable ASLR or leave it in the default state
Adrian Prantl05097242018-04-30 16:49:04 +0000170 // (i.e. enabled if the platform supports it). First check if the process
171 // launch options explicitly turn on/off
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172 // disabling ASLR. If so, use that setting;
173 // otherwise, use the 'settings target.disable-aslr' setting.
174 bool disable_aslr = false;
175 if (m_options.disable_aslr != eLazyBoolCalculate) {
Adrian Prantl05097242018-04-30 16:49:04 +0000176 // The user specified an explicit setting on the process launch line.
177 // Use it.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000178 disable_aslr = (m_options.disable_aslr == eLazyBoolYes);
179 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000180 // The user did not explicitly specify whether to disable ASLR. Fall
181 // back to the target.disable-aslr setting.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182 disable_aslr = target->GetDisableASLR();
183 }
184
185 if (disable_aslr)
186 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
187 else
188 m_options.launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
189
190 if (target->GetDetachOnError())
191 m_options.launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
192
193 if (target->GetDisableSTDIO())
194 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO);
195
Pavel Labath62930e52018-01-10 11:57:31 +0000196 m_options.launch_info.GetEnvironment() = target->GetEnvironment();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197
Zachary Turner31d97a52016-11-17 18:08:12 +0000198 if (!target_settings_argv0.empty()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 m_options.launch_info.GetArguments().AppendArgument(
Zachary Turner31d97a52016-11-17 18:08:12 +0000200 target_settings_argv0);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 m_options.launch_info.SetExecutableFile(
202 exe_module_sp->GetPlatformFileSpec(), false);
203 } else {
204 m_options.launch_info.SetExecutableFile(
205 exe_module_sp->GetPlatformFileSpec(), true);
206 }
207
208 if (launch_args.GetArgumentCount() == 0) {
209 m_options.launch_info.GetArguments().AppendArguments(
210 target->GetProcessLaunchInfo().GetArguments());
211 } else {
212 m_options.launch_info.GetArguments().AppendArguments(launch_args);
213 // Save the arguments for subsequent runs in the current target.
214 target->SetRunArguments(launch_args);
215 }
216
217 StreamString stream;
Zachary Turner97206d52017-05-12 04:51:55 +0000218 Status error = target->Launch(m_options.launch_info, &stream);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219
220 if (error.Success()) {
221 ProcessSP process_sp(target->GetProcessSP());
222 if (process_sp) {
223 // There is a race condition where this thread will return up the call
Adrian Prantl05097242018-04-30 16:49:04 +0000224 // stack to the main command handler and show an (lldb) prompt before
225 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
226 // PushProcessIOHandler().
Pavel Labath3879fe02018-05-09 14:29:30 +0000227 process_sp->SyncIOHandler(0, std::chrono::seconds(2));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228
Zachary Turnerc1564272016-11-16 21:15:24 +0000229 llvm::StringRef data = stream.GetString();
230 if (!data.empty())
231 result.AppendMessage(data);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 const char *archname =
233 exe_module_sp->GetArchitecture().GetArchitectureName();
234 result.AppendMessageWithFormat(
235 "Process %" PRIu64 " launched: '%s' (%s)\n", process_sp->GetID(),
236 exe_module_sp->GetFileSpec().GetPath().c_str(), archname);
237 result.SetStatus(eReturnStatusSuccessFinishResult);
238 result.SetDidChangeProcessState(true);
239 } else {
240 result.AppendError(
241 "no error returned from Target::Launch, and target has no process");
242 result.SetStatus(eReturnStatusFailed);
243 }
244 } else {
245 result.AppendError(error.AsCString());
246 result.SetStatus(eReturnStatusFailed);
247 }
248 return result.Succeeded();
249 }
250
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000251protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252 ProcessLaunchCommandOptions m_options;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000253};
254
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000255static constexpr OptionDefinition g_process_attach_options[] = {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000256 // clang-format off
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000257 { LLDB_OPT_SET_ALL, false, "continue", 'c', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Immediately continue the process once attached." },
258 { LLDB_OPT_SET_ALL, false, "plugin", 'P', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePlugin, "Name of the process plugin you want to use." },
259 { LLDB_OPT_SET_1, false, "pid", 'p', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePid, "The process ID of an existing process to attach to." },
260 { LLDB_OPT_SET_2, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeProcessName, "The name of the process to attach to." },
261 { LLDB_OPT_SET_2, false, "include-existing", 'i', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Include existing processes when doing attach -w." },
262 { LLDB_OPT_SET_2, false, "waitfor", 'w', OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, "Wait for the process with <process-name> to launch." },
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000263 // clang-format on
264};
265
Jim Inghambb9caf72010-12-09 18:58:16 +0000266#pragma mark CommandObjectProcessAttach
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000268public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 class CommandOptions : public Options {
270 public:
271 CommandOptions() : Options() {
272 // Keep default values of all options in one place: OptionParsingStarting
273 // ()
274 OptionParsingStarting(nullptr);
Jim Ingham5aee1622010-08-09 23:31:02 +0000275 }
276
Kate Stoneb9c1b512016-09-06 20:57:50 +0000277 ~CommandOptions() override = default;
Jim Ingham5aee1622010-08-09 23:31:02 +0000278
Zachary Turner97206d52017-05-12 04:51:55 +0000279 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
280 ExecutionContext *execution_context) override {
281 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 const int short_option = m_getopt_table[option_idx].val;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283 switch (short_option) {
284 case 'c':
285 attach_info.SetContinueOnceAttached(true);
286 break;
287
288 case 'p': {
Zachary Turnerfe114832016-11-12 16:56:47 +0000289 lldb::pid_t pid;
290 if (option_arg.getAsInteger(0, pid)) {
291 error.SetErrorStringWithFormat("invalid process ID '%s'",
292 option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293 } else {
294 attach_info.SetProcessID(pid);
295 }
296 } break;
297
298 case 'P':
299 attach_info.SetProcessPluginName(option_arg);
300 break;
301
302 case 'n':
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000303 attach_info.GetExecutableFile().SetFile(option_arg,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000304 FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305 break;
306
307 case 'w':
308 attach_info.SetWaitForLaunch(true);
309 break;
310
311 case 'i':
312 attach_info.SetIgnoreExisting(false);
313 break;
314
315 default:
316 error.SetErrorStringWithFormat("invalid short option character '%c'",
317 short_option);
318 break;
319 }
320 return error;
Jim Ingham5a988412012-06-08 21:56:10 +0000321 }
322
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 void OptionParsingStarting(ExecutionContext *execution_context) override {
324 attach_info.Clear();
325 }
326
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000327 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +0000328 return llvm::makeArrayRef(g_process_attach_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000329 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330
331 bool HandleOptionArgumentCompletion(
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000332 CompletionRequest &request, OptionElementVector &opt_element_vector,
333 int opt_element_index, CommandInterpreter &interpreter) override {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000334 int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos;
335 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
336
337 // We are only completing the name option for now...
338
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000339 if (GetDefinitions()[opt_defs_index].short_option == 'n') {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 // Are we in the name?
341
342 // Look to see if there is a -P argument provided, and if so use that
Adrian Prantl05097242018-04-30 16:49:04 +0000343 // plugin, otherwise use the default plugin.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344
345 const char *partial_name = nullptr;
Raphael Isemanna2e76c02018-07-13 18:28:14 +0000346 partial_name = request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347
348 PlatformSP platform_sp(interpreter.GetPlatform(true));
349 if (platform_sp) {
350 ProcessInstanceInfoList process_infos;
351 ProcessInstanceInfoMatch match_info;
352 if (partial_name) {
353 match_info.GetProcessInfo().GetExecutableFile().SetFile(
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000354 partial_name, FileSpec::Style::native);
Pavel Labathc4a33952017-02-20 11:35:33 +0000355 match_info.SetNameMatchType(NameMatch::StartsWith);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 }
357 platform_sp->FindProcesses(match_info, process_infos);
358 const size_t num_matches = process_infos.GetSize();
359 if (num_matches > 0) {
360 for (size_t i = 0; i < num_matches; ++i) {
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +0000361 request.AddCompletion(llvm::StringRef(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 process_infos.GetProcessNameAtIndex(i),
Raphael Isemann1a6d7ab2018-07-27 18:42:46 +0000363 process_infos.GetProcessNameLengthAtIndex(i)));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 }
365 }
366 }
367 }
368
369 return false;
370 }
371
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 // Instance variables to hold the values for command options.
373
374 ProcessAttachInfo attach_info;
375 };
376
377 CommandObjectProcessAttach(CommandInterpreter &interpreter)
378 : CommandObjectProcessLaunchOrAttach(
379 interpreter, "process attach", "Attach to a process.",
380 "process attach <cmd-options>", 0, "attach"),
381 m_options() {}
382
383 ~CommandObjectProcessAttach() override = default;
384
385 Options *GetOptions() override { return &m_options; }
386
Jim Ingham5a988412012-06-08 21:56:10 +0000387protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 bool DoExecute(Args &command, CommandReturnObject &result) override {
389 PlatformSP platform_sp(
Jonas Devlieghere57179862019-04-27 06:19:42 +0000390 GetDebugger().GetPlatformList().GetSelectedPlatform());
Oleksiy Vyalov926af0c2015-02-03 00:04:35 +0000391
Jonas Devlieghere57179862019-04-27 06:19:42 +0000392 Target *target = GetDebugger().GetSelectedTarget().get();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 // N.B. The attach should be synchronous. It doesn't help much to get the
Adrian Prantl05097242018-04-30 16:49:04 +0000394 // prompt back between initiating the attach and the target actually
395 // stopping. So even if the interpreter is set to be asynchronous, we wait
396 // for the stop ourselves here.
Jim Ingham5aee1622010-08-09 23:31:02 +0000397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 StateType state = eStateInvalid;
399 Process *process = m_exe_ctx.GetProcessPtr();
Oleksiy Vyalov926af0c2015-02-03 00:04:35 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 if (!StopProcessIfNecessary(process, state, result))
402 return false;
Oleksiy Vyalov926af0c2015-02-03 00:04:35 +0000403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 if (target == nullptr) {
405 // If there isn't a current target create one.
406 TargetSP new_target_sp;
Zachary Turner97206d52017-05-12 04:51:55 +0000407 Status error;
Oleksiy Vyalov926af0c2015-02-03 00:04:35 +0000408
Jonas Devlieghere57179862019-04-27 06:19:42 +0000409 error = GetDebugger().GetTargetList().CreateTarget(
410 GetDebugger(), "", "", eLoadDependentsNo,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 nullptr, // No platform options
412 new_target_sp);
413 target = new_target_sp.get();
414 if (target == nullptr || error.Fail()) {
415 result.AppendError(error.AsCString("Error creating target"));
416 return false;
417 }
Jonas Devlieghere57179862019-04-27 06:19:42 +0000418 GetDebugger().GetTargetList().SetSelectedTarget(target);
Jim Ingham5aee1622010-08-09 23:31:02 +0000419 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420
421 // Record the old executable module, we want to issue a warning if the
Adrian Prantl05097242018-04-30 16:49:04 +0000422 // process of attaching changed the current executable (like somebody said
423 // "file foo" then attached to a PID whose executable was bar.)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424
425 ModuleSP old_exec_module_sp = target->GetExecutableModule();
426 ArchSpec old_arch_spec = target->GetArchitecture();
427
428 if (command.GetArgumentCount()) {
429 result.AppendErrorWithFormat("Invalid arguments for '%s'.\nUsage: %s\n",
430 m_cmd_name.c_str(), m_cmd_syntax.c_str());
431 result.SetStatus(eReturnStatusFailed);
432 return false;
433 }
434
435 m_interpreter.UpdateExecutionContext(nullptr);
436 StreamString stream;
437 const auto error = target->Attach(m_options.attach_info, &stream);
438 if (error.Success()) {
439 ProcessSP process_sp(target->GetProcessSP());
440 if (process_sp) {
Zachary Turnerc1564272016-11-16 21:15:24 +0000441 result.AppendMessage(stream.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 result.SetStatus(eReturnStatusSuccessFinishNoResult);
443 result.SetDidChangeProcessState(true);
444 result.SetAbnormalStopWasExpected(true);
445 } else {
446 result.AppendError(
447 "no error returned from Target::Attach, and target has no process");
448 result.SetStatus(eReturnStatusFailed);
449 }
450 } else {
451 result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString());
452 result.SetStatus(eReturnStatusFailed);
453 }
454
455 if (!result.Succeeded())
456 return false;
457
458 // Okay, we're done. Last step is to warn if the executable module has
459 // changed:
460 char new_path[PATH_MAX];
461 ModuleSP new_exec_module_sp(target->GetExecutableModule());
462 if (!old_exec_module_sp) {
463 // We might not have a module if we attached to a raw pid...
464 if (new_exec_module_sp) {
465 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
466 result.AppendMessageWithFormat("Executable module set to \"%s\".\n",
467 new_path);
468 }
469 } else if (old_exec_module_sp->GetFileSpec() !=
470 new_exec_module_sp->GetFileSpec()) {
471 char old_path[PATH_MAX];
472
473 old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX);
474 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
475
476 result.AppendWarningWithFormat(
477 "Executable module changed from \"%s\" to \"%s\".\n", old_path,
478 new_path);
479 }
480
481 if (!old_arch_spec.IsValid()) {
482 result.AppendMessageWithFormat(
483 "Architecture set to: %s.\n",
484 target->GetArchitecture().GetTriple().getTriple().c_str());
485 } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) {
486 result.AppendWarningWithFormat(
487 "Architecture changed from %s to %s.\n",
488 old_arch_spec.GetTriple().getTriple().c_str(),
489 target->GetArchitecture().GetTriple().getTriple().c_str());
490 }
491
Adrian Prantl05097242018-04-30 16:49:04 +0000492 // This supports the use-case scenario of immediately continuing the
493 // process once attached.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 if (m_options.attach_info.GetContinueOnceAttached())
495 m_interpreter.HandleCommand("process continue", eLazyBoolNo, result);
496
497 return result.Succeeded();
498 }
499
500 CommandOptions m_options;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000501};
502
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000503// CommandObjectProcessContinue
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000504
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000505static constexpr OptionDefinition g_process_continue_options[] = {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000506 // clang-format off
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000507 { LLDB_OPT_SET_ALL, false, "ignore-count",'i', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeUnsignedInteger, "Ignore <N> crossings of the breakpoint (if it exists) for the currently selected thread." }
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000508 // clang-format on
509};
510
Jim Inghambb9caf72010-12-09 18:58:16 +0000511#pragma mark CommandObjectProcessContinue
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000512
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513class CommandObjectProcessContinue : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000514public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 CommandObjectProcessContinue(CommandInterpreter &interpreter)
516 : CommandObjectParsed(
517 interpreter, "process continue",
518 "Continue execution of all threads in the current process.",
519 "process continue",
520 eCommandRequiresProcess | eCommandTryTargetAPILock |
521 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
522 m_options() {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000523
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524 ~CommandObjectProcessContinue() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000525
Jim Ingham5a988412012-06-08 21:56:10 +0000526protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527 class CommandOptions : public Options {
528 public:
529 CommandOptions() : Options() {
530 // Keep default values of all options in one place: OptionParsingStarting
531 // ()
532 OptionParsingStarting(nullptr);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000533 }
Jim Ingham0e410842012-08-11 01:27:55 +0000534
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 ~CommandOptions() override = default;
536
Zachary Turner97206d52017-05-12 04:51:55 +0000537 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
538 ExecutionContext *execution_context) override {
539 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540 const int short_option = m_getopt_table[option_idx].val;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 switch (short_option) {
542 case 'i':
Zachary Turnerfe114832016-11-12 16:56:47 +0000543 if (option_arg.getAsInteger(0, m_ignore))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 error.SetErrorStringWithFormat(
545 "invalid value for ignore option: \"%s\", should be a number.",
Zachary Turnerfe114832016-11-12 16:56:47 +0000546 option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 break;
548
549 default:
550 error.SetErrorStringWithFormat("invalid short option character '%c'",
551 short_option);
552 break;
553 }
554 return error;
Jim Ingham0e410842012-08-11 01:27:55 +0000555 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556
557 void OptionParsingStarting(ExecutionContext *execution_context) override {
558 m_ignore = 0;
559 }
560
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000561 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +0000562 return llvm::makeArrayRef(g_process_continue_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000563 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564
565 uint32_t m_ignore;
566 };
567
568 bool DoExecute(Args &command, CommandReturnObject &result) override {
569 Process *process = m_exe_ctx.GetProcessPtr();
570 bool synchronous_execution = m_interpreter.GetSynchronous();
571 StateType state = process->GetState();
572 if (state == eStateStopped) {
573 if (command.GetArgumentCount() != 0) {
574 result.AppendErrorWithFormat(
575 "The '%s' command does not take any arguments.\n",
576 m_cmd_name.c_str());
577 result.SetStatus(eReturnStatusFailed);
578 return false;
579 }
580
581 if (m_options.m_ignore > 0) {
582 ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this());
583 if (sel_thread_sp) {
584 StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo();
585 if (stop_info_sp &&
586 stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
587 lldb::break_id_t bp_site_id =
588 (lldb::break_id_t)stop_info_sp->GetValue();
589 BreakpointSiteSP bp_site_sp(
590 process->GetBreakpointSiteList().FindByID(bp_site_id));
591 if (bp_site_sp) {
592 const size_t num_owners = bp_site_sp->GetNumberOfOwners();
593 for (size_t i = 0; i < num_owners; i++) {
594 Breakpoint &bp_ref =
595 bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
596 if (!bp_ref.IsInternal()) {
597 bp_ref.SetIgnoreCount(m_options.m_ignore);
598 }
599 }
600 }
601 }
602 }
603 }
604
605 { // Scope for thread list mutex:
606 std::lock_guard<std::recursive_mutex> guard(
607 process->GetThreadList().GetMutex());
608 const uint32_t num_threads = process->GetThreadList().GetSize();
609
610 // Set the actions that the threads should each take when resuming
611 for (uint32_t idx = 0; idx < num_threads; ++idx) {
612 const bool override_suspend = false;
613 process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState(
614 eStateRunning, override_suspend);
615 }
616 }
617
618 const uint32_t iohandler_id = process->GetIOHandlerID();
619
620 StreamString stream;
Zachary Turner97206d52017-05-12 04:51:55 +0000621 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622 if (synchronous_execution)
623 error = process->ResumeSynchronous(&stream);
624 else
625 error = process->Resume();
626
627 if (error.Success()) {
628 // There is a race condition where this thread will return up the call
Adrian Prantl05097242018-04-30 16:49:04 +0000629 // stack to the main command handler and show an (lldb) prompt before
630 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
631 // PushProcessIOHandler().
Pavel Labath3879fe02018-05-09 14:29:30 +0000632 process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633
634 result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
635 process->GetID());
636 if (synchronous_execution) {
637 // If any state changed events had anything to say, add that to the
638 // result
Zachary Turnerc1564272016-11-16 21:15:24 +0000639 result.AppendMessage(stream.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000640
641 result.SetDidChangeProcessState(true);
642 result.SetStatus(eReturnStatusSuccessFinishNoResult);
643 } else {
644 result.SetStatus(eReturnStatusSuccessContinuingNoResult);
645 }
646 } else {
647 result.AppendErrorWithFormat("Failed to resume process: %s.\n",
648 error.AsCString());
649 result.SetStatus(eReturnStatusFailed);
650 }
651 } else {
652 result.AppendErrorWithFormat(
653 "Process cannot be continued from its current state (%s).\n",
654 StateAsCString(state));
655 result.SetStatus(eReturnStatusFailed);
656 }
657 return result.Succeeded();
658 }
659
660 Options *GetOptions() override { return &m_options; }
661
662 CommandOptions m_options;
Jim Ingham0e410842012-08-11 01:27:55 +0000663};
664
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000665// CommandObjectProcessDetach
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000666static constexpr OptionDefinition g_process_detach_options[] = {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000667 // clang-format off
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000668 { LLDB_OPT_SET_1, false, "keep-stopped", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Whether or not the process should be kept stopped on detach (if possible)." },
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000669 // clang-format on
670};
671
Jim Inghambb9caf72010-12-09 18:58:16 +0000672#pragma mark CommandObjectProcessDetach
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000673
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674class CommandObjectProcessDetach : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000675public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000676 class CommandOptions : public Options {
677 public:
678 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
679
680 ~CommandOptions() override = default;
681
Zachary Turner97206d52017-05-12 04:51:55 +0000682 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
683 ExecutionContext *execution_context) override {
684 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685 const int short_option = m_getopt_table[option_idx].val;
686
687 switch (short_option) {
688 case 's':
689 bool tmp_result;
690 bool success;
Pavel Labath47cbf4a2018-04-10 09:03:59 +0000691 tmp_result = OptionArgParser::ToBoolean(option_arg, false, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 if (!success)
693 error.SetErrorStringWithFormat("invalid boolean option: \"%s\"",
Zachary Turnerfe114832016-11-12 16:56:47 +0000694 option_arg.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 else {
696 if (tmp_result)
697 m_keep_stopped = eLazyBoolYes;
698 else
699 m_keep_stopped = eLazyBoolNo;
Jim Inghamacff8952013-05-02 00:27:30 +0000700 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 break;
702 default:
703 error.SetErrorStringWithFormat("invalid short option character '%c'",
704 short_option);
705 break;
706 }
707 return error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000708 }
709
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 void OptionParsingStarting(ExecutionContext *execution_context) override {
711 m_keep_stopped = eLazyBoolCalculate;
Jim Inghamacff8952013-05-02 00:27:30 +0000712 }
713
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000714 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +0000715 return llvm::makeArrayRef(g_process_detach_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000716 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717
718 // Instance variables to hold the values for command options.
719 LazyBool m_keep_stopped;
720 };
721
722 CommandObjectProcessDetach(CommandInterpreter &interpreter)
723 : CommandObjectParsed(interpreter, "process detach",
724 "Detach from the current target process.",
725 "process detach",
726 eCommandRequiresProcess | eCommandTryTargetAPILock |
727 eCommandProcessMustBeLaunched),
728 m_options() {}
729
730 ~CommandObjectProcessDetach() override = default;
731
732 Options *GetOptions() override { return &m_options; }
733
Jim Ingham5a988412012-06-08 21:56:10 +0000734protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 bool DoExecute(Args &command, CommandReturnObject &result) override {
736 Process *process = m_exe_ctx.GetProcessPtr();
737 // FIXME: This will be a Command Option:
738 bool keep_stopped;
739 if (m_options.m_keep_stopped == eLazyBoolCalculate) {
740 // Check the process default:
741 keep_stopped = process->GetDetachKeepsStopped();
742 } else if (m_options.m_keep_stopped == eLazyBoolYes)
743 keep_stopped = true;
744 else
745 keep_stopped = false;
Jim Inghamacff8952013-05-02 00:27:30 +0000746
Zachary Turner97206d52017-05-12 04:51:55 +0000747 Status error(process->Detach(keep_stopped));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000748 if (error.Success()) {
749 result.SetStatus(eReturnStatusSuccessFinishResult);
750 } else {
751 result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString());
752 result.SetStatus(eReturnStatusFailed);
753 return false;
754 }
755 return result.Succeeded();
756 }
757
758 CommandOptions m_options;
Jim Inghamacff8952013-05-02 00:27:30 +0000759};
760
Greg Claytonb766a732011-02-04 01:58:07 +0000761// CommandObjectProcessConnect
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000762
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000763static constexpr OptionDefinition g_process_connect_options[] = {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000764 // clang-format off
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000765 { LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePlugin, "Name of the process plugin you want to use." },
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000766 // clang-format on
767};
768
Greg Claytonb766a732011-02-04 01:58:07 +0000769#pragma mark CommandObjectProcessConnect
770
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771class CommandObjectProcessConnect : public CommandObjectParsed {
Greg Claytonb766a732011-02-04 01:58:07 +0000772public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773 class CommandOptions : public Options {
774 public:
775 CommandOptions() : Options() {
776 // Keep default values of all options in one place: OptionParsingStarting
777 // ()
778 OptionParsingStarting(nullptr);
Greg Claytonb766a732011-02-04 01:58:07 +0000779 }
Greg Claytonb766a732011-02-04 01:58:07 +0000780
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 ~CommandOptions() override = default;
Eugene Zelenko49bcfd82016-02-23 01:43:44 +0000782
Zachary Turner97206d52017-05-12 04:51:55 +0000783 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
784 ExecutionContext *execution_context) override {
785 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 const int short_option = m_getopt_table[option_idx].val;
787
788 switch (short_option) {
789 case 'p':
790 plugin_name.assign(option_arg);
791 break;
792
793 default:
794 error.SetErrorStringWithFormat("invalid short option character '%c'",
795 short_option);
796 break;
797 }
798 return error;
Jim Ingham5a988412012-06-08 21:56:10 +0000799 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800
801 void OptionParsingStarting(ExecutionContext *execution_context) override {
802 plugin_name.clear();
803 }
804
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000805 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +0000806 return llvm::makeArrayRef(g_process_connect_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000807 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000808
809 // Instance variables to hold the values for command options.
810
811 std::string plugin_name;
812 };
813
814 CommandObjectProcessConnect(CommandInterpreter &interpreter)
815 : CommandObjectParsed(interpreter, "process connect",
816 "Connect to a remote debug service.",
817 "process connect <remote-url>", 0),
818 m_options() {}
819
820 ~CommandObjectProcessConnect() override = default;
821
822 Options *GetOptions() override { return &m_options; }
823
Jim Ingham5a988412012-06-08 21:56:10 +0000824protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000825 bool DoExecute(Args &command, CommandReturnObject &result) override {
826 if (command.GetArgumentCount() != 1) {
827 result.AppendErrorWithFormat(
828 "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(),
829 m_cmd_syntax.c_str());
830 result.SetStatus(eReturnStatusFailed);
831 return false;
Greg Claytonb766a732011-02-04 01:58:07 +0000832 }
Tamas Berghammerccd6cff2015-12-08 14:08:19 +0000833
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 Process *process = m_exe_ctx.GetProcessPtr();
835 if (process && process->IsAlive()) {
836 result.AppendErrorWithFormat(
837 "Process %" PRIu64
838 " is currently being debugged, kill the process before connecting.\n",
839 process->GetID());
840 result.SetStatus(eReturnStatusFailed);
841 return false;
842 }
843
844 const char *plugin_name = nullptr;
845 if (!m_options.plugin_name.empty())
846 plugin_name = m_options.plugin_name.c_str();
847
Zachary Turner97206d52017-05-12 04:51:55 +0000848 Status error;
Jonas Devlieghere57179862019-04-27 06:19:42 +0000849 Debugger &debugger = GetDebugger();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 PlatformSP platform_sp = m_interpreter.GetPlatform(true);
851 ProcessSP process_sp = platform_sp->ConnectProcess(
852 command.GetArgumentAtIndex(0), plugin_name, debugger,
853 debugger.GetSelectedTarget().get(), error);
854 if (error.Fail() || process_sp == nullptr) {
855 result.AppendError(error.AsCString("Error connecting to the process"));
856 result.SetStatus(eReturnStatusFailed);
857 return false;
858 }
859 return true;
860 }
861
862 CommandOptions m_options;
Greg Claytonb766a732011-02-04 01:58:07 +0000863};
864
Greg Clayton998255b2012-10-13 02:07:45 +0000865// CommandObjectProcessPlugin
Greg Clayton998255b2012-10-13 02:07:45 +0000866#pragma mark CommandObjectProcessPlugin
867
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868class CommandObjectProcessPlugin : public CommandObjectProxy {
Greg Clayton998255b2012-10-13 02:07:45 +0000869public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 CommandObjectProcessPlugin(CommandInterpreter &interpreter)
871 : CommandObjectProxy(
872 interpreter, "process plugin",
873 "Send a custom command to the current target process plug-in.",
874 "process plugin <args>", 0) {}
Eugene Zelenko49bcfd82016-02-23 01:43:44 +0000875
Kate Stoneb9c1b512016-09-06 20:57:50 +0000876 ~CommandObjectProcessPlugin() override = default;
Greg Clayton998255b2012-10-13 02:07:45 +0000877
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 CommandObject *GetProxyCommandObject() override {
879 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
880 if (process)
881 return process->GetPluginCommandObject();
882 return nullptr;
883 }
Greg Clayton998255b2012-10-13 02:07:45 +0000884};
885
Greg Clayton8f343b02010-11-04 01:54:29 +0000886// CommandObjectProcessLoad
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000887
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000888static constexpr OptionDefinition g_process_load_options[] = {
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000889 // clang-format off
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +0000890 { LLDB_OPT_SET_ALL, false, "install", 'i', OptionParser::eOptionalArgument, 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." },
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000891 // clang-format on
892};
893
Jim Inghambb9caf72010-12-09 18:58:16 +0000894#pragma mark CommandObjectProcessLoad
Greg Clayton8f343b02010-11-04 01:54:29 +0000895
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896class CommandObjectProcessLoad : public CommandObjectParsed {
Greg Clayton8f343b02010-11-04 01:54:29 +0000897public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 class CommandOptions : public Options {
899 public:
900 CommandOptions() : Options() {
901 // Keep default values of all options in one place: OptionParsingStarting
902 // ()
903 OptionParsingStarting(nullptr);
Greg Clayton8f343b02010-11-04 01:54:29 +0000904 }
905
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 ~CommandOptions() override = default;
Tamas Berghammer4fbd67a2015-12-08 13:43:59 +0000907
Zachary Turner97206d52017-05-12 04:51:55 +0000908 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
909 ExecutionContext *execution_context) override {
910 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000911 const int short_option = m_getopt_table[option_idx].val;
912 switch (short_option) {
913 case 'i':
914 do_install = true;
Zachary Turnerfe114832016-11-12 16:56:47 +0000915 if (!option_arg.empty())
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000916 install_path.SetFile(option_arg, FileSpec::Style::native);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 break;
918 default:
919 error.SetErrorStringWithFormat("invalid short option character '%c'",
920 short_option);
921 break;
922 }
923 return error;
Greg Clayton8f343b02010-11-04 01:54:29 +0000924 }
925
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 void OptionParsingStarting(ExecutionContext *execution_context) override {
927 do_install = false;
928 install_path.Clear();
929 }
930
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000931 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +0000932 return llvm::makeArrayRef(g_process_load_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +0000933 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000934
935 // Instance variables to hold the values for command options.
936 bool do_install;
937 FileSpec install_path;
938 };
939
940 CommandObjectProcessLoad(CommandInterpreter &interpreter)
941 : CommandObjectParsed(interpreter, "process load",
942 "Load a shared library into the current process.",
943 "process load <filename> [<filename> ...]",
944 eCommandRequiresProcess | eCommandTryTargetAPILock |
945 eCommandProcessMustBeLaunched |
946 eCommandProcessMustBePaused),
947 m_options() {}
948
949 ~CommandObjectProcessLoad() override = default;
950
951 Options *GetOptions() override { return &m_options; }
952
Jim Ingham5a988412012-06-08 21:56:10 +0000953protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000954 bool DoExecute(Args &command, CommandReturnObject &result) override {
955 Process *process = m_exe_ctx.GetProcessPtr();
Greg Clayton8f343b02010-11-04 01:54:29 +0000956
Zachary Turner97d2c402016-10-05 23:40:23 +0000957 for (auto &entry : command.entries()) {
Zachary Turner97206d52017-05-12 04:51:55 +0000958 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959 PlatformSP platform = process->GetTarget().GetPlatform();
Zachary Turner97d2c402016-10-05 23:40:23 +0000960 llvm::StringRef image_path = entry.ref;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN;
Tamas Berghammer4fbd67a2015-12-08 13:43:59 +0000962
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963 if (!m_options.do_install) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000964 FileSpec image_spec(image_path);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965 platform->ResolveRemotePath(image_spec, image_spec);
966 image_token =
967 platform->LoadImage(process, FileSpec(), image_spec, error);
968 } else if (m_options.install_path) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000969 FileSpec image_spec(image_path);
970 FileSystem::Instance().Resolve(image_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 platform->ResolveRemotePath(m_options.install_path,
972 m_options.install_path);
973 image_token = platform->LoadImage(process, image_spec,
974 m_options.install_path, error);
975 } else {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000976 FileSpec image_spec(image_path);
977 FileSystem::Instance().Resolve(image_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000978 image_token =
979 platform->LoadImage(process, image_spec, FileSpec(), error);
980 }
Tamas Berghammer4fbd67a2015-12-08 13:43:59 +0000981
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 if (image_token != LLDB_INVALID_IMAGE_TOKEN) {
983 result.AppendMessageWithFormat(
Zachary Turner97d2c402016-10-05 23:40:23 +0000984 "Loading \"%s\"...ok\nImage %u loaded.\n", image_path.str().c_str(),
985 image_token);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000986 result.SetStatus(eReturnStatusSuccessFinishResult);
987 } else {
Zachary Turner97d2c402016-10-05 23:40:23 +0000988 result.AppendErrorWithFormat("failed to load '%s': %s",
989 image_path.str().c_str(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 error.AsCString());
991 result.SetStatus(eReturnStatusFailed);
992 }
Greg Clayton8f343b02010-11-04 01:54:29 +0000993 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994 return result.Succeeded();
995 }
996
997 CommandOptions m_options;
Greg Clayton8f343b02010-11-04 01:54:29 +0000998};
999
Greg Clayton8f343b02010-11-04 01:54:29 +00001000// CommandObjectProcessUnload
Jim Inghambb9caf72010-12-09 18:58:16 +00001001#pragma mark CommandObjectProcessUnload
Greg Clayton8f343b02010-11-04 01:54:29 +00001002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003class CommandObjectProcessUnload : public CommandObjectParsed {
Greg Clayton8f343b02010-11-04 01:54:29 +00001004public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 CommandObjectProcessUnload(CommandInterpreter &interpreter)
1006 : CommandObjectParsed(
1007 interpreter, "process unload",
1008 "Unload a shared library from the current process using the index "
1009 "returned by a previous call to \"process load\".",
1010 "process unload <index>",
1011 eCommandRequiresProcess | eCommandTryTargetAPILock |
1012 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
Greg Clayton8f343b02010-11-04 01:54:29 +00001013
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 ~CommandObjectProcessUnload() override = default;
Greg Clayton8f343b02010-11-04 01:54:29 +00001015
Jim Ingham5a988412012-06-08 21:56:10 +00001016protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 bool DoExecute(Args &command, CommandReturnObject &result) override {
1018 Process *process = m_exe_ctx.GetProcessPtr();
Greg Clayton8f343b02010-11-04 01:54:29 +00001019
Zachary Turner97d2c402016-10-05 23:40:23 +00001020 for (auto &entry : command.entries()) {
1021 uint32_t image_token;
1022 if (entry.ref.getAsInteger(0, image_token)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 result.AppendErrorWithFormat("invalid image index argument '%s'",
Zachary Turner97d2c402016-10-05 23:40:23 +00001024 entry.ref.str().c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025 result.SetStatus(eReturnStatusFailed);
1026 break;
1027 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00001028 Status error(process->GetTarget().GetPlatform()->UnloadImage(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001029 process, image_token));
1030 if (error.Success()) {
1031 result.AppendMessageWithFormat(
1032 "Unloading shared library with index %u...ok\n", image_token);
1033 result.SetStatus(eReturnStatusSuccessFinishResult);
1034 } else {
1035 result.AppendErrorWithFormat("failed to unload image: %s",
1036 error.AsCString());
1037 result.SetStatus(eReturnStatusFailed);
1038 break;
Greg Clayton8f343b02010-11-04 01:54:29 +00001039 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001041 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 return result.Succeeded();
1043 }
Greg Clayton8f343b02010-11-04 01:54:29 +00001044};
1045
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001046// CommandObjectProcessSignal
Jim Inghambb9caf72010-12-09 18:58:16 +00001047#pragma mark CommandObjectProcessSignal
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001048
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049class CommandObjectProcessSignal : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001051 CommandObjectProcessSignal(CommandInterpreter &interpreter)
1052 : CommandObjectParsed(interpreter, "process signal",
1053 "Send a UNIX signal to the current target process.",
1054 nullptr, eCommandRequiresProcess |
1055 eCommandTryTargetAPILock) {
1056 CommandArgumentEntry arg;
1057 CommandArgumentData signal_arg;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001058
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 // Define the first (and only) variant of this arg.
1060 signal_arg.arg_type = eArgTypeUnixSignal;
1061 signal_arg.arg_repetition = eArgRepeatPlain;
1062
1063 // There is only one variant this argument could be; put it into the
1064 // argument entry.
1065 arg.push_back(signal_arg);
1066
1067 // Push the data for the first argument into the m_arguments vector.
1068 m_arguments.push_back(arg);
1069 }
1070
1071 ~CommandObjectProcessSignal() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001072
Jim Ingham5a988412012-06-08 21:56:10 +00001073protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001074 bool DoExecute(Args &command, CommandReturnObject &result) override {
1075 Process *process = m_exe_ctx.GetProcessPtr();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 if (command.GetArgumentCount() == 1) {
1078 int signo = LLDB_INVALID_SIGNAL_NUMBER;
1079
1080 const char *signal_name = command.GetArgumentAtIndex(0);
1081 if (::isxdigit(signal_name[0]))
1082 signo =
1083 StringConvert::ToSInt32(signal_name, LLDB_INVALID_SIGNAL_NUMBER, 0);
1084 else
1085 signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name);
1086
1087 if (signo == LLDB_INVALID_SIGNAL_NUMBER) {
1088 result.AppendErrorWithFormat("Invalid signal argument '%s'.\n",
1089 command.GetArgumentAtIndex(0));
1090 result.SetStatus(eReturnStatusFailed);
1091 } else {
Zachary Turner97206d52017-05-12 04:51:55 +00001092 Status error(process->Signal(signo));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 if (error.Success()) {
1094 result.SetStatus(eReturnStatusSuccessFinishResult);
1095 } else {
1096 result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo,
1097 error.AsCString());
1098 result.SetStatus(eReturnStatusFailed);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001099 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 }
1101 } else {
1102 result.AppendErrorWithFormat(
1103 "'%s' takes exactly one signal number argument:\nUsage: %s\n",
1104 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1105 result.SetStatus(eReturnStatusFailed);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001106 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107 return result.Succeeded();
1108 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001109};
1110
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001111// CommandObjectProcessInterrupt
Jim Inghambb9caf72010-12-09 18:58:16 +00001112#pragma mark CommandObjectProcessInterrupt
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001113
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114class CommandObjectProcessInterrupt : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001115public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 CommandObjectProcessInterrupt(CommandInterpreter &interpreter)
1117 : CommandObjectParsed(interpreter, "process interrupt",
1118 "Interrupt the current target process.",
1119 "process interrupt",
1120 eCommandRequiresProcess | eCommandTryTargetAPILock |
1121 eCommandProcessMustBeLaunched) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 ~CommandObjectProcessInterrupt() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001124
Jim Ingham5a988412012-06-08 21:56:10 +00001125protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126 bool DoExecute(Args &command, CommandReturnObject &result) override {
1127 Process *process = m_exe_ctx.GetProcessPtr();
1128 if (process == nullptr) {
1129 result.AppendError("no process to halt");
1130 result.SetStatus(eReturnStatusFailed);
1131 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001132 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133
1134 if (command.GetArgumentCount() == 0) {
1135 bool clear_thread_plans = true;
Zachary Turner97206d52017-05-12 04:51:55 +00001136 Status error(process->Halt(clear_thread_plans));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001137 if (error.Success()) {
1138 result.SetStatus(eReturnStatusSuccessFinishResult);
1139 } else {
1140 result.AppendErrorWithFormat("Failed to halt process: %s\n",
1141 error.AsCString());
1142 result.SetStatus(eReturnStatusFailed);
1143 }
1144 } else {
1145 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n",
1146 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1147 result.SetStatus(eReturnStatusFailed);
1148 }
1149 return result.Succeeded();
1150 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001151};
1152
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001153// CommandObjectProcessKill
Jim Inghambb9caf72010-12-09 18:58:16 +00001154#pragma mark CommandObjectProcessKill
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001155
Kate Stoneb9c1b512016-09-06 20:57:50 +00001156class CommandObjectProcessKill : public CommandObjectParsed {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001158 CommandObjectProcessKill(CommandInterpreter &interpreter)
1159 : CommandObjectParsed(interpreter, "process kill",
1160 "Terminate the current target process.",
1161 "process kill",
1162 eCommandRequiresProcess | eCommandTryTargetAPILock |
1163 eCommandProcessMustBeLaunched) {}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001164
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165 ~CommandObjectProcessKill() override = default;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001166
Jim Ingham5a988412012-06-08 21:56:10 +00001167protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 bool DoExecute(Args &command, CommandReturnObject &result) override {
1169 Process *process = m_exe_ctx.GetProcessPtr();
1170 if (process == nullptr) {
1171 result.AppendError("no process to kill");
1172 result.SetStatus(eReturnStatusFailed);
1173 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175
1176 if (command.GetArgumentCount() == 0) {
Zachary Turner97206d52017-05-12 04:51:55 +00001177 Status error(process->Destroy(true));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001178 if (error.Success()) {
1179 result.SetStatus(eReturnStatusSuccessFinishResult);
1180 } else {
1181 result.AppendErrorWithFormat("Failed to kill process: %s\n",
1182 error.AsCString());
1183 result.SetStatus(eReturnStatusFailed);
1184 }
1185 } else {
1186 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n",
1187 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1188 result.SetStatus(eReturnStatusFailed);
1189 }
1190 return result.Succeeded();
1191 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192};
1193
Greg Claytona2715cf2014-06-13 00:54:12 +00001194// CommandObjectProcessSaveCore
Greg Claytona2715cf2014-06-13 00:54:12 +00001195#pragma mark CommandObjectProcessSaveCore
1196
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197class CommandObjectProcessSaveCore : public CommandObjectParsed {
Greg Claytona2715cf2014-06-13 00:54:12 +00001198public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199 CommandObjectProcessSaveCore(CommandInterpreter &interpreter)
1200 : CommandObjectParsed(interpreter, "process save-core",
1201 "Save the current process as a core file using an "
1202 "appropriate file type.",
1203 "process save-core FILE",
1204 eCommandRequiresProcess | eCommandTryTargetAPILock |
1205 eCommandProcessMustBeLaunched) {}
Eugene Zelenko49bcfd82016-02-23 01:43:44 +00001206
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207 ~CommandObjectProcessSaveCore() override = default;
Eugene Zelenko49bcfd82016-02-23 01:43:44 +00001208
Greg Claytona2715cf2014-06-13 00:54:12 +00001209protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 bool DoExecute(Args &command, CommandReturnObject &result) override {
1211 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1212 if (process_sp) {
1213 if (command.GetArgumentCount() == 1) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001214 FileSpec output_file(command.GetArgumentAtIndex(0));
Zachary Turner97206d52017-05-12 04:51:55 +00001215 Status error = PluginManager::SaveCore(process_sp, output_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216 if (error.Success()) {
1217 result.SetStatus(eReturnStatusSuccessFinishResult);
1218 } else {
1219 result.AppendErrorWithFormat(
1220 "Failed to save core file for process: %s\n", error.AsCString());
1221 result.SetStatus(eReturnStatusFailed);
Greg Claytona2715cf2014-06-13 00:54:12 +00001222 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001223 } else {
1224 result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n",
1225 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1226 result.SetStatus(eReturnStatusFailed);
1227 }
1228 } else {
1229 result.AppendError("invalid process");
1230 result.SetStatus(eReturnStatusFailed);
1231 return false;
Greg Claytona2715cf2014-06-13 00:54:12 +00001232 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233
1234 return result.Succeeded();
1235 }
Greg Claytona2715cf2014-06-13 00:54:12 +00001236};
1237
Jim Ingham4b9bea82010-06-18 01:23:09 +00001238// CommandObjectProcessStatus
Jim Inghambb9caf72010-12-09 18:58:16 +00001239#pragma mark CommandObjectProcessStatus
1240
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241class CommandObjectProcessStatus : public CommandObjectParsed {
Jim Ingham4b9bea82010-06-18 01:23:09 +00001242public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001243 CommandObjectProcessStatus(CommandInterpreter &interpreter)
1244 : CommandObjectParsed(
1245 interpreter, "process status",
1246 "Show status and stop location for the current target process.",
1247 "process status",
1248 eCommandRequiresProcess | eCommandTryTargetAPILock) {}
Jim Ingham4b9bea82010-06-18 01:23:09 +00001249
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250 ~CommandObjectProcessStatus() override = default;
Jim Ingham4b9bea82010-06-18 01:23:09 +00001251
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 bool DoExecute(Args &command, CommandReturnObject &result) override {
1253 Stream &strm = result.GetOutputStream();
1254 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1255 // No need to check "process" for validity as eCommandRequiresProcess
1256 // ensures it is valid
1257 Process *process = m_exe_ctx.GetProcessPtr();
1258 const bool only_threads_with_stop_reason = true;
1259 const uint32_t start_frame = 0;
1260 const uint32_t num_frames = 1;
1261 const uint32_t num_frames_with_source = 1;
Jim Ingham6a9767c2016-11-08 20:36:40 +00001262 const bool stop_format = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001263 process->GetStatus(strm);
1264 process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
Jim Ingham6a9767c2016-11-08 20:36:40 +00001265 num_frames, num_frames_with_source, stop_format);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001266 return result.Succeeded();
1267 }
Jim Ingham4b9bea82010-06-18 01:23:09 +00001268};
1269
Caroline Tice35731352010-10-13 20:44:39 +00001270// CommandObjectProcessHandle
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001271
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00001272static constexpr OptionDefinition g_process_handle_options[] = {
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001273 // clang-format off
Tatyana Krasnukha8fe53c492018-09-26 18:50:19 +00001274 { LLDB_OPT_SET_1, false, "stop", 's', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Whether or not the process should be stopped if the signal is received." },
1275 { LLDB_OPT_SET_1, false, "notify", 'n', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Whether or not the debugger should notify the user if the signal is received." },
1276 { LLDB_OPT_SET_1, false, "pass", 'p', OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean, "Whether or not the signal should be passed to the process." }
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001277 // clang-format on
1278};
1279
Jim Inghambb9caf72010-12-09 18:58:16 +00001280#pragma mark CommandObjectProcessHandle
Caroline Tice35731352010-10-13 20:44:39 +00001281
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282class CommandObjectProcessHandle : public CommandObjectParsed {
Caroline Tice35731352010-10-13 20:44:39 +00001283public:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 class CommandOptions : public Options {
1285 public:
1286 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
Caroline Tice35731352010-10-13 20:44:39 +00001287
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288 ~CommandOptions() override = default;
Caroline Tice35731352010-10-13 20:44:39 +00001289
Zachary Turner97206d52017-05-12 04:51:55 +00001290 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1291 ExecutionContext *execution_context) override {
1292 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293 const int short_option = m_getopt_table[option_idx].val;
Caroline Tice35731352010-10-13 20:44:39 +00001294
Kate Stoneb9c1b512016-09-06 20:57:50 +00001295 switch (short_option) {
1296 case 's':
1297 stop = option_arg;
1298 break;
1299 case 'n':
1300 notify = option_arg;
1301 break;
1302 case 'p':
1303 pass = option_arg;
1304 break;
1305 default:
1306 error.SetErrorStringWithFormat("invalid short option character '%c'",
1307 short_option);
1308 break;
1309 }
1310 return error;
Caroline Tice35731352010-10-13 20:44:39 +00001311 }
1312
Kate Stoneb9c1b512016-09-06 20:57:50 +00001313 void OptionParsingStarting(ExecutionContext *execution_context) override {
1314 stop.clear();
1315 notify.clear();
1316 pass.clear();
Caroline Tice35731352010-10-13 20:44:39 +00001317 }
1318
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001319 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
Zachary Turner70602432016-09-22 21:06:13 +00001320 return llvm::makeArrayRef(g_process_handle_options);
Zachary Turner1f0f5b52016-09-22 20:22:55 +00001321 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322
1323 // Instance variables to hold the values for command options.
1324
1325 std::string stop;
1326 std::string notify;
1327 std::string pass;
1328 };
1329
1330 CommandObjectProcessHandle(CommandInterpreter &interpreter)
1331 : CommandObjectParsed(interpreter, "process handle",
1332 "Manage LLDB handling of OS signals for the "
1333 "current target process. Defaults to showing "
1334 "current policy.",
1335 nullptr),
1336 m_options() {
1337 SetHelpLong("\nIf no signals are specified, update them all. If no update "
1338 "option is specified, list the current values.");
1339 CommandArgumentEntry arg;
1340 CommandArgumentData signal_arg;
1341
1342 signal_arg.arg_type = eArgTypeUnixSignal;
1343 signal_arg.arg_repetition = eArgRepeatStar;
1344
1345 arg.push_back(signal_arg);
1346
1347 m_arguments.push_back(arg);
1348 }
1349
1350 ~CommandObjectProcessHandle() override = default;
1351
1352 Options *GetOptions() override { return &m_options; }
1353
1354 bool VerifyCommandOptionValue(const std::string &option, int &real_value) {
1355 bool okay = true;
1356 bool success = false;
Pavel Labath47cbf4a2018-04-10 09:03:59 +00001357 bool tmp_value = OptionArgParser::ToBoolean(option, false, &success);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358
1359 if (success && tmp_value)
1360 real_value = 1;
1361 else if (success && !tmp_value)
1362 real_value = 0;
1363 else {
1364 // If the value isn't 'true' or 'false', it had better be 0 or 1.
1365 real_value = StringConvert::ToUInt32(option.c_str(), 3);
1366 if (real_value != 0 && real_value != 1)
1367 okay = false;
Caroline Tice35731352010-10-13 20:44:39 +00001368 }
1369
Kate Stoneb9c1b512016-09-06 20:57:50 +00001370 return okay;
1371 }
Caroline Tice10ad7992010-10-14 21:31:13 +00001372
Kate Stoneb9c1b512016-09-06 20:57:50 +00001373 void PrintSignalHeader(Stream &str) {
1374 str.Printf("NAME PASS STOP NOTIFY\n");
1375 str.Printf("=========== ===== ===== ======\n");
1376 }
Caroline Tice10ad7992010-10-14 21:31:13 +00001377
Kate Stoneb9c1b512016-09-06 20:57:50 +00001378 void PrintSignal(Stream &str, int32_t signo, const char *sig_name,
1379 const UnixSignalsSP &signals_sp) {
1380 bool stop;
1381 bool suppress;
1382 bool notify;
1383
1384 str.Printf("%-11s ", sig_name);
1385 if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) {
1386 bool pass = !suppress;
1387 str.Printf("%s %s %s", (pass ? "true " : "false"),
1388 (stop ? "true " : "false"), (notify ? "true " : "false"));
Caroline Tice10ad7992010-10-14 21:31:13 +00001389 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001390 str.Printf("\n");
1391 }
Caroline Tice10ad7992010-10-14 21:31:13 +00001392
Kate Stoneb9c1b512016-09-06 20:57:50 +00001393 void PrintSignalInformation(Stream &str, Args &signal_args,
1394 int num_valid_signals,
1395 const UnixSignalsSP &signals_sp) {
1396 PrintSignalHeader(str);
1397
1398 if (num_valid_signals > 0) {
1399 size_t num_args = signal_args.GetArgumentCount();
1400 for (size_t i = 0; i < num_args; ++i) {
1401 int32_t signo = signals_sp->GetSignalNumberFromName(
1402 signal_args.GetArgumentAtIndex(i));
1403 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
1404 PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i),
1405 signals_sp);
1406 }
1407 } else // Print info for ALL signals
Caroline Tice10ad7992010-10-14 21:31:13 +00001408 {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001409 int32_t signo = signals_sp->GetFirstSignalNumber();
1410 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1411 PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo),
1412 signals_sp);
1413 signo = signals_sp->GetNextSignalNumber(signo);
1414 }
Caroline Tice10ad7992010-10-14 21:31:13 +00001415 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001416 }
Caroline Tice10ad7992010-10-14 21:31:13 +00001417
Jim Ingham5a988412012-06-08 21:56:10 +00001418protected:
Kate Stoneb9c1b512016-09-06 20:57:50 +00001419 bool DoExecute(Args &signal_args, CommandReturnObject &result) override {
Jonas Devlieghere57179862019-04-27 06:19:42 +00001420 TargetSP target_sp = GetDebugger().GetSelectedTarget();
Caroline Tice35731352010-10-13 20:44:39 +00001421
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422 if (!target_sp) {
1423 result.AppendError("No current target;"
1424 " cannot handle signals until you have a valid target "
1425 "and process.\n");
1426 result.SetStatus(eReturnStatusFailed);
1427 return false;
Caroline Tice35731352010-10-13 20:44:39 +00001428 }
1429
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430 ProcessSP process_sp = target_sp->GetProcessSP();
1431
1432 if (!process_sp) {
1433 result.AppendError("No current process; cannot handle signals until you "
1434 "have a valid process.\n");
1435 result.SetStatus(eReturnStatusFailed);
1436 return false;
1437 }
1438
1439 int stop_action = -1; // -1 means leave the current setting alone
1440 int pass_action = -1; // -1 means leave the current setting alone
1441 int notify_action = -1; // -1 means leave the current setting alone
1442
1443 if (!m_options.stop.empty() &&
1444 !VerifyCommandOptionValue(m_options.stop, stop_action)) {
1445 result.AppendError("Invalid argument for command option --stop; must be "
1446 "true or false.\n");
1447 result.SetStatus(eReturnStatusFailed);
1448 return false;
1449 }
1450
1451 if (!m_options.notify.empty() &&
1452 !VerifyCommandOptionValue(m_options.notify, notify_action)) {
1453 result.AppendError("Invalid argument for command option --notify; must "
1454 "be true or false.\n");
1455 result.SetStatus(eReturnStatusFailed);
1456 return false;
1457 }
1458
1459 if (!m_options.pass.empty() &&
1460 !VerifyCommandOptionValue(m_options.pass, pass_action)) {
1461 result.AppendError("Invalid argument for command option --pass; must be "
1462 "true or false.\n");
1463 result.SetStatus(eReturnStatusFailed);
1464 return false;
1465 }
1466
1467 size_t num_args = signal_args.GetArgumentCount();
1468 UnixSignalsSP signals_sp = process_sp->GetUnixSignals();
1469 int num_signals_set = 0;
1470
1471 if (num_args > 0) {
Zachary Turnerd6a24752016-11-22 17:10:15 +00001472 for (const auto &arg : signal_args) {
1473 int32_t signo = signals_sp->GetSignalNumberFromName(arg.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001474 if (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1475 // Casting the actions as bools here should be okay, because
Adrian Prantl05097242018-04-30 16:49:04 +00001476 // VerifyCommandOptionValue guarantees the value is either 0 or 1.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001477 if (stop_action != -1)
1478 signals_sp->SetShouldStop(signo, stop_action);
1479 if (pass_action != -1) {
1480 bool suppress = !pass_action;
1481 signals_sp->SetShouldSuppress(signo, suppress);
1482 }
1483 if (notify_action != -1)
1484 signals_sp->SetShouldNotify(signo, notify_action);
1485 ++num_signals_set;
1486 } else {
1487 result.AppendErrorWithFormat("Invalid signal name '%s'\n",
Zachary Turnerd6a24752016-11-22 17:10:15 +00001488 arg.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001489 }
1490 }
1491 } else {
1492 // No signal specified, if any command options were specified, update ALL
1493 // signals.
1494 if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) {
1495 if (m_interpreter.Confirm(
1496 "Do you really want to update all the signals?", false)) {
1497 int32_t signo = signals_sp->GetFirstSignalNumber();
1498 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1499 if (notify_action != -1)
1500 signals_sp->SetShouldNotify(signo, notify_action);
1501 if (stop_action != -1)
1502 signals_sp->SetShouldStop(signo, stop_action);
1503 if (pass_action != -1) {
1504 bool suppress = !pass_action;
1505 signals_sp->SetShouldSuppress(signo, suppress);
1506 }
1507 signo = signals_sp->GetNextSignalNumber(signo);
1508 }
1509 }
1510 }
1511 }
1512
1513 PrintSignalInformation(result.GetOutputStream(), signal_args,
1514 num_signals_set, signals_sp);
1515
1516 if (num_signals_set > 0)
1517 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1518 else
1519 result.SetStatus(eReturnStatusFailed);
1520
1521 return result.Succeeded();
1522 }
1523
1524 CommandOptions m_options;
Caroline Tice35731352010-10-13 20:44:39 +00001525};
1526
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001527// CommandObjectMultiwordProcess
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001528
Kate Stoneb9c1b512016-09-06 20:57:50 +00001529CommandObjectMultiwordProcess::CommandObjectMultiwordProcess(
1530 CommandInterpreter &interpreter)
1531 : CommandObjectMultiword(
1532 interpreter, "process",
1533 "Commands for interacting with processes on the current platform.",
1534 "process <subcommand> [<subcommand-options>]") {
1535 LoadSubCommand("attach",
1536 CommandObjectSP(new CommandObjectProcessAttach(interpreter)));
1537 LoadSubCommand("launch",
1538 CommandObjectSP(new CommandObjectProcessLaunch(interpreter)));
1539 LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue(
1540 interpreter)));
1541 LoadSubCommand("connect",
1542 CommandObjectSP(new CommandObjectProcessConnect(interpreter)));
1543 LoadSubCommand("detach",
1544 CommandObjectSP(new CommandObjectProcessDetach(interpreter)));
1545 LoadSubCommand("load",
1546 CommandObjectSP(new CommandObjectProcessLoad(interpreter)));
1547 LoadSubCommand("unload",
1548 CommandObjectSP(new CommandObjectProcessUnload(interpreter)));
1549 LoadSubCommand("signal",
1550 CommandObjectSP(new CommandObjectProcessSignal(interpreter)));
1551 LoadSubCommand("handle",
1552 CommandObjectSP(new CommandObjectProcessHandle(interpreter)));
1553 LoadSubCommand("status",
1554 CommandObjectSP(new CommandObjectProcessStatus(interpreter)));
1555 LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt(
1556 interpreter)));
1557 LoadSubCommand("kill",
1558 CommandObjectSP(new CommandObjectProcessKill(interpreter)));
1559 LoadSubCommand("plugin",
1560 CommandObjectSP(new CommandObjectProcessPlugin(interpreter)));
1561 LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore(
1562 interpreter)));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001563}
1564
Eugene Zelenko49bcfd82016-02-23 01:43:44 +00001565CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default;