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