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