Fixed debugserver to properly attach to a process by name with the 
"vAttachName;<PROCNAME>" packet, and wait for a new process by name to launch 
with the "vAttachWait;<PROCNAME>".

Fixed a few issues with attaching where if DoAttach() returned no error, yet
there was no valid process ID, we would deadlock waiting for an event that
would never happen.

Added a new "process launch" option "--tty" that will launch the process 
in a new terminal if the Host layer supports the "Host::LaunchInNewTerminal(...)"
function. This currently works on MacOSX and will allow the debugging of 
terminal applications that do complex operations with the terminal. 

Cleaned up the output when the process resumes, stops and halts to be 
consistent with the output format.



git-svn-id: https://llvm.org/svn/llvm-project/llvdb/trunk@116693 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/source/Commands/CommandObjectProcess.cpp b/source/Commands/CommandObjectProcess.cpp
index 62b4a0f..e357934 100644
--- a/source/Commands/CommandObjectProcess.cpp
+++ b/source/Commands/CommandObjectProcess.cpp
@@ -62,6 +62,7 @@
                 case 'i':   stdin_path  = option_arg;   break;
                 case 'o':   stdout_path = option_arg;   break;
                 case 'p':   plugin_name = option_arg;   break;
+                case 't':   in_new_tty = true; break;
                 default:
                     error.SetErrorStringWithFormat("Invalid short option character '%c'.\n", short_option);
                     break;
@@ -75,6 +76,7 @@
         {
             Options::ResetOptionValues();
             stop_at_entry = false;
+            in_new_tty = false;
             stdin_path.clear();
             stdout_path.clear();
             stderr_path.clear();
@@ -94,6 +96,7 @@
         // Instance variables to hold the values for command options.
 
         bool stop_at_entry;
+        bool in_new_tty;
         std::string stderr_path;
         std::string stdin_path;
         std::string stdout_path;
@@ -146,7 +149,7 @@
 
         // If our listener is NULL, users aren't allows to launch
         char filename[PATH_MAX];
-        Module *exe_module = target->GetExecutableModule().get();
+        const Module *exe_module = target->GetExecutableModule().get();
         exe_module->GetFileSpec().GetPath(filename, sizeof(filename));
 
         Process *process = m_interpreter.GetDebugger().GetExecutionContext().process;
@@ -181,6 +184,21 @@
                 launch_args = process->GetRunArguments();
         }
         
+        if (m_options.in_new_tty)
+        {
+            char exec_file_path[PATH_MAX];
+            if (exe_module->GetFileSpec().GetPath(exec_file_path, sizeof(exec_file_path)))
+            {
+                launch_args.InsertArgumentAtIndex(0, exec_file_path);
+            }
+            else
+            {
+                result.AppendError("invalid executable");
+                result.SetStatus (eReturnStatusFailed);
+                return false;
+            }
+        }
+
         Args environment;
         
         process->GetEnvironmentAsArgs (environment);
@@ -189,48 +207,83 @@
         
         if (process->GetDisableASLR())
             launch_flags |= eLaunchFlagDisableASLR;
+    
+        const char **inferior_argv = launch_args.GetArgumentCount() ? launch_args.GetConstArgumentVector() : NULL;
+        const char **inferior_envp = environment.GetArgumentCount() ? environment.GetConstArgumentVector() : NULL;
 
-        const char *archname = exe_module->GetArchitecture().AsCString();
+        Error error;
 
-        const char * stdin_path = NULL;
-        const char * stdout_path = NULL;
-        const char * stderr_path = NULL;
-
-        // Were any standard input/output/error paths given on the command line?
-        if (m_options.stdin_path.empty() &&
-            m_options.stdout_path.empty() &&
-            m_options.stderr_path.empty())
+        if (m_options.in_new_tty)
         {
-            // No standard file handles were given on the command line, check
-            // with the process object in case they were give using "set settings"
-            stdin_path = process->GetStandardInputPath();
-            stdout_path = process->GetStandardOutputPath(); 
-            stderr_path = process->GetStandardErrorPath(); 
+        
+            lldb::pid_t terminal_pid = Host::LaunchInNewTerminal (inferior_argv,
+                                                                  inferior_envp,
+                                                                  &exe_module->GetArchitecture(),
+                                                                  true,
+                                                                  process->GetDisableASLR());
+            
+            // Let the app get launched and stopped...
+            const char *process_name = exe_module->GetFileSpec().GetFilename().AsCString("<invalid>");
+
+            if (terminal_pid == LLDB_INVALID_PROCESS_ID)
+            {
+                error.SetErrorStringWithFormat ("failed to launch '%s' in new terminal", process_name);
+            }
+            else
+            {
+                for (int i=0; i<20; i++)
+                {
+                    usleep (250000);
+                    error = process->Attach (process_name, false);
+                    if (error.Success())
+                        break;
+                }
+            }
         }
         else
         {
-            stdin_path = m_options.stdin_path.empty()  ? NULL : m_options.stdin_path.c_str();
-            stdout_path = m_options.stdout_path.empty() ? NULL : m_options.stdout_path.c_str();
-            stderr_path = m_options.stderr_path.empty() ? NULL : m_options.stderr_path.c_str();
+            const char * stdin_path = NULL;
+            const char * stdout_path = NULL;
+            const char * stderr_path = NULL;
+
+            // Were any standard input/output/error paths given on the command line?
+            if (m_options.stdin_path.empty() &&
+                m_options.stdout_path.empty() &&
+                m_options.stderr_path.empty())
+            {
+                // No standard file handles were given on the command line, check
+                // with the process object in case they were give using "set settings"
+                stdin_path = process->GetStandardInputPath();
+                stdout_path = process->GetStandardOutputPath(); 
+                stderr_path = process->GetStandardErrorPath(); 
+            }
+            else
+            {
+                stdin_path = m_options.stdin_path.empty()  ? NULL : m_options.stdin_path.c_str();
+                stdout_path = m_options.stdout_path.empty() ? NULL : m_options.stdout_path.c_str();
+                stderr_path = m_options.stderr_path.empty() ? NULL : m_options.stderr_path.c_str();
+            }
+
+            if (stdin_path == NULL)
+                stdin_path = "/dev/null";
+            if (stdout_path == NULL)
+                stdout_path = "/dev/null";
+            if (stderr_path == NULL)
+                stderr_path = "/dev/null";
+
+            error = process->Launch (inferior_argv,
+                                     inferior_envp,
+                                     launch_flags,
+                                     stdin_path,
+                                     stdout_path,
+                                     stderr_path);
         }
-
-        if (stdin_path == NULL)
-            stdin_path = "/dev/null";
-        if (stdout_path == NULL)
-            stdout_path = "/dev/null";
-        if (stderr_path == NULL)
-            stderr_path = "/dev/null";
-
-        Error error (process->Launch (launch_args.GetArgumentCount() ? launch_args.GetConstArgumentVector() : NULL,
-                                      environment.GetArgumentCount() ? environment.GetConstArgumentVector() : NULL,
-                                      launch_flags,
-                                      stdin_path,
-                                      stdout_path,
-                                      stderr_path));
                      
         if (error.Success())
         {
-            result.AppendMessageWithFormat ("Launching '%s'  (%s)\n", filename, archname);
+            const char *archname = exe_module->GetArchitecture().AsCString();
+
+            result.AppendMessageWithFormat ("Process %i launched: '%s' (%s)\n", process->GetID(), filename, archname);
             result.SetDidChangeProcessState (true);
             if (m_options.stop_at_entry == false)
             {
@@ -273,17 +326,23 @@
 };
 
 
+#define SET1 LLDB_OPT_SET_1
+#define SET2 LLDB_OPT_SET_2
+
 lldb::OptionDefinition
 CommandObjectProcessLaunch::CommandOptions::g_option_table[] =
 {
-{ LLDB_OPT_SET_1, false, "stop-at-entry", 's', no_argument,       NULL, 0, eArgTypeNone,        "Stop at the entry point of the program when launching a process."},
-{ LLDB_OPT_SET_1, false, "stdin",         'i', required_argument, NULL, 0, eArgTypePath,    "Redirect stdin for the process to <path>."},
-{ LLDB_OPT_SET_1, false, "stdout",        'o', required_argument, NULL, 0, eArgTypePath,    "Redirect stdout for the process to <path>."},
-{ LLDB_OPT_SET_1, false, "stderr",        'e', required_argument, NULL, 0, eArgTypePath,    "Redirect stderr for the process to <path>."},
-{ LLDB_OPT_SET_1, false, "plugin",        'p', required_argument, NULL, 0, eArgTypePlugin,  "Name of the process plugin you want to use."},
-{ 0, false, NULL, 0, 0, NULL, 0, eArgTypeNone, NULL }
+{ SET1 | SET2, false, "stop-at-entry", 's', no_argument,       NULL, 0, eArgTypeNone,    "Stop at the entry point of the program when launching a process."},
+{ SET1       , false, "stdin",         'i', required_argument, NULL, 0, eArgTypePath,    "Redirect stdin for the process to <path>."},
+{ SET1       , false, "stdout",        'o', required_argument, NULL, 0, eArgTypePath,    "Redirect stdout for the process to <path>."},
+{ SET1       , false, "stderr",        'e', required_argument, NULL, 0, eArgTypePath,    "Redirect stderr for the process to <path>."},
+{ SET1 | SET2, false, "plugin",        'p', required_argument, NULL, 0, eArgTypePlugin,  "Name of the process plugin you want to use."},
+{        SET2, false, "tty",           't', no_argument,       NULL, 0, eArgTypeNone,    "Start the process in a new terminal (tty)."},
+{ 0,           false, NULL,             0,  0,                 NULL, 0, eArgTypeNone,    NULL }
 };
 
+#undef SET1
+#undef SET2
 
 //-------------------------------------------------------------------------
 // CommandObjectProcessAttach
@@ -722,7 +781,7 @@
             Error error(process->Resume());
             if (error.Success())
             {
-                result.AppendMessageWithFormat ("Resuming process %i\n", process->GetID());
+                result.AppendMessageWithFormat ("Process %i resuming\n", process->GetID());
                 if (synchronous_execution)
                 {
                     state = process->WaitForProcessToStop (NULL);
diff --git a/source/Commands/CommandObjectThread.cpp b/source/Commands/CommandObjectThread.cpp
index ece29d3..01708a4 100644
--- a/source/Commands/CommandObjectThread.cpp
+++ b/source/Commands/CommandObjectThread.cpp
@@ -924,7 +924,7 @@
             Error error (process->Resume());
             if (error.Success())
             {
-                result.AppendMessageWithFormat ("Resuming process %i\n", process->GetID());
+                result.AppendMessageWithFormat ("Process %i resuming\n", process->GetID());
                 if (synchronous_execution)
                 {
                     state = process->WaitForProcessToStop (NULL);
@@ -1223,7 +1223,7 @@
             Error error (process->Resume ());
             if (error.Success())
             {
-                result.AppendMessageWithFormat ("Resuming process %i\n", process->GetID());
+                result.AppendMessageWithFormat ("Process %i resuming\n", process->GetID());
                 if (synchronous_execution)
                 {
                     StateType state = process->WaitForProcessToStop (NULL);
diff --git a/source/Core/State.cpp b/source/Core/State.cpp
index 741df1f..a68ac73 100644
--- a/source/Core/State.cpp
+++ b/source/Core/State.cpp
@@ -22,17 +22,17 @@
 {
     switch (state)
     {
-    case eStateInvalid:     return "Invalid";
-    case eStateUnloaded:    return "Unloaded";
-    case eStateAttaching:   return "Attaching";
-    case eStateLaunching:   return "Launching";
-    case eStateStopped:     return "Stopped";
-    case eStateRunning:     return "Running";
-    case eStateStepping:    return "Stepping";
-    case eStateCrashed:     return "Crashed";
-    case eStateDetached:    return "Detached";
-    case eStateExited:      return "Exited";
-    case eStateSuspended:   return "Suspended";
+    case eStateInvalid:     return "invalid";
+    case eStateUnloaded:    return "unloaded";
+    case eStateAttaching:   return "attaching";
+    case eStateLaunching:   return "launching";
+    case eStateStopped:     return "stopped";
+    case eStateRunning:     return "running";
+    case eStateStepping:    return "stepping";
+    case eStateCrashed:     return "crashed";
+    case eStateDetached:    return "detached";
+    case eStateExited:      return "exited";
+    case eStateSuspended:   return "suspended";
     }
     static char unknown_state_string[64];
     snprintf(unknown_state_string, sizeof (unknown_state_string), "StateType = %i", state);
diff --git a/source/Host/macosx/Host.mm b/source/Host/macosx/Host.mm
index 298aec4..c7c6e49 100644
--- a/source/Host/macosx/Host.mm
+++ b/source/Host/macosx/Host.mm
@@ -220,7 +220,7 @@
             command_file.Printf("\"%s\" ", argv[i]);
         }
     }
-    command_file.EOL();
+    command_file.PutCString("\necho Process exited with status $?\n");
     command_file.Close();
     if (::chmod (temp_file_path, S_IRWXU | S_IRWXG) != 0)
         return LLDB_INVALID_PROCESS_ID;
diff --git a/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp b/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
index 3da1d59..4b45bd4 100644
--- a/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
+++ b/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
@@ -366,7 +366,6 @@
     return error;
 }
 
-//#define LAUNCH_WITH_LAUNCH_SERVICES 1
 //----------------------------------------------------------------------
 // Process Control
 //----------------------------------------------------------------------
@@ -383,30 +382,6 @@
 )
 {
     Error error;
-#if defined (LAUNCH_WITH_LAUNCH_SERVICES)
-    ArchSpec inferior_arch(module->GetArchitecture());
-
-    //FileSpec app_file_spec (argv[0]);
-    pid_t pid = Host::LaunchInNewTerminal (argv,
-                                           envp,
-                                           &inferior_arch,
-                                           true, // stop at entry
-                                           (launch_flags & eLaunchFlagDisableASLR) != 0);
-    
-    // Let the app get launched and stopped...
-    sleep (1);
-
-    if (pid != LLDB_INVALID_PROCESS_ID)
-    {
-        FileSpec program(argv[0]);
-        error = DoAttachToProcessWithName (program.GetFilename().AsCString(), false);
-        //error = DoAttachToProcessWithID (pid);
-    }
-    else
-    {
-        error.SetErrorString("Host::LaunchApplication(() failed to launch process");
-    }
-#else
     //  ::LogSetBitMask (GDBR_LOG_DEFAULT);
     //  ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
     //  ::LogSetLogFile ("/dev/stdout");
@@ -522,7 +497,6 @@
         SetID(LLDB_INVALID_PROCESS_ID);
         error.SetErrorStringWithFormat("Failed to get object file from '%s' for arch %s.\n", module->GetFileSpec().GetFilename().AsCString(), module->GetArchitecture().AsCString());
     }
-#endif
     return error;
 
 }
@@ -646,13 +620,9 @@
 void
 ProcessGDBRemote::DidLaunch ()
 {
-#if defined (LAUNCH_WITH_LAUNCH_SERVICES)
-    DidAttach ();
-#else
     DidLaunchOrAttach ();
     if (m_dynamic_loader_ap.get())
         m_dynamic_loader_ap->DidLaunch();
-#endif
 }
 
 Error
@@ -795,9 +765,10 @@
             {
                 StreamString packet;
                 
-                packet.PutCString("vAttach");
                 if (wait_for_launch)
-                    packet.PutCString("Wait");
+                    packet.PutCString("vAttachWait");
+                else
+                    packet.PutCString("vAttachName");
                 packet.PutChar(';');
                 packet.PutBytesAsRawHex8(process_name, strlen(process_name), eByteOrderHost, eByteOrderHost);
                 StringExtractorGDBRemote response;
@@ -835,7 +806,11 @@
     if (pid == LLDB_INVALID_PROCESS_ID)
     {
         KillDebugserverProcess();
+        
+        if (error.Success())
+            error.SetErrorStringWithFormat("unable to attach to process named '%s'", process_name);
     }
+    
     return error;
 }
 
diff --git a/source/Target/Process.cpp b/source/Target/Process.cpp
index 7c9a841..aea8255 100644
--- a/source/Target/Process.cpp
+++ b/source/Target/Process.cpp
@@ -1109,6 +1109,12 @@
 Process::CompleteAttach ()
 {
     Error error;
+
+    if (GetID() == LLDB_INVALID_PROCESS_ID)
+    {
+        error.SetErrorString("no process");
+    }
+
     EventSP event_sp;
     StateType state = WaitForProcessStopPrivate(NULL, event_sp);
     if (state == eStateStopped || state == eStateCrashed)
@@ -1205,7 +1211,7 @@
     if (!wait_for_launch)
     {
         ArchSpec attach_spec = GetArchSpecForExistingProcess (process_name);
-        if (attach_spec != GetTarget().GetArchitecture())
+        if (attach_spec.IsValid() && attach_spec != GetTarget().GetArchitecture())
         {
             // Set the architecture on the target.
             GetTarget().SetArchitecture(attach_spec);
diff --git a/tools/debugserver/debugserver.xcodeproj/project.pbxproj b/tools/debugserver/debugserver.xcodeproj/project.pbxproj
index 6c5d973..9cbe29e 100644
--- a/tools/debugserver/debugserver.xcodeproj/project.pbxproj
+++ b/tools/debugserver/debugserver.xcodeproj/project.pbxproj
@@ -369,6 +369,7 @@
 			isa = PBXProject;
 			buildConfigurationList = 1DEB914E08733D8E0010E9CD /* Build configuration list for PBXProject "debugserver" */;
 			compatibilityVersion = "Xcode 3.1";
+			developmentRegion = English;
 			hasScannedForEncodings = 1;
 			knownRegions = (
 				English,
diff --git a/tools/debugserver/source/DNB.cpp b/tools/debugserver/source/DNB.cpp
index ce7670c..948125b 100644
--- a/tools/debugserver/source/DNB.cpp
+++ b/tools/debugserver/source/DNB.cpp
@@ -433,9 +433,12 @@
 }
 
 nub_process_t
-DNBProcessAttachWait (const char *waitfor_process_name, nub_launch_flavor_t launch_flavor,
-                      struct timespec *timeout_abstime, useconds_t waitfor_interval,
-                      char *err_str, size_t err_len,
+DNBProcessAttachWait (const char *waitfor_process_name, 
+                      nub_launch_flavor_t launch_flavor,
+                      struct timespec *timeout_abstime, 
+                      useconds_t waitfor_interval,
+                      char *err_str, 
+                      size_t err_len,
                       DNBShouldCancelCallback should_cancel_callback,
                       void *callback_data)
 {
diff --git a/tools/debugserver/source/RNBRemote.cpp b/tools/debugserver/source/RNBRemote.cpp
index 986cb4f..f8dab01 100644
--- a/tools/debugserver/source/RNBRemote.cpp
+++ b/tools/debugserver/source/RNBRemote.cpp
@@ -138,6 +138,7 @@
     t.push_back (Packet (thread_alive_p,                &RNBRemote::HandlePacket_T,             NULL, "T", "Is thread alive"));
     t.push_back (Packet (vattach,                       &RNBRemote::HandlePacket_v,             NULL, "vAttach", "Attach to a new process"));
     t.push_back (Packet (vattachwait,                   &RNBRemote::HandlePacket_v,             NULL, "vAttachWait", "Wait for a process to start up then attach to it"));
+    t.push_back (Packet (vattachname,                   &RNBRemote::HandlePacket_v,             NULL, "vAttachName", "Attach to an existing process by name"));
     t.push_back (Packet (vcont_list_actions,            &RNBRemote::HandlePacket_v,             NULL, "vCont;", "Verbose resume with thread actions"));
     t.push_back (Packet (vcont_list_actions,            &RNBRemote::HandlePacket_v,             NULL, "vCont?", "List valid continue-with-thread-actions actions"));
     // The X packet doesn't currently work. If/when it does, remove the line above and uncomment out the line below
@@ -2551,6 +2552,31 @@
             attach_pid = DNBProcessAttachWait(attach_name.c_str (), m_ctx.LaunchFlavor(), NULL, 1000, err_str, sizeof(err_str), RNBRemoteShouldCancelCallback);
 
         }
+        if (strstr (p, "vAttachName;") == p)
+        {
+            p += strlen("vAttachName;");
+            std::string attach_name;
+            while (*p != '\0')
+            {
+                char smallbuf[3];
+                smallbuf[0] = *p;
+                smallbuf[1] = *(p + 1);
+                smallbuf[2] = '\0';
+
+                errno = 0;
+                int ch = strtoul (smallbuf, NULL, 16);
+                if (errno != 0 && ch == 0)
+                {
+                    return HandlePacket_ILLFORMED ("non-hex char in arg on 'vAttachWait' pkt");
+                }
+
+                attach_name.push_back(ch);
+                p += 2;
+            }
+
+            attach_pid = DNBProcessAttachByName (attach_name.c_str(), NULL, err_str, sizeof(err_str));
+
+        }
         else if (strstr (p, "vAttach;") == p)
         {
             p += strlen("vAttach;");
diff --git a/tools/debugserver/source/RNBRemote.h b/tools/debugserver/source/RNBRemote.h
index af9ce87..30ab7e6 100644
--- a/tools/debugserver/source/RNBRemote.h
+++ b/tools/debugserver/source/RNBRemote.h
@@ -61,8 +61,9 @@
         single_step_with_sig,           // 'S'
         search_mem_backwards,           // 't'
         thread_alive_p,                 // 'T'
-        vattach,                        // 'vAttach'
-        vattachwait,                    // 'vAttachWait'
+        vattach,                        // 'vAttach;pid'
+        vattachwait,                    // 'vAttachWait:XX...' where XX is one or more hex encoded process name ASCII bytes
+        vattachname,                    // 'vAttachName:XX...' where XX is one or more hex encoded process name ASCII bytes
         vcont,                          // 'vCont'
         vcont_list_actions,             // 'vCont?'
         write_data_to_memory,           // 'X'