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