Merge "fs_mgr: validate corrected signatures"
diff --git a/adb/file_sync_service.cpp b/adb/file_sync_service.cpp
index 926dbcf..14c26cb 100644
--- a/adb/file_sync_service.cpp
+++ b/adb/file_sync_service.cpp
@@ -21,13 +21,13 @@
 
 #include <dirent.h>
 #include <errno.h>
-#include <log/log.h>
-#include <selinux/android.h>
+#include <linux/xattr.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <sys/stat.h>
 #include <sys/types.h>
+#include <sys/xattr.h>
 #include <unistd.h>
 #include <utime.h>
 
@@ -39,6 +39,8 @@
 
 #include <android-base/stringprintf.h>
 #include <android-base/strings.h>
+#include <log/log.h>
+#include <selinux/android.h>
 
 static bool should_use_fs_config(const std::string& path) {
     // TODO: use fs_config to configure permissions on /data.
@@ -47,11 +49,27 @@
            android::base::StartsWith(path, "/oem/");
 }
 
+static bool update_capabilities(const char* path, uint64_t capabilities) {
+    if (capabilities == 0) {
+        // Ensure we clean up in case the capabilities weren't 0 in the past.
+        removexattr(path, XATTR_NAME_CAPS);
+        return true;
+    }
+
+    vfs_cap_data cap_data = {};
+    cap_data.magic_etc = VFS_CAP_REVISION | VFS_CAP_FLAGS_EFFECTIVE;
+    cap_data.data[0].permitted = (capabilities & 0xffffffff);
+    cap_data.data[0].inheritable = 0;
+    cap_data.data[1].permitted = (capabilities >> 32);
+    cap_data.data[1].inheritable = 0;
+    return setxattr(path, XATTR_NAME_CAPS, &cap_data, sizeof(cap_data), 0) != -1;
+}
+
 static bool secure_mkdirs(const std::string& path) {
     uid_t uid = -1;
     gid_t gid = -1;
     unsigned int mode = 0775;
-    uint64_t cap = 0;
+    uint64_t capabilities = 0;
 
     if (path[0] != '/') return false;
 
@@ -62,18 +80,19 @@
         partial_path += path_component;
 
         if (should_use_fs_config(partial_path)) {
-            fs_config(partial_path.c_str(), 1, nullptr, &uid, &gid, &mode, &cap);
+            fs_config(partial_path.c_str(), 1, nullptr, &uid, &gid, &mode, &capabilities);
         }
         if (adb_mkdir(partial_path.c_str(), mode) == -1) {
             if (errno != EEXIST) {
                 return false;
             }
         } else {
-            if (chown(partial_path.c_str(), uid, gid) == -1) {
-                return false;
-            }
+            if (chown(partial_path.c_str(), uid, gid) == -1) return false;
+
             // Not all filesystems support setting SELinux labels. http://b/23530370.
             selinux_android_restorecon(partial_path.c_str(), 0);
+
+            if (!update_capabilities(partial_path.c_str(), capabilities)) return false;
         }
     }
     return true;
@@ -83,8 +102,7 @@
     syncmsg msg;
     msg.stat.id = ID_STAT;
 
-    struct stat st;
-    memset(&st, 0, sizeof(st));
+    struct stat st = {};
     // TODO: add a way to report that the stat failed!
     lstat(path, &st);
     msg.stat.mode = st.st_mode;
@@ -146,8 +164,8 @@
     return SendSyncFail(fd, android::base::StringPrintf("%s: %s", reason.c_str(), strerror(errno)));
 }
 
-static bool handle_send_file(int s, const char* path, uid_t uid,
-                             gid_t gid, mode_t mode, std::vector<char>& buffer, bool do_unlink) {
+static bool handle_send_file(int s, const char* path, uid_t uid, gid_t gid, uint64_t capabilities,
+                             mode_t mode, std::vector<char>& buffer, bool do_unlink) {
     syncmsg msg;
     unsigned int timestamp = 0;
 
@@ -178,8 +196,13 @@
 
         // fchown clears the setuid bit - restore it if present.
         // Ignore the result of calling fchmod. It's not supported
-        // by all filesystems. b/12441485
+        // by all filesystems, so we don't check for success. b/12441485
         fchmod(fd, mode);
+
+        if (!update_capabilities(path, capabilities)) {
+            SendSyncFailErrno(s, "update_capabilities failed");
+            goto fail;
+        }
     }
 
     while (true) {
@@ -338,13 +361,13 @@
 
     uid_t uid = -1;
     gid_t gid = -1;
-    uint64_t cap = 0;
+    uint64_t capabilities = 0;
     if (should_use_fs_config(path)) {
         unsigned int broken_api_hack = mode;
-        fs_config(path.c_str(), 0, nullptr, &uid, &gid, &broken_api_hack, &cap);
+        fs_config(path.c_str(), 0, nullptr, &uid, &gid, &broken_api_hack, &capabilities);
         mode = broken_api_hack;
     }
-    return handle_send_file(s, path.c_str(), uid, gid, mode, buffer, do_unlink);
+    return handle_send_file(s, path.c_str(), uid, gid, capabilities, mode, buffer, do_unlink);
 }
 
 static bool do_recv(int s, const char* path, std::vector<char>& buffer) {
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),