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