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