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