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