Merge "adb: Add "unauthorized" connection state"
diff --git a/adb/adb.c b/adb/adb.c
index 744e847..a3cd281 100644
--- a/adb/adb.c
+++ b/adb/adb.c
@@ -1021,6 +1021,7 @@
     /* message since the pipe handles must be inheritable, we use a     */
     /* security attribute                                               */
     HANDLE                pipe_read, pipe_write;
+    HANDLE                stdout_handle, stderr_handle;
     SECURITY_ATTRIBUTES   sa;
     STARTUPINFO           startup;
     PROCESS_INFORMATION   pinfo;
@@ -1040,6 +1041,26 @@
 
     SetHandleInformation( pipe_read, HANDLE_FLAG_INHERIT, 0 );
 
+    /* Some programs want to launch an adb command and collect its output by
+     * calling CreateProcess with inheritable stdout/stderr handles, then
+     * using read() to get its output. When this happens, the stdout/stderr
+     * handles passed to the adb client process will also be inheritable.
+     * When starting the adb server here, care must be taken to reset them
+     * to non-inheritable.
+     * Otherwise, something bad happens: even if the adb command completes,
+     * the calling process is stuck while read()-ing from the stdout/stderr
+     * descriptors, because they're connected to corresponding handles in the
+     * adb server process (even if the latter never uses/writes to them).
+     */
+    stdout_handle = GetStdHandle( STD_OUTPUT_HANDLE );
+    stderr_handle = GetStdHandle( STD_ERROR_HANDLE );
+    if (stdout_handle != INVALID_HANDLE_VALUE) {
+        SetHandleInformation( stdout_handle, HANDLE_FLAG_INHERIT, 0 );
+    }
+    if (stderr_handle != INVALID_HANDLE_VALUE) {
+        SetHandleInformation( stderr_handle, HANDLE_FLAG_INHERIT, 0 );
+    }
+
     ZeroMemory( &startup, sizeof(startup) );
     startup.cb = sizeof(startup);
     startup.hStdInput  = GetStdHandle( STD_INPUT_HANDLE );
diff --git a/fastboot/engine.c b/fastboot/engine.c
index 7a55260..8d46991 100644
--- a/fastboot/engine.c
+++ b/fastboot/engine.c
@@ -29,6 +29,7 @@
 #include "fastboot.h"
 #include "make_ext4fs.h"
 
+#include <errno.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdarg.h>
@@ -45,8 +46,6 @@
 #include <sys/mman.h>
 #endif
 
-extern struct fs_info info;
-
 #define ARRAY_SIZE(x)           (sizeof(x)/sizeof(x[0]))
 
 double now()
@@ -302,10 +301,7 @@
 #else
     fd = fileno(tmpfile());
 #endif
-    /* reset ext4fs info so we can be called multiple times */
-    reset_ext4fs_info();
-    info.len = image->partition_size;
-    make_ext4fs_internal(fd, NULL, NULL, NULL, 0, 1, 0, 0, 0, NULL);
+    make_ext4fs_sparse_fd(fd, image->partition_size, NULL, NULL);
 
     fstat(fd, &st);
     image->image_size = st.st_size;
diff --git a/init/property_service.c b/init/property_service.c
index 61dd86f..5780001 100755
--- a/init/property_service.c
+++ b/init/property_service.c
@@ -123,7 +123,7 @@
         /* dev is a tmpfs that we can use to carve a shared workspace
          * out of, so let's do that...
          */
-    fd = open("/dev/__properties__", O_RDWR | O_CREAT | O_NOFOLLOW, 0600);
+    fd = open(PROP_FILENAME, O_RDWR | O_CREAT | O_NOFOLLOW, 0644);
     if (fd < 0)
         return -1;
 
@@ -136,12 +136,10 @@
 
     close(fd);
 
-    fd = open("/dev/__properties__", O_RDONLY | O_NOFOLLOW);
+    fd = open(PROP_FILENAME, O_RDONLY | O_NOFOLLOW);
     if (fd < 0)
         return -1;
 
-    unlink("/dev/__properties__");
-
     w->data = data;
     w->size = size;
     w->fd = fd;
diff --git a/logwrapper/include/logwrap/logwrap.h b/logwrapper/include/logwrap/logwrap.h
index 722dda2..6593f3c 100644
--- a/logwrapper/include/logwrap/logwrap.h
+++ b/logwrapper/include/logwrap/logwrap.h
@@ -18,6 +18,8 @@
 #ifndef __LIBS_LOGWRAP_H
 #define __LIBS_LOGWRAP_H
 
+#include <stdbool.h>
+
 __BEGIN_DECLS
 
 /*
@@ -36,13 +38,17 @@
  *           NULL-terminated
  *   status: the equivalent child status as populated by wait(status). This
  *           value is only valid when logwrap successfully completes
+ *   ignore_int_quit: set to true if you want to completely ignore SIGINT and
+ *           SIGQUIT while logwrap is running. This may force the end-user to
+ *           send a signal twice to signal the caller (once for the child, and
+ *           once for the caller)
  *
  * Return value:
  *   0 when logwrap successfully run the child process and captured its status
  *   -1 when an internal error occurred
  *
  */
-int logwrap(int argc, char* argv[], int *status);
+int logwrap(int argc, char* argv[], int *status, bool ignore_int_quit);
 
 __END_DECLS
 
diff --git a/logwrapper/logwrap.c b/logwrapper/logwrap.c
index c2b36be..f6a96e0 100644
--- a/logwrapper/logwrap.c
+++ b/logwrapper/logwrap.c
@@ -16,7 +16,7 @@
 
 #include <string.h>
 #include <sys/types.h>
-#include <sys/signalfd.h>
+#include <sys/socket.h>
 #include <signal.h>
 #include <poll.h>
 #include <sys/wait.h>
@@ -26,6 +26,7 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <libgen.h>
+#include <stdbool.h>
 
 #include <logwrap/logwrap.h>
 #include "private/android_filesystem_config.h"
@@ -33,83 +34,111 @@
 
 #define ARRAY_SIZE(x)	(sizeof(x) / sizeof(*(x)))
 
-static int fatal(const char *msg) {
-    fprintf(stderr, "%s", msg);
-    ALOG(LOG_ERROR, "logwrapper", "%s", msg);
-    return -1;
-}
+static int signal_fd_write;
+
+#define ERROR(fmt, args...)                                                   \
+do {                                                                          \
+    fprintf(stderr, fmt, ## args);                                            \
+    ALOG(LOG_ERROR, "logwrapper", fmt, ## args);                              \
+} while(0)
+
+#define FATAL_CHILD(fmt, args...)                                             \
+do {                                                                          \
+    ERROR(fmt, ## args);                                                      \
+    _exit(-1);                                                                \
+} while(0)
 
 static int parent(const char *tag, int parent_read, int signal_fd, pid_t pid,
         int *chld_sts) {
-    int status;
+    int status = 0;
     char buffer[4096];
     struct pollfd poll_fds[] = {
         [0] = {
-            .fd = parent_read,
-            .events = POLLIN,
-        },
-        [1] = {
             .fd = signal_fd,
             .events = POLLIN,
         },
+        [1] = {
+            .fd = parent_read,
+            .events = POLLIN,
+        },
     };
+    int rc = 0;
+    sigset_t chldset;
 
     int a = 0;  // start index of unprocessed data
     int b = 0;  // end index of unprocessed data
     int sz;
+    bool remote_hung = false;
+    bool found_child = false;
 
     char *btag = basename(tag);
     if (!btag) btag = (char*) tag;
 
-    while (1) {
-        if (poll(poll_fds, ARRAY_SIZE(poll_fds), -1) <= 0) {
-            return fatal("poll failed\n");
+    sigemptyset(&chldset);
+    sigaddset(&chldset, SIGCHLD);
+    pthread_sigmask(SIG_UNBLOCK, &chldset, NULL);
+
+    while (!found_child) {
+        if (poll(poll_fds, remote_hung ? 1 : 2, -1) < 0) {
+            if (errno == EINTR)
+                continue;
+            ERROR("poll failed\n");
+            rc = -1;
+            goto err_poll;
         }
 
-        if (poll_fds[0].revents & POLLIN) {
-            sz = read(parent_read, &buffer[b], sizeof(buffer) - 1 - b);
+        if (!remote_hung) {
+            if (poll_fds[1].revents & POLLIN) {
+                sz = read(parent_read, &buffer[b], sizeof(buffer) - 1 - b);
 
-            sz += b;
-            // Log one line at a time
-            for (b = 0; b < sz; b++) {
-                if (buffer[b] == '\r') {
-                    buffer[b] = '\0';
-                } else if (buffer[b] == '\n') {
+                sz += b;
+                // Log one line at a time
+                for (b = 0; b < sz; b++) {
+                    if (buffer[b] == '\r') {
+                        buffer[b] = '\0';
+                    } else if (buffer[b] == '\n') {
+                        buffer[b] = '\0';
+                        ALOG(LOG_INFO, btag, "%s", &buffer[a]);
+                        a = b + 1;
+                    }
+                }
+
+                if (a == 0 && b == sizeof(buffer) - 1) {
+                    // buffer is full, flush
                     buffer[b] = '\0';
                     ALOG(LOG_INFO, btag, "%s", &buffer[a]);
-                    a = b + 1;
+                    b = 0;
+                } else if (a != b) {
+                    // Keep left-overs
+                    b -= a;
+                    memmove(buffer, &buffer[a], b);
+                    a = 0;
+                } else {
+                    a = 0;
+                    b = 0;
                 }
             }
 
-            if (a == 0 && b == sizeof(buffer) - 1) {
-                // buffer is full, flush
-                buffer[b] = '\0';
-                ALOG(LOG_INFO, btag, "%s", &buffer[a]);
-                b = 0;
-            } else if (a != b) {
-                // Keep left-overs
-                b -= a;
-                memmove(buffer, &buffer[a], b);
-                a = 0;
-            } else {
-                a = 0;
-                b = 0;
+            if (poll_fds[1].revents & POLLHUP) {
+                remote_hung = true;
             }
         }
 
-        if (poll_fds[1].revents & POLLIN) {
-            struct signalfd_siginfo sfd_info;
-            pid_t wpid;
+        if (poll_fds[0].revents & POLLIN) {
+            char tmp[32];
+            int ret;
 
-            // Clear all pending signals before reading the child's status
-            while (read(signal_fd, &sfd_info, sizeof(sfd_info)) > 0) {
-                if ((pid_t)sfd_info.ssi_pid != pid)
-                    ALOG(LOG_WARN, "logwrapper", "cleared SIGCHLD for pid %u\n",
-                            sfd_info.ssi_pid);
+            read(signal_fd, tmp, sizeof(tmp));
+            while (!found_child) {
+                do {
+                    ret = waitpid(-1, &status, WNOHANG);
+                } while (ret < 0 && errno == EINTR);
+
+                if (ret <= 0)
+                    break;
+
+                found_child = (pid == ret);
             }
-            wpid = waitpid(pid, &status, WNOHANG);
-            if (wpid > 0)
-                break;
         }
     }
 
@@ -121,19 +150,20 @@
 
     if (WIFEXITED(status)) {
         if (WEXITSTATUS(status))
-            ALOG(LOG_INFO, "logwrapper", "%s terminated by exit(%d)", tag,
+            ALOG(LOG_INFO, "logwrapper", "%s terminated by exit(%d)", btag,
                     WEXITSTATUS(status));
     } else if (WIFSIGNALED(status)) {
-        ALOG(LOG_INFO, "logwrapper", "%s terminated by signal %d", tag,
+        ALOG(LOG_INFO, "logwrapper", "%s terminated by signal %d", btag,
                 WTERMSIG(status));
     } else if (WIFSTOPPED(status)) {
-        ALOG(LOG_INFO, "logwrapper", "%s stopped by signal %d", tag,
+        ALOG(LOG_INFO, "logwrapper", "%s stopped by signal %d", btag,
                 WSTOPSIG(status));
     }
     if (chld_sts != NULL)
         *chld_sts = status;
 
-    return 0;
+err_poll:
+    return rc;
 }
 
 static void child(int argc, char* argv[]) {
@@ -143,46 +173,62 @@
     argv_child[argc] = NULL;
 
     if (execvp(argv_child[0], argv_child)) {
-        ALOG(LOG_ERROR, "logwrapper",
-            "executing %s failed: %s\n", argv_child[0], strerror(errno));
-        exit(-1);
+        FATAL_CHILD("executing %s failed: %s\n", argv_child[0],
+                strerror(errno));
     }
 }
 
-int logwrap(int argc, char* argv[], int *status) {
-    pid_t pid;
+void sigchld_handler(int sig) {
+    write(signal_fd_write, &sig, 1);
+}
 
+int logwrap(int argc, char* argv[], int *status, bool ignore_int_quit) {
+    pid_t pid;
     int parent_ptty;
     int child_ptty;
     char *child_devname = NULL;
-    sigset_t chldset;
+    struct sigaction chldact;
+    struct sigaction oldchldact;
+    struct sigaction intact;
+    struct sigaction quitact;
+    sigset_t blockset;
+    sigset_t oldset;
+    int sockets[2];
+    int rc = 0;
 
     /* Use ptty instead of socketpair so that STDOUT is not buffered */
     parent_ptty = open("/dev/ptmx", O_RDWR);
     if (parent_ptty < 0) {
-        return fatal("Cannot create parent ptty\n");
+        ERROR("Cannot create parent ptty\n");
+        rc = -1;
+        goto err_open;
     }
 
     if (grantpt(parent_ptty) || unlockpt(parent_ptty) ||
             ((child_devname = (char*)ptsname(parent_ptty)) == 0)) {
-        return fatal("Problem with /dev/ptmx\n");
+        ERROR("Problem with /dev/ptmx\n");
+        rc = -1;
+        goto err_ptty;
     }
 
-    sigemptyset(&chldset);
-    sigaddset(&chldset, SIGCHLD);
-    sigprocmask(SIG_BLOCK, &chldset, NULL);
+    sigemptyset(&blockset);
+    sigaddset(&blockset, SIGINT);
+    sigaddset(&blockset, SIGQUIT);
+    sigaddset(&blockset, SIGCHLD);
+    pthread_sigmask(SIG_BLOCK, &blockset, &oldset);
 
     pid = fork();
     if (pid < 0) {
-        close(parent_ptty);
-        sigprocmask(SIG_UNBLOCK, &chldset, NULL);
-        return fatal("Failed to fork\n");
+        ERROR("Failed to fork\n");
+        rc = -1;
+        goto err_fork;
     } else if (pid == 0) {
+        pthread_sigmask(SIG_SETMASK, &oldset, NULL);
         close(parent_ptty);
-        sigprocmask(SIG_UNBLOCK, &chldset, NULL);
+
         child_ptty = open(child_devname, O_RDWR);
         if (child_ptty < 0) {
-            return fatal("Problem with child ptty\n");
+            FATAL_CHILD("Problem with child ptty\n");
         }
 
         // redirect stdout and stderr
@@ -190,36 +236,59 @@
         dup2(child_ptty, 2);
         close(child_ptty);
 
-        child(argc - 1, &argv[1]);
-        return fatal("This should never happen\n");
-
+        child(argc, argv);
     } else {
-        int rc;
-        int fd;
+        struct sigaction ignact;
 
-        fd = signalfd(-1, &chldset, SFD_NONBLOCK);
-        if (fd == -1) {
-            char msg[40];
+        memset(&chldact, 0, sizeof(chldact));
+        chldact.sa_handler = sigchld_handler;
+        chldact.sa_flags = SA_NOCLDSTOP;
 
-            snprintf(msg, sizeof(msg), "signalfd failed: %d\n", errno);
-
-            close(parent_ptty);
-            sigprocmask(SIG_UNBLOCK, &chldset, NULL);
-            return fatal(msg);
+        sigaction(SIGCHLD, &chldact, &oldchldact);
+        if ((!(oldchldact.sa_flags & SA_SIGINFO) &&
+                oldchldact.sa_handler != SIG_DFL &&
+                oldchldact.sa_handler != SIG_IGN) ||
+                ((oldchldact.sa_flags & SA_SIGINFO) &&
+                oldchldact.sa_sigaction != NULL)) {
+            ALOG(LOG_WARN, "logwrapper", "logwrap replaced the SIGCHLD "
+                    "handler and might cause interaction issues");
         }
 
-        // switch user and group to "log"
-        // this may fail if we are not root,
-        // but in that case switching user/group is unnecessary
-        setgid(AID_LOG);
-        setuid(AID_LOG);
+        if (ignore_int_quit) {
+            memset(&ignact, 0, sizeof(ignact));
+            ignact.sa_handler = SIG_IGN;
+            sigaction(SIGINT, &ignact, &intact);
+            sigaction(SIGQUIT, &ignact, &quitact);
+        }
 
-        rc = parent(argv[1], parent_ptty, fd, pid, status);
-        close(parent_ptty);
-        close(fd);
+        rc = socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
+        if (rc == -1) {
+            ERROR("socketpair failed: %s\n", strerror(errno));
+            goto err_socketpair;
+        }
 
-        sigprocmask(SIG_UNBLOCK, &chldset, NULL);
+        fcntl(sockets[0], F_SETFD, FD_CLOEXEC);
+        fcntl(sockets[0], F_SETFL, O_NONBLOCK);
+        fcntl(sockets[1], F_SETFD, FD_CLOEXEC);
+        fcntl(sockets[1], F_SETFL, O_NONBLOCK);
 
-        return rc;
+        signal_fd_write = sockets[0];
+
+        rc = parent(argv[0], parent_ptty, sockets[1], pid, status);
     }
+
+    close(sockets[0]);
+    close(sockets[1]);
+err_socketpair:
+    if (ignore_int_quit) {
+        sigaction(SIGINT, &intact, NULL);
+        sigaction(SIGQUIT, &quitact, NULL);
+    }
+    sigaction(SIGCHLD, &oldchldact, NULL);
+err_fork:
+    pthread_sigmask(SIG_SETMASK, &oldset, NULL);
+err_ptty:
+    close(parent_ptty);
+err_open:
+    return rc;
 }
diff --git a/logwrapper/logwrapper.c b/logwrapper/logwrapper.c
index 4f1bff9..563fcee 100644
--- a/logwrapper/logwrapper.c
+++ b/logwrapper/logwrapper.c
@@ -59,7 +59,7 @@
         usage();
     }
 
-    rc = logwrap(argc, argv, &status);
+    rc = logwrap(argc - 1, &argv[1], &status, true);
     if (!rc) {
         if (WIFEXITED(status))
             rc = WEXITSTATUS(status);
diff --git a/toolbox/renice.c b/toolbox/renice.c
index 978b329..9dfeb51 100644
--- a/toolbox/renice.c
+++ b/toolbox/renice.c
@@ -35,11 +35,12 @@
 #include <sys/time.h>
 #include <sys/resource.h>
 #include <sched.h>
+#include <getopt.h>
 
 static void
 usage(const char *s)
 {
-    fprintf(stderr, "USAGE: %s [[-r] priority pids ...] [-g pid]\n", s);
+    fprintf(stderr, "USAGE: %s [[-r] [-t TYPE] priority pids ...] [-g pid]\n", s);
     exit(EXIT_FAILURE);
 }
 
@@ -74,32 +75,49 @@
            sched_get_priority_min(sched), sched_get_priority_max(sched));
 }
 
+int get_sched(char *str)
+{
+    if (strcasecmp(str, "RR") == 0)
+        return SCHED_RR;
+    else if (strcasecmp(str, "FIFO") == 0)
+        return SCHED_FIFO;
+    else if (strcasecmp(str, "NORMAL") == 0)
+        return SCHED_OTHER;
+    else if (strcasecmp(str, "OTHER") == 0)
+        return SCHED_OTHER;
+    return SCHED_RR;
+}
+
 int renice_main(int argc, char *argv[])
 {
     int prio;
     int realtime = 0;
+    int opt;
+    int sched = SCHED_RR;
     char *cmd = argv[0];
 
-    // consume command name
-    argc--;
-    argv++;
-
-    if (argc < 1)
-        usage(cmd);
-
-    if(strcmp("-r", argv[0]) == 0) {
-        // do realtime priority adjustment
-        realtime = 1;
-        argc--;
-        argv++;
-    }
-
-	if(strcmp("-g", argv[0]) == 0) {
-        if (argc < 2)
+    do {
+        opt = getopt(argc, argv, "rt:g:");
+        if (opt == -1)
+            break;
+        switch (opt) {
+        case 'r':
+            // do realtime priority adjustment
+            realtime = 1;
+            break;
+        case 't':
+            sched = get_sched(optarg);
+            break;
+        case 'g':
+            print_prio(atoi(optarg));
+            return 0;
+        default:
             usage(cmd);
-        print_prio(atoi(argv[1]));
-        return 0;
-    }
+        }
+    } while (1);
+
+    argc -= optind;
+    argv += optind;
 
     if (argc < 1)
         usage(cmd);
@@ -122,7 +140,7 @@
             struct sched_param sp = { .sched_priority = prio };
             int ret;
 
-            ret = sched_setscheduler(pid, SCHED_RR, &sp);
+            ret = sched_setscheduler(pid, sched, &sp);
             if (ret) {
                 perror("sched_set_scheduler");
                 exit(EXIT_FAILURE);
@@ -137,8 +155,6 @@
             }
         }
     }
-   
+
     return 0;
 }
-
-