Merge "Set zygote process priority to -20 to speed up VM startup time."
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 3f14f1a..c3f1a96 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -329,8 +329,6 @@
 
 void handle_packet(apacket *p, atransport *t)
 {
-    asocket *s;
-
     D("handle_packet() %c%c%c%c", ((char*) (&(p->msg.command)))[0],
             ((char*) (&(p->msg.command)))[1],
             ((char*) (&(p->msg.command)))[2],
@@ -339,7 +337,7 @@
 
     switch(p->msg.command){
     case A_SYNC:
-        if(p->msg.arg0){
+        if (p->msg.arg0){
             send_packet(p, t);
 #if ADB_HOST
             send_connect(t);
@@ -384,8 +382,8 @@
         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 == 0) {
             char *name = (char*) p->data;
             name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0;
-            s = create_local_service_socket(name, t);
-            if(s == 0) {
+            asocket* s = create_local_service_socket(name, t);
+            if (s == nullptr) {
                 send_close(0, p->msg.arg0, t);
             } else {
                 s->peer = create_remote_socket(p->msg.arg0, t);
@@ -398,7 +396,8 @@
 
     case A_OKAY: /* READY(local-id, remote-id, "") */
         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
-            if((s = find_local_socket(p->msg.arg1, 0))) {
+            asocket* s = find_local_socket(p->msg.arg1, 0);
+            if (s) {
                 if(s->peer == 0) {
                     /* On first READY message, create the connection. */
                     s->peer = create_remote_socket(p->msg.arg0, t);
@@ -422,7 +421,8 @@
 
     case A_CLSE: /* CLOSE(local-id, remote-id, "") or CLOSE(0, remote-id, "") */
         if (t->online && p->msg.arg1 != 0) {
-            if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
+            asocket* s = find_local_socket(p->msg.arg1, p->msg.arg0);
+            if (s) {
                 /* According to protocol.txt, p->msg.arg0 might be 0 to indicate
                  * a failed OPEN only. However, due to a bug in previous ADB
                  * versions, CLOSE(0, remote-id, "") was also used for normal
@@ -445,11 +445,12 @@
 
     case A_WRTE: /* WRITE(local-id, remote-id, <data>) */
         if (t->online && p->msg.arg0 != 0 && p->msg.arg1 != 0) {
-            if((s = find_local_socket(p->msg.arg1, p->msg.arg0))) {
+            asocket* s = find_local_socket(p->msg.arg1, p->msg.arg0);
+            if (s) {
                 unsigned rid = p->msg.arg0;
                 p->len = p->msg.data_length;
 
-                if(s->enqueue(s, p) == 0) {
+                if (s->enqueue(s, p) == 0) {
                     D("Enqueue the socket");
                     send_ready(s->id, rid, t);
                 }
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index 82fa19a..0d6ecb8 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -872,27 +872,26 @@
  *   we hang up.
  */
 static int adb_sideload_host(const char* fn) {
-    printf("loading: '%s'", fn);
-    fflush(stdout);
+    fprintf(stderr, "loading: '%s'...\n", fn);
 
     std::string content;
     if (!android::base::ReadFileToString(fn, &content)) {
-        printf("\n");
-        fprintf(stderr, "* cannot read '%s' *\n", fn);
+        fprintf(stderr, "failed: %s\n", strerror(errno));
         return -1;
     }
 
     const uint8_t* data = reinterpret_cast<const uint8_t*>(content.data());
     unsigned sz = content.size();
 
+    fprintf(stderr, "connecting...\n");
     std::string service =
             android::base::StringPrintf("sideload-host:%d:%d", sz, SIDELOAD_HOST_BLOCK_SIZE);
     std::string error;
     unique_fd fd(adb_connect(service, &error));
-    if (fd >= 0) {
+    if (fd < 0) {
         // Try falling back to the older sideload method.  Maybe this
         // is an older device that doesn't support sideload-host.
-        printf("\n");
+        fprintf(stderr, "falling back to older sideload method...\n");
         return adb_download_buffer("sideload", fn, data, sz, true);
     }
 
diff --git a/adb/sockets.cpp b/adb/sockets.cpp
index b2555d0..4ed1c45 100644
--- a/adb/sockets.cpp
+++ b/adb/sockets.cpp
@@ -410,7 +410,7 @@
 #endif
     int fd = service_to_fd(name, transport);
     if (fd < 0) {
-        return 0;
+        return nullptr;
     }
 
     asocket* s = create_local_socket(fd);
diff --git a/fs_mgr/fs_mgr_slotselect.c b/fs_mgr/fs_mgr_slotselect.c
index ca07b18..0f59115 100644
--- a/fs_mgr/fs_mgr_slotselect.c
+++ b/fs_mgr/fs_mgr_slotselect.c
@@ -41,7 +41,7 @@
     int n;
     int misc_fd;
     ssize_t num_read;
-    struct bootloader_message msg;
+    struct bootloader_message_ab msg;
 
     misc_fd = -1;
     for (n = 0; n < fstab->num_entries; n++) {
diff --git a/fs_mgr/fs_mgr_verity.cpp b/fs_mgr/fs_mgr_verity.cpp
index aa32600..25b023e 100644
--- a/fs_mgr/fs_mgr_verity.cpp
+++ b/fs_mgr/fs_mgr_verity.cpp
@@ -142,6 +142,18 @@
     return retval;
 }
 
+static int verify_verity_signature(const struct fec_verity_metadata& verity)
+{
+    if (verify_table(verity.signature, sizeof(verity.signature),
+            verity.table, verity.table_length) == 0 ||
+        verify_table(verity.ecc_signature, sizeof(verity.ecc_signature),
+            verity.table, verity.table_length) == 0) {
+        return 0;
+    }
+
+    return -1;
+}
+
 static int invalidate_table(char *table, size_t table_length)
 {
     size_t n = 0;
@@ -947,8 +959,7 @@
     }
 
     // verify the signature on the table
-    if (verify_table(verity.signature, sizeof(verity.signature), params.table,
-            verity.table_length) < 0) {
+    if (verify_verity_signature(verity) < 0) {
         if (params.mode == VERITY_MODE_LOGGING) {
             // the user has been warned, allow mounting without dm-verity
             retval = FS_MGR_SETUP_VERITY_SUCCESS;
diff --git a/init/devices.cpp b/init/devices.cpp
index 1410e3b..32fec52 100644
--- a/init/devices.cpp
+++ b/init/devices.cpp
@@ -257,11 +257,25 @@
     /* If the node already exists update its SELinux label to handle cases when
      * it was created with the wrong context during coldboot procedure. */
     if (mknod(path, mode, dev) && (errno == EEXIST)) {
-        if (lsetfilecon(path, secontext)) {
+
+        char* fcon = nullptr;
+        int rc = lgetfilecon(path, &fcon);
+        if (rc < 0) {
+            ERROR("Cannot get SELinux label on '%s' device (%s)\n",
+                    path, strerror(errno));
+            goto out;
+        }
+
+        bool different = strcmp(fcon, secontext) != 0;
+        freecon(fcon);
+
+        if (different && lsetfilecon(path, secontext)) {
             ERROR("Cannot set '%s' SELinux label on '%s' device (%s)\n",
                     secontext, path, strerror(errno));
         }
     }
+
+out:
     chown(path, uid, -1);
     setegid(AID_ROOT);
 
diff --git a/init/readme.txt b/init/readme.txt
index aa372eb..8130806 100644
--- a/init/readme.txt
+++ b/init/readme.txt
@@ -184,6 +184,9 @@
   Write the child's pid to the given files when it forks. Meant for
   cgroup/cpuset usage.
 
+priority <priority>
+  Scheduling priority of the service process. This value has to be in range
+  -20 to 19. Default priority is 0. Priority is set via setpriority().
 
 Triggers
 --------
diff --git a/init/service.cpp b/init/service.cpp
index 4175d05..6e68878 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -17,7 +17,9 @@
 #include "service.h"
 
 #include <fcntl.h>
+#include <sys/resource.h>
 #include <sys/stat.h>
+#include <sys/time.h>
 #include <sys/types.h>
 #include <sys/wait.h>
 #include <termios.h>
@@ -29,6 +31,7 @@
 #include <android-base/stringprintf.h>
 #include <cutils/android_reboot.h>
 #include <cutils/sockets.h>
+#include <system/thread_defs.h>
 
 #include <processgroup/processgroup.h>
 
@@ -65,7 +68,7 @@
                  const std::vector<std::string>& args)
     : name_(name), classname_(classname), flags_(0), pid_(0), time_started_(0),
       time_crashed_(0), nr_crashed_(0), uid_(0), gid_(0), seclabel_(""),
-      ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
+      ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), priority_(0), args_(args) {
     onrestart_.InitSingleTrigger("onrestart");
 }
 
@@ -74,7 +77,8 @@
                  const std::string& seclabel,  const std::vector<std::string>& args)
     : name_(name), classname_(classname), flags_(flags), pid_(0), time_started_(0),
       time_crashed_(0), nr_crashed_(0), uid_(uid), gid_(gid), supp_gids_(supp_gids),
-      seclabel_(seclabel), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), args_(args) {
+      seclabel_(seclabel), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), priority_(0),
+      args_(args) {
     onrestart_.InitSingleTrigger("onrestart");
 }
 
@@ -197,6 +201,19 @@
     return true;
 }
 
+bool Service::HandlePriority(const std::vector<std::string>& args, std::string* err) {
+    priority_ = std::stoi(args[1]);
+
+    if (priority_ < ANDROID_PRIORITY_HIGHEST || priority_ > ANDROID_PRIORITY_LOWEST) {
+        priority_ = 0;
+        *err = StringPrintf("process priority value must be range %d - %d",
+                ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
+        return false;
+    }
+
+    return true;
+}
+
 bool Service::HandleIoprio(const std::vector<std::string>& args, std::string* err) {
     ioprio_pri_ = std::stoul(args[2], 0, 8);
 
@@ -290,6 +307,7 @@
         {"disabled",    {0,     0,    &Service::HandleDisabled}},
         {"group",       {1,     NR_SVC_SUPP_GIDS + 1, &Service::HandleGroup}},
         {"ioprio",      {2,     2,    &Service::HandleIoprio}},
+        {"priority",    {1,     1,    &Service::HandlePriority}},
         {"keycodes",    {1,     kMax, &Service::HandleKeycodes}},
         {"oneshot",     {0,     0,    &Service::HandleOneshot}},
         {"onrestart",   {1,     kMax, &Service::HandleOnrestart}},
@@ -470,14 +488,28 @@
                 _exit(127);
             }
         }
+        if (priority_ != 0) {
+            if (setpriority(PRIO_PROCESS, 0, priority_) != 0) {
+                ERROR("setpriority failed: %s\n", strerror(errno));
+                _exit(127);
+            }
+        }
 
+        std::vector<std::string> expanded_args;
         std::vector<char*> strs;
-        for (const auto& s : args_) {
-            strs.push_back(const_cast<char*>(s.c_str()));
+        expanded_args.resize(args_.size());
+        strs.push_back(const_cast<char*>(args_[0].c_str()));
+        for (std::size_t i = 1; i < args_.size(); ++i) {
+            if (!expand_props(args_[i], &expanded_args[i])) {
+                ERROR("%s: cannot expand '%s'\n", args_[0].c_str(), args_[i].c_str());
+                _exit(127);
+            }
+            strs.push_back(const_cast<char*>(expanded_args[i].c_str()));
         }
         strs.push_back(nullptr);
-        if (execve(args_[0].c_str(), (char**) &strs[0], (char**) ENV) < 0) {
-            ERROR("cannot execve('%s'): %s\n", args_[0].c_str(), strerror(errno));
+
+        if (execve(strs[0], (char**) &strs[0], (char**) ENV) < 0) {
+            ERROR("cannot execve('%s'): %s\n", strs[0], strerror(errno));
         }
 
         _exit(127);
diff --git a/init/service.h b/init/service.h
index d6ce664..dc14f9a 100644
--- a/init/service.h
+++ b/init/service.h
@@ -93,6 +93,7 @@
     pid_t pid() const { return pid_; }
     uid_t uid() const { return uid_; }
     gid_t gid() const { return gid_; }
+    int priority() const { return priority_; }
     const std::vector<gid_t>& supp_gids() const { return supp_gids_; }
     const std::string& seclabel() const { return seclabel_; }
     const std::vector<int>& keycodes() const { return keycodes_; }
@@ -116,6 +117,7 @@
     bool HandleCritical(const std::vector<std::string>& args, std::string* err);
     bool HandleDisabled(const std::vector<std::string>& args, std::string* err);
     bool HandleGroup(const std::vector<std::string>& args, std::string* err);
+    bool HandlePriority(const std::vector<std::string>& args, std::string* err);
     bool HandleIoprio(const std::vector<std::string>& args, std::string* err);
     bool HandleKeycodes(const std::vector<std::string>& args, std::string* err);
     bool HandleOneshot(const std::vector<std::string>& args, std::string* err);
@@ -155,6 +157,7 @@
 
     IoSchedClass ioprio_class_;
     int ioprio_pri_;
+    int priority_;
 
     std::vector<std::string> args_;
 };
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 52f49cc..ea698c8 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -27,7 +27,6 @@
 
 #include <android-base/file.h>
 #include <android-base/strings.h>
-#include <cutils/properties.h>
 #include <cutils/sched_policy.h>
 #include <cutils/sockets.h>
 #include <log/event_tag_map.h>
@@ -281,16 +280,17 @@
     fprintf(stderr, "options include:\n"
                     "  -s              Set default filter to silent. Equivalent to filterspec '*:S'\n"
                     "  -f <file>, --file=<file>               Log to file. Default is stdout\n"
-                    "  -r <kbytes>, --rotate-kbytes=<kbytes>  Rotate log every kbytes. Requires -f\n"
-                    "                  option. Permits property expansion.\n"
-                    "  -n <count>, --rotate-count=<count>     Sets max number of rotated logs to\n"
-                    "                  <count>, default 4. Permits property expansion.\n"
+                    "  -r <kbytes>, --rotate-kbytes=<kbytes>\n"
+                    "                  Rotate log every kbytes. Requires -f option\n"
+                    "  -n <count>, --rotate-count=<count>\n"
+                    "                  Sets max number of rotated logs to <count>, default 4\n"
                     "  -v <format>, --format=<format>\n"
                     "                  Sets the log print format, where <format> is:\n"
                     "                    brief color epoch long monotonic printable process raw\n"
                     "                    tag thread threadtime time uid usec UTC year zone\n"
                     "  -D, --dividers  Print dividers between each log buffer\n"
                     "  -c, --clear     Clear (flush) the entire log and exit\n"
+                    "                  if Log to File specified, clear fileset instead\n"
                     "  -d              Dump the log and then exit (don't block)\n"
                     "  -e <expr>, --regex=<expr>\n"
                     "                  Only print lines where the log message matches <expr>\n"
@@ -318,7 +318,6 @@
                     "                  'system', 'radio', 'events', 'crash', 'default' or 'all'.\n"
                     "                  Multiple -b parameters or comma separated list of buffers are\n"
                     "                  allowed. Buffers interleaved. Default -b main,system,crash.\n"
-                    "                  Permits property expansion.\n"
                     "  -B, --binary    Output the log in binary.\n"
                     "  -S, --statistics                       Output statistics.\n"
                     "  -p, --prune     Print prune white and ~black list. Service is specified as\n"
@@ -336,11 +335,7 @@
                     "                  comes first. Improves efficiency of polling by providing\n"
                     "                  an about-to-wrap wakeup.\n");
 
-    fprintf(stderr,"\nProperty expansion where available, may need to be single quoted to prevent\n"
-                   "shell expansion:\n"
-                   "  ${key}          - Expand string with property value associated with key\n"
-                   "  ${key:-default} - Expand, if property key value clear, use default\n"
-                   "\nfilterspecs are a series of \n"
+    fprintf(stderr,"\nfilterspecs are a series of \n"
                    "  <tag>[:priority]\n\n"
                    "where <tag> is a log component tag (or * for all) and priority is:\n"
                    "  V    Verbose (default for <tag>)\n"
@@ -538,49 +533,6 @@
     return retval;
 }
 
-// Expand multiple flat property references ${<tag>:-default} or ${tag}.
-//
-// ToDo: Do we permit nesting?
-//   ${persist.logcat.something:-${ro.logcat.something:-maybesomething}}
-// For now this will result in a syntax error for caller and is acceptable.
-//
-std::string expand(const char *str)
-{
-  std::string retval(str);
-
-  // Caller has no use for ${, } or :- as literals so no use for escape
-  // character. Result expectations are a number or a string, with validity
-  // checking for both in caller. Recursive expansion or other syntax errors
-  // will result in content caller can not obviously tolerate, error must
-  // report substring if applicable, expanded and original content (if
-  // different) so that it will be clear to user what they did wrong.
-  for (size_t pos; (pos = retval.find("${")) != std::string::npos; ) {
-    size_t epos = retval.find("}", pos + 2);
-    if (epos == std::string::npos) {
-      break; // Caller will error out, showing this unexpanded.
-    }
-    size_t def = retval.find(":-", pos + 2);
-    if (def >= epos) {
-      def = std::string::npos;
-    }
-    std::string default_value("");
-    std::string key;
-    if (def == std::string::npos) {
-      key = retval.substr(pos + 2, epos - (pos + 2));
-    } else {
-      key = retval.substr(pos + 2, def - (pos + 2));
-      default_value = retval.substr(def + 2, epos - (def + 2));
-    }
-    char value[PROPERTY_VALUE_MAX];
-    property_get(key.c_str(), value, default_value.c_str());
-    // Caller will error out, syntactically empty content at this point
-    // will not be tolerated as expected.
-    retval.replace(pos, epos - pos + 1, value);
-  }
-
-  return retval;
-}
-
 } /* namespace android */
 
 
@@ -812,35 +764,23 @@
 
             case 'b': {
                 unsigned idMask = 0;
-                std::string expanded = expand(optarg);
-                std::istringstream copy(expanded);
-                std::string token;
-                // wish for strtok and ",:; \t\n\r\f" for hidden flexibility
-                while (std::getline(copy, token, ',')) { // settle for ","
-                    if (token.compare("default") == 0) {
+                while ((optarg = strtok(optarg, ",:; \t\n\r\f")) != NULL) {
+                    if (strcmp(optarg, "default") == 0) {
                         idMask |= (1 << LOG_ID_MAIN) |
                                   (1 << LOG_ID_SYSTEM) |
                                   (1 << LOG_ID_CRASH);
-                    } else if (token.compare("all") == 0) {
+                    } else if (strcmp(optarg, "all") == 0) {
                         idMask = (unsigned)-1;
                     } else {
-                        log_id_t log_id = android_name_to_log_id(token.c_str());
+                        log_id_t log_id = android_name_to_log_id(optarg);
                         const char *name = android_log_id_to_name(log_id);
 
-                        if (token.compare(name) != 0) {
-                            bool strDifferent = expanded.compare(token);
-                            if (expanded.compare(optarg)) {
-                                expanded += " expanded from ";
-                                expanded += optarg;
-                            }
-                            if (strDifferent) {
-                                expanded = token + " within " + expanded;
-                            }
-                            logcat_panic(true, "unknown buffer -b %s\n",
-                                         expanded.c_str());
+                        if (strcmp(name, optarg) != 0) {
+                            logcat_panic(true, "unknown buffer %s\n", optarg);
                         }
                         idMask |= (1 << log_id);
                     }
+                    optarg = NULL;
                 }
 
                 for (int i = LOG_ID_MIN; i < LOG_ID_MAX; ++i) {
@@ -895,36 +835,22 @@
                 g_outputFileName = optarg;
             break;
 
-            case 'r': {
-                std::string expanded = expand(optarg);
-                if (!getSizeTArg(expanded.c_str(), &g_logRotateSizeKBytes, 1)) {
-                    if (expanded.compare(optarg)) {
-                        expanded += " expanded from ";
-                        expanded += optarg;
-                    }
-                    logcat_panic(true, "Invalid parameter -r %s\n",
-                                 expanded.c_str());
+            case 'r':
+                if (!getSizeTArg(optarg, &g_logRotateSizeKBytes, 1)) {
+                    logcat_panic(true, "Invalid parameter %s to -r\n", optarg);
                 }
-            }
             break;
 
-            case 'n': {
-                std::string expanded = expand(optarg);
-                if (!getSizeTArg(expanded.c_str(), &g_maxRotatedLogs, 1)) {
-                    if (expanded.compare(optarg)) {
-                        expanded += " expanded from ";
-                        expanded += optarg;
-                    }
-                    logcat_panic(true, "Invalid parameter -n %s\n",
-                                 expanded.c_str());
+            case 'n':
+                if (!getSizeTArg(optarg, &g_maxRotatedLogs, 1)) {
+                    logcat_panic(true, "Invalid parameter %s to -n\n", optarg);
                 }
-            }
             break;
 
             case 'v':
                 err = setLogFormat (optarg);
                 if (err < 0) {
-                    logcat_panic(true, "Invalid parameter -v %s\n", optarg);
+                    logcat_panic(true, "Invalid parameter %s to -v\n", optarg);
                 }
                 hasSetLogFormat |= err;
             break;
@@ -1108,7 +1034,35 @@
         }
 
         if (clearLog) {
-            if (android_logger_clear(dev->logger)) {
+            if (g_outputFileName) {
+                int maxRotationCountDigits =
+                    (g_maxRotatedLogs > 0) ? (int) (floor(log10(g_maxRotatedLogs) + 1)) : 0;
+
+                for (int i = g_maxRotatedLogs ; i >= 0 ; --i) {
+                    char *file;
+
+                    if (i == 0) {
+                        asprintf(&file, "%s", g_outputFileName);
+                    } else {
+                        asprintf(&file, "%s.%.*d", g_outputFileName, maxRotationCountDigits, i);
+                    }
+
+                    if (!file) {
+                        perror("while clearing log files");
+                        clearFail = clearFail ?: dev->device;
+                        break;
+                    }
+
+                    err = unlink(file);
+
+                    if (err < 0 && errno != ENOENT && clearFail == NULL) {
+                        perror("while clearing log files");
+                        clearFail = dev->device;
+                    }
+
+                    free(file);
+                }
+            } else if (android_logger_clear(dev->logger)) {
                 clearFail = clearFail ?: dev->device;
             }
         }
diff --git a/logcat/logcatd.rc b/logcat/logcatd.rc
index 70d1dd4..7d70dd9 100644
--- a/logcat/logcatd.rc
+++ b/logcat/logcatd.rc
@@ -5,6 +5,16 @@
     exec - logd log -- /system/bin/logcat -L -b ${persist.logd.logpersistd.buffer:-all} -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 1024 -n ${persist.logd.logpersistd.size:-256}
     start logcatd
 
+on property:persist.logd.logpersistd=clear
+    stop logcatd
+    # logd for clear of only our files in /data/misc/logd
+    exec - logd log -- /system/bin/logcat -c -f /data/misc/logd/logcat -n ${persist.logd.logpersistd.size:-256}
+    setprop persist.logd.logpersistd ""
+
+on property:persist.logd.logpersistd=stop
+    stop logcatd
+    setprop persist.logd.logpersistd ""
+
 service logcatd /system/bin/logcat -b ${persist.logd.logpersistd.buffer:-all} -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 1024 -n ${persist.logd.logpersistd.size:-256}
     class late_start
     disabled
diff --git a/logcat/logpersist b/logcat/logpersist
index bd465c8..d1eda37 100755
--- a/logcat/logpersist
+++ b/logcat/logpersist
@@ -73,10 +73,7 @@
   current_size="`getprop ${property}.size`"
   if [ "${service}" = "`getprop ${property}`" ]; then
     if [ "true" = "${clear}" ]; then
-      su root stop ${service}
-      su root setprop ${property} ""
-      # 20ms done, guarantees content stop before rm
-      sleep 1
+      setprop ${property} "clear"
     elif [ "${buffer}|${size}" != "${current_buffer}|${current_size}" ]; then
       echo   "ERROR: Changing existing collection parameters from" >&2
       if [ "${buffer}" != "${current_buffer}" ]; then
@@ -98,18 +95,20 @@
       echo   "       To blindly override and retain data, ${progname%.*}.stop first." >&2
       exit 1
     fi
-  fi
-  if [ "true" = "${clear}" ]; then
-    su logd,misc rm -rf "${data}"
+  elif [ "true" = "${clear}" ]; then
+    setprop ${property} "clear"
   fi
   if [ -n "${buffer}${current_buffer}" ]; then
-    su root setprop ${property}.buffer "${buffer}"
+    setprop ${property}.buffer "${buffer}"
   fi
   if [ -n "${size}${current_size}" ]; then
-    su root setprop ${property}.size "${size}"
+    setprop ${property}.size "${size}"
   fi
+  while [ "clear" = "`getprop ${property}`" ]; do
+    continue
+  done
   # ${service}.rc does the heavy lifting with the following trigger
-  su root setprop ${property} ${service}
+  setprop ${property} ${service}
   getprop ${property}
   # 20ms done, to permit process feedback check
   sleep 1
@@ -120,19 +119,20 @@
   if [ -n "${size}${buffer}" ]; then
     echo "WARNING: Can not use --size or --buffer with ${progname%.*}.stop" >&2
   fi
-  su root stop ${service}
-  su root setprop ${property} ""
+  if [ "true" = "${clear}" ]; then
+    setprop ${property} "clear"
+  else
+    setprop ${property} "stop"
+  fi
   if [ -n "`getprop ${property}.buffer`" ]; then
-    su root setprop ${property}.buffer ""
+    setprop ${property}.buffer ""
   fi
   if [ -n "`getprop ${property}.size`" ]; then
-    su root setprop ${property}.size ""
+    setprop ${property}.size ""
   fi
-  if [ "true" = "${clear}" ]; then
-    # 20ms done, guarantees content stop before rm
-    sleep 1
-    su logd,misc rm -rf "${data}"
-  fi
+  while [ "clear" = "`getprop ${property}`" ]; do
+    continue
+  done
   ;;
 *)
   echo "ERROR: Unexpected command ${0##*/} ${args}" >&2
diff --git a/logcat/tests/Android.mk b/logcat/tests/Android.mk
index 3bf8a0b..a28664e 100644
--- a/logcat/tests/Android.mk
+++ b/logcat/tests/Android.mk
@@ -56,6 +56,6 @@
 LOCAL_MODULE := $(test_module_prefix)unit-tests
 LOCAL_MODULE_TAGS := $(test_tags)
 LOCAL_CFLAGS += $(test_c_flags)
-LOCAL_SHARED_LIBRARIES := liblog libcutils
+LOCAL_SHARED_LIBRARIES := liblog
 LOCAL_SRC_FILES := $(test_src_files)
 include $(BUILD_NATIVE_TEST)
diff --git a/logcat/tests/logcat_test.cpp b/logcat/tests/logcat_test.cpp
index 920d504..0043d1b 100644
--- a/logcat/tests/logcat_test.cpp
+++ b/logcat/tests/logcat_test.cpp
@@ -25,7 +25,6 @@
 
 #include <memory>
 
-#include <cutils/properties.h>
 #include <gtest/gtest.h>
 #include <log/log.h>
 #include <log/logger.h>
@@ -426,14 +425,6 @@
       "logcat -v brief -b radio,events,system,main -g 2>/dev/null"));
 }
 
-// duplicate test for get_size, but use test.logcat.buffer property
-TEST(logcat, property_expand) {
-    property_set("test.logcat.buffer", "radio,events");
-    EXPECT_EQ(4, get_groups(
-      "logcat -v brief -b 'system,${test.logcat.buffer:-bogo},main' -g 2>/dev/null"));
-    property_set("test.logcat.buffer", "");
-}
-
 TEST(logcat, bad_buffer) {
     ASSERT_EQ(0, get_groups(
       "logcat -v brief -b radio,events,bogo,system,main -g 2>/dev/null"));
@@ -781,6 +772,82 @@
     EXPECT_FALSE(system(command));
 }
 
+TEST(logcat, logrotate_clear) {
+    static const char tmp_out_dir_form[] = "/data/local/tmp/logcat.logrotate.XXXXXX";
+    char tmp_out_dir[sizeof(tmp_out_dir_form)];
+    ASSERT_TRUE(NULL != mkdtemp(strcpy(tmp_out_dir, tmp_out_dir_form)));
+
+    static const char log_filename[] = "log.txt";
+    static const unsigned num_val = 32;
+    static const char logcat_cmd[] = "logcat -b all -d -f %s/%s -n %d -r 1";
+    static const char clear_cmd[] = " -c";
+    static const char cleanup_cmd[] = "rm -rf %s";
+    char command[sizeof(tmp_out_dir) + sizeof(logcat_cmd) + sizeof(log_filename) + sizeof(clear_cmd) + 32];
+
+    // Run command with all data
+    {
+        snprintf(command, sizeof(command) - sizeof(clear_cmd),
+                 logcat_cmd, tmp_out_dir, log_filename, num_val);
+
+        int ret;
+        EXPECT_FALSE((ret = system(command)));
+        if (ret) {
+            snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
+            EXPECT_FALSE(system(command));
+            return;
+        }
+        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir), closedir);
+        EXPECT_NE(nullptr, dir);
+        if (!dir) {
+            snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
+            EXPECT_FALSE(system(command));
+            return;
+        }
+        struct dirent *entry;
+        unsigned count = 0;
+        while ((entry = readdir(dir.get()))) {
+            if (strncmp(entry->d_name, log_filename, sizeof(log_filename) - 1)) {
+                continue;
+            }
+            ++count;
+        }
+        EXPECT_EQ(count, num_val + 1);
+    }
+
+    {
+        // Now with -c option tacked onto the end
+        strcat(command, clear_cmd);
+
+        int ret;
+        EXPECT_FALSE((ret = system(command)));
+        if (ret) {
+            snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
+            EXPECT_FALSE(system(command));
+            return;
+        }
+        std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(tmp_out_dir), closedir);
+        EXPECT_NE(nullptr, dir);
+        if (!dir) {
+            snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
+            EXPECT_FALSE(system(command));
+            return;
+        }
+        struct dirent *entry;
+        unsigned count = 0;
+        while ((entry = readdir(dir.get()))) {
+            if (strncmp(entry->d_name, log_filename, sizeof(log_filename) - 1)) {
+                continue;
+            }
+            fprintf(stderr, "Found %s/%s!!!\n", tmp_out_dir, entry->d_name);
+            ++count;
+        }
+        EXPECT_EQ(count, 0U);
+    }
+
+    snprintf(command, sizeof(command), cleanup_cmd, tmp_out_dir);
+    EXPECT_FALSE(system(command));
+}
+
 TEST(logcat, logrotate_nodir) {
     // expect logcat to error out on writing content and exit(1) for nodir
     EXPECT_EQ(W_EXITCODE(1, 0),
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index feeffda..413d61f 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -38,7 +38,6 @@
     sendevent \
     start \
     stop \
-    top \
 
 ALL_TOOLS = $(BSD_TOOLS) $(OUR_TOOLS)
 
diff --git a/toolbox/top.c b/toolbox/top.c
deleted file mode 100644
index 003f4c9..0000000
--- a/toolbox/top.c
+++ /dev/null
@@ -1,589 +0,0 @@
-/*
- * Copyright (c) 2008, The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *  * Neither the name of Google, Inc. nor the names of its contributors
- *    may be used to endorse or promote products derived from this
- *    software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <ctype.h>
-#include <dirent.h>
-#include <grp.h>
-#include <inttypes.h>
-#include <pwd.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <cutils/sched_policy.h>
-
-struct cpu_info {
-    long unsigned utime, ntime, stime, itime;
-    long unsigned iowtime, irqtime, sirqtime;
-};
-
-#define PROC_NAME_LEN 64
-#define THREAD_NAME_LEN 32
-#define POLICY_NAME_LEN 4
-
-struct proc_info {
-    struct proc_info *next;
-    pid_t pid;
-    pid_t tid;
-    uid_t uid;
-    gid_t gid;
-    char name[PROC_NAME_LEN];
-    char tname[THREAD_NAME_LEN];
-    char state;
-    uint64_t utime;
-    uint64_t stime;
-    char pr[3];
-    long ni;
-    uint64_t delta_utime;
-    uint64_t delta_stime;
-    uint64_t delta_time;
-    uint64_t vss;
-    uint64_t rss;
-    int num_threads;
-    char policy[POLICY_NAME_LEN];
-};
-
-struct proc_list {
-    struct proc_info **array;
-    int size;
-};
-
-#define die(...) { fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); }
-
-#define INIT_PROCS 50
-#define THREAD_MULT 8
-static struct proc_info **old_procs, **new_procs;
-static int num_old_procs, num_new_procs;
-static struct proc_info *free_procs;
-static int num_used_procs, num_free_procs;
-
-static int max_procs, delay, iterations, threads;
-
-static struct cpu_info old_cpu, new_cpu;
-
-static struct proc_info *alloc_proc(void);
-static void free_proc(struct proc_info *proc);
-static void read_procs(void);
-static int read_stat(char *filename, struct proc_info *proc);
-static void read_policy(int pid, struct proc_info *proc);
-static void add_proc(int proc_num, struct proc_info *proc);
-static int read_cmdline(char *filename, struct proc_info *proc);
-static int read_status(char *filename, struct proc_info *proc);
-static void print_procs(void);
-static struct proc_info *find_old_proc(pid_t pid, pid_t tid);
-static void free_old_procs(void);
-static int (*proc_cmp)(const void *a, const void *b);
-static int proc_cpu_cmp(const void *a, const void *b);
-static int proc_vss_cmp(const void *a, const void *b);
-static int proc_rss_cmp(const void *a, const void *b);
-static int proc_thr_cmp(const void *a, const void *b);
-static int numcmp(long long a, long long b);
-static void usage(char *cmd);
-
-int top_main(int argc, char *argv[]) {
-    num_used_procs = num_free_procs = 0;
-
-    max_procs = 0;
-    delay = 3;
-    iterations = -1;
-    proc_cmp = &proc_cpu_cmp;
-    for (int i = 1; i < argc; i++) {
-        if (!strcmp(argv[i], "-m")) {
-            if (i + 1 >= argc) {
-                fprintf(stderr, "Option -m expects an argument.\n");
-                usage(argv[0]);
-                exit(EXIT_FAILURE);
-            }
-            max_procs = atoi(argv[++i]);
-            continue;
-        }
-        if (!strcmp(argv[i], "-n")) {
-            if (i + 1 >= argc) {
-                fprintf(stderr, "Option -n expects an argument.\n");
-                usage(argv[0]);
-                exit(EXIT_FAILURE);
-            }
-            iterations = atoi(argv[++i]);
-            continue;
-        }
-        if (!strcmp(argv[i], "-d")) {
-            if (i + 1 >= argc) {
-                fprintf(stderr, "Option -d expects an argument.\n");
-                usage(argv[0]);
-                exit(EXIT_FAILURE);
-            }
-            delay = atoi(argv[++i]);
-            continue;
-        }
-        if (!strcmp(argv[i], "-s")) {
-            if (i + 1 >= argc) {
-                fprintf(stderr, "Option -s expects an argument.\n");
-                usage(argv[0]);
-                exit(EXIT_FAILURE);
-            }
-            ++i;
-            if (!strcmp(argv[i], "cpu")) { proc_cmp = &proc_cpu_cmp; continue; }
-            if (!strcmp(argv[i], "vss")) { proc_cmp = &proc_vss_cmp; continue; }
-            if (!strcmp(argv[i], "rss")) { proc_cmp = &proc_rss_cmp; continue; }
-            if (!strcmp(argv[i], "thr")) { proc_cmp = &proc_thr_cmp; continue; }
-            fprintf(stderr, "Invalid argument \"%s\" for option -s.\n", argv[i]);
-            exit(EXIT_FAILURE);
-        }
-        if (!strcmp(argv[i], "-H") || !strcmp(argv[i], "-t")) { threads = 1; continue; }
-        if (!strcmp(argv[i], "-h")) {
-            usage(argv[0]);
-            exit(EXIT_SUCCESS);
-        }
-        fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
-        usage(argv[0]);
-        exit(EXIT_FAILURE);
-    }
-
-    if (threads && proc_cmp == &proc_thr_cmp) {
-        fprintf(stderr, "Sorting by threads per thread makes no sense!\n");
-        exit(EXIT_FAILURE);
-    }
-
-    free_procs = NULL;
-
-    num_new_procs = num_old_procs = 0;
-    new_procs = old_procs = NULL;
-
-    read_procs();
-    while ((iterations == -1) || (iterations-- > 0)) {
-        old_procs = new_procs;
-        num_old_procs = num_new_procs;
-        memcpy(&old_cpu, &new_cpu, sizeof(old_cpu));
-        read_procs();
-        print_procs();
-        free_old_procs();
-        fflush(stdout);
-        if (iterations != 0) sleep(delay);
-    }
-
-    return 0;
-}
-
-static struct proc_info *alloc_proc(void) {
-    struct proc_info *proc;
-
-    if (free_procs) {
-        proc = free_procs;
-        free_procs = free_procs->next;
-        num_free_procs--;
-    } else {
-        proc = malloc(sizeof(*proc));
-        if (!proc) die("Could not allocate struct process_info.\n");
-    }
-
-    num_used_procs++;
-
-    return proc;
-}
-
-static void free_proc(struct proc_info *proc) {
-    proc->next = free_procs;
-    free_procs = proc;
-
-    num_used_procs--;
-    num_free_procs++;
-}
-
-#define MAX_LINE 256
-
-static void read_procs(void) {
-    DIR *proc_dir, *task_dir;
-    struct dirent *pid_dir, *tid_dir;
-    char filename[64];
-    FILE *file;
-    int proc_num;
-    struct proc_info *proc;
-    pid_t pid, tid;
-
-    int i;
-
-    proc_dir = opendir("/proc");
-    if (!proc_dir) die("Could not open /proc.\n");
-
-    new_procs = calloc(INIT_PROCS * (threads ? THREAD_MULT : 1), sizeof(struct proc_info *));
-    num_new_procs = INIT_PROCS * (threads ? THREAD_MULT : 1);
-
-    file = fopen("/proc/stat", "r");
-    if (!file) die("Could not open /proc/stat.\n");
-    fscanf(file, "cpu  %lu %lu %lu %lu %lu %lu %lu", &new_cpu.utime, &new_cpu.ntime, &new_cpu.stime,
-            &new_cpu.itime, &new_cpu.iowtime, &new_cpu.irqtime, &new_cpu.sirqtime);
-    fclose(file);
-
-    proc_num = 0;
-    while ((pid_dir = readdir(proc_dir))) {
-        if (!isdigit(pid_dir->d_name[0]))
-            continue;
-
-        pid = atoi(pid_dir->d_name);
-
-        struct proc_info cur_proc;
-
-        if (!threads) {
-            proc = alloc_proc();
-
-            proc->pid = proc->tid = pid;
-
-            snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
-            read_stat(filename, proc);
-
-            snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
-            read_cmdline(filename, proc);
-
-            snprintf(filename, sizeof(filename), "/proc/%d/status", pid);
-            read_status(filename, proc);
-
-            read_policy(pid, proc);
-
-            proc->num_threads = 0;
-        } else {
-            snprintf(filename, sizeof(filename), "/proc/%d/cmdline", pid);
-            read_cmdline(filename, &cur_proc);
-
-            snprintf(filename, sizeof(filename), "/proc/%d/status", pid);
-            read_status(filename, &cur_proc);
-
-            proc = NULL;
-        }
-
-        snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
-        task_dir = opendir(filename);
-        if (!task_dir) continue;
-
-        while ((tid_dir = readdir(task_dir))) {
-            if (!isdigit(tid_dir->d_name[0]))
-                continue;
-
-            if (threads) {
-                tid = atoi(tid_dir->d_name);
-
-                proc = alloc_proc();
-
-                proc->pid = pid; proc->tid = tid;
-
-                snprintf(filename, sizeof(filename), "/proc/%d/task/%d/stat", pid, tid);
-                read_stat(filename, proc);
-
-                read_policy(tid, proc);
-
-                strcpy(proc->name, cur_proc.name);
-                proc->uid = cur_proc.uid;
-                proc->gid = cur_proc.gid;
-
-                add_proc(proc_num++, proc);
-            } else {
-                proc->num_threads++;
-            }
-        }
-
-        closedir(task_dir);
-
-        if (!threads)
-            add_proc(proc_num++, proc);
-    }
-
-    for (i = proc_num; i < num_new_procs; i++)
-        new_procs[i] = NULL;
-
-    closedir(proc_dir);
-}
-
-static int read_stat(char *filename, struct proc_info *proc) {
-    FILE *file;
-    char buf[MAX_LINE], *open_paren, *close_paren;
-
-    file = fopen(filename, "r");
-    if (!file) return 1;
-    fgets(buf, MAX_LINE, file);
-    fclose(file);
-
-    /* Split at first '(' and last ')' to get process name. */
-    open_paren = strchr(buf, '(');
-    close_paren = strrchr(buf, ')');
-    if (!open_paren || !close_paren) return 1;
-
-    *open_paren = *close_paren = '\0';
-    strncpy(proc->tname, open_paren + 1, THREAD_NAME_LEN);
-    proc->tname[THREAD_NAME_LEN-1] = 0;
-
-    // Scan rest of string.
-    long pr;
-    sscanf(close_paren + 1,
-           " %c "
-           "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
-           "%" SCNu64 // utime %lu (14)
-           "%" SCNu64 // stime %lu (15)
-           "%*d %*d "
-           "%ld " // priority %ld (18)
-           "%ld " // nice %ld (19)
-           "%*d %*d %*d "
-           "%" SCNu64 // vsize %lu (23)
-           "%" SCNu64, // rss %ld (24)
-           &proc->state,
-           &proc->utime,
-           &proc->stime,
-           &pr,
-           &proc->ni,
-           &proc->vss,
-           &proc->rss);
-
-    // Translate the PR field.
-    if (pr < -9) strcpy(proc->pr, "RT");
-    else snprintf(proc->pr, sizeof(proc->pr), "%ld", pr);
-
-    return 0;
-}
-
-static void add_proc(int proc_num, struct proc_info *proc) {
-    int i;
-
-    if (proc_num >= num_new_procs) {
-        new_procs = realloc(new_procs, 2 * num_new_procs * sizeof(struct proc_info *));
-        if (!new_procs) die("Could not expand procs array.\n");
-        for (i = num_new_procs; i < 2 * num_new_procs; i++)
-            new_procs[i] = NULL;
-        num_new_procs = 2 * num_new_procs;
-    }
-    new_procs[proc_num] = proc;
-}
-
-static int read_cmdline(char *filename, struct proc_info *proc) {
-    FILE *file;
-    char line[MAX_LINE];
-
-    line[0] = '\0';
-    file = fopen(filename, "r");
-    if (!file) return 1;
-    fgets(line, MAX_LINE, file);
-    fclose(file);
-    if (strlen(line) > 0) {
-        strncpy(proc->name, line, PROC_NAME_LEN);
-        proc->name[PROC_NAME_LEN-1] = 0;
-    } else
-        proc->name[0] = 0;
-    return 0;
-}
-
-static void read_policy(int pid, struct proc_info *proc) {
-    SchedPolicy p;
-    if (get_sched_policy(pid, &p) < 0)
-        strlcpy(proc->policy, "unk", POLICY_NAME_LEN);
-    else {
-        strlcpy(proc->policy, get_sched_policy_name(p), POLICY_NAME_LEN);
-        proc->policy[2] = '\0';
-    }
-}
-
-static int read_status(char *filename, struct proc_info *proc) {
-    FILE *file;
-    char line[MAX_LINE];
-    unsigned int uid, gid;
-
-    file = fopen(filename, "r");
-    if (!file) return 1;
-    while (fgets(line, MAX_LINE, file)) {
-        sscanf(line, "Uid: %u", &uid);
-        sscanf(line, "Gid: %u", &gid);
-    }
-    fclose(file);
-    proc->uid = uid; proc->gid = gid;
-    return 0;
-}
-
-static void print_procs(void) {
-    static int call = 0;
-    int i;
-    struct proc_info *old_proc, *proc;
-    long unsigned total_delta_time;
-
-    for (i = 0; i < num_new_procs; i++) {
-        if (new_procs[i]) {
-            old_proc = find_old_proc(new_procs[i]->pid, new_procs[i]->tid);
-            if (old_proc) {
-                new_procs[i]->delta_utime = new_procs[i]->utime - old_proc->utime;
-                new_procs[i]->delta_stime = new_procs[i]->stime - old_proc->stime;
-            } else {
-                new_procs[i]->delta_utime = 0;
-                new_procs[i]->delta_stime = 0;
-            }
-            new_procs[i]->delta_time = new_procs[i]->delta_utime + new_procs[i]->delta_stime;
-        }
-    }
-
-    total_delta_time = (new_cpu.utime + new_cpu.ntime + new_cpu.stime + new_cpu.itime
-                        + new_cpu.iowtime + new_cpu.irqtime + new_cpu.sirqtime)
-                     - (old_cpu.utime + old_cpu.ntime + old_cpu.stime + old_cpu.itime
-                        + old_cpu.iowtime + old_cpu.irqtime + old_cpu.sirqtime);
-
-    qsort(new_procs, num_new_procs, sizeof(struct proc_info *), proc_cmp);
-
-    if (call++ > 0) printf("\n\n\n");
-    printf("User %ld%%, System %ld%%, IOW %ld%%, IRQ %ld%%\n",
-            ((new_cpu.utime + new_cpu.ntime) - (old_cpu.utime + old_cpu.ntime)) * 100  / total_delta_time,
-            ((new_cpu.stime ) - (old_cpu.stime)) * 100 / total_delta_time,
-            ((new_cpu.iowtime) - (old_cpu.iowtime)) * 100 / total_delta_time,
-            ((new_cpu.irqtime + new_cpu.sirqtime)
-                    - (old_cpu.irqtime + old_cpu.sirqtime)) * 100 / total_delta_time);
-    printf("User %ld + Nice %ld + Sys %ld + Idle %ld + IOW %ld + IRQ %ld + SIRQ %ld = %ld\n",
-            new_cpu.utime - old_cpu.utime,
-            new_cpu.ntime - old_cpu.ntime,
-            new_cpu.stime - old_cpu.stime,
-            new_cpu.itime - old_cpu.itime,
-            new_cpu.iowtime - old_cpu.iowtime,
-            new_cpu.irqtime - old_cpu.irqtime,
-            new_cpu.sirqtime - old_cpu.sirqtime,
-            total_delta_time);
-    printf("\n");
-    if (!threads)
-        printf("%5s %-8s %2s %3s %4s %1s %5s %7s %7s %3s %s\n", "PID", "USER", "PR", "NI", "CPU%", "S", "#THR", "VSS", "RSS", "PCY", "Name");
-    else
-        printf("%5s %5s %-8s %2s %3s %4s %1s %7s %7s %3s %-15s %s\n", "PID", "TID", "USER", "PR", "NI", "CPU%", "S", "VSS", "RSS", "PCY", "Thread", "Proc");
-
-    for (i = 0; i < num_new_procs; i++) {
-        proc = new_procs[i];
-
-        if (!proc || (max_procs && (i >= max_procs)))
-            break;
-        struct passwd* user = getpwuid(proc->uid);
-        char user_buf[20];
-        char* user_str;
-        if (user && user->pw_name) {
-            user_str = user->pw_name;
-        } else {
-            snprintf(user_buf, sizeof(user_buf), "%d", proc->uid);
-            user_str = user_buf;
-        }
-        if (!threads) {
-            printf("%5d %-8.8s %2s %3ld %3" PRIu64 "%% %c %5d %6" PRIu64 "K %6" PRIu64 "K %3s %s\n",
-                   proc->pid, user_str, proc->pr, proc->ni,
-                   proc->delta_time * 100 / total_delta_time, proc->state, proc->num_threads,
-                   proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy,
-                   proc->name[0] != 0 ? proc->name : proc->tname);
-        } else {
-            printf("%5d %5d %-8.8s %2s %3ld %3" PRIu64 "%% %c %6" PRIu64 "K %6" PRIu64 "K %3s %-15s %s\n",
-                   proc->pid, proc->tid, user_str, proc->pr, proc->ni,
-                   proc->delta_time * 100 / total_delta_time, proc->state,
-                   proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy,
-                   proc->tname, proc->name);
-        }
-    }
-}
-
-static struct proc_info *find_old_proc(pid_t pid, pid_t tid) {
-    int i;
-
-    for (i = 0; i < num_old_procs; i++)
-        if (old_procs[i] && (old_procs[i]->pid == pid) && (old_procs[i]->tid == tid))
-            return old_procs[i];
-
-    return NULL;
-}
-
-static void free_old_procs(void) {
-    int i;
-
-    for (i = 0; i < num_old_procs; i++)
-        if (old_procs[i])
-            free_proc(old_procs[i]);
-
-    free(old_procs);
-}
-
-static int proc_cpu_cmp(const void *a, const void *b) {
-    struct proc_info *pa, *pb;
-
-    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
-
-    if (!pa && !pb) return 0;
-    if (!pa) return 1;
-    if (!pb) return -1;
-
-    return -numcmp(pa->delta_time, pb->delta_time);
-}
-
-static int proc_vss_cmp(const void *a, const void *b) {
-    struct proc_info *pa, *pb;
-
-    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
-
-    if (!pa && !pb) return 0;
-    if (!pa) return 1;
-    if (!pb) return -1;
-
-    return -numcmp(pa->vss, pb->vss);
-}
-
-static int proc_rss_cmp(const void *a, const void *b) {
-    struct proc_info *pa, *pb;
-
-    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
-
-    if (!pa && !pb) return 0;
-    if (!pa) return 1;
-    if (!pb) return -1;
-
-    return -numcmp(pa->rss, pb->rss);
-}
-
-static int proc_thr_cmp(const void *a, const void *b) {
-    struct proc_info *pa, *pb;
-
-    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
-
-    if (!pa && !pb) return 0;
-    if (!pa) return 1;
-    if (!pb) return -1;
-
-    return -numcmp(pa->num_threads, pb->num_threads);
-}
-
-static int numcmp(long long a, long long b) {
-    if (a < b) return -1;
-    if (a > b) return 1;
-    return 0;
-}
-
-static void usage(char *cmd) {
-    fprintf(stderr, "Usage: %s [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]\n"
-                    "    -m num  Maximum number of processes to display.\n"
-                    "    -n num  Updates to show before exiting.\n"
-                    "    -d num  Seconds to wait between updates.\n"
-                    "    -s col  Column to sort by (cpu,vss,rss,thr).\n"
-                    "    -H      Show threads instead of processes.\n"
-                    "    -h      Display this help screen.\n",
-        cmd);
-}