1 //===-- CommandObjectProcess.cpp --------------------------------*- C++ -*-===//
3 // 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
7 //===----------------------------------------------------------------------===//
9 #include "CommandObjectProcess.h"
10 #include "lldb/Breakpoint/Breakpoint.h"
11 #include "lldb/Breakpoint/BreakpointLocation.h"
12 #include "lldb/Breakpoint/BreakpointSite.h"
13 #include "lldb/Core/Module.h"
14 #include "lldb/Core/PluginManager.h"
15 #include "lldb/Host/Host.h"
16 #include "lldb/Host/OptionParser.h"
17 #include "lldb/Host/StringConvert.h"
18 #include "lldb/Interpreter/CommandInterpreter.h"
19 #include "lldb/Interpreter/CommandReturnObject.h"
20 #include "lldb/Interpreter/OptionArgParser.h"
21 #include "lldb/Interpreter/Options.h"
22 #include "lldb/Target/Platform.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Target/StopInfo.h"
25 #include "lldb/Target/Target.h"
26 #include "lldb/Target/Thread.h"
27 #include "lldb/Target/UnixSignals.h"
28 #include "lldb/Utility/Args.h"
29 #include "lldb/Utility/State.h"
32 using namespace lldb_private;
34 class CommandObjectProcessLaunchOrAttach : public CommandObjectParsed {
36 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) {}
43 ~CommandObjectProcessLaunchOrAttach() override = default;
46 bool StopProcessIfNecessary(Process *process, StateType &state,
47 CommandReturnObject &result) {
48 state = eStateInvalid;
50 state = process->GetState();
52 if (process->IsAlive() && state != eStateConnected) {
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());
63 ::snprintf(message, sizeof(message),
64 "There is a running process, kill it and %s?",
65 m_new_process_action.c_str());
67 if (!m_interpreter.Confirm(message, true)) {
68 result.SetStatus(eReturnStatusFailed);
71 if (process->GetShouldDetach()) {
72 bool keep_stopped = false;
73 Status detach_error(process->Detach(keep_stopped));
74 if (detach_error.Success()) {
75 result.SetStatus(eReturnStatusSuccessFinishResult);
78 result.AppendErrorWithFormat(
79 "Failed to detach from process: %s\n",
80 detach_error.AsCString());
81 result.SetStatus(eReturnStatusFailed);
84 Status destroy_error(process->Destroy(false));
85 if (destroy_error.Success()) {
86 result.SetStatus(eReturnStatusSuccessFinishResult);
89 result.AppendErrorWithFormat("Failed to kill process: %s\n",
90 destroy_error.AsCString());
91 result.SetStatus(eReturnStatusFailed);
97 return result.Succeeded();
100 std::string m_new_process_action;
103 // CommandObjectProcessLaunch
104 #pragma mark CommandObjectProcessLaunch
105 class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach {
107 CommandObjectProcessLaunch(CommandInterpreter &interpreter)
108 : CommandObjectProcessLaunchOrAttach(
109 interpreter, "process launch",
110 "Launch the executable in the debugger.", nullptr,
111 eCommandRequiresTarget, "restart"),
113 CommandArgumentEntry arg;
114 CommandArgumentData run_args_arg;
116 // Define the first (and only) variant of this arg.
117 run_args_arg.arg_type = eArgTypeRunArgs;
118 run_args_arg.arg_repetition = eArgRepeatOptional;
120 // There is only one variant this argument could be; put it into the
122 arg.push_back(run_args_arg);
124 // Push the data for the first argument into the m_arguments vector.
125 m_arguments.push_back(arg);
128 ~CommandObjectProcessLaunch() override = default;
131 HandleArgumentCompletion(CompletionRequest &request,
132 OptionElementVector &opt_element_vector) override {
134 CommandCompletions::InvokeCommonCompletionCallbacks(
135 GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
139 Options *GetOptions() override { return &m_options; }
141 const char *GetRepeatCommand(Args ¤t_command_args,
142 uint32_t index) override {
143 // No repeat for "process launch"...
148 bool DoExecute(Args &launch_args, CommandReturnObject &result) override {
149 Debugger &debugger = GetDebugger();
150 Target *target = debugger.GetSelectedTarget().get();
151 // If our listener is nullptr, users aren't allows to launch
152 ModuleSP exe_module_sp = target->GetExecutableModule();
154 if (exe_module_sp == nullptr) {
155 result.AppendError("no file in target, create a debug target using the "
156 "'target create' command");
157 result.SetStatus(eReturnStatusFailed);
161 StateType state = eStateInvalid;
163 if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result))
166 llvm::StringRef target_settings_argv0 = target->GetArg0();
168 // Determine whether we will disable ASLR or leave it in the default state
169 // (i.e. enabled if the platform supports it). First check if the process
170 // launch options explicitly turn on/off
171 // disabling ASLR. If so, use that setting;
172 // otherwise, use the 'settings target.disable-aslr' setting.
173 bool disable_aslr = false;
174 if (m_options.disable_aslr != eLazyBoolCalculate) {
175 // The user specified an explicit setting on the process launch line.
177 disable_aslr = (m_options.disable_aslr == eLazyBoolYes);
179 // The user did not explicitly specify whether to disable ASLR. Fall
180 // back to the target.disable-aslr setting.
181 disable_aslr = target->GetDisableASLR();
185 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
187 m_options.launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
189 if (target->GetDetachOnError())
190 m_options.launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
192 if (target->GetDisableSTDIO())
193 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO);
195 // Merge the launch info environment with the target environment.
196 Environment target_env = target->GetEnvironment();
197 m_options.launch_info.GetEnvironment().insert(target_env.begin(),
200 if (!target_settings_argv0.empty()) {
201 m_options.launch_info.GetArguments().AppendArgument(
202 target_settings_argv0);
203 m_options.launch_info.SetExecutableFile(
204 exe_module_sp->GetPlatformFileSpec(), false);
206 m_options.launch_info.SetExecutableFile(
207 exe_module_sp->GetPlatformFileSpec(), true);
210 if (launch_args.GetArgumentCount() == 0) {
211 m_options.launch_info.GetArguments().AppendArguments(
212 target->GetProcessLaunchInfo().GetArguments());
214 m_options.launch_info.GetArguments().AppendArguments(launch_args);
215 // Save the arguments for subsequent runs in the current target.
216 target->SetRunArguments(launch_args);
220 Status error = target->Launch(m_options.launch_info, &stream);
222 if (error.Success()) {
223 ProcessSP process_sp(target->GetProcessSP());
225 // There is a race condition where this thread will return up the call
226 // stack to the main command handler and show an (lldb) prompt before
227 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
228 // PushProcessIOHandler().
229 process_sp->SyncIOHandler(0, std::chrono::seconds(2));
231 llvm::StringRef data = stream.GetString();
233 result.AppendMessage(data);
234 const char *archname =
235 exe_module_sp->GetArchitecture().GetArchitectureName();
236 result.AppendMessageWithFormat(
237 "Process %" PRIu64 " launched: '%s' (%s)\n", process_sp->GetID(),
238 exe_module_sp->GetFileSpec().GetPath().c_str(), archname);
239 result.SetStatus(eReturnStatusSuccessFinishResult);
240 result.SetDidChangeProcessState(true);
243 "no error returned from Target::Launch, and target has no process");
244 result.SetStatus(eReturnStatusFailed);
247 result.AppendError(error.AsCString());
248 result.SetStatus(eReturnStatusFailed);
250 return result.Succeeded();
254 ProcessLaunchCommandOptions m_options;
257 #define LLDB_OPTIONS_process_attach
258 #include "CommandOptions.inc"
260 #pragma mark CommandObjectProcessAttach
261 class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach {
263 class CommandOptions : public Options {
265 CommandOptions() : Options() {
266 // Keep default values of all options in one place: OptionParsingStarting
268 OptionParsingStarting(nullptr);
271 ~CommandOptions() override = default;
273 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
274 ExecutionContext *execution_context) override {
276 const int short_option = m_getopt_table[option_idx].val;
277 switch (short_option) {
279 attach_info.SetContinueOnceAttached(true);
284 if (option_arg.getAsInteger(0, pid)) {
285 error.SetErrorStringWithFormat("invalid process ID '%s'",
286 option_arg.str().c_str());
288 attach_info.SetProcessID(pid);
293 attach_info.SetProcessPluginName(option_arg);
297 attach_info.GetExecutableFile().SetFile(option_arg,
298 FileSpec::Style::native);
302 attach_info.SetWaitForLaunch(true);
306 attach_info.SetIgnoreExisting(false);
310 llvm_unreachable("Unimplemented option");
315 void OptionParsingStarting(ExecutionContext *execution_context) override {
319 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
320 return llvm::makeArrayRef(g_process_attach_options);
323 void HandleOptionArgumentCompletion(
324 CompletionRequest &request, OptionElementVector &opt_element_vector,
325 int opt_element_index, CommandInterpreter &interpreter) override {
326 int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos;
327 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
329 // We are only completing the name option for now...
331 // Are we in the name?
332 if (GetDefinitions()[opt_defs_index].short_option != 'n')
335 // Look to see if there is a -P argument provided, and if so use that
336 // plugin, otherwise use the default plugin.
338 const char *partial_name = nullptr;
339 partial_name = request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos);
341 PlatformSP platform_sp(interpreter.GetPlatform(true));
344 ProcessInstanceInfoList process_infos;
345 ProcessInstanceInfoMatch match_info;
347 match_info.GetProcessInfo().GetExecutableFile().SetFile(
348 partial_name, FileSpec::Style::native);
349 match_info.SetNameMatchType(NameMatch::StartsWith);
351 platform_sp->FindProcesses(match_info, process_infos);
352 const size_t num_matches = process_infos.GetSize();
353 if (num_matches == 0)
355 for (size_t i = 0; i < num_matches; ++i) {
356 request.AddCompletion(process_infos.GetProcessNameAtIndex(i));
360 // Instance variables to hold the values for command options.
362 ProcessAttachInfo attach_info;
365 CommandObjectProcessAttach(CommandInterpreter &interpreter)
366 : CommandObjectProcessLaunchOrAttach(
367 interpreter, "process attach", "Attach to a process.",
368 "process attach <cmd-options>", 0, "attach"),
371 ~CommandObjectProcessAttach() override = default;
373 Options *GetOptions() override { return &m_options; }
376 bool DoExecute(Args &command, CommandReturnObject &result) override {
377 PlatformSP platform_sp(
378 GetDebugger().GetPlatformList().GetSelectedPlatform());
380 Target *target = GetDebugger().GetSelectedTarget().get();
381 // N.B. The attach should be synchronous. It doesn't help much to get the
382 // prompt back between initiating the attach and the target actually
383 // stopping. So even if the interpreter is set to be asynchronous, we wait
384 // for the stop ourselves here.
386 StateType state = eStateInvalid;
387 Process *process = m_exe_ctx.GetProcessPtr();
389 if (!StopProcessIfNecessary(process, state, result))
392 if (target == nullptr) {
393 // If there isn't a current target create one.
394 TargetSP new_target_sp;
397 error = GetDebugger().GetTargetList().CreateTarget(
398 GetDebugger(), "", "", eLoadDependentsNo,
399 nullptr, // No platform options
401 target = new_target_sp.get();
402 if (target == nullptr || error.Fail()) {
403 result.AppendError(error.AsCString("Error creating target"));
406 GetDebugger().GetTargetList().SetSelectedTarget(target);
409 // Record the old executable module, we want to issue a warning if the
410 // process of attaching changed the current executable (like somebody said
411 // "file foo" then attached to a PID whose executable was bar.)
413 ModuleSP old_exec_module_sp = target->GetExecutableModule();
414 ArchSpec old_arch_spec = target->GetArchitecture();
416 if (command.GetArgumentCount()) {
417 result.AppendErrorWithFormat("Invalid arguments for '%s'.\nUsage: %s\n",
418 m_cmd_name.c_str(), m_cmd_syntax.c_str());
419 result.SetStatus(eReturnStatusFailed);
423 m_interpreter.UpdateExecutionContext(nullptr);
425 const auto error = target->Attach(m_options.attach_info, &stream);
426 if (error.Success()) {
427 ProcessSP process_sp(target->GetProcessSP());
429 result.AppendMessage(stream.GetString());
430 result.SetStatus(eReturnStatusSuccessFinishNoResult);
431 result.SetDidChangeProcessState(true);
434 "no error returned from Target::Attach, and target has no process");
435 result.SetStatus(eReturnStatusFailed);
438 result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString());
439 result.SetStatus(eReturnStatusFailed);
442 if (!result.Succeeded())
445 // Okay, we're done. Last step is to warn if the executable module has
447 char new_path[PATH_MAX];
448 ModuleSP new_exec_module_sp(target->GetExecutableModule());
449 if (!old_exec_module_sp) {
450 // We might not have a module if we attached to a raw pid...
451 if (new_exec_module_sp) {
452 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
453 result.AppendMessageWithFormat("Executable module set to \"%s\".\n",
456 } else if (old_exec_module_sp->GetFileSpec() !=
457 new_exec_module_sp->GetFileSpec()) {
458 char old_path[PATH_MAX];
460 old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX);
461 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
463 result.AppendWarningWithFormat(
464 "Executable module changed from \"%s\" to \"%s\".\n", old_path,
468 if (!old_arch_spec.IsValid()) {
469 result.AppendMessageWithFormat(
470 "Architecture set to: %s.\n",
471 target->GetArchitecture().GetTriple().getTriple().c_str());
472 } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) {
473 result.AppendWarningWithFormat(
474 "Architecture changed from %s to %s.\n",
475 old_arch_spec.GetTriple().getTriple().c_str(),
476 target->GetArchitecture().GetTriple().getTriple().c_str());
479 // This supports the use-case scenario of immediately continuing the
480 // process once attached.
481 if (m_options.attach_info.GetContinueOnceAttached())
482 m_interpreter.HandleCommand("process continue", eLazyBoolNo, result);
484 return result.Succeeded();
487 CommandOptions m_options;
490 // CommandObjectProcessContinue
492 #define LLDB_OPTIONS_process_continue
493 #include "CommandOptions.inc"
495 #pragma mark CommandObjectProcessContinue
497 class CommandObjectProcessContinue : public CommandObjectParsed {
499 CommandObjectProcessContinue(CommandInterpreter &interpreter)
500 : CommandObjectParsed(
501 interpreter, "process continue",
502 "Continue execution of all threads in the current process.",
504 eCommandRequiresProcess | eCommandTryTargetAPILock |
505 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
508 ~CommandObjectProcessContinue() override = default;
511 class CommandOptions : public Options {
513 CommandOptions() : Options() {
514 // Keep default values of all options in one place: OptionParsingStarting
516 OptionParsingStarting(nullptr);
519 ~CommandOptions() override = default;
521 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
522 ExecutionContext *execution_context) override {
524 const int short_option = m_getopt_table[option_idx].val;
525 switch (short_option) {
527 if (option_arg.getAsInteger(0, m_ignore))
528 error.SetErrorStringWithFormat(
529 "invalid value for ignore option: \"%s\", should be a number.",
530 option_arg.str().c_str());
534 llvm_unreachable("Unimplemented option");
539 void OptionParsingStarting(ExecutionContext *execution_context) override {
543 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
544 return llvm::makeArrayRef(g_process_continue_options);
550 bool DoExecute(Args &command, CommandReturnObject &result) override {
551 Process *process = m_exe_ctx.GetProcessPtr();
552 bool synchronous_execution = m_interpreter.GetSynchronous();
553 StateType state = process->GetState();
554 if (state == eStateStopped) {
555 if (command.GetArgumentCount() != 0) {
556 result.AppendErrorWithFormat(
557 "The '%s' command does not take any arguments.\n",
559 result.SetStatus(eReturnStatusFailed);
563 if (m_options.m_ignore > 0) {
564 ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this());
566 StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo();
568 stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
569 lldb::break_id_t bp_site_id =
570 (lldb::break_id_t)stop_info_sp->GetValue();
571 BreakpointSiteSP bp_site_sp(
572 process->GetBreakpointSiteList().FindByID(bp_site_id));
574 const size_t num_owners = bp_site_sp->GetNumberOfOwners();
575 for (size_t i = 0; i < num_owners; i++) {
577 bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
578 if (!bp_ref.IsInternal()) {
579 bp_ref.SetIgnoreCount(m_options.m_ignore);
587 { // Scope for thread list mutex:
588 std::lock_guard<std::recursive_mutex> guard(
589 process->GetThreadList().GetMutex());
590 const uint32_t num_threads = process->GetThreadList().GetSize();
592 // Set the actions that the threads should each take when resuming
593 for (uint32_t idx = 0; idx < num_threads; ++idx) {
594 const bool override_suspend = false;
595 process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState(
596 eStateRunning, override_suspend);
600 const uint32_t iohandler_id = process->GetIOHandlerID();
604 if (synchronous_execution)
605 error = process->ResumeSynchronous(&stream);
607 error = process->Resume();
609 if (error.Success()) {
610 // There is a race condition where this thread will return up the call
611 // stack to the main command handler and show an (lldb) prompt before
612 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
613 // PushProcessIOHandler().
614 process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
616 result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
618 if (synchronous_execution) {
619 // If any state changed events had anything to say, add that to the
621 result.AppendMessage(stream.GetString());
623 result.SetDidChangeProcessState(true);
624 result.SetStatus(eReturnStatusSuccessFinishNoResult);
626 result.SetStatus(eReturnStatusSuccessContinuingNoResult);
629 result.AppendErrorWithFormat("Failed to resume process: %s.\n",
631 result.SetStatus(eReturnStatusFailed);
634 result.AppendErrorWithFormat(
635 "Process cannot be continued from its current state (%s).\n",
636 StateAsCString(state));
637 result.SetStatus(eReturnStatusFailed);
639 return result.Succeeded();
642 Options *GetOptions() override { return &m_options; }
644 CommandOptions m_options;
647 // CommandObjectProcessDetach
648 #define LLDB_OPTIONS_process_detach
649 #include "CommandOptions.inc"
651 #pragma mark CommandObjectProcessDetach
653 class CommandObjectProcessDetach : public CommandObjectParsed {
655 class CommandOptions : public Options {
657 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
659 ~CommandOptions() override = default;
661 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
662 ExecutionContext *execution_context) override {
664 const int short_option = m_getopt_table[option_idx].val;
666 switch (short_option) {
670 tmp_result = OptionArgParser::ToBoolean(option_arg, false, &success);
672 error.SetErrorStringWithFormat("invalid boolean option: \"%s\"",
673 option_arg.str().c_str());
676 m_keep_stopped = eLazyBoolYes;
678 m_keep_stopped = eLazyBoolNo;
682 llvm_unreachable("Unimplemented option");
687 void OptionParsingStarting(ExecutionContext *execution_context) override {
688 m_keep_stopped = eLazyBoolCalculate;
691 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
692 return llvm::makeArrayRef(g_process_detach_options);
695 // Instance variables to hold the values for command options.
696 LazyBool m_keep_stopped;
699 CommandObjectProcessDetach(CommandInterpreter &interpreter)
700 : CommandObjectParsed(interpreter, "process detach",
701 "Detach from the current target process.",
703 eCommandRequiresProcess | eCommandTryTargetAPILock |
704 eCommandProcessMustBeLaunched),
707 ~CommandObjectProcessDetach() override = default;
709 Options *GetOptions() override { return &m_options; }
712 bool DoExecute(Args &command, CommandReturnObject &result) override {
713 Process *process = m_exe_ctx.GetProcessPtr();
714 // FIXME: This will be a Command Option:
716 if (m_options.m_keep_stopped == eLazyBoolCalculate) {
717 // Check the process default:
718 keep_stopped = process->GetDetachKeepsStopped();
719 } else if (m_options.m_keep_stopped == eLazyBoolYes)
722 keep_stopped = false;
724 Status error(process->Detach(keep_stopped));
725 if (error.Success()) {
726 result.SetStatus(eReturnStatusSuccessFinishResult);
728 result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString());
729 result.SetStatus(eReturnStatusFailed);
732 return result.Succeeded();
735 CommandOptions m_options;
738 // CommandObjectProcessConnect
739 #define LLDB_OPTIONS_process_connect
740 #include "CommandOptions.inc"
742 #pragma mark CommandObjectProcessConnect
744 class CommandObjectProcessConnect : public CommandObjectParsed {
746 class CommandOptions : public Options {
748 CommandOptions() : Options() {
749 // Keep default values of all options in one place: OptionParsingStarting
751 OptionParsingStarting(nullptr);
754 ~CommandOptions() override = default;
756 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
757 ExecutionContext *execution_context) override {
759 const int short_option = m_getopt_table[option_idx].val;
761 switch (short_option) {
763 plugin_name.assign(option_arg);
767 llvm_unreachable("Unimplemented option");
772 void OptionParsingStarting(ExecutionContext *execution_context) override {
776 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
777 return llvm::makeArrayRef(g_process_connect_options);
780 // Instance variables to hold the values for command options.
782 std::string plugin_name;
785 CommandObjectProcessConnect(CommandInterpreter &interpreter)
786 : CommandObjectParsed(interpreter, "process connect",
787 "Connect to a remote debug service.",
788 "process connect <remote-url>", 0),
791 ~CommandObjectProcessConnect() override = default;
793 Options *GetOptions() override { return &m_options; }
796 bool DoExecute(Args &command, CommandReturnObject &result) override {
797 if (command.GetArgumentCount() != 1) {
798 result.AppendErrorWithFormat(
799 "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(),
800 m_cmd_syntax.c_str());
801 result.SetStatus(eReturnStatusFailed);
805 Process *process = m_exe_ctx.GetProcessPtr();
806 if (process && process->IsAlive()) {
807 result.AppendErrorWithFormat(
809 " is currently being debugged, kill the process before connecting.\n",
811 result.SetStatus(eReturnStatusFailed);
815 const char *plugin_name = nullptr;
816 if (!m_options.plugin_name.empty())
817 plugin_name = m_options.plugin_name.c_str();
820 Debugger &debugger = GetDebugger();
821 PlatformSP platform_sp = m_interpreter.GetPlatform(true);
822 ProcessSP process_sp = platform_sp->ConnectProcess(
823 command.GetArgumentAtIndex(0), plugin_name, debugger,
824 debugger.GetSelectedTarget().get(), error);
825 if (error.Fail() || process_sp == nullptr) {
826 result.AppendError(error.AsCString("Error connecting to the process"));
827 result.SetStatus(eReturnStatusFailed);
833 CommandOptions m_options;
836 // CommandObjectProcessPlugin
837 #pragma mark CommandObjectProcessPlugin
839 class CommandObjectProcessPlugin : public CommandObjectProxy {
841 CommandObjectProcessPlugin(CommandInterpreter &interpreter)
842 : CommandObjectProxy(
843 interpreter, "process plugin",
844 "Send a custom command to the current target process plug-in.",
845 "process plugin <args>", 0) {}
847 ~CommandObjectProcessPlugin() override = default;
849 CommandObject *GetProxyCommandObject() override {
850 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
852 return process->GetPluginCommandObject();
857 // CommandObjectProcessLoad
858 #define LLDB_OPTIONS_process_load
859 #include "CommandOptions.inc"
861 #pragma mark CommandObjectProcessLoad
863 class CommandObjectProcessLoad : public CommandObjectParsed {
865 class CommandOptions : public Options {
867 CommandOptions() : Options() {
868 // Keep default values of all options in one place: OptionParsingStarting
870 OptionParsingStarting(nullptr);
873 ~CommandOptions() override = default;
875 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
876 ExecutionContext *execution_context) override {
878 const int short_option = m_getopt_table[option_idx].val;
879 switch (short_option) {
882 if (!option_arg.empty())
883 install_path.SetFile(option_arg, FileSpec::Style::native);
886 llvm_unreachable("Unimplemented option");
891 void OptionParsingStarting(ExecutionContext *execution_context) override {
893 install_path.Clear();
896 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
897 return llvm::makeArrayRef(g_process_load_options);
900 // Instance variables to hold the values for command options.
902 FileSpec install_path;
905 CommandObjectProcessLoad(CommandInterpreter &interpreter)
906 : CommandObjectParsed(interpreter, "process load",
907 "Load a shared library into the current process.",
908 "process load <filename> [<filename> ...]",
909 eCommandRequiresProcess | eCommandTryTargetAPILock |
910 eCommandProcessMustBeLaunched |
911 eCommandProcessMustBePaused),
914 ~CommandObjectProcessLoad() override = default;
916 Options *GetOptions() override { return &m_options; }
919 bool DoExecute(Args &command, CommandReturnObject &result) override {
920 Process *process = m_exe_ctx.GetProcessPtr();
922 for (auto &entry : command.entries()) {
924 PlatformSP platform = process->GetTarget().GetPlatform();
925 llvm::StringRef image_path = entry.ref();
926 uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN;
928 if (!m_options.do_install) {
929 FileSpec image_spec(image_path);
930 platform->ResolveRemotePath(image_spec, image_spec);
932 platform->LoadImage(process, FileSpec(), image_spec, error);
933 } else if (m_options.install_path) {
934 FileSpec image_spec(image_path);
935 FileSystem::Instance().Resolve(image_spec);
936 platform->ResolveRemotePath(m_options.install_path,
937 m_options.install_path);
938 image_token = platform->LoadImage(process, image_spec,
939 m_options.install_path, error);
941 FileSpec image_spec(image_path);
942 FileSystem::Instance().Resolve(image_spec);
944 platform->LoadImage(process, image_spec, FileSpec(), error);
947 if (image_token != LLDB_INVALID_IMAGE_TOKEN) {
948 result.AppendMessageWithFormat(
949 "Loading \"%s\"...ok\nImage %u loaded.\n", image_path.str().c_str(),
951 result.SetStatus(eReturnStatusSuccessFinishResult);
953 result.AppendErrorWithFormat("failed to load '%s': %s",
954 image_path.str().c_str(),
956 result.SetStatus(eReturnStatusFailed);
959 return result.Succeeded();
962 CommandOptions m_options;
965 // CommandObjectProcessUnload
966 #pragma mark CommandObjectProcessUnload
968 class CommandObjectProcessUnload : public CommandObjectParsed {
970 CommandObjectProcessUnload(CommandInterpreter &interpreter)
971 : CommandObjectParsed(
972 interpreter, "process unload",
973 "Unload a shared library from the current process using the index "
974 "returned by a previous call to \"process load\".",
975 "process unload <index>",
976 eCommandRequiresProcess | eCommandTryTargetAPILock |
977 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
979 ~CommandObjectProcessUnload() override = default;
982 bool DoExecute(Args &command, CommandReturnObject &result) override {
983 Process *process = m_exe_ctx.GetProcessPtr();
985 for (auto &entry : command.entries()) {
986 uint32_t image_token;
987 if (entry.ref().getAsInteger(0, image_token)) {
988 result.AppendErrorWithFormat("invalid image index argument '%s'",
989 entry.ref().str().c_str());
990 result.SetStatus(eReturnStatusFailed);
993 Status error(process->GetTarget().GetPlatform()->UnloadImage(
994 process, image_token));
995 if (error.Success()) {
996 result.AppendMessageWithFormat(
997 "Unloading shared library with index %u...ok\n", image_token);
998 result.SetStatus(eReturnStatusSuccessFinishResult);
1000 result.AppendErrorWithFormat("failed to unload image: %s",
1002 result.SetStatus(eReturnStatusFailed);
1007 return result.Succeeded();
1011 // CommandObjectProcessSignal
1012 #pragma mark CommandObjectProcessSignal
1014 class CommandObjectProcessSignal : public CommandObjectParsed {
1016 CommandObjectProcessSignal(CommandInterpreter &interpreter)
1017 : CommandObjectParsed(interpreter, "process signal",
1018 "Send a UNIX signal to the current target process.",
1019 nullptr, eCommandRequiresProcess |
1020 eCommandTryTargetAPILock) {
1021 CommandArgumentEntry arg;
1022 CommandArgumentData signal_arg;
1024 // Define the first (and only) variant of this arg.
1025 signal_arg.arg_type = eArgTypeUnixSignal;
1026 signal_arg.arg_repetition = eArgRepeatPlain;
1028 // There is only one variant this argument could be; put it into the
1030 arg.push_back(signal_arg);
1032 // Push the data for the first argument into the m_arguments vector.
1033 m_arguments.push_back(arg);
1036 ~CommandObjectProcessSignal() override = default;
1039 bool DoExecute(Args &command, CommandReturnObject &result) override {
1040 Process *process = m_exe_ctx.GetProcessPtr();
1042 if (command.GetArgumentCount() == 1) {
1043 int signo = LLDB_INVALID_SIGNAL_NUMBER;
1045 const char *signal_name = command.GetArgumentAtIndex(0);
1046 if (::isxdigit(signal_name[0]))
1048 StringConvert::ToSInt32(signal_name, LLDB_INVALID_SIGNAL_NUMBER, 0);
1050 signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name);
1052 if (signo == LLDB_INVALID_SIGNAL_NUMBER) {
1053 result.AppendErrorWithFormat("Invalid signal argument '%s'.\n",
1054 command.GetArgumentAtIndex(0));
1055 result.SetStatus(eReturnStatusFailed);
1057 Status error(process->Signal(signo));
1058 if (error.Success()) {
1059 result.SetStatus(eReturnStatusSuccessFinishResult);
1061 result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo,
1063 result.SetStatus(eReturnStatusFailed);
1067 result.AppendErrorWithFormat(
1068 "'%s' takes exactly one signal number argument:\nUsage: %s\n",
1069 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1070 result.SetStatus(eReturnStatusFailed);
1072 return result.Succeeded();
1076 // CommandObjectProcessInterrupt
1077 #pragma mark CommandObjectProcessInterrupt
1079 class CommandObjectProcessInterrupt : public CommandObjectParsed {
1081 CommandObjectProcessInterrupt(CommandInterpreter &interpreter)
1082 : CommandObjectParsed(interpreter, "process interrupt",
1083 "Interrupt the current target process.",
1084 "process interrupt",
1085 eCommandRequiresProcess | eCommandTryTargetAPILock |
1086 eCommandProcessMustBeLaunched) {}
1088 ~CommandObjectProcessInterrupt() override = default;
1091 bool DoExecute(Args &command, CommandReturnObject &result) override {
1092 Process *process = m_exe_ctx.GetProcessPtr();
1093 if (process == nullptr) {
1094 result.AppendError("no process to halt");
1095 result.SetStatus(eReturnStatusFailed);
1099 if (command.GetArgumentCount() == 0) {
1100 bool clear_thread_plans = true;
1101 Status error(process->Halt(clear_thread_plans));
1102 if (error.Success()) {
1103 result.SetStatus(eReturnStatusSuccessFinishResult);
1105 result.AppendErrorWithFormat("Failed to halt process: %s\n",
1107 result.SetStatus(eReturnStatusFailed);
1110 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n",
1111 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1112 result.SetStatus(eReturnStatusFailed);
1114 return result.Succeeded();
1118 // CommandObjectProcessKill
1119 #pragma mark CommandObjectProcessKill
1121 class CommandObjectProcessKill : public CommandObjectParsed {
1123 CommandObjectProcessKill(CommandInterpreter &interpreter)
1124 : CommandObjectParsed(interpreter, "process kill",
1125 "Terminate the current target process.",
1127 eCommandRequiresProcess | eCommandTryTargetAPILock |
1128 eCommandProcessMustBeLaunched) {}
1130 ~CommandObjectProcessKill() override = default;
1133 bool DoExecute(Args &command, CommandReturnObject &result) override {
1134 Process *process = m_exe_ctx.GetProcessPtr();
1135 if (process == nullptr) {
1136 result.AppendError("no process to kill");
1137 result.SetStatus(eReturnStatusFailed);
1141 if (command.GetArgumentCount() == 0) {
1142 Status error(process->Destroy(true));
1143 if (error.Success()) {
1144 result.SetStatus(eReturnStatusSuccessFinishResult);
1146 result.AppendErrorWithFormat("Failed to kill process: %s\n",
1148 result.SetStatus(eReturnStatusFailed);
1151 result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n",
1152 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1153 result.SetStatus(eReturnStatusFailed);
1155 return result.Succeeded();
1159 // CommandObjectProcessSaveCore
1160 #pragma mark CommandObjectProcessSaveCore
1162 class CommandObjectProcessSaveCore : public CommandObjectParsed {
1164 CommandObjectProcessSaveCore(CommandInterpreter &interpreter)
1165 : CommandObjectParsed(interpreter, "process save-core",
1166 "Save the current process as a core file using an "
1167 "appropriate file type.",
1168 "process save-core FILE",
1169 eCommandRequiresProcess | eCommandTryTargetAPILock |
1170 eCommandProcessMustBeLaunched) {}
1172 ~CommandObjectProcessSaveCore() override = default;
1175 bool DoExecute(Args &command, CommandReturnObject &result) override {
1176 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1178 if (command.GetArgumentCount() == 1) {
1179 FileSpec output_file(command.GetArgumentAtIndex(0));
1180 Status error = PluginManager::SaveCore(process_sp, output_file);
1181 if (error.Success()) {
1182 result.SetStatus(eReturnStatusSuccessFinishResult);
1184 result.AppendErrorWithFormat(
1185 "Failed to save core file for process: %s\n", error.AsCString());
1186 result.SetStatus(eReturnStatusFailed);
1189 result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n",
1190 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1191 result.SetStatus(eReturnStatusFailed);
1194 result.AppendError("invalid process");
1195 result.SetStatus(eReturnStatusFailed);
1199 return result.Succeeded();
1203 // CommandObjectProcessStatus
1204 #pragma mark CommandObjectProcessStatus
1206 class CommandObjectProcessStatus : public CommandObjectParsed {
1208 CommandObjectProcessStatus(CommandInterpreter &interpreter)
1209 : CommandObjectParsed(
1210 interpreter, "process status",
1211 "Show status and stop location for the current target process.",
1213 eCommandRequiresProcess | eCommandTryTargetAPILock) {}
1215 ~CommandObjectProcessStatus() override = default;
1217 bool DoExecute(Args &command, CommandReturnObject &result) override {
1218 Stream &strm = result.GetOutputStream();
1219 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1220 // No need to check "process" for validity as eCommandRequiresProcess
1221 // ensures it is valid
1222 Process *process = m_exe_ctx.GetProcessPtr();
1223 const bool only_threads_with_stop_reason = true;
1224 const uint32_t start_frame = 0;
1225 const uint32_t num_frames = 1;
1226 const uint32_t num_frames_with_source = 1;
1227 const bool stop_format = true;
1228 process->GetStatus(strm);
1229 process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1230 num_frames, num_frames_with_source, stop_format);
1231 return result.Succeeded();
1235 // CommandObjectProcessHandle
1236 #define LLDB_OPTIONS_process_handle
1237 #include "CommandOptions.inc"
1239 #pragma mark CommandObjectProcessHandle
1241 class CommandObjectProcessHandle : public CommandObjectParsed {
1243 class CommandOptions : public Options {
1245 CommandOptions() : Options() { OptionParsingStarting(nullptr); }
1247 ~CommandOptions() override = default;
1249 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1250 ExecutionContext *execution_context) override {
1252 const int short_option = m_getopt_table[option_idx].val;
1254 switch (short_option) {
1259 notify = option_arg;
1265 llvm_unreachable("Unimplemented option");
1270 void OptionParsingStarting(ExecutionContext *execution_context) override {
1276 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1277 return llvm::makeArrayRef(g_process_handle_options);
1280 // Instance variables to hold the values for command options.
1287 CommandObjectProcessHandle(CommandInterpreter &interpreter)
1288 : CommandObjectParsed(interpreter, "process handle",
1289 "Manage LLDB handling of OS signals for the "
1290 "current target process. Defaults to showing "
1292 nullptr, eCommandRequiresTarget),
1294 SetHelpLong("\nIf no signals are specified, update them all. If no update "
1295 "option is specified, list the current values.");
1296 CommandArgumentEntry arg;
1297 CommandArgumentData signal_arg;
1299 signal_arg.arg_type = eArgTypeUnixSignal;
1300 signal_arg.arg_repetition = eArgRepeatStar;
1302 arg.push_back(signal_arg);
1304 m_arguments.push_back(arg);
1307 ~CommandObjectProcessHandle() override = default;
1309 Options *GetOptions() override { return &m_options; }
1311 bool VerifyCommandOptionValue(const std::string &option, int &real_value) {
1313 bool success = false;
1314 bool tmp_value = OptionArgParser::ToBoolean(option, false, &success);
1316 if (success && tmp_value)
1318 else if (success && !tmp_value)
1321 // If the value isn't 'true' or 'false', it had better be 0 or 1.
1322 real_value = StringConvert::ToUInt32(option.c_str(), 3);
1323 if (real_value != 0 && real_value != 1)
1330 void PrintSignalHeader(Stream &str) {
1331 str.Printf("NAME PASS STOP NOTIFY\n");
1332 str.Printf("=========== ===== ===== ======\n");
1335 void PrintSignal(Stream &str, int32_t signo, const char *sig_name,
1336 const UnixSignalsSP &signals_sp) {
1341 str.Printf("%-11s ", sig_name);
1342 if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) {
1343 bool pass = !suppress;
1344 str.Printf("%s %s %s", (pass ? "true " : "false"),
1345 (stop ? "true " : "false"), (notify ? "true " : "false"));
1350 void PrintSignalInformation(Stream &str, Args &signal_args,
1351 int num_valid_signals,
1352 const UnixSignalsSP &signals_sp) {
1353 PrintSignalHeader(str);
1355 if (num_valid_signals > 0) {
1356 size_t num_args = signal_args.GetArgumentCount();
1357 for (size_t i = 0; i < num_args; ++i) {
1358 int32_t signo = signals_sp->GetSignalNumberFromName(
1359 signal_args.GetArgumentAtIndex(i));
1360 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
1361 PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i),
1364 } else // Print info for ALL signals
1366 int32_t signo = signals_sp->GetFirstSignalNumber();
1367 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1368 PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo),
1370 signo = signals_sp->GetNextSignalNumber(signo);
1376 bool DoExecute(Args &signal_args, CommandReturnObject &result) override {
1377 Target *target_sp = &GetSelectedTarget();
1379 ProcessSP process_sp = target_sp->GetProcessSP();
1382 result.AppendError("No current process; cannot handle signals until you "
1383 "have a valid process.\n");
1384 result.SetStatus(eReturnStatusFailed);
1388 int stop_action = -1; // -1 means leave the current setting alone
1389 int pass_action = -1; // -1 means leave the current setting alone
1390 int notify_action = -1; // -1 means leave the current setting alone
1392 if (!m_options.stop.empty() &&
1393 !VerifyCommandOptionValue(m_options.stop, stop_action)) {
1394 result.AppendError("Invalid argument for command option --stop; must be "
1395 "true or false.\n");
1396 result.SetStatus(eReturnStatusFailed);
1400 if (!m_options.notify.empty() &&
1401 !VerifyCommandOptionValue(m_options.notify, notify_action)) {
1402 result.AppendError("Invalid argument for command option --notify; must "
1403 "be true or false.\n");
1404 result.SetStatus(eReturnStatusFailed);
1408 if (!m_options.pass.empty() &&
1409 !VerifyCommandOptionValue(m_options.pass, pass_action)) {
1410 result.AppendError("Invalid argument for command option --pass; must be "
1411 "true or false.\n");
1412 result.SetStatus(eReturnStatusFailed);
1416 size_t num_args = signal_args.GetArgumentCount();
1417 UnixSignalsSP signals_sp = process_sp->GetUnixSignals();
1418 int num_signals_set = 0;
1421 for (const auto &arg : signal_args) {
1422 int32_t signo = signals_sp->GetSignalNumberFromName(arg.c_str());
1423 if (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1424 // Casting the actions as bools here should be okay, because
1425 // VerifyCommandOptionValue guarantees the value is either 0 or 1.
1426 if (stop_action != -1)
1427 signals_sp->SetShouldStop(signo, stop_action);
1428 if (pass_action != -1) {
1429 bool suppress = !pass_action;
1430 signals_sp->SetShouldSuppress(signo, suppress);
1432 if (notify_action != -1)
1433 signals_sp->SetShouldNotify(signo, notify_action);
1436 result.AppendErrorWithFormat("Invalid signal name '%s'\n",
1441 // No signal specified, if any command options were specified, update ALL
1443 if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) {
1444 if (m_interpreter.Confirm(
1445 "Do you really want to update all the signals?", false)) {
1446 int32_t signo = signals_sp->GetFirstSignalNumber();
1447 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1448 if (notify_action != -1)
1449 signals_sp->SetShouldNotify(signo, notify_action);
1450 if (stop_action != -1)
1451 signals_sp->SetShouldStop(signo, stop_action);
1452 if (pass_action != -1) {
1453 bool suppress = !pass_action;
1454 signals_sp->SetShouldSuppress(signo, suppress);
1456 signo = signals_sp->GetNextSignalNumber(signo);
1462 PrintSignalInformation(result.GetOutputStream(), signal_args,
1463 num_signals_set, signals_sp);
1465 if (num_signals_set > 0)
1466 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1468 result.SetStatus(eReturnStatusFailed);
1470 return result.Succeeded();
1473 CommandOptions m_options;
1476 // CommandObjectMultiwordProcess
1478 CommandObjectMultiwordProcess::CommandObjectMultiwordProcess(
1479 CommandInterpreter &interpreter)
1480 : CommandObjectMultiword(
1481 interpreter, "process",
1482 "Commands for interacting with processes on the current platform.",
1483 "process <subcommand> [<subcommand-options>]") {
1484 LoadSubCommand("attach",
1485 CommandObjectSP(new CommandObjectProcessAttach(interpreter)));
1486 LoadSubCommand("launch",
1487 CommandObjectSP(new CommandObjectProcessLaunch(interpreter)));
1488 LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue(
1490 LoadSubCommand("connect",
1491 CommandObjectSP(new CommandObjectProcessConnect(interpreter)));
1492 LoadSubCommand("detach",
1493 CommandObjectSP(new CommandObjectProcessDetach(interpreter)));
1494 LoadSubCommand("load",
1495 CommandObjectSP(new CommandObjectProcessLoad(interpreter)));
1496 LoadSubCommand("unload",
1497 CommandObjectSP(new CommandObjectProcessUnload(interpreter)));
1498 LoadSubCommand("signal",
1499 CommandObjectSP(new CommandObjectProcessSignal(interpreter)));
1500 LoadSubCommand("handle",
1501 CommandObjectSP(new CommandObjectProcessHandle(interpreter)));
1502 LoadSubCommand("status",
1503 CommandObjectSP(new CommandObjectProcessStatus(interpreter)));
1504 LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt(
1506 LoadSubCommand("kill",
1507 CommandObjectSP(new CommandObjectProcessKill(interpreter)));
1508 LoadSubCommand("plugin",
1509 CommandObjectSP(new CommandObjectProcessPlugin(interpreter)));
1510 LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore(
1514 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default;