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