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