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