Avoid leakage of file descriptors in LLDB and LLGS

Summary:
Both LLDB and LLGS are leaking file descriptors into the debugged process. This plugs the leak by
closing the unneeded descriptors. In one case I use O_CLOEXEC, which I hope is supported on
relevant platforms. I also added a regression test and plugged a fd leak in dosep.py.

Reviewers: vharron, clayborg

Subscribers: lldb-commits

Differential Revision: http://reviews.llvm.org/D7372

llvm-svn: 228130
diff --git a/lldb/source/Plugins/Process/Linux/ProcessMonitor.cpp b/lldb/source/Plugins/Process/Linux/ProcessMonitor.cpp
index 43a1942..e87e662 100644
--- a/lldb/source/Plugins/Process/Linux/ProcessMonitor.cpp
+++ b/lldb/source/Plugins/Process/Linux/ProcessMonitor.cpp
@@ -1356,6 +1356,11 @@
         if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL, 0) < 0)
             exit(ePtraceFailed);
 
+        // terminal has already dupped the tty descriptors to stdin/out/err.
+        // This closes original fd from which they were copied (and avoids
+        // leaking descriptors to the debugged process.
+        terminal.CloseSlaveFileDescriptor();
+
         // Do not inherit setgid powers.
         if (setgid(getgid()) != 0)
             exit(eSetGidFailed);
@@ -2319,7 +2324,10 @@
     if (target_fd == -1)
         return false;
 
-    return (dup2(target_fd, fd) == -1) ? false : true;
+    if (dup2(target_fd, fd) == -1)
+        return false;
+
+    return (close(target_fd) == -1) ? false : true;
 }
 
 void