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