xref: /llvm-project/lldb/source/Commands/CommandObjectProcess.cpp (revision 0d9a201e2624998922f825ebbe01aae0cce4bbd5)
1 //===-- CommandObjectProcess.cpp --------------------------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
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"
30 
31 using namespace lldb;
32 using namespace lldb_private;
33 
34 class CommandObjectProcessLaunchOrAttach : public CommandObjectParsed {
35 public:
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) {}
42 
43   ~CommandObjectProcessLaunchOrAttach() override = default;
44 
45 protected:
46   bool StopProcessIfNecessary(Process *process, StateType &state,
47                               CommandReturnObject &result) {
48     state = eStateInvalid;
49     if (process) {
50       state = process->GetState();
51 
52       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;
73             Status detach_error(process->Detach(keep_stopped));
74             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 {
84             Status destroy_error(process->Destroy(false));
85             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;
101 };
102 
103 // CommandObjectProcessLaunch
104 #pragma mark CommandObjectProcessLaunch
105 class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach {
106 public:
107   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;
115 
116     // Define the first (and only) variant of this arg.
117     run_args_arg.arg_type = eArgTypeRunArgs;
118     run_args_arg.arg_repetition = eArgRepeatOptional;
119 
120     // There is only one variant this argument could be; put it into the
121     // argument entry.
122     arg.push_back(run_args_arg);
123 
124     // Push the data for the first argument into the m_arguments vector.
125     m_arguments.push_back(arg);
126   }
127 
128   ~CommandObjectProcessLaunch() override = default;
129 
130   void
131   HandleArgumentCompletion(CompletionRequest &request,
132                            OptionElementVector &opt_element_vector) override {
133 
134     CommandCompletions::InvokeCommonCompletionCallbacks(
135         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
136         request, nullptr);
137   }
138 
139   Options *GetOptions() override { return &m_options; }
140 
141   const char *GetRepeatCommand(Args &current_command_args,
142                                uint32_t index) override {
143     // No repeat for "process launch"...
144     return "";
145   }
146 
147 protected:
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();
153 
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);
158       return false;
159     }
160 
161     StateType state = eStateInvalid;
162 
163     if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result))
164       return false;
165 
166     llvm::StringRef target_settings_argv0 = target->GetArg0();
167 
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.
176       // Use it.
177       disable_aslr = (m_options.disable_aslr == eLazyBoolYes);
178     } else {
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();
182     }
183 
184     if (disable_aslr)
185       m_options.launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
186     else
187       m_options.launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
188 
189     if (target->GetDetachOnError())
190       m_options.launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
191 
192     if (target->GetDisableSTDIO())
193       m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO);
194 
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(),
198                                                   target_env.end());
199 
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);
205     } else {
206       m_options.launch_info.SetExecutableFile(
207           exe_module_sp->GetPlatformFileSpec(), true);
208     }
209 
210     if (launch_args.GetArgumentCount() == 0) {
211       m_options.launch_info.GetArguments().AppendArguments(
212           target->GetProcessLaunchInfo().GetArguments());
213     } else {
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);
217     }
218 
219     StreamString stream;
220     Status error = target->Launch(m_options.launch_info, &stream);
221 
222     if (error.Success()) {
223       ProcessSP process_sp(target->GetProcessSP());
224       if (process_sp) {
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));
230 
231         llvm::StringRef data = stream.GetString();
232         if (!data.empty())
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);
241       } else {
242         result.AppendError(
243             "no error returned from Target::Launch, and target has no process");
244         result.SetStatus(eReturnStatusFailed);
245       }
246     } else {
247       result.AppendError(error.AsCString());
248       result.SetStatus(eReturnStatusFailed);
249     }
250     return result.Succeeded();
251   }
252 
253 protected:
254   ProcessLaunchCommandOptions m_options;
255 };
256 
257 #define LLDB_OPTIONS_process_attach
258 #include "CommandOptions.inc"
259 
260 #pragma mark CommandObjectProcessAttach
261 class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach {
262 public:
263   class CommandOptions : public Options {
264   public:
265     CommandOptions() : Options() {
266       // Keep default values of all options in one place: OptionParsingStarting
267       // ()
268       OptionParsingStarting(nullptr);
269     }
270 
271     ~CommandOptions() override = default;
272 
273     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
274                           ExecutionContext *execution_context) override {
275       Status error;
276       const int short_option = m_getopt_table[option_idx].val;
277       switch (short_option) {
278       case 'c':
279         attach_info.SetContinueOnceAttached(true);
280         break;
281 
282       case 'p': {
283         lldb::pid_t pid;
284         if (option_arg.getAsInteger(0, pid)) {
285           error.SetErrorStringWithFormat("invalid process ID '%s'",
286                                          option_arg.str().c_str());
287         } else {
288           attach_info.SetProcessID(pid);
289         }
290       } break;
291 
292       case 'P':
293         attach_info.SetProcessPluginName(option_arg);
294         break;
295 
296       case 'n':
297         attach_info.GetExecutableFile().SetFile(option_arg,
298                                                 FileSpec::Style::native);
299         break;
300 
301       case 'w':
302         attach_info.SetWaitForLaunch(true);
303         break;
304 
305       case 'i':
306         attach_info.SetIgnoreExisting(false);
307         break;
308 
309       default:
310         llvm_unreachable("Unimplemented option");
311       }
312       return error;
313     }
314 
315     void OptionParsingStarting(ExecutionContext *execution_context) override {
316       attach_info.Clear();
317     }
318 
319     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
320       return llvm::makeArrayRef(g_process_attach_options);
321     }
322 
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;
328 
329       // We are only completing the name option for now...
330 
331       // Are we in the name?
332       if (GetDefinitions()[opt_defs_index].short_option != 'n')
333         return;
334 
335       // Look to see if there is a -P argument provided, and if so use that
336       // plugin, otherwise use the default plugin.
337 
338       const char *partial_name = nullptr;
339       partial_name = request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos);
340 
341       PlatformSP platform_sp(interpreter.GetPlatform(true));
342       if (!platform_sp)
343         return;
344       ProcessInstanceInfoList process_infos;
345       ProcessInstanceInfoMatch match_info;
346       if (partial_name) {
347         match_info.GetProcessInfo().GetExecutableFile().SetFile(
348             partial_name, FileSpec::Style::native);
349         match_info.SetNameMatchType(NameMatch::StartsWith);
350       }
351       platform_sp->FindProcesses(match_info, process_infos);
352       const size_t num_matches = process_infos.GetSize();
353       if (num_matches == 0)
354         return;
355       for (size_t i = 0; i < num_matches; ++i) {
356         request.AddCompletion(process_infos.GetProcessNameAtIndex(i));
357       }
358     }
359 
360     // Instance variables to hold the values for command options.
361 
362     ProcessAttachInfo attach_info;
363   };
364 
365   CommandObjectProcessAttach(CommandInterpreter &interpreter)
366       : CommandObjectProcessLaunchOrAttach(
367             interpreter, "process attach", "Attach to a process.",
368             "process attach <cmd-options>", 0, "attach"),
369         m_options() {}
370 
371   ~CommandObjectProcessAttach() override = default;
372 
373   Options *GetOptions() override { return &m_options; }
374 
375 protected:
376   bool DoExecute(Args &command, CommandReturnObject &result) override {
377     PlatformSP platform_sp(
378         GetDebugger().GetPlatformList().GetSelectedPlatform());
379 
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.
385 
386     StateType state = eStateInvalid;
387     Process *process = m_exe_ctx.GetProcessPtr();
388 
389     if (!StopProcessIfNecessary(process, state, result))
390       return false;
391 
392     if (target == nullptr) {
393       // If there isn't a current target create one.
394       TargetSP new_target_sp;
395       Status error;
396 
397       error = GetDebugger().GetTargetList().CreateTarget(
398           GetDebugger(), "", "", eLoadDependentsNo,
399           nullptr, // No platform options
400           new_target_sp);
401       target = new_target_sp.get();
402       if (target == nullptr || error.Fail()) {
403         result.AppendError(error.AsCString("Error creating target"));
404         return false;
405       }
406       GetDebugger().GetTargetList().SetSelectedTarget(target);
407     }
408 
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.)
412 
413     ModuleSP old_exec_module_sp = target->GetExecutableModule();
414     ArchSpec old_arch_spec = target->GetArchitecture();
415 
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);
420       return false;
421     }
422 
423     m_interpreter.UpdateExecutionContext(nullptr);
424     StreamString stream;
425     const auto error = target->Attach(m_options.attach_info, &stream);
426     if (error.Success()) {
427       ProcessSP process_sp(target->GetProcessSP());
428       if (process_sp) {
429         result.AppendMessage(stream.GetString());
430         result.SetStatus(eReturnStatusSuccessFinishNoResult);
431         result.SetDidChangeProcessState(true);
432         result.SetAbnormalStopWasExpected(true);
433       } else {
434         result.AppendError(
435             "no error returned from Target::Attach, and target has no process");
436         result.SetStatus(eReturnStatusFailed);
437       }
438     } else {
439       result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString());
440       result.SetStatus(eReturnStatusFailed);
441     }
442 
443     if (!result.Succeeded())
444       return false;
445 
446     // Okay, we're done.  Last step is to warn if the executable module has
447     // changed:
448     char new_path[PATH_MAX];
449     ModuleSP new_exec_module_sp(target->GetExecutableModule());
450     if (!old_exec_module_sp) {
451       // We might not have a module if we attached to a raw pid...
452       if (new_exec_module_sp) {
453         new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
454         result.AppendMessageWithFormat("Executable module set to \"%s\".\n",
455                                        new_path);
456       }
457     } else if (old_exec_module_sp->GetFileSpec() !=
458                new_exec_module_sp->GetFileSpec()) {
459       char old_path[PATH_MAX];
460 
461       old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX);
462       new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
463 
464       result.AppendWarningWithFormat(
465           "Executable module changed from \"%s\" to \"%s\".\n", old_path,
466           new_path);
467     }
468 
469     if (!old_arch_spec.IsValid()) {
470       result.AppendMessageWithFormat(
471           "Architecture set to: %s.\n",
472           target->GetArchitecture().GetTriple().getTriple().c_str());
473     } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) {
474       result.AppendWarningWithFormat(
475           "Architecture changed from %s to %s.\n",
476           old_arch_spec.GetTriple().getTriple().c_str(),
477           target->GetArchitecture().GetTriple().getTriple().c_str());
478     }
479 
480     // This supports the use-case scenario of immediately continuing the
481     // process once attached.
482     if (m_options.attach_info.GetContinueOnceAttached())
483       m_interpreter.HandleCommand("process continue", eLazyBoolNo, result);
484 
485     return result.Succeeded();
486   }
487 
488   CommandOptions m_options;
489 };
490 
491 // CommandObjectProcessContinue
492 
493 #define LLDB_OPTIONS_process_continue
494 #include "CommandOptions.inc"
495 
496 #pragma mark CommandObjectProcessContinue
497 
498 class CommandObjectProcessContinue : public CommandObjectParsed {
499 public:
500   CommandObjectProcessContinue(CommandInterpreter &interpreter)
501       : CommandObjectParsed(
502             interpreter, "process continue",
503             "Continue execution of all threads in the current process.",
504             "process continue",
505             eCommandRequiresProcess | eCommandTryTargetAPILock |
506                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
507         m_options() {}
508 
509   ~CommandObjectProcessContinue() override = default;
510 
511 protected:
512   class CommandOptions : public Options {
513   public:
514     CommandOptions() : Options() {
515       // Keep default values of all options in one place: OptionParsingStarting
516       // ()
517       OptionParsingStarting(nullptr);
518     }
519 
520     ~CommandOptions() override = default;
521 
522     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
523                           ExecutionContext *execution_context) override {
524       Status error;
525       const int short_option = m_getopt_table[option_idx].val;
526       switch (short_option) {
527       case 'i':
528         if (option_arg.getAsInteger(0, m_ignore))
529           error.SetErrorStringWithFormat(
530               "invalid value for ignore option: \"%s\", should be a number.",
531               option_arg.str().c_str());
532         break;
533 
534       default:
535         llvm_unreachable("Unimplemented option");
536       }
537       return error;
538     }
539 
540     void OptionParsingStarting(ExecutionContext *execution_context) override {
541       m_ignore = 0;
542     }
543 
544     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
545       return llvm::makeArrayRef(g_process_continue_options);
546     }
547 
548     uint32_t m_ignore;
549   };
550 
551   bool DoExecute(Args &command, CommandReturnObject &result) override {
552     Process *process = m_exe_ctx.GetProcessPtr();
553     bool synchronous_execution = m_interpreter.GetSynchronous();
554     StateType state = process->GetState();
555     if (state == eStateStopped) {
556       if (command.GetArgumentCount() != 0) {
557         result.AppendErrorWithFormat(
558             "The '%s' command does not take any arguments.\n",
559             m_cmd_name.c_str());
560         result.SetStatus(eReturnStatusFailed);
561         return false;
562       }
563 
564       if (m_options.m_ignore > 0) {
565         ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this());
566         if (sel_thread_sp) {
567           StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo();
568           if (stop_info_sp &&
569               stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
570             lldb::break_id_t bp_site_id =
571                 (lldb::break_id_t)stop_info_sp->GetValue();
572             BreakpointSiteSP bp_site_sp(
573                 process->GetBreakpointSiteList().FindByID(bp_site_id));
574             if (bp_site_sp) {
575               const size_t num_owners = bp_site_sp->GetNumberOfOwners();
576               for (size_t i = 0; i < num_owners; i++) {
577                 Breakpoint &bp_ref =
578                     bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
579                 if (!bp_ref.IsInternal()) {
580                   bp_ref.SetIgnoreCount(m_options.m_ignore);
581                 }
582               }
583             }
584           }
585         }
586       }
587 
588       { // Scope for thread list mutex:
589         std::lock_guard<std::recursive_mutex> guard(
590             process->GetThreadList().GetMutex());
591         const uint32_t num_threads = process->GetThreadList().GetSize();
592 
593         // Set the actions that the threads should each take when resuming
594         for (uint32_t idx = 0; idx < num_threads; ++idx) {
595           const bool override_suspend = false;
596           process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState(
597               eStateRunning, override_suspend);
598         }
599       }
600 
601       const uint32_t iohandler_id = process->GetIOHandlerID();
602 
603       StreamString stream;
604       Status error;
605       if (synchronous_execution)
606         error = process->ResumeSynchronous(&stream);
607       else
608         error = process->Resume();
609 
610       if (error.Success()) {
611         // There is a race condition where this thread will return up the call
612         // stack to the main command handler and show an (lldb) prompt before
613         // HandlePrivateEvent (from PrivateStateThread) has a chance to call
614         // PushProcessIOHandler().
615         process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
616 
617         result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
618                                        process->GetID());
619         if (synchronous_execution) {
620           // If any state changed events had anything to say, add that to the
621           // result
622           result.AppendMessage(stream.GetString());
623 
624           result.SetDidChangeProcessState(true);
625           result.SetStatus(eReturnStatusSuccessFinishNoResult);
626         } else {
627           result.SetStatus(eReturnStatusSuccessContinuingNoResult);
628         }
629       } else {
630         result.AppendErrorWithFormat("Failed to resume process: %s.\n",
631                                      error.AsCString());
632         result.SetStatus(eReturnStatusFailed);
633       }
634     } else {
635       result.AppendErrorWithFormat(
636           "Process cannot be continued from its current state (%s).\n",
637           StateAsCString(state));
638       result.SetStatus(eReturnStatusFailed);
639     }
640     return result.Succeeded();
641   }
642 
643   Options *GetOptions() override { return &m_options; }
644 
645   CommandOptions m_options;
646 };
647 
648 // CommandObjectProcessDetach
649 #define LLDB_OPTIONS_process_detach
650 #include "CommandOptions.inc"
651 
652 #pragma mark CommandObjectProcessDetach
653 
654 class CommandObjectProcessDetach : public CommandObjectParsed {
655 public:
656   class CommandOptions : public Options {
657   public:
658     CommandOptions() : Options() { OptionParsingStarting(nullptr); }
659 
660     ~CommandOptions() override = default;
661 
662     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
663                           ExecutionContext *execution_context) override {
664       Status error;
665       const int short_option = m_getopt_table[option_idx].val;
666 
667       switch (short_option) {
668       case 's':
669         bool tmp_result;
670         bool success;
671         tmp_result = OptionArgParser::ToBoolean(option_arg, false, &success);
672         if (!success)
673           error.SetErrorStringWithFormat("invalid boolean option: \"%s\"",
674                                          option_arg.str().c_str());
675         else {
676           if (tmp_result)
677             m_keep_stopped = eLazyBoolYes;
678           else
679             m_keep_stopped = eLazyBoolNo;
680         }
681         break;
682       default:
683         llvm_unreachable("Unimplemented option");
684       }
685       return error;
686     }
687 
688     void OptionParsingStarting(ExecutionContext *execution_context) override {
689       m_keep_stopped = eLazyBoolCalculate;
690     }
691 
692     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
693       return llvm::makeArrayRef(g_process_detach_options);
694     }
695 
696     // Instance variables to hold the values for command options.
697     LazyBool m_keep_stopped;
698   };
699 
700   CommandObjectProcessDetach(CommandInterpreter &interpreter)
701       : CommandObjectParsed(interpreter, "process detach",
702                             "Detach from the current target process.",
703                             "process detach",
704                             eCommandRequiresProcess | eCommandTryTargetAPILock |
705                                 eCommandProcessMustBeLaunched),
706         m_options() {}
707 
708   ~CommandObjectProcessDetach() override = default;
709 
710   Options *GetOptions() override { return &m_options; }
711 
712 protected:
713   bool DoExecute(Args &command, CommandReturnObject &result) override {
714     Process *process = m_exe_ctx.GetProcessPtr();
715     // FIXME: This will be a Command Option:
716     bool keep_stopped;
717     if (m_options.m_keep_stopped == eLazyBoolCalculate) {
718       // Check the process default:
719       keep_stopped = process->GetDetachKeepsStopped();
720     } else if (m_options.m_keep_stopped == eLazyBoolYes)
721       keep_stopped = true;
722     else
723       keep_stopped = false;
724 
725     Status error(process->Detach(keep_stopped));
726     if (error.Success()) {
727       result.SetStatus(eReturnStatusSuccessFinishResult);
728     } else {
729       result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString());
730       result.SetStatus(eReturnStatusFailed);
731       return false;
732     }
733     return result.Succeeded();
734   }
735 
736   CommandOptions m_options;
737 };
738 
739 // CommandObjectProcessConnect
740 #define LLDB_OPTIONS_process_connect
741 #include "CommandOptions.inc"
742 
743 #pragma mark CommandObjectProcessConnect
744 
745 class CommandObjectProcessConnect : public CommandObjectParsed {
746 public:
747   class CommandOptions : public Options {
748   public:
749     CommandOptions() : Options() {
750       // Keep default values of all options in one place: OptionParsingStarting
751       // ()
752       OptionParsingStarting(nullptr);
753     }
754 
755     ~CommandOptions() override = default;
756 
757     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
758                           ExecutionContext *execution_context) override {
759       Status error;
760       const int short_option = m_getopt_table[option_idx].val;
761 
762       switch (short_option) {
763       case 'p':
764         plugin_name.assign(option_arg);
765         break;
766 
767       default:
768         llvm_unreachable("Unimplemented option");
769       }
770       return error;
771     }
772 
773     void OptionParsingStarting(ExecutionContext *execution_context) override {
774       plugin_name.clear();
775     }
776 
777     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
778       return llvm::makeArrayRef(g_process_connect_options);
779     }
780 
781     // Instance variables to hold the values for command options.
782 
783     std::string plugin_name;
784   };
785 
786   CommandObjectProcessConnect(CommandInterpreter &interpreter)
787       : CommandObjectParsed(interpreter, "process connect",
788                             "Connect to a remote debug service.",
789                             "process connect <remote-url>", 0),
790         m_options() {}
791 
792   ~CommandObjectProcessConnect() override = default;
793 
794   Options *GetOptions() override { return &m_options; }
795 
796 protected:
797   bool DoExecute(Args &command, CommandReturnObject &result) override {
798     if (command.GetArgumentCount() != 1) {
799       result.AppendErrorWithFormat(
800           "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(),
801           m_cmd_syntax.c_str());
802       result.SetStatus(eReturnStatusFailed);
803       return false;
804     }
805 
806     Process *process = m_exe_ctx.GetProcessPtr();
807     if (process && process->IsAlive()) {
808       result.AppendErrorWithFormat(
809           "Process %" PRIu64
810           " is currently being debugged, kill the process before connecting.\n",
811           process->GetID());
812       result.SetStatus(eReturnStatusFailed);
813       return false;
814     }
815 
816     const char *plugin_name = nullptr;
817     if (!m_options.plugin_name.empty())
818       plugin_name = m_options.plugin_name.c_str();
819 
820     Status error;
821     Debugger &debugger = GetDebugger();
822     PlatformSP platform_sp = m_interpreter.GetPlatform(true);
823     ProcessSP process_sp = platform_sp->ConnectProcess(
824         command.GetArgumentAtIndex(0), plugin_name, debugger,
825         debugger.GetSelectedTarget().get(), error);
826     if (error.Fail() || process_sp == nullptr) {
827       result.AppendError(error.AsCString("Error connecting to the process"));
828       result.SetStatus(eReturnStatusFailed);
829       return false;
830     }
831     return true;
832   }
833 
834   CommandOptions m_options;
835 };
836 
837 // CommandObjectProcessPlugin
838 #pragma mark CommandObjectProcessPlugin
839 
840 class CommandObjectProcessPlugin : public CommandObjectProxy {
841 public:
842   CommandObjectProcessPlugin(CommandInterpreter &interpreter)
843       : CommandObjectProxy(
844             interpreter, "process plugin",
845             "Send a custom command to the current target process plug-in.",
846             "process plugin <args>", 0) {}
847 
848   ~CommandObjectProcessPlugin() override = default;
849 
850   CommandObject *GetProxyCommandObject() override {
851     Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
852     if (process)
853       return process->GetPluginCommandObject();
854     return nullptr;
855   }
856 };
857 
858 // CommandObjectProcessLoad
859 #define LLDB_OPTIONS_process_load
860 #include "CommandOptions.inc"
861 
862 #pragma mark CommandObjectProcessLoad
863 
864 class CommandObjectProcessLoad : public CommandObjectParsed {
865 public:
866   class CommandOptions : public Options {
867   public:
868     CommandOptions() : Options() {
869       // Keep default values of all options in one place: OptionParsingStarting
870       // ()
871       OptionParsingStarting(nullptr);
872     }
873 
874     ~CommandOptions() override = default;
875 
876     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
877                           ExecutionContext *execution_context) override {
878       Status error;
879       const int short_option = m_getopt_table[option_idx].val;
880       switch (short_option) {
881       case 'i':
882         do_install = true;
883         if (!option_arg.empty())
884           install_path.SetFile(option_arg, FileSpec::Style::native);
885         break;
886       default:
887         llvm_unreachable("Unimplemented option");
888       }
889       return error;
890     }
891 
892     void OptionParsingStarting(ExecutionContext *execution_context) override {
893       do_install = false;
894       install_path.Clear();
895     }
896 
897     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
898       return llvm::makeArrayRef(g_process_load_options);
899     }
900 
901     // Instance variables to hold the values for command options.
902     bool do_install;
903     FileSpec install_path;
904   };
905 
906   CommandObjectProcessLoad(CommandInterpreter &interpreter)
907       : CommandObjectParsed(interpreter, "process load",
908                             "Load a shared library into the current process.",
909                             "process load <filename> [<filename> ...]",
910                             eCommandRequiresProcess | eCommandTryTargetAPILock |
911                                 eCommandProcessMustBeLaunched |
912                                 eCommandProcessMustBePaused),
913         m_options() {}
914 
915   ~CommandObjectProcessLoad() override = default;
916 
917   Options *GetOptions() override { return &m_options; }
918 
919 protected:
920   bool DoExecute(Args &command, CommandReturnObject &result) override {
921     Process *process = m_exe_ctx.GetProcessPtr();
922 
923     for (auto &entry : command.entries()) {
924       Status error;
925       PlatformSP platform = process->GetTarget().GetPlatform();
926       llvm::StringRef image_path = entry.ref();
927       uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN;
928 
929       if (!m_options.do_install) {
930         FileSpec image_spec(image_path);
931         platform->ResolveRemotePath(image_spec, image_spec);
932         image_token =
933             platform->LoadImage(process, FileSpec(), image_spec, error);
934       } else if (m_options.install_path) {
935         FileSpec image_spec(image_path);
936         FileSystem::Instance().Resolve(image_spec);
937         platform->ResolveRemotePath(m_options.install_path,
938                                     m_options.install_path);
939         image_token = platform->LoadImage(process, image_spec,
940                                           m_options.install_path, error);
941       } else {
942         FileSpec image_spec(image_path);
943         FileSystem::Instance().Resolve(image_spec);
944         image_token =
945             platform->LoadImage(process, image_spec, FileSpec(), error);
946       }
947 
948       if (image_token != LLDB_INVALID_IMAGE_TOKEN) {
949         result.AppendMessageWithFormat(
950             "Loading \"%s\"...ok\nImage %u loaded.\n", image_path.str().c_str(),
951             image_token);
952         result.SetStatus(eReturnStatusSuccessFinishResult);
953       } else {
954         result.AppendErrorWithFormat("failed to load '%s': %s",
955                                      image_path.str().c_str(),
956                                      error.AsCString());
957         result.SetStatus(eReturnStatusFailed);
958       }
959     }
960     return result.Succeeded();
961   }
962 
963   CommandOptions m_options;
964 };
965 
966 // CommandObjectProcessUnload
967 #pragma mark CommandObjectProcessUnload
968 
969 class CommandObjectProcessUnload : public CommandObjectParsed {
970 public:
971   CommandObjectProcessUnload(CommandInterpreter &interpreter)
972       : CommandObjectParsed(
973             interpreter, "process unload",
974             "Unload a shared library from the current process using the index "
975             "returned by a previous call to \"process load\".",
976             "process unload <index>",
977             eCommandRequiresProcess | eCommandTryTargetAPILock |
978                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
979 
980   ~CommandObjectProcessUnload() override = default;
981 
982 protected:
983   bool DoExecute(Args &command, CommandReturnObject &result) override {
984     Process *process = m_exe_ctx.GetProcessPtr();
985 
986     for (auto &entry : command.entries()) {
987       uint32_t image_token;
988       if (entry.ref().getAsInteger(0, image_token)) {
989         result.AppendErrorWithFormat("invalid image index argument '%s'",
990                                      entry.ref().str().c_str());
991         result.SetStatus(eReturnStatusFailed);
992         break;
993       } else {
994         Status error(process->GetTarget().GetPlatform()->UnloadImage(
995             process, image_token));
996         if (error.Success()) {
997           result.AppendMessageWithFormat(
998               "Unloading shared library with index %u...ok\n", image_token);
999           result.SetStatus(eReturnStatusSuccessFinishResult);
1000         } else {
1001           result.AppendErrorWithFormat("failed to unload image: %s",
1002                                        error.AsCString());
1003           result.SetStatus(eReturnStatusFailed);
1004           break;
1005         }
1006       }
1007     }
1008     return result.Succeeded();
1009   }
1010 };
1011 
1012 // CommandObjectProcessSignal
1013 #pragma mark CommandObjectProcessSignal
1014 
1015 class CommandObjectProcessSignal : public CommandObjectParsed {
1016 public:
1017   CommandObjectProcessSignal(CommandInterpreter &interpreter)
1018       : CommandObjectParsed(interpreter, "process signal",
1019                             "Send a UNIX signal to the current target process.",
1020                             nullptr, eCommandRequiresProcess |
1021                                          eCommandTryTargetAPILock) {
1022     CommandArgumentEntry arg;
1023     CommandArgumentData signal_arg;
1024 
1025     // Define the first (and only) variant of this arg.
1026     signal_arg.arg_type = eArgTypeUnixSignal;
1027     signal_arg.arg_repetition = eArgRepeatPlain;
1028 
1029     // There is only one variant this argument could be; put it into the
1030     // argument entry.
1031     arg.push_back(signal_arg);
1032 
1033     // Push the data for the first argument into the m_arguments vector.
1034     m_arguments.push_back(arg);
1035   }
1036 
1037   ~CommandObjectProcessSignal() override = default;
1038 
1039 protected:
1040   bool DoExecute(Args &command, CommandReturnObject &result) override {
1041     Process *process = m_exe_ctx.GetProcessPtr();
1042 
1043     if (command.GetArgumentCount() == 1) {
1044       int signo = LLDB_INVALID_SIGNAL_NUMBER;
1045 
1046       const char *signal_name = command.GetArgumentAtIndex(0);
1047       if (::isxdigit(signal_name[0]))
1048         signo =
1049             StringConvert::ToSInt32(signal_name, LLDB_INVALID_SIGNAL_NUMBER, 0);
1050       else
1051         signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name);
1052 
1053       if (signo == LLDB_INVALID_SIGNAL_NUMBER) {
1054         result.AppendErrorWithFormat("Invalid signal argument '%s'.\n",
1055                                      command.GetArgumentAtIndex(0));
1056         result.SetStatus(eReturnStatusFailed);
1057       } else {
1058         Status error(process->Signal(signo));
1059         if (error.Success()) {
1060           result.SetStatus(eReturnStatusSuccessFinishResult);
1061         } else {
1062           result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo,
1063                                        error.AsCString());
1064           result.SetStatus(eReturnStatusFailed);
1065         }
1066       }
1067     } else {
1068       result.AppendErrorWithFormat(
1069           "'%s' takes exactly one signal number argument:\nUsage: %s\n",
1070           m_cmd_name.c_str(), m_cmd_syntax.c_str());
1071       result.SetStatus(eReturnStatusFailed);
1072     }
1073     return result.Succeeded();
1074   }
1075 };
1076 
1077 // CommandObjectProcessInterrupt
1078 #pragma mark CommandObjectProcessInterrupt
1079 
1080 class CommandObjectProcessInterrupt : public CommandObjectParsed {
1081 public:
1082   CommandObjectProcessInterrupt(CommandInterpreter &interpreter)
1083       : CommandObjectParsed(interpreter, "process interrupt",
1084                             "Interrupt the current target process.",
1085                             "process interrupt",
1086                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1087                                 eCommandProcessMustBeLaunched) {}
1088 
1089   ~CommandObjectProcessInterrupt() override = default;
1090 
1091 protected:
1092   bool DoExecute(Args &command, CommandReturnObject &result) override {
1093     Process *process = m_exe_ctx.GetProcessPtr();
1094     if (process == nullptr) {
1095       result.AppendError("no process to halt");
1096       result.SetStatus(eReturnStatusFailed);
1097       return false;
1098     }
1099 
1100     if (command.GetArgumentCount() == 0) {
1101       bool clear_thread_plans = true;
1102       Status error(process->Halt(clear_thread_plans));
1103       if (error.Success()) {
1104         result.SetStatus(eReturnStatusSuccessFinishResult);
1105       } else {
1106         result.AppendErrorWithFormat("Failed to halt process: %s\n",
1107                                      error.AsCString());
1108         result.SetStatus(eReturnStatusFailed);
1109       }
1110     } else {
1111       result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n",
1112                                    m_cmd_name.c_str(), m_cmd_syntax.c_str());
1113       result.SetStatus(eReturnStatusFailed);
1114     }
1115     return result.Succeeded();
1116   }
1117 };
1118 
1119 // CommandObjectProcessKill
1120 #pragma mark CommandObjectProcessKill
1121 
1122 class CommandObjectProcessKill : public CommandObjectParsed {
1123 public:
1124   CommandObjectProcessKill(CommandInterpreter &interpreter)
1125       : CommandObjectParsed(interpreter, "process kill",
1126                             "Terminate the current target process.",
1127                             "process kill",
1128                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1129                                 eCommandProcessMustBeLaunched) {}
1130 
1131   ~CommandObjectProcessKill() override = default;
1132 
1133 protected:
1134   bool DoExecute(Args &command, CommandReturnObject &result) override {
1135     Process *process = m_exe_ctx.GetProcessPtr();
1136     if (process == nullptr) {
1137       result.AppendError("no process to kill");
1138       result.SetStatus(eReturnStatusFailed);
1139       return false;
1140     }
1141 
1142     if (command.GetArgumentCount() == 0) {
1143       Status error(process->Destroy(true));
1144       if (error.Success()) {
1145         result.SetStatus(eReturnStatusSuccessFinishResult);
1146       } else {
1147         result.AppendErrorWithFormat("Failed to kill process: %s\n",
1148                                      error.AsCString());
1149         result.SetStatus(eReturnStatusFailed);
1150       }
1151     } else {
1152       result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n",
1153                                    m_cmd_name.c_str(), m_cmd_syntax.c_str());
1154       result.SetStatus(eReturnStatusFailed);
1155     }
1156     return result.Succeeded();
1157   }
1158 };
1159 
1160 // CommandObjectProcessSaveCore
1161 #pragma mark CommandObjectProcessSaveCore
1162 
1163 class CommandObjectProcessSaveCore : public CommandObjectParsed {
1164 public:
1165   CommandObjectProcessSaveCore(CommandInterpreter &interpreter)
1166       : CommandObjectParsed(interpreter, "process save-core",
1167                             "Save the current process as a core file using an "
1168                             "appropriate file type.",
1169                             "process save-core FILE",
1170                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1171                                 eCommandProcessMustBeLaunched) {}
1172 
1173   ~CommandObjectProcessSaveCore() override = default;
1174 
1175 protected:
1176   bool DoExecute(Args &command, CommandReturnObject &result) override {
1177     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1178     if (process_sp) {
1179       if (command.GetArgumentCount() == 1) {
1180         FileSpec output_file(command.GetArgumentAtIndex(0));
1181         Status error = PluginManager::SaveCore(process_sp, output_file);
1182         if (error.Success()) {
1183           result.SetStatus(eReturnStatusSuccessFinishResult);
1184         } else {
1185           result.AppendErrorWithFormat(
1186               "Failed to save core file for process: %s\n", error.AsCString());
1187           result.SetStatus(eReturnStatusFailed);
1188         }
1189       } else {
1190         result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n",
1191                                      m_cmd_name.c_str(), m_cmd_syntax.c_str());
1192         result.SetStatus(eReturnStatusFailed);
1193       }
1194     } else {
1195       result.AppendError("invalid process");
1196       result.SetStatus(eReturnStatusFailed);
1197       return false;
1198     }
1199 
1200     return result.Succeeded();
1201   }
1202 };
1203 
1204 // CommandObjectProcessStatus
1205 #pragma mark CommandObjectProcessStatus
1206 
1207 class CommandObjectProcessStatus : public CommandObjectParsed {
1208 public:
1209   CommandObjectProcessStatus(CommandInterpreter &interpreter)
1210       : CommandObjectParsed(
1211             interpreter, "process status",
1212             "Show status and stop location for the current target process.",
1213             "process status",
1214             eCommandRequiresProcess | eCommandTryTargetAPILock) {}
1215 
1216   ~CommandObjectProcessStatus() override = default;
1217 
1218   bool DoExecute(Args &command, CommandReturnObject &result) override {
1219     Stream &strm = result.GetOutputStream();
1220     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1221     // No need to check "process" for validity as eCommandRequiresProcess
1222     // ensures it is valid
1223     Process *process = m_exe_ctx.GetProcessPtr();
1224     const bool only_threads_with_stop_reason = true;
1225     const uint32_t start_frame = 0;
1226     const uint32_t num_frames = 1;
1227     const uint32_t num_frames_with_source = 1;
1228     const bool     stop_format = true;
1229     process->GetStatus(strm);
1230     process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1231                              num_frames, num_frames_with_source, stop_format);
1232     return result.Succeeded();
1233   }
1234 };
1235 
1236 // CommandObjectProcessHandle
1237 #define LLDB_OPTIONS_process_handle
1238 #include "CommandOptions.inc"
1239 
1240 #pragma mark CommandObjectProcessHandle
1241 
1242 class CommandObjectProcessHandle : public CommandObjectParsed {
1243 public:
1244   class CommandOptions : public Options {
1245   public:
1246     CommandOptions() : Options() { OptionParsingStarting(nullptr); }
1247 
1248     ~CommandOptions() override = default;
1249 
1250     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1251                           ExecutionContext *execution_context) override {
1252       Status error;
1253       const int short_option = m_getopt_table[option_idx].val;
1254 
1255       switch (short_option) {
1256       case 's':
1257         stop = option_arg;
1258         break;
1259       case 'n':
1260         notify = option_arg;
1261         break;
1262       case 'p':
1263         pass = option_arg;
1264         break;
1265       default:
1266         llvm_unreachable("Unimplemented option");
1267       }
1268       return error;
1269     }
1270 
1271     void OptionParsingStarting(ExecutionContext *execution_context) override {
1272       stop.clear();
1273       notify.clear();
1274       pass.clear();
1275     }
1276 
1277     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1278       return llvm::makeArrayRef(g_process_handle_options);
1279     }
1280 
1281     // Instance variables to hold the values for command options.
1282 
1283     std::string stop;
1284     std::string notify;
1285     std::string pass;
1286   };
1287 
1288   CommandObjectProcessHandle(CommandInterpreter &interpreter)
1289       : CommandObjectParsed(interpreter, "process handle",
1290                             "Manage LLDB handling of OS signals for the "
1291                             "current target process.  Defaults to showing "
1292                             "current policy.",
1293                             nullptr, eCommandRequiresTarget),
1294         m_options() {
1295     SetHelpLong("\nIf no signals are specified, update them all.  If no update "
1296                 "option is specified, list the current values.");
1297     CommandArgumentEntry arg;
1298     CommandArgumentData signal_arg;
1299 
1300     signal_arg.arg_type = eArgTypeUnixSignal;
1301     signal_arg.arg_repetition = eArgRepeatStar;
1302 
1303     arg.push_back(signal_arg);
1304 
1305     m_arguments.push_back(arg);
1306   }
1307 
1308   ~CommandObjectProcessHandle() override = default;
1309 
1310   Options *GetOptions() override { return &m_options; }
1311 
1312   bool VerifyCommandOptionValue(const std::string &option, int &real_value) {
1313     bool okay = true;
1314     bool success = false;
1315     bool tmp_value = OptionArgParser::ToBoolean(option, false, &success);
1316 
1317     if (success && tmp_value)
1318       real_value = 1;
1319     else if (success && !tmp_value)
1320       real_value = 0;
1321     else {
1322       // If the value isn't 'true' or 'false', it had better be 0 or 1.
1323       real_value = StringConvert::ToUInt32(option.c_str(), 3);
1324       if (real_value != 0 && real_value != 1)
1325         okay = false;
1326     }
1327 
1328     return okay;
1329   }
1330 
1331   void PrintSignalHeader(Stream &str) {
1332     str.Printf("NAME         PASS   STOP   NOTIFY\n");
1333     str.Printf("===========  =====  =====  ======\n");
1334   }
1335 
1336   void PrintSignal(Stream &str, int32_t signo, const char *sig_name,
1337                    const UnixSignalsSP &signals_sp) {
1338     bool stop;
1339     bool suppress;
1340     bool notify;
1341 
1342     str.Printf("%-11s  ", sig_name);
1343     if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) {
1344       bool pass = !suppress;
1345       str.Printf("%s  %s  %s", (pass ? "true " : "false"),
1346                  (stop ? "true " : "false"), (notify ? "true " : "false"));
1347     }
1348     str.Printf("\n");
1349   }
1350 
1351   void PrintSignalInformation(Stream &str, Args &signal_args,
1352                               int num_valid_signals,
1353                               const UnixSignalsSP &signals_sp) {
1354     PrintSignalHeader(str);
1355 
1356     if (num_valid_signals > 0) {
1357       size_t num_args = signal_args.GetArgumentCount();
1358       for (size_t i = 0; i < num_args; ++i) {
1359         int32_t signo = signals_sp->GetSignalNumberFromName(
1360             signal_args.GetArgumentAtIndex(i));
1361         if (signo != LLDB_INVALID_SIGNAL_NUMBER)
1362           PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i),
1363                       signals_sp);
1364       }
1365     } else // Print info for ALL signals
1366     {
1367       int32_t signo = signals_sp->GetFirstSignalNumber();
1368       while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1369         PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo),
1370                     signals_sp);
1371         signo = signals_sp->GetNextSignalNumber(signo);
1372       }
1373     }
1374   }
1375 
1376 protected:
1377   bool DoExecute(Args &signal_args, CommandReturnObject &result) override {
1378     Target *target_sp = &GetSelectedTarget();
1379 
1380     ProcessSP process_sp = target_sp->GetProcessSP();
1381 
1382     if (!process_sp) {
1383       result.AppendError("No current process; cannot handle signals until you "
1384                          "have a valid process.\n");
1385       result.SetStatus(eReturnStatusFailed);
1386       return false;
1387     }
1388 
1389     int stop_action = -1;   // -1 means leave the current setting alone
1390     int pass_action = -1;   // -1 means leave the current setting alone
1391     int notify_action = -1; // -1 means leave the current setting alone
1392 
1393     if (!m_options.stop.empty() &&
1394         !VerifyCommandOptionValue(m_options.stop, stop_action)) {
1395       result.AppendError("Invalid argument for command option --stop; must be "
1396                          "true or false.\n");
1397       result.SetStatus(eReturnStatusFailed);
1398       return false;
1399     }
1400 
1401     if (!m_options.notify.empty() &&
1402         !VerifyCommandOptionValue(m_options.notify, notify_action)) {
1403       result.AppendError("Invalid argument for command option --notify; must "
1404                          "be true or false.\n");
1405       result.SetStatus(eReturnStatusFailed);
1406       return false;
1407     }
1408 
1409     if (!m_options.pass.empty() &&
1410         !VerifyCommandOptionValue(m_options.pass, pass_action)) {
1411       result.AppendError("Invalid argument for command option --pass; must be "
1412                          "true or false.\n");
1413       result.SetStatus(eReturnStatusFailed);
1414       return false;
1415     }
1416 
1417     size_t num_args = signal_args.GetArgumentCount();
1418     UnixSignalsSP signals_sp = process_sp->GetUnixSignals();
1419     int num_signals_set = 0;
1420 
1421     if (num_args > 0) {
1422       for (const auto &arg : signal_args) {
1423         int32_t signo = signals_sp->GetSignalNumberFromName(arg.c_str());
1424         if (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1425           // Casting the actions as bools here should be okay, because
1426           // VerifyCommandOptionValue guarantees the value is either 0 or 1.
1427           if (stop_action != -1)
1428             signals_sp->SetShouldStop(signo, stop_action);
1429           if (pass_action != -1) {
1430             bool suppress = !pass_action;
1431             signals_sp->SetShouldSuppress(signo, suppress);
1432           }
1433           if (notify_action != -1)
1434             signals_sp->SetShouldNotify(signo, notify_action);
1435           ++num_signals_set;
1436         } else {
1437           result.AppendErrorWithFormat("Invalid signal name '%s'\n",
1438                                        arg.c_str());
1439         }
1440       }
1441     } else {
1442       // No signal specified, if any command options were specified, update ALL
1443       // signals.
1444       if ((notify_action != -1) || (stop_action != -1) || (pass_action != -1)) {
1445         if (m_interpreter.Confirm(
1446                 "Do you really want to update all the signals?", false)) {
1447           int32_t signo = signals_sp->GetFirstSignalNumber();
1448           while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1449             if (notify_action != -1)
1450               signals_sp->SetShouldNotify(signo, notify_action);
1451             if (stop_action != -1)
1452               signals_sp->SetShouldStop(signo, stop_action);
1453             if (pass_action != -1) {
1454               bool suppress = !pass_action;
1455               signals_sp->SetShouldSuppress(signo, suppress);
1456             }
1457             signo = signals_sp->GetNextSignalNumber(signo);
1458           }
1459         }
1460       }
1461     }
1462 
1463     PrintSignalInformation(result.GetOutputStream(), signal_args,
1464                            num_signals_set, signals_sp);
1465 
1466     if (num_signals_set > 0)
1467       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1468     else
1469       result.SetStatus(eReturnStatusFailed);
1470 
1471     return result.Succeeded();
1472   }
1473 
1474   CommandOptions m_options;
1475 };
1476 
1477 // CommandObjectMultiwordProcess
1478 
1479 CommandObjectMultiwordProcess::CommandObjectMultiwordProcess(
1480     CommandInterpreter &interpreter)
1481     : CommandObjectMultiword(
1482           interpreter, "process",
1483           "Commands for interacting with processes on the current platform.",
1484           "process <subcommand> [<subcommand-options>]") {
1485   LoadSubCommand("attach",
1486                  CommandObjectSP(new CommandObjectProcessAttach(interpreter)));
1487   LoadSubCommand("launch",
1488                  CommandObjectSP(new CommandObjectProcessLaunch(interpreter)));
1489   LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue(
1490                                  interpreter)));
1491   LoadSubCommand("connect",
1492                  CommandObjectSP(new CommandObjectProcessConnect(interpreter)));
1493   LoadSubCommand("detach",
1494                  CommandObjectSP(new CommandObjectProcessDetach(interpreter)));
1495   LoadSubCommand("load",
1496                  CommandObjectSP(new CommandObjectProcessLoad(interpreter)));
1497   LoadSubCommand("unload",
1498                  CommandObjectSP(new CommandObjectProcessUnload(interpreter)));
1499   LoadSubCommand("signal",
1500                  CommandObjectSP(new CommandObjectProcessSignal(interpreter)));
1501   LoadSubCommand("handle",
1502                  CommandObjectSP(new CommandObjectProcessHandle(interpreter)));
1503   LoadSubCommand("status",
1504                  CommandObjectSP(new CommandObjectProcessStatus(interpreter)));
1505   LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt(
1506                                   interpreter)));
1507   LoadSubCommand("kill",
1508                  CommandObjectSP(new CommandObjectProcessKill(interpreter)));
1509   LoadSubCommand("plugin",
1510                  CommandObjectSP(new CommandObjectProcessPlugin(interpreter)));
1511   LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore(
1512                                   interpreter)));
1513 }
1514 
1515 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default;
1516