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