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