Merge "ziparchive: Allow ExtractEntryToFile() to work with block device."
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 4cd423a..7f4a0dd 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -43,7 +43,9 @@
#include <sys/types.h>
#include <unistd.h>
+#include <chrono>
#include <functional>
+#include <thread>
#include <utility>
#include <vector>
@@ -301,7 +303,7 @@
announce = false;
fprintf(stderr, "< waiting for %s >\n", serial ? serial : "any device");
}
- usleep(1000);
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
diff --git a/fastboot/usb_linux.cpp b/fastboot/usb_linux.cpp
index 6db1e27..cdab4f1 100644
--- a/fastboot/usb_linux.cpp
+++ b/fastboot/usb_linux.cpp
@@ -43,11 +43,15 @@
#include <linux/version.h>
#include <linux/usb/ch9.h>
+#include <chrono>
#include <memory>
+#include <thread>
#include "fastboot.h"
#include "usb.h"
+using namespace std::chrono_literals;
+
#define MAX_RETRIES 5
/* Timeout in seconds for usb_wait_for_disconnect.
@@ -426,7 +430,7 @@
return -1;
}
- while(len > 0) {
+ while (len > 0) {
int xfer = (len > MAX_USBFS_BULK_SIZE) ? MAX_USBFS_BULK_SIZE : len;
bulk.ep = handle_->ep_in;
@@ -435,18 +439,17 @@
bulk.timeout = 0;
retry = 0;
- do{
- DBG("[ usb read %d fd = %d], fname=%s\n", xfer, handle_->desc, handle_->fname);
- n = ioctl(handle_->desc, USBDEVFS_BULK, &bulk);
- DBG("[ usb read %d ] = %d, fname=%s, Retry %d \n", xfer, n, handle_->fname, retry);
+ do {
+ DBG("[ usb read %d fd = %d], fname=%s\n", xfer, handle_->desc, handle_->fname);
+ n = ioctl(handle_->desc, USBDEVFS_BULK, &bulk);
+ DBG("[ usb read %d ] = %d, fname=%s, Retry %d \n", xfer, n, handle_->fname, retry);
- if( n < 0 ) {
- DBG1("ERROR: n = %d, errno = %d (%s)\n",n, errno, strerror(errno));
- if ( ++retry > MAX_RETRIES ) return -1;
- sleep( 1 );
- }
- }
- while( n < 0 );
+ if (n < 0) {
+ DBG1("ERROR: n = %d, errno = %d (%s)\n",n, errno, strerror(errno));
+ if (++retry > MAX_RETRIES) return -1;
+ std::this_thread::sleep_for(1s);
+ }
+ } while (n < 0);
count += n;
len -= n;
@@ -488,9 +491,8 @@
{
double deadline = now() + WAIT_FOR_DISCONNECT_TIMEOUT;
while (now() < deadline) {
- if (access(handle_->fname, F_OK))
- return 0;
- usleep(50000);
+ if (access(handle_->fname, F_OK)) return 0;
+ std::this_thread::sleep_for(50ms);
}
return -1;
}
diff --git a/fastboot/usb_windows.cpp b/fastboot/usb_windows.cpp
index 1cdeb32..3dab5ac 100644
--- a/fastboot/usb_windows.cpp
+++ b/fastboot/usb_windows.cpp
@@ -362,9 +362,3 @@
std::unique_ptr<usb_handle> handle = find_usb_device(callback);
return handle ? new WindowsUsbTransport(std::move(handle)) : nullptr;
}
-
-// called from fastboot.c
-void sleep(int seconds)
-{
- Sleep(seconds * 1000);
-}
diff --git a/init/action.cpp b/init/action.cpp
index a12f225..ccc18cf 100644
--- a/init/action.cpp
+++ b/init/action.cpp
@@ -118,16 +118,14 @@
Timer t;
int result = command.InvokeFunc();
- double duration_ms = t.duration() * 1000;
- // Any action longer than 50ms will be warned to user as slow operation
- if (duration_ms > 50.0 ||
- android::base::GetMinimumLogSeverity() <= android::base::DEBUG) {
+ // TODO: this should probably be changed to "if (failed || took a long time)"...
+ if (android::base::GetMinimumLogSeverity() <= android::base::DEBUG) {
std::string trigger_name = BuildTriggersString();
std::string cmd_str = command.BuildCommandString();
std::string source = command.BuildSourceString();
LOG(INFO) << "Command '" << cmd_str << "' action=" << trigger_name << source
- << " returned " << result << " took " << duration_ms << "ms.";
+ << " returned " << result << " took " << t.duration() << "s";
}
}
@@ -249,7 +247,9 @@
result += event_trigger_;
result += ' ';
}
- result.pop_back();
+ if (!result.empty()) {
+ result.pop_back();
+ }
return result;
}
diff --git a/init/builtins.cpp b/init/builtins.cpp
index 3e50f4d..ebdc8c9 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -38,6 +38,8 @@
#include <linux/loop.h>
#include <linux/module.h>
+#include <thread>
+
#include <selinux/selinux.h>
#include <selinux/label.h>
@@ -65,10 +67,9 @@
#include "util.h"
#define chmod DO_NOT_USE_CHMOD_USE_FCHMODAT_SYMLINK_NOFOLLOW
-#define UNMOUNT_CHECK_MS 5000
#define UNMOUNT_CHECK_TIMES 10
-static const int kTerminateServiceDelayMicroSeconds = 50000;
+static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s;
static int insmod(const char *filename, const char *options, int flags) {
int fd = open(filename, O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
@@ -192,11 +193,9 @@
close(fd);
break;
} else if (errno == EBUSY) {
- /* Some processes using |entry->mnt_dir| are still alive. Wait for a
- * while then retry.
- */
- TEMP_FAILURE_RETRY(
- usleep(UNMOUNT_CHECK_MS * 1000 / UNMOUNT_CHECK_TIMES));
+ // Some processes using |entry->mnt_dir| are still alive. Wait for a
+ // while then retry.
+ std::this_thread::sleep_for(5000ms / UNMOUNT_CHECK_TIMES);
continue;
} else {
/* Cannot open the device. Give up. */
@@ -444,7 +443,7 @@
return -1;
} else {
if (wait)
- wait_for_file(source, COMMAND_RETRY_TIMEOUT);
+ wait_for_file(source, kCommandRetryTimeout);
if (mount(source, target, system, flags, options) < 0) {
return -1;
}
@@ -749,7 +748,7 @@
}
// Wait a bit before recounting the number or running services.
- usleep(kTerminateServiceDelayMicroSeconds);
+ std::this_thread::sleep_for(50ms);
}
LOG(VERBOSE) << "Terminating running services took " << t.duration() << " seconds";
}
@@ -956,11 +955,11 @@
static int do_wait(const std::vector<std::string>& args) {
if (args.size() == 2) {
- return wait_for_file(args[1].c_str(), COMMAND_RETRY_TIMEOUT);
+ return wait_for_file(args[1].c_str(), kCommandRetryTimeout);
} else if (args.size() == 3) {
int timeout;
if (android::base::ParseInt(args[2], &timeout)) {
- return wait_for_file(args[1].c_str(), timeout);
+ return wait_for_file(args[1].c_str(), std::chrono::seconds(timeout));
}
}
return -1;
diff --git a/init/devices.cpp b/init/devices.cpp
index 1a6912f..5098fb3 100644
--- a/init/devices.cpp
+++ b/init/devices.cpp
@@ -23,6 +23,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/sendfile.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
@@ -34,6 +35,7 @@
#include <linux/netlink.h>
#include <memory>
+#include <thread>
#include <selinux/selinux.h>
#include <selinux/label.h>
@@ -784,139 +786,87 @@
}
}
-static int load_firmware(int fw_fd, int loading_fd, int data_fd)
-{
- struct stat st;
- long len_to_copy;
- int ret = 0;
+static void load_firmware(uevent* uevent, const std::string& root,
+ int fw_fd, size_t fw_size,
+ int loading_fd, int data_fd) {
+ // Start transfer.
+ android::base::WriteFully(loading_fd, "1", 1);
- if(fstat(fw_fd, &st) < 0)
- return -1;
- len_to_copy = st.st_size;
-
- write(loading_fd, "1", 1); /* start transfer */
-
- while (len_to_copy > 0) {
- char buf[PAGE_SIZE];
- ssize_t nr;
-
- nr = read(fw_fd, buf, sizeof(buf));
- if(!nr)
- break;
- if(nr < 0) {
- ret = -1;
- break;
- }
- if (!android::base::WriteFully(data_fd, buf, nr)) {
- ret = -1;
- break;
- }
- len_to_copy -= nr;
+ // Copy the firmware.
+ int rc = sendfile(data_fd, fw_fd, nullptr, fw_size);
+ if (rc == -1) {
+ PLOG(ERROR) << "firmware: sendfile failed { '" << root << "', '" << uevent->firmware << "' }";
}
- if(!ret)
- write(loading_fd, "0", 1); /* successful end of transfer */
- else
- write(loading_fd, "-1", 2); /* abort transfer */
-
- return ret;
+ // Tell the firmware whether to abort or commit.
+ const char* response = (rc != -1) ? "0" : "-1";
+ android::base::WriteFully(loading_fd, response, strlen(response));
}
-static int is_booting(void)
-{
+static int is_booting() {
return access("/dev/.booting", F_OK) == 0;
}
-static void process_firmware_event(struct uevent *uevent)
-{
- char *root, *loading, *data;
- int l, loading_fd, data_fd, fw_fd;
- size_t i;
+static void process_firmware_event(uevent* uevent) {
int booting = is_booting();
LOG(INFO) << "firmware: loading '" << uevent->firmware << "' for '" << uevent->path << "'";
- l = asprintf(&root, SYSFS_PREFIX"%s/", uevent->path);
- if (l == -1)
+ std::string root = android::base::StringPrintf("/sys%s", uevent->path);
+ std::string loading = root + "/loading";
+ std::string data = root + "/data";
+
+ android::base::unique_fd loading_fd(open(loading.c_str(), O_WRONLY|O_CLOEXEC));
+ if (loading_fd == -1) {
+ PLOG(ERROR) << "couldn't open firmware loading fd for " << uevent->firmware;
return;
+ }
- l = asprintf(&loading, "%sloading", root);
- if (l == -1)
- goto root_free_out;
-
- l = asprintf(&data, "%sdata", root);
- if (l == -1)
- goto loading_free_out;
-
- loading_fd = open(loading, O_WRONLY|O_CLOEXEC);
- if(loading_fd < 0)
- goto data_free_out;
-
- data_fd = open(data, O_WRONLY|O_CLOEXEC);
- if(data_fd < 0)
- goto loading_close_out;
+ android::base::unique_fd data_fd(open(data.c_str(), O_WRONLY|O_CLOEXEC));
+ if (data_fd == -1) {
+ PLOG(ERROR) << "couldn't open firmware data fd for " << uevent->firmware;
+ return;
+ }
try_loading_again:
- for (i = 0; i < arraysize(firmware_dirs); i++) {
- char *file = NULL;
- l = asprintf(&file, "%s/%s", firmware_dirs[i], uevent->firmware);
- if (l == -1)
- goto data_free_out;
- fw_fd = open(file, O_RDONLY|O_CLOEXEC);
- free(file);
- if (fw_fd >= 0) {
- if (!load_firmware(fw_fd, loading_fd, data_fd)) {
- LOG(INFO) << "firmware: copy success { '" << root << "', '" << uevent->firmware << "' }";
- } else {
- LOG(ERROR) << "firmware: copy failure { '" << root << "', '" << uevent->firmware << "' }";
- }
- break;
+ for (size_t i = 0; i < arraysize(firmware_dirs); i++) {
+ std::string file = android::base::StringPrintf("%s/%s", firmware_dirs[i], uevent->firmware);
+ android::base::unique_fd fw_fd(open(file.c_str(), O_RDONLY|O_CLOEXEC));
+ struct stat sb;
+ if (fw_fd != -1 && fstat(fw_fd, &sb) != -1) {
+ load_firmware(uevent, root, fw_fd, sb.st_size, loading_fd, data_fd);
+ return;
}
}
- if (fw_fd < 0) {
- if (booting) {
- /* If we're not fully booted, we may be missing
- * filesystems needed for firmware, wait and retry.
- */
- usleep(100000);
- booting = is_booting();
- goto try_loading_again;
- }
- PLOG(ERROR) << "firmware: could not open '" << uevent->firmware << "'";
- write(loading_fd, "-1", 2);
- goto data_close_out;
- }
- close(fw_fd);
-data_close_out:
- close(data_fd);
-loading_close_out:
- close(loading_fd);
-data_free_out:
- free(data);
-loading_free_out:
- free(loading);
-root_free_out:
- free(root);
+ if (booting) {
+ // If we're not fully booted, we may be missing
+ // filesystems needed for firmware, wait and retry.
+ std::this_thread::sleep_for(100ms);
+ booting = is_booting();
+ goto try_loading_again;
+ }
+
+ LOG(ERROR) << "firmware: could not find firmware for " << uevent->firmware;
+
+ // Write "-1" as our response to the kernel's firmware request, since we have nothing for it.
+ write(loading_fd, "-1", 2);
}
-static void handle_firmware_event(struct uevent *uevent)
-{
- pid_t pid;
+static void handle_firmware_event(uevent* uevent) {
+ if (strcmp(uevent->subsystem, "firmware")) return;
+ if (strcmp(uevent->action, "add")) return;
- if(strcmp(uevent->subsystem, "firmware"))
- return;
-
- if(strcmp(uevent->action, "add"))
- return;
-
- /* we fork, to avoid making large memory allocations in init proper */
- pid = fork();
- if (!pid) {
+ // Loading the firmware in a child means we can do that in parallel...
+ // (We ignore SIGCHLD rather than wait for our children.)
+ pid_t pid = fork();
+ if (pid == 0) {
+ Timer t;
process_firmware_event(uevent);
+ LOG(INFO) << "loading " << uevent->path << " took " << t.duration() << "s";
_exit(EXIT_SUCCESS);
- } else if (pid < 0) {
- PLOG(ERROR) << "could not fork to process firmware event";
+ } else if (pid == -1) {
+ PLOG(ERROR) << "could not fork to process firmware event for " << uevent->firmware;
}
}
@@ -1091,7 +1041,6 @@
LOG(INFO) << "Coldboot took " << t.duration() << "s.";
}
-int get_device_fd()
-{
+int get_device_fd() {
return device_fd;
}
diff --git a/init/init.cpp b/init/init.cpp
index 7c37d28..cbd46bf 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -18,6 +18,7 @@
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
+#include <inttypes.h>
#include <libgen.h>
#include <paths.h>
#include <signal.h>
@@ -67,6 +68,8 @@
#include "util.h"
#include "watchdogd.h"
+using android::base::StringPrintf;
+
struct selabel_handle *sehandle;
struct selabel_handle *sehandle_prop;
@@ -75,7 +78,7 @@
static char qemu[32];
std::string default_console = "/dev/console";
-static time_t process_needs_restart;
+static time_t process_needs_restart_at;
const char *ENV[32];
@@ -132,11 +135,10 @@
static void restart_processes()
{
- process_needs_restart = 0;
- ServiceManager::GetInstance().
- ForEachServiceWithFlags(SVC_RESTARTING, [] (Service* s) {
- s->RestartIfNeeded(process_needs_restart);
- });
+ process_needs_restart_at = 0;
+ ServiceManager::GetInstance().ForEachServiceWithFlags(SVC_RESTARTING, [](Service* s) {
+ s->RestartIfNeeded(&process_needs_restart_at);
+ });
}
void handle_control_message(const std::string& msg, const std::string& name) {
@@ -164,7 +166,7 @@
// Any longer than 1s is an unreasonable length of time to delay booting.
// If you're hitting this timeout, check that you didn't make your
// sepolicy regular expressions too expensive (http://b/19899875).
- if (wait_for_file(COLDBOOT_DONE, 1)) {
+ if (wait_for_file(COLDBOOT_DONE, 1s)) {
LOG(ERROR) << "Timed out waiting for " COLDBOOT_DONE;
}
@@ -268,15 +270,14 @@
if (for_emulator) {
// In the emulator, export any kernel option with the "ro.kernel." prefix.
- property_set(android::base::StringPrintf("ro.kernel.%s", key.c_str()).c_str(), value.c_str());
+ property_set(StringPrintf("ro.kernel.%s", key.c_str()).c_str(), value.c_str());
return;
}
if (key == "qemu") {
strlcpy(qemu, value.c_str(), sizeof(qemu));
} else if (android::base::StartsWith(key, "androidboot.")) {
- property_set(android::base::StringPrintf("ro.boot.%s", key.c_str() + 12).c_str(),
- value.c_str());
+ property_set(StringPrintf("ro.boot.%s", key.c_str() + 12).c_str(), value.c_str());
}
}
@@ -314,7 +315,7 @@
static void process_kernel_dt() {
static const char android_dir[] = "/proc/device-tree/firmware/android";
- std::string file_name = android::base::StringPrintf("%s/compatible", android_dir);
+ std::string file_name = StringPrintf("%s/compatible", android_dir);
std::string dt_file;
android::base::ReadFileToString(file_name, &dt_file);
@@ -332,12 +333,12 @@
continue;
}
- file_name = android::base::StringPrintf("%s/%s", android_dir, dp->d_name);
+ file_name = StringPrintf("%s/%s", android_dir, dp->d_name);
android::base::ReadFileToString(file_name, &dt_file);
std::replace(dt_file.begin(), dt_file.end(), ',', '.');
- std::string property_name = android::base::StringPrintf("ro.boot.%s", dp->d_name);
+ std::string property_name = StringPrintf("ro.boot.%s", dp->d_name);
property_set(property_name.c_str(), dt_file.c_str());
}
}
@@ -566,12 +567,14 @@
return watchdogd_main(argc, argv);
}
+ boot_clock::time_point start_time = boot_clock::now();
+
// Clear the umask.
umask(0);
add_environment("PATH", _PATH_DEFPATH);
- bool is_first_stage = (argc == 1) || (strcmp(argv[1], "--second-stage") != 0);
+ bool is_first_stage = (getenv("INIT_SECOND_STAGE") == nullptr);
// Don't expose the raw commandline to unprivileged processes.
chmod("/proc/cmdline", 0440);
@@ -596,32 +599,34 @@
// talk to the outside world...
InitKernelLogging(argv);
- if (is_first_stage) {
- LOG(INFO) << "init first stage started!";
+ LOG(INFO) << "init " << (is_first_stage ? "first" : "second") << " stage started!";
+ if (is_first_stage) {
// Mount devices defined in android.early.* kernel commandline
early_mount();
- // Set up SELinux, including loading the SELinux policy if we're in the kernel domain.
+ // Set up SELinux, loading the SELinux policy.
selinux_initialize(true);
- // If we're in the kernel domain, re-exec init to transition to the init domain now
+ // We're in the kernel domain, so re-exec init to transition to the init domain now
// that the SELinux policy has been loaded.
-
if (restorecon("/init") == -1) {
PLOG(ERROR) << "restorecon failed";
security_failure();
}
+
+ setenv("INIT_SECOND_STAGE", "true", 1);
+
+ uint64_t start_ns = start_time.time_since_epoch().count();
+ setenv("INIT_STARTED_AT", StringPrintf("%" PRIu64, start_ns).c_str(), 1);
+
char* path = argv[0];
- char* args[] = { path, const_cast<char*>("--second-stage"), nullptr };
+ char* args[] = { path, nullptr };
if (execv(path, args) == -1) {
PLOG(ERROR) << "execv(\"" << path << "\") failed";
security_failure();
}
-
} else {
- LOG(INFO) << "init second stage started!";
-
// Indicate that booting is in progress to background fw loaders, etc.
close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
@@ -636,7 +641,10 @@
// used by init as well as the current required properties.
export_kernel_boot_props();
- // Now set up SELinux for second stage
+ // Make the time that init started available for bootstat to log.
+ property_set("init.start", getenv("INIT_STARTED_AT"));
+
+ // Now set up SELinux for second stage.
selinux_initialize(false);
}
@@ -710,21 +718,22 @@
restart_processes();
}
- int timeout = -1;
- if (process_needs_restart) {
- timeout = (process_needs_restart - gettime()) * 1000;
- if (timeout < 0)
- timeout = 0;
+ // By default, sleep until something happens.
+ int epoll_timeout_ms = -1;
+
+ // If there's more work to do, wake up again immediately.
+ if (am.HasMoreCommands()) epoll_timeout_ms = 0;
+
+ // If there's a process that needs restarting, wake up in time for that.
+ if (process_needs_restart_at != 0) {
+ epoll_timeout_ms = (process_needs_restart_at - time(nullptr)) * 1000;
+ if (epoll_timeout_ms < 0) epoll_timeout_ms = 0;
}
- if (am.HasMoreCommands()) {
- timeout = 0;
- }
-
- bootchart_sample(&timeout);
+ bootchart_sample(&epoll_timeout_ms);
epoll_event ev;
- int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, timeout));
+ int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, epoll_timeout_ms));
if (nr == -1) {
PLOG(ERROR) << "epoll_wait failed";
} else if (nr == 1) {
diff --git a/init/init.h b/init/init.h
index 0019337..cfb3139 100644
--- a/init/init.h
+++ b/init/init.h
@@ -22,8 +22,6 @@
class Action;
class Service;
-#define COMMAND_RETRY_TIMEOUT 5
-
extern const char *ENV[32];
extern bool waiting_for_exec;
extern std::string default_console;
diff --git a/init/readme.txt b/init/readme.txt
index 500b1d8..7e9d21b 100644
--- a/init/readme.txt
+++ b/init/readme.txt
@@ -440,8 +440,16 @@
Init provides information about the services that it is responsible
for via the below properties.
+init.start
+ Time after boot in ns (via the CLOCK_BOOTTIME clock) at which the first
+ stage of init started.
+
init.svc.<name>
- State of a named service ("stopped", "stopping", "running", "restarting")
+ State of a named service ("stopped", "stopping", "running", "restarting")
+
+init.svc.<name>.start
+ Time after boot in ns (via the CLOCK_BOOTTIME clock) that the service was
+ most recently started.
Bootcharting
@@ -537,10 +545,10 @@
For quicker turnaround when working on init itself, use:
- mm -j
- m ramdisk-nodeps
- m bootimage-nodeps
- adb reboot bootloader
+ mm -j &&
+ m ramdisk-nodeps &&
+ m bootimage-nodeps &&
+ adb reboot bootloader &&
fastboot boot $ANDROID_PRODUCT_OUT/boot.img
Alternatively, use the emulator:
diff --git a/init/service.cpp b/init/service.cpp
index f093dd9..1f53a1b 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -17,6 +17,7 @@
#include "service.h"
#include <fcntl.h>
+#include <inttypes.h>
#include <linux/securebits.h>
#include <sched.h>
#include <sys/mount.h>
@@ -51,9 +52,6 @@
using android::base::StringPrintf;
using android::base::WriteStringToFile;
-#define CRITICAL_CRASH_THRESHOLD 4 // if we crash >4 times ...
-#define CRITICAL_CRASH_WINDOW (4*60) // ... in 4 minutes, goto recovery
-
static std::string ComputeContextFromExecutable(std::string& service_name,
const std::string& service_path) {
std::string computed_context;
@@ -154,8 +152,8 @@
Service::Service(const std::string& name, const std::string& classname,
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), namespace_flags_(0),
+ : name_(name), classname_(classname), flags_(0), pid_(0),
+ crash_count_(0), uid_(0), gid_(0), namespace_flags_(0),
seclabel_(""), ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0),
priority_(0), oom_score_adjust_(-1000), args_(args) {
onrestart_.InitSingleTrigger("onrestart");
@@ -168,7 +166,7 @@
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),
+ crash_count_(0), uid_(uid), gid_(gid),
supp_gids_(supp_gids), capabilities_(capabilities),
namespace_flags_(namespace_flags), seclabel_(seclabel),
ioprio_class_(IoSchedClass_NONE), ioprio_pri_(0), priority_(0),
@@ -190,6 +188,12 @@
}
property_set(prop_name.c_str(), new_state.c_str());
+
+ if (new_state == "running") {
+ prop_name += ".start";
+ uint64_t start_ns = time_started_.time_since_epoch().count();
+ property_set(prop_name.c_str(), StringPrintf("%" PRIu64, start_ns).c_str());
+ }
}
void Service::KillProcessGroup(int signal) {
@@ -274,20 +278,19 @@
return false;
}
- time_t now = gettime();
+ // If we crash > 4 times in 4 minutes, reboot into recovery.
+ boot_clock::time_point now = boot_clock::now();
if ((flags_ & SVC_CRITICAL) && !(flags_ & SVC_RESTART)) {
- if (time_crashed_ + CRITICAL_CRASH_WINDOW >= now) {
- if (++nr_crashed_ > CRITICAL_CRASH_THRESHOLD) {
- LOG(ERROR) << "critical process '" << name_ << "' exited "
- << CRITICAL_CRASH_THRESHOLD << " times in "
- << (CRITICAL_CRASH_WINDOW / 60) << " minutes; "
+ if (now < time_crashed_ + 4min) {
+ if (++crash_count_ > 4) {
+ LOG(ERROR) << "critical process '" << name_ << "' exited 4 times in 4 minutes; "
<< "rebooting into recovery mode";
android_reboot(ANDROID_RB_RESTART2, 0, "recovery");
return false;
}
} else {
time_crashed_ = now;
- nr_crashed_ = 1;
+ crash_count_ = 1;
}
}
@@ -553,7 +556,6 @@
// Starting a service removes it from the disabled or reset state and
// immediately takes it out of the restarting state if it was in there.
flags_ &= (~(SVC_DISABLED|SVC_RESTARTING|SVC_RESET|SVC_RESTART|SVC_DISABLED_START));
- time_started_ = 0;
// Running processes require no additional work --- if they're in the
// process of exiting, we've ensured that they will immediately restart
@@ -667,7 +669,7 @@
}
}
- time_started_ = gettime();
+ time_started_ = boot_clock::now();
pid_ = pid;
flags_ |= SVC_RUNNING;
@@ -731,18 +733,19 @@
} /* else: Service is restarting anyways. */
}
-void Service::RestartIfNeeded(time_t& process_needs_restart) {
- time_t next_start_time = time_started_ + 5;
-
- if (next_start_time <= gettime()) {
+void Service::RestartIfNeeded(time_t* process_needs_restart_at) {
+ boot_clock::time_point now = boot_clock::now();
+ boot_clock::time_point next_start = time_started_ + 5s;
+ if (now > next_start) {
flags_ &= (~SVC_RESTARTING);
Start();
return;
}
- if ((next_start_time < process_needs_restart) ||
- (process_needs_restart == 0)) {
- process_needs_restart = next_start_time;
+ time_t next_start_time_t = time(nullptr) +
+ time_t(std::chrono::duration_cast<std::chrono::seconds>(next_start - now).count());
+ if (next_start_time_t < *process_needs_restart_at || *process_needs_restart_at == 0) {
+ *process_needs_restart_at = next_start_time_t;
}
}
diff --git a/init/service.h b/init/service.h
index d9e8f57..013e65f 100644
--- a/init/service.h
+++ b/init/service.h
@@ -30,6 +30,7 @@
#include "descriptors.h"
#include "init_parser.h"
#include "keyword_map.h"
+#include "util.h"
#define SVC_DISABLED 0x001 // do not autostart with class
#define SVC_ONESHOT 0x002 // do not restart on exit
@@ -75,7 +76,7 @@
void Stop();
void Terminate();
void Restart();
- void RestartIfNeeded(time_t& process_needs_restart);
+ void RestartIfNeeded(time_t* process_needs_restart_at);
bool Reap();
void DumpState() const;
@@ -134,9 +135,9 @@
unsigned flags_;
pid_t pid_;
- time_t time_started_; // time of last start
- time_t time_crashed_; // first crash within inspection window
- int nr_crashed_; // number of times crashed within window
+ boot_clock::time_point time_started_; // time of last start
+ boot_clock::time_point time_crashed_; // first crash within inspection window
+ int crash_count_; // number of times crashed within window
uid_t uid_;
gid_t gid_;
diff --git a/init/util.cpp b/init/util.cpp
index ff46e4f..cb5a094 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -34,6 +34,8 @@
#include <sys/types.h>
#include <sys/un.h>
+#include <thread>
+
#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
@@ -258,16 +260,11 @@
return result;
}
-time_t gettime() {
- timespec now;
- clock_gettime(CLOCK_MONOTONIC, &now);
- return now.tv_sec;
-}
-
-uint64_t gettime_ns() {
- timespec now;
- clock_gettime(CLOCK_MONOTONIC, &now);
- return static_cast<uint64_t>(now.tv_sec) * UINT64_C(1000000000) + now.tv_nsec;
+boot_clock::time_point boot_clock::now() {
+ timespec ts;
+ clock_gettime(CLOCK_BOOTTIME, &ts);
+ return boot_clock::time_point(std::chrono::seconds(ts.tv_sec) +
+ std::chrono::nanoseconds(ts.tv_nsec));
}
int mkdir_recursive(const char *pathname, mode_t mode)
@@ -325,16 +322,15 @@
}
}
-int wait_for_file(const char *filename, int timeout)
-{
- struct stat info;
- uint64_t timeout_time_ns = gettime_ns() + timeout * UINT64_C(1000000000);
- int ret = -1;
+int wait_for_file(const char* filename, std::chrono::nanoseconds timeout) {
+ boot_clock::time_point timeout_time = boot_clock::now() + timeout;
+ while (boot_clock::now() < timeout_time) {
+ struct stat sb;
+ if (stat(filename, &sb) != -1) return 0;
- while (gettime_ns() < timeout_time_ns && ((ret = stat(filename, &info)) < 0))
- usleep(10000);
-
- return ret;
+ std::this_thread::sleep_for(10ms);
+ }
+ return -1;
}
void import_kernel_cmdline(bool in_qemu,
diff --git a/init/util.h b/init/util.h
index 12ab173..dccec04 100644
--- a/init/util.h
+++ b/init/util.h
@@ -20,11 +20,14 @@
#include <sys/stat.h>
#include <sys/types.h>
+#include <chrono>
#include <string>
#include <functional>
#define COLDBOOT_DONE "/dev/.coldboot_done"
+using namespace std::chrono_literals;
+
int create_socket(const char *name, int type, mode_t perm,
uid_t uid, gid_t gid, const char *socketcon);
int create_file(const char *path, int mode, mode_t perm,
@@ -33,27 +36,35 @@
bool read_file(const char* path, std::string* content);
int write_file(const char* path, const char* content);
-time_t gettime();
-uint64_t gettime_ns();
+// A std::chrono clock based on CLOCK_BOOTTIME.
+class boot_clock {
+ public:
+ typedef std::chrono::nanoseconds duration;
+ typedef std::chrono::time_point<boot_clock, duration> time_point;
+ static constexpr bool is_steady = true;
+
+ static time_point now();
+};
class Timer {
public:
- Timer() : t0(gettime_ns()) {
+ Timer() : start_(boot_clock::now()) {
}
double duration() {
- return static_cast<double>(gettime_ns() - t0) / 1000000000.0;
+ typedef std::chrono::duration<double> double_duration;
+ return std::chrono::duration_cast<double_duration>(boot_clock::now() - start_).count();
}
private:
- uint64_t t0;
+ boot_clock::time_point start_;
};
unsigned int decode_uid(const char *s);
int mkdir_recursive(const char *pathname, mode_t mode);
void sanitize(char *p);
-int wait_for_file(const char *filename, int timeout);
+int wait_for_file(const char *filename, std::chrono::nanoseconds timeout);
void import_kernel_cmdline(bool in_qemu,
const std::function<void(const std::string&, const std::string&, bool)>&);
int make_dir(const char *path, mode_t mode);
diff --git a/libappfuse/Android.bp b/libappfuse/Android.bp
index 8b46154..f729faf 100644
--- a/libappfuse/Android.bp
+++ b/libappfuse/Android.bp
@@ -15,12 +15,20 @@
name: "libappfuse",
defaults: ["libappfuse_defaults"],
export_include_dirs: ["include"],
- srcs: ["FuseBuffer.cc", "FuseBridgeLoop.cc"]
+ srcs: [
+ "FuseAppLoop.cc",
+ "FuseBuffer.cc",
+ "FuseBridgeLoop.cc",
+ ]
}
cc_test {
name: "libappfuse_test",
defaults: ["libappfuse_defaults"],
shared_libs: ["libappfuse"],
- srcs: ["tests/FuseBridgeLoopTest.cc", "tests/FuseBufferTest.cc"]
+ srcs: [
+ "tests/FuseAppLoopTest.cc",
+ "tests/FuseBridgeLoopTest.cc",
+ "tests/FuseBufferTest.cc",
+ ]
}
diff --git a/libappfuse/FuseAppLoop.cc b/libappfuse/FuseAppLoop.cc
new file mode 100644
index 0000000..a31880e
--- /dev/null
+++ b/libappfuse/FuseAppLoop.cc
@@ -0,0 +1,221 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseAppLoop.h"
+
+#include <sys/stat.h>
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+
+namespace android {
+namespace fuse {
+
+namespace {
+
+void HandleLookUp(FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+ // AppFuse does not support directory structure now.
+ // It can lookup only files under the mount point.
+ if (buffer->request.header.nodeid != FUSE_ROOT_ID) {
+ LOG(ERROR) << "Nodeid is not FUSE_ROOT_ID.";
+ buffer->response.Reset(0, -ENOENT, buffer->request.header.unique);
+ return;
+ }
+
+ // Ensure that the filename ends with 0.
+ const size_t filename_length =
+ buffer->request.header.len - sizeof(fuse_in_header);
+ if (buffer->request.lookup_name[filename_length - 1] != 0) {
+ LOG(ERROR) << "File name does not end with 0.";
+ buffer->response.Reset(0, -ENOENT, buffer->request.header.unique);
+ return;
+ }
+
+ const uint64_t inode =
+ static_cast<uint64_t>(atol(buffer->request.lookup_name));
+ if (inode == 0 || inode == LONG_MAX) {
+ LOG(ERROR) << "Invalid filename";
+ buffer->response.Reset(0, -ENOENT, buffer->request.header.unique);
+ return;
+ }
+
+ const int64_t size = callback->OnGetSize(inode);
+ if (size < 0) {
+ buffer->response.Reset(0, size, buffer->request.header.unique);
+ return;
+ }
+
+ buffer->response.Reset(sizeof(fuse_entry_out), 0,
+ buffer->request.header.unique);
+ buffer->response.entry_out.nodeid = inode;
+ buffer->response.entry_out.attr_valid = 10;
+ buffer->response.entry_out.entry_valid = 10;
+ buffer->response.entry_out.attr.ino = inode;
+ buffer->response.entry_out.attr.mode = S_IFREG | 0777;
+ buffer->response.entry_out.attr.size = size;
+}
+
+void HandleGetAttr(FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+ const uint64_t nodeid = buffer->request.header.nodeid;
+ int64_t size;
+ uint32_t mode;
+ if (nodeid == FUSE_ROOT_ID) {
+ size = 0;
+ mode = S_IFDIR | 0777;
+ } else {
+ size = callback->OnGetSize(buffer->request.header.nodeid);
+ if (size < 0) {
+ buffer->response.Reset(0, size, buffer->request.header.unique);
+ return;
+ }
+ mode = S_IFREG | 0777;
+ }
+
+ buffer->response.Reset(sizeof(fuse_attr_out), 0,
+ buffer->request.header.unique);
+ buffer->response.attr_out.attr_valid = 10;
+ buffer->response.attr_out.attr.ino = nodeid;
+ buffer->response.attr_out.attr.mode = mode;
+ buffer->response.attr_out.attr.size = size;
+}
+
+void HandleOpen(FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+ const int32_t file_handle = callback->OnOpen(buffer->request.header.nodeid);
+ if (file_handle < 0) {
+ buffer->response.Reset(0, file_handle, buffer->request.header.unique);
+ return;
+ }
+ buffer->response.Reset(sizeof(fuse_open_out), kFuseSuccess,
+ buffer->request.header.unique);
+ buffer->response.open_out.fh = file_handle;
+}
+
+void HandleFsync(FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+ buffer->response.Reset(0, callback->OnFsync(buffer->request.header.nodeid),
+ buffer->request.header.unique);
+}
+
+void HandleRelease(FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+ buffer->response.Reset(0, callback->OnRelease(buffer->request.header.nodeid),
+ buffer->request.header.unique);
+}
+
+void HandleRead(FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+ const uint64_t unique = buffer->request.header.unique;
+ const uint64_t nodeid = buffer->request.header.nodeid;
+ const uint64_t offset = buffer->request.read_in.offset;
+ const uint32_t size = buffer->request.read_in.size;
+
+ if (size > kFuseMaxRead) {
+ buffer->response.Reset(0, -EINVAL, buffer->request.header.unique);
+ return;
+ }
+
+ const int32_t read_size = callback->OnRead(nodeid, offset, size,
+ buffer->response.read_data);
+ if (read_size < 0) {
+ buffer->response.Reset(0, read_size, buffer->request.header.unique);
+ return;
+ }
+
+ buffer->response.ResetHeader(read_size, kFuseSuccess, unique);
+}
+
+void HandleWrite(FuseBuffer* buffer, FuseAppLoopCallback* callback) {
+ const uint64_t unique = buffer->request.header.unique;
+ const uint64_t nodeid = buffer->request.header.nodeid;
+ const uint64_t offset = buffer->request.write_in.offset;
+ const uint32_t size = buffer->request.write_in.size;
+
+ if (size > kFuseMaxWrite) {
+ buffer->response.Reset(0, -EINVAL, buffer->request.header.unique);
+ return;
+ }
+
+ const int32_t write_size = callback->OnWrite(nodeid, offset, size,
+ buffer->request.write_data);
+ if (write_size < 0) {
+ buffer->response.Reset(0, write_size, buffer->request.header.unique);
+ return;
+ }
+
+ buffer->response.Reset(sizeof(fuse_write_out), kFuseSuccess, unique);
+ buffer->response.write_out.size = write_size;
+}
+
+} // namespace
+
+bool StartFuseAppLoop(int raw_fd, FuseAppLoopCallback* callback) {
+ base::unique_fd fd(raw_fd);
+ FuseBuffer buffer;
+
+ LOG(DEBUG) << "Start fuse loop.";
+ while (callback->IsActive()) {
+ if (!buffer.request.Read(fd)) {
+ return false;
+ }
+
+ const uint32_t opcode = buffer.request.header.opcode;
+ LOG(VERBOSE) << "Read a fuse packet, opcode=" << opcode;
+ switch (opcode) {
+ case FUSE_FORGET:
+ // Do not reply to FUSE_FORGET.
+ continue;
+
+ case FUSE_LOOKUP:
+ HandleLookUp(&buffer, callback);
+ break;
+
+ case FUSE_GETATTR:
+ HandleGetAttr(&buffer, callback);
+ break;
+
+ case FUSE_OPEN:
+ HandleOpen(&buffer, callback);
+ break;
+
+ case FUSE_READ:
+ HandleRead(&buffer, callback);
+ break;
+
+ case FUSE_WRITE:
+ HandleWrite(&buffer, callback);
+ break;
+
+ case FUSE_RELEASE:
+ HandleRelease(&buffer, callback);
+ break;
+
+ case FUSE_FSYNC:
+ HandleFsync(&buffer, callback);
+ break;
+
+ default:
+ buffer.HandleNotImpl();
+ break;
+ }
+
+ if (!buffer.response.Write(fd)) {
+ LOG(ERROR) << "Failed to write a response to the device.";
+ return false;
+ }
+ }
+
+ return true;
+}
+
+} // namespace fuse
+} // namespace android
diff --git a/libappfuse/FuseBridgeLoop.cc b/libappfuse/FuseBridgeLoop.cc
index 332556d..acb963c 100644
--- a/libappfuse/FuseBridgeLoop.cc
+++ b/libappfuse/FuseBridgeLoop.cc
@@ -25,14 +25,15 @@
int raw_dev_fd, int raw_proxy_fd, FuseBridgeLoop::Callback* callback) {
base::unique_fd dev_fd(raw_dev_fd);
base::unique_fd proxy_fd(raw_proxy_fd);
+ fuse::FuseBuffer buffer;
LOG(DEBUG) << "Start fuse loop.";
while (true) {
- if (!buffer_.request.Read(dev_fd)) {
+ if (!buffer.request.Read(dev_fd)) {
return false;
}
- const uint32_t opcode = buffer_.request.header.opcode;
+ const uint32_t opcode = buffer.request.header.opcode;
LOG(VERBOSE) << "Read a fuse packet, opcode=" << opcode;
switch (opcode) {
case FUSE_FORGET:
@@ -45,27 +46,27 @@
case FUSE_READ:
case FUSE_WRITE:
case FUSE_RELEASE:
- case FUSE_FLUSH:
- if (!buffer_.request.Write(proxy_fd)) {
+ case FUSE_FSYNC:
+ if (!buffer.request.Write(proxy_fd)) {
LOG(ERROR) << "Failed to write a request to the proxy.";
return false;
}
- if (!buffer_.response.Read(proxy_fd)) {
+ if (!buffer.response.Read(proxy_fd)) {
LOG(ERROR) << "Failed to read a response from the proxy.";
return false;
}
break;
case FUSE_INIT:
- buffer_.HandleInit();
+ buffer.HandleInit();
break;
default:
- buffer_.HandleNotImpl();
+ buffer.HandleNotImpl();
break;
}
- if (!buffer_.response.Write(dev_fd)) {
+ if (!buffer.response.Write(dev_fd)) {
LOG(ERROR) << "Failed to write a response to the device.";
return false;
}
@@ -76,4 +77,12 @@
}
}
+namespace fuse {
+
+bool StartFuseBridgeLoop(
+ int raw_dev_fd, int raw_proxy_fd, FuseBridgeLoopCallback* callback) {
+ return FuseBridgeLoop().Start(raw_dev_fd, raw_proxy_fd, callback);
+}
+
+} // namespace fuse
} // namespace android
diff --git a/libappfuse/FuseBuffer.cc b/libappfuse/FuseBuffer.cc
index 45280a5..74fe756 100644
--- a/libappfuse/FuseBuffer.cc
+++ b/libappfuse/FuseBuffer.cc
@@ -21,15 +21,22 @@
#include <unistd.h>
#include <algorithm>
+#include <type_traits>
#include <android-base/logging.h>
#include <android-base/macros.h>
namespace android {
+namespace fuse {
-template <typename T, typename Header>
-bool FuseMessage<T, Header>::CheckHeaderLength() const {
- if (sizeof(Header) <= header.len && header.len <= sizeof(T)) {
+static_assert(
+ std::is_standard_layout<FuseBuffer>::value,
+ "FuseBuffer must be standard layout union.");
+
+template <typename T>
+bool FuseMessage<T>::CheckHeaderLength() const {
+ const auto& header = static_cast<const T*>(this)->header;
+ if (sizeof(header) <= header.len && header.len <= sizeof(T)) {
return true;
} else {
LOG(ERROR) << "Packet size is invalid=" << header.len;
@@ -37,27 +44,29 @@
}
}
-template <typename T, typename Header>
-bool FuseMessage<T, Header>::CheckResult(
+template <typename T>
+bool FuseMessage<T>::CheckResult(
int result, const char* operation_name) const {
+ const auto& header = static_cast<const T*>(this)->header;
if (result >= 0 && static_cast<uint32_t>(result) == header.len) {
return true;
} else {
PLOG(ERROR) << "Failed to " << operation_name
- << " a packet from FD. result=" << result << " header.len="
+ << " a packet. result=" << result << " header.len="
<< header.len;
return false;
}
}
-template <typename T, typename Header>
-bool FuseMessage<T, Header>::Read(int fd) {
+template <typename T>
+bool FuseMessage<T>::Read(int fd) {
const ssize_t result = TEMP_FAILURE_RETRY(::read(fd, this, sizeof(T)));
return CheckHeaderLength() && CheckResult(result, "read");
}
-template <typename T, typename Header>
-bool FuseMessage<T, Header>::Write(int fd) const {
+template <typename T>
+bool FuseMessage<T>::Write(int fd) const {
+ const auto& header = static_cast<const T*>(this)->header;
if (!CheckHeaderLength()) {
return false;
}
@@ -65,8 +74,16 @@
return CheckResult(result, "write");
}
-template struct FuseMessage<FuseRequest, fuse_in_header>;
-template struct FuseMessage<FuseResponse, fuse_out_header>;
+template class FuseMessage<FuseRequest>;
+template class FuseMessage<FuseResponse>;
+
+void FuseRequest::Reset(
+ uint32_t data_length, uint32_t opcode, uint64_t unique) {
+ memset(this, 0, sizeof(fuse_in_header) + data_length);
+ header.len = sizeof(fuse_in_header) + data_length;
+ header.opcode = opcode;
+ header.unique = unique;
+}
void FuseResponse::ResetHeader(
uint32_t data_length, int32_t error, uint64_t unique) {
@@ -133,4 +150,5 @@
response.Reset(0, -ENOSYS, unique);
}
+} // namespace fuse
} // namespace android
diff --git a/libappfuse/include/libappfuse/FuseAppLoop.h b/libappfuse/include/libappfuse/FuseAppLoop.h
new file mode 100644
index 0000000..c3edfcc
--- /dev/null
+++ b/libappfuse/include/libappfuse/FuseAppLoop.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specic language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef ANDROID_LIBAPPFUSE_FUSEAPPLOOP_H_
+#define ANDROID_LIBAPPFUSE_FUSEAPPLOOP_H_
+
+#include "libappfuse/FuseBuffer.h"
+
+namespace android {
+namespace fuse {
+
+class FuseAppLoopCallback {
+ public:
+ virtual bool IsActive() = 0;
+ virtual int64_t OnGetSize(uint64_t inode) = 0;
+ virtual int32_t OnFsync(uint64_t inode) = 0;
+ virtual int32_t OnWrite(
+ uint64_t inode, uint64_t offset, uint32_t size, const void* data) = 0;
+ virtual int32_t OnRead(
+ uint64_t inode, uint64_t offset, uint32_t size, void* data) = 0;
+ virtual int32_t OnOpen(uint64_t inode) = 0;
+ virtual int32_t OnRelease(uint64_t inode) = 0;
+ virtual ~FuseAppLoopCallback() = default;
+};
+
+bool StartFuseAppLoop(int fd, FuseAppLoopCallback* callback);
+
+} // namespace fuse
+} // namespace android
+
+#endif // ANDROID_LIBAPPFUSE_FUSEAPPLOOP_H_
diff --git a/libappfuse/include/libappfuse/FuseBridgeLoop.h b/libappfuse/include/libappfuse/FuseBridgeLoop.h
index 2006532..38043bc 100644
--- a/libappfuse/include/libappfuse/FuseBridgeLoop.h
+++ b/libappfuse/include/libappfuse/FuseBridgeLoop.h
@@ -21,7 +21,9 @@
namespace android {
-class FuseBridgeLoop {
+// TODO: Remove the class after switching to StartFuseBridgeLoop in the
+// framework code.
+class FuseBridgeLoop final {
public:
class Callback {
public:
@@ -30,11 +32,15 @@
};
bool Start(int dev_fd, int proxy_fd, Callback* callback);
-
- private:
- FuseBuffer buffer_;
};
+namespace fuse {
+
+class FuseBridgeLoopCallback : public FuseBridgeLoop::Callback {};
+bool StartFuseBridgeLoop(
+ int dev_fd, int proxy_fd, FuseBridgeLoopCallback* callback);
+
+} // namespace fuse
} // namespace android
#endif // ANDROID_LIBAPPFUSE_FUSEBRIDGELOOP_H_
diff --git a/libappfuse/include/libappfuse/FuseBuffer.h b/libappfuse/include/libappfuse/FuseBuffer.h
index 071b777..e7f620c 100644
--- a/libappfuse/include/libappfuse/FuseBuffer.h
+++ b/libappfuse/include/libappfuse/FuseBuffer.h
@@ -20,6 +20,7 @@
#include <linux/fuse.h>
namespace android {
+namespace fuse {
// The numbers came from sdcard.c.
// Maximum number of bytes to write/read in one request/one reply.
@@ -27,9 +28,9 @@
constexpr size_t kFuseMaxRead = 128 * 1024;
constexpr int32_t kFuseSuccess = 0;
-template<typename T, typename Header>
-struct FuseMessage {
- Header header;
+template<typename T>
+class FuseMessage {
+ public:
bool Read(int fd);
bool Write(int fd) const;
private:
@@ -37,33 +38,53 @@
bool CheckResult(int result, const char* operation_name) const;
};
-struct FuseRequest : public FuseMessage<FuseRequest, fuse_in_header> {
+// FuseRequest represents file operation requests from /dev/fuse. It starts
+// from fuse_in_header. The body layout depends on the operation code.
+struct FuseRequest : public FuseMessage<FuseRequest> {
+ fuse_in_header header;
union {
+ // for FUSE_WRITE
struct {
fuse_write_in write_in;
char write_data[kFuseMaxWrite];
};
+ // for FUSE_OPEN
fuse_open_in open_in;
+ // for FUSE_INIT
fuse_init_in init_in;
+ // for FUSE_READ
fuse_read_in read_in;
+ // for FUSE_LOOKUP
char lookup_name[0];
};
+ void Reset(uint32_t data_length, uint32_t opcode, uint64_t unique);
};
-struct FuseResponse : public FuseMessage<FuseResponse, fuse_out_header> {
+// FuseResponse represents file operation responses to /dev/fuse. It starts
+// from fuse_out_header. The body layout depends on the operation code.
+struct FuseResponse : public FuseMessage<FuseResponse> {
+ fuse_out_header header;
union {
+ // for FUSE_INIT
fuse_init_out init_out;
+ // for FUSE_LOOKUP
fuse_entry_out entry_out;
+ // for FUSE_GETATTR
fuse_attr_out attr_out;
+ // for FUSE_OPEN
fuse_open_out open_out;
+ // for FUSE_READ
char read_data[kFuseMaxRead];
+ // for FUSE_WRITE
fuse_write_out write_out;
};
void Reset(uint32_t data_length, int32_t error, uint64_t unique);
void ResetHeader(uint32_t data_length, int32_t error, uint64_t unique);
};
-union FuseBuffer {
+// To reduce memory usage, FuseBuffer shares the memory region for request and
+// response.
+union FuseBuffer final {
FuseRequest request;
FuseResponse response;
@@ -71,19 +92,7 @@
void HandleNotImpl();
};
-class FuseProxyLoop {
- class IFuseProxyLoopCallback {
- public:
- virtual void OnMount() = 0;
- virtual ~IFuseProxyLoopCallback() = default;
- };
-
- bool Start(int dev_fd, int proxy_fd, IFuseProxyLoopCallback* callback);
-
- private:
- FuseBuffer buffer_;
-};
-
+} // namespace fuse
} // namespace android
#endif // ANDROID_LIBAPPFUSE_FUSEBUFFER_H_
diff --git a/libappfuse/tests/FuseAppLoopTest.cc b/libappfuse/tests/FuseAppLoopTest.cc
new file mode 100644
index 0000000..25906cf
--- /dev/null
+++ b/libappfuse/tests/FuseAppLoopTest.cc
@@ -0,0 +1,307 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specic language governing permissions and
+ * limitations under the License.
+ */
+
+#include "libappfuse/FuseAppLoop.h"
+
+#include <sys/socket.h>
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+#include <gtest/gtest.h>
+#include <thread>
+
+namespace android {
+namespace fuse {
+namespace {
+
+constexpr unsigned int kTestFileSize = 1024;
+
+struct CallbackRequest {
+ uint32_t code;
+ uint64_t inode;
+};
+
+class Callback : public FuseAppLoopCallback {
+ public:
+ std::vector<CallbackRequest> requests;
+
+ bool IsActive() override {
+ return true;
+ }
+
+ int64_t OnGetSize(uint64_t inode) override {
+ if (inode == FUSE_ROOT_ID) {
+ return 0;
+ } else {
+ return kTestFileSize;
+ }
+ }
+
+ int32_t OnFsync(uint64_t inode) override {
+ requests.push_back({
+ .code = FUSE_FSYNC,
+ .inode = inode
+ });
+ return 0;
+ }
+
+ int32_t OnWrite(uint64_t inode,
+ uint64_t offset ATTRIBUTE_UNUSED,
+ uint32_t size ATTRIBUTE_UNUSED,
+ const void* data ATTRIBUTE_UNUSED) override {
+ requests.push_back({
+ .code = FUSE_WRITE,
+ .inode = inode
+ });
+ return 0;
+ }
+
+ int32_t OnRead(uint64_t inode,
+ uint64_t offset ATTRIBUTE_UNUSED,
+ uint32_t size ATTRIBUTE_UNUSED,
+ void* data ATTRIBUTE_UNUSED) override {
+ requests.push_back({
+ .code = FUSE_READ,
+ .inode = inode
+ });
+ return 0;
+ }
+
+ int32_t OnOpen(uint64_t inode) override {
+ requests.push_back({
+ .code = FUSE_OPEN,
+ .inode = inode
+ });
+ return 0;
+ }
+
+ int32_t OnRelease(uint64_t inode) override {
+ requests.push_back({
+ .code = FUSE_RELEASE,
+ .inode = inode
+ });
+ return 0;
+ }
+};
+
+class FuseAppLoopTest : public ::testing::Test {
+ private:
+ std::thread thread_;
+
+ protected:
+ base::unique_fd sockets_[2];
+ Callback callback_;
+ FuseRequest request_;
+ FuseResponse response_;
+
+ void SetUp() override {
+ base::SetMinimumLogSeverity(base::VERBOSE);
+ int sockets[2];
+ ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets));
+ sockets_[0].reset(sockets[0]);
+ sockets_[1].reset(sockets[1]);
+ thread_ = std::thread([this] {
+ StartFuseAppLoop(sockets_[1].release(), &callback_);
+ });
+ }
+
+ void CheckCallback(
+ size_t data_size, uint32_t code, size_t expected_out_size) {
+ request_.Reset(data_size, code, 1);
+ request_.header.nodeid = 10;
+
+ ASSERT_TRUE(request_.Write(sockets_[0]));
+ ASSERT_TRUE(response_.Read(sockets_[0]));
+
+ Close();
+
+ EXPECT_EQ(kFuseSuccess, response_.header.error);
+ EXPECT_EQ(sizeof(fuse_out_header) + expected_out_size,
+ response_.header.len);
+ EXPECT_EQ(1u, response_.header.unique);
+
+ ASSERT_EQ(1u, callback_.requests.size());
+ EXPECT_EQ(code, callback_.requests[0].code);
+ EXPECT_EQ(10u, callback_.requests[0].inode);
+ }
+
+ void Close() {
+ sockets_[0].reset();
+ sockets_[1].reset();
+ if (thread_.joinable()) {
+ thread_.join();
+ }
+ }
+
+ void TearDown() override {
+ Close();
+ }
+};
+
+} // namespace
+
+TEST_F(FuseAppLoopTest, LookUp) {
+ request_.Reset(3u, FUSE_LOOKUP, 1);
+ request_.header.nodeid = FUSE_ROOT_ID;
+ strcpy(request_.lookup_name, "10");
+
+ ASSERT_TRUE(request_.Write(sockets_[0].get()));
+ ASSERT_TRUE(response_.Read(sockets_[0].get()));
+
+ EXPECT_EQ(kFuseSuccess, response_.header.error);
+ EXPECT_EQ(sizeof(fuse_out_header) + sizeof(fuse_entry_out),
+ response_.header.len);
+ EXPECT_EQ(1u, response_.header.unique);
+
+ EXPECT_EQ(10u, response_.entry_out.nodeid);
+ EXPECT_EQ(0u, response_.entry_out.generation);
+ EXPECT_EQ(10u, response_.entry_out.entry_valid);
+ EXPECT_EQ(10u, response_.entry_out.attr_valid);
+ EXPECT_EQ(0u, response_.entry_out.entry_valid_nsec);
+ EXPECT_EQ(0u, response_.entry_out.attr_valid_nsec);
+
+ EXPECT_EQ(10u, response_.entry_out.attr.ino);
+ EXPECT_EQ(kTestFileSize, response_.entry_out.attr.size);
+ EXPECT_EQ(0u, response_.entry_out.attr.blocks);
+ EXPECT_EQ(0u, response_.entry_out.attr.atime);
+ EXPECT_EQ(0u, response_.entry_out.attr.mtime);
+ EXPECT_EQ(0u, response_.entry_out.attr.ctime);
+ EXPECT_EQ(0u, response_.entry_out.attr.atimensec);
+ EXPECT_EQ(0u, response_.entry_out.attr.mtimensec);
+ EXPECT_EQ(0u, response_.entry_out.attr.ctimensec);
+ EXPECT_EQ(S_IFREG | 0777u, response_.entry_out.attr.mode);
+ EXPECT_EQ(0u, response_.entry_out.attr.nlink);
+ EXPECT_EQ(0u, response_.entry_out.attr.uid);
+ EXPECT_EQ(0u, response_.entry_out.attr.gid);
+ EXPECT_EQ(0u, response_.entry_out.attr.rdev);
+ EXPECT_EQ(0u, response_.entry_out.attr.blksize);
+ EXPECT_EQ(0u, response_.entry_out.attr.padding);
+}
+
+TEST_F(FuseAppLoopTest, LookUp_InvalidName) {
+ request_.Reset(3u, FUSE_LOOKUP, 1);
+ request_.header.nodeid = FUSE_ROOT_ID;
+ strcpy(request_.lookup_name, "aa");
+
+ ASSERT_TRUE(request_.Write(sockets_[0].get()));
+ ASSERT_TRUE(response_.Read(sockets_[0].get()));
+
+ EXPECT_EQ(sizeof(fuse_out_header), response_.header.len);
+ EXPECT_EQ(-ENOENT, response_.header.error);
+ EXPECT_EQ(1u, response_.header.unique);
+}
+
+TEST_F(FuseAppLoopTest, LookUp_TooLargeName) {
+ request_.Reset(21u, FUSE_LOOKUP, 1);
+ request_.header.nodeid = FUSE_ROOT_ID;
+ strcpy(request_.lookup_name, "18446744073709551616");
+
+ ASSERT_TRUE(request_.Write(sockets_[0].get()));
+ ASSERT_TRUE(response_.Read(sockets_[0].get()));
+
+ EXPECT_EQ(sizeof(fuse_out_header), response_.header.len);
+ EXPECT_EQ(-ENOENT, response_.header.error);
+ EXPECT_EQ(1u, response_.header.unique);
+}
+
+TEST_F(FuseAppLoopTest, GetAttr) {
+ request_.Reset(sizeof(fuse_getattr_in), FUSE_GETATTR, 1);
+ request_.header.nodeid = 10;
+
+ ASSERT_TRUE(request_.Write(sockets_[0].get()));
+ ASSERT_TRUE(response_.Read(sockets_[0].get()));
+
+ EXPECT_EQ(kFuseSuccess, response_.header.error);
+ EXPECT_EQ(sizeof(fuse_out_header) + sizeof(fuse_attr_out),
+ response_.header.len);
+ EXPECT_EQ(1u, response_.header.unique);
+
+ EXPECT_EQ(10u, response_.attr_out.attr_valid);
+ EXPECT_EQ(0u, response_.attr_out.attr_valid_nsec);
+
+ EXPECT_EQ(10u, response_.attr_out.attr.ino);
+ EXPECT_EQ(kTestFileSize, response_.attr_out.attr.size);
+ EXPECT_EQ(0u, response_.attr_out.attr.blocks);
+ EXPECT_EQ(0u, response_.attr_out.attr.atime);
+ EXPECT_EQ(0u, response_.attr_out.attr.mtime);
+ EXPECT_EQ(0u, response_.attr_out.attr.ctime);
+ EXPECT_EQ(0u, response_.attr_out.attr.atimensec);
+ EXPECT_EQ(0u, response_.attr_out.attr.mtimensec);
+ EXPECT_EQ(0u, response_.attr_out.attr.ctimensec);
+ EXPECT_EQ(S_IFREG | 0777u, response_.attr_out.attr.mode);
+ EXPECT_EQ(0u, response_.attr_out.attr.nlink);
+ EXPECT_EQ(0u, response_.attr_out.attr.uid);
+ EXPECT_EQ(0u, response_.attr_out.attr.gid);
+ EXPECT_EQ(0u, response_.attr_out.attr.rdev);
+ EXPECT_EQ(0u, response_.attr_out.attr.blksize);
+ EXPECT_EQ(0u, response_.attr_out.attr.padding);
+}
+
+TEST_F(FuseAppLoopTest, GetAttr_Root) {
+ request_.Reset(sizeof(fuse_getattr_in), FUSE_GETATTR, 1);
+ request_.header.nodeid = FUSE_ROOT_ID;
+
+ ASSERT_TRUE(request_.Write(sockets_[0].get()));
+ ASSERT_TRUE(response_.Read(sockets_[0].get()));
+
+ EXPECT_EQ(kFuseSuccess, response_.header.error);
+ EXPECT_EQ(sizeof(fuse_out_header) + sizeof(fuse_attr_out),
+ response_.header.len);
+ EXPECT_EQ(1u, response_.header.unique);
+
+ EXPECT_EQ(10u, response_.attr_out.attr_valid);
+ EXPECT_EQ(0u, response_.attr_out.attr_valid_nsec);
+
+ EXPECT_EQ(static_cast<unsigned>(FUSE_ROOT_ID), response_.attr_out.attr.ino);
+ EXPECT_EQ(0u, response_.attr_out.attr.size);
+ EXPECT_EQ(0u, response_.attr_out.attr.blocks);
+ EXPECT_EQ(0u, response_.attr_out.attr.atime);
+ EXPECT_EQ(0u, response_.attr_out.attr.mtime);
+ EXPECT_EQ(0u, response_.attr_out.attr.ctime);
+ EXPECT_EQ(0u, response_.attr_out.attr.atimensec);
+ EXPECT_EQ(0u, response_.attr_out.attr.mtimensec);
+ EXPECT_EQ(0u, response_.attr_out.attr.ctimensec);
+ EXPECT_EQ(S_IFDIR | 0777u, response_.attr_out.attr.mode);
+ EXPECT_EQ(0u, response_.attr_out.attr.nlink);
+ EXPECT_EQ(0u, response_.attr_out.attr.uid);
+ EXPECT_EQ(0u, response_.attr_out.attr.gid);
+ EXPECT_EQ(0u, response_.attr_out.attr.rdev);
+ EXPECT_EQ(0u, response_.attr_out.attr.blksize);
+ EXPECT_EQ(0u, response_.attr_out.attr.padding);
+}
+
+TEST_F(FuseAppLoopTest, Open) {
+ CheckCallback(sizeof(fuse_open_in), FUSE_OPEN, sizeof(fuse_open_out));
+}
+
+TEST_F(FuseAppLoopTest, Fsync) {
+ CheckCallback(0u, FUSE_FSYNC, 0u);
+}
+
+TEST_F(FuseAppLoopTest, Release) {
+ CheckCallback(0u, FUSE_RELEASE, 0u);
+}
+
+TEST_F(FuseAppLoopTest, Read) {
+ CheckCallback(sizeof(fuse_read_in), FUSE_READ, 0u);
+}
+
+TEST_F(FuseAppLoopTest, Write) {
+ CheckCallback(sizeof(fuse_write_in), FUSE_WRITE, sizeof(fuse_write_out));
+}
+
+} // namespace fuse
+} // namespace android
diff --git a/libappfuse/tests/FuseBridgeLoopTest.cc b/libappfuse/tests/FuseBridgeLoopTest.cc
index 31e3690..bd503eb 100644
--- a/libappfuse/tests/FuseBridgeLoopTest.cc
+++ b/libappfuse/tests/FuseBridgeLoopTest.cc
@@ -21,11 +21,15 @@
#include <sstream>
#include <thread>
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
#include <gtest/gtest.h>
namespace android {
+namespace fuse {
+namespace {
-class Callback : public FuseBridgeLoop::Callback {
+class Callback : public FuseBridgeLoopCallback {
public:
bool mounted;
Callback() : mounted(false) {}
@@ -36,20 +40,28 @@
class FuseBridgeLoopTest : public ::testing::Test {
protected:
- int dev_sockets_[2];
- int proxy_sockets_[2];
+ base::unique_fd dev_sockets_[2];
+ base::unique_fd proxy_sockets_[2];
Callback callback_;
std::thread thread_;
FuseRequest request_;
FuseResponse response_;
- void SetUp() {
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, dev_sockets_));
- ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, proxy_sockets_));
+ void SetUp() override {
+ base::SetMinimumLogSeverity(base::VERBOSE);
+ int dev_sockets[2];
+ int proxy_sockets[2];
+ ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, dev_sockets));
+ ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_SEQPACKET, 0, proxy_sockets));
+ dev_sockets_[0].reset(dev_sockets[0]);
+ dev_sockets_[1].reset(dev_sockets[1]);
+ proxy_sockets_[0].reset(proxy_sockets[0]);
+ proxy_sockets_[1].reset(proxy_sockets[1]);
+
thread_ = std::thread([this] {
- FuseBridgeLoop loop;
- loop.Start(dev_sockets_[1], proxy_sockets_[0], &callback_);
+ StartFuseBridgeLoop(
+ dev_sockets_[1].release(), proxy_sockets_[0].release(), &callback_);
});
}
@@ -103,20 +115,22 @@
}
void Close() {
- close(dev_sockets_[0]);
- close(dev_sockets_[1]);
- close(proxy_sockets_[0]);
- close(proxy_sockets_[1]);
+ dev_sockets_[0].reset();
+ dev_sockets_[1].reset();
+ proxy_sockets_[0].reset();
+ proxy_sockets_[1].reset();
if (thread_.joinable()) {
thread_.join();
}
}
- void TearDown() {
+ void TearDown() override {
Close();
}
};
+} // namespace
+
TEST_F(FuseBridgeLoopTest, FuseInit) {
SendInitRequest(1u);
@@ -156,11 +170,11 @@
CheckNotImpl(FUSE_RENAME);
CheckNotImpl(FUSE_LINK);
CheckNotImpl(FUSE_STATFS);
- CheckNotImpl(FUSE_FSYNC);
CheckNotImpl(FUSE_SETXATTR);
CheckNotImpl(FUSE_GETXATTR);
CheckNotImpl(FUSE_LISTXATTR);
CheckNotImpl(FUSE_REMOVEXATTR);
+ CheckNotImpl(FUSE_FLUSH);
CheckNotImpl(FUSE_OPENDIR);
CheckNotImpl(FUSE_READDIR);
CheckNotImpl(FUSE_RELEASEDIR);
@@ -190,7 +204,8 @@
CheckProxy(FUSE_READ);
CheckProxy(FUSE_WRITE);
CheckProxy(FUSE_RELEASE);
- CheckProxy(FUSE_FLUSH);
+ CheckProxy(FUSE_FSYNC);
}
-} // android
+} // namespace fuse
+} // namespace android
diff --git a/libappfuse/tests/FuseBufferTest.cc b/libappfuse/tests/FuseBufferTest.cc
index 1aacfe3..17f1306 100644
--- a/libappfuse/tests/FuseBufferTest.cc
+++ b/libappfuse/tests/FuseBufferTest.cc
@@ -24,6 +24,7 @@
#include <gtest/gtest.h>
namespace android {
+namespace fuse {
constexpr char kTempFile[] = "/data/local/tmp/appfuse_test_dump";
@@ -183,5 +184,6 @@
ASSERT_EQ(sizeof(fuse_out_header), buffer.response.header.len);
EXPECT_EQ(-ENOSYS, buffer.response.header.error);
}
-}
- // namespace android
+
+} // namespace fuse
+} // namespace android
diff --git a/libbacktrace/BacktracePtrace.cpp b/libbacktrace/BacktracePtrace.cpp
index 148c418..fd8b713 100644
--- a/libbacktrace/BacktracePtrace.cpp
+++ b/libbacktrace/BacktracePtrace.cpp
@@ -17,7 +17,6 @@
#include <errno.h>
#include <stdint.h>
#include <string.h>
-#include <sys/uio.h>
#include <sys/param.h>
#include <sys/ptrace.h>
#include <sys/types.h>
@@ -73,20 +72,42 @@
if (!BacktraceMap::IsValid(map) || !(map.flags & PROT_READ)) {
return 0;
}
+
bytes = MIN(map.end - addr, bytes);
-
- struct iovec local_io;
- local_io.iov_base = buffer;
- local_io.iov_len = bytes;
-
- struct iovec remote_io;
- remote_io.iov_base = reinterpret_cast<void*>(addr);
- remote_io.iov_len = bytes;
-
- ssize_t bytes_read = process_vm_readv(Tid(), &local_io, 1, &remote_io, 1, 0);
- if (bytes_read == -1) {
- return 0;
+ size_t bytes_read = 0;
+ word_t data_word;
+ size_t align_bytes = addr & (sizeof(word_t) - 1);
+ if (align_bytes != 0) {
+ if (!PtraceRead(Tid(), addr & ~(sizeof(word_t) - 1), &data_word)) {
+ return 0;
+ }
+ size_t copy_bytes = MIN(sizeof(word_t) - align_bytes, bytes);
+ memcpy(buffer, reinterpret_cast<uint8_t*>(&data_word) + align_bytes, copy_bytes);
+ addr += copy_bytes;
+ buffer += copy_bytes;
+ bytes -= copy_bytes;
+ bytes_read += copy_bytes;
}
- return static_cast<size_t>(bytes_read);
+
+ size_t num_words = bytes / sizeof(word_t);
+ for (size_t i = 0; i < num_words; i++) {
+ if (!PtraceRead(Tid(), addr, &data_word)) {
+ return bytes_read;
+ }
+ memcpy(buffer, &data_word, sizeof(word_t));
+ buffer += sizeof(word_t);
+ addr += sizeof(word_t);
+ bytes_read += sizeof(word_t);
+ }
+
+ size_t left_over = bytes & (sizeof(word_t) - 1);
+ if (left_over) {
+ if (!PtraceRead(Tid(), addr, &data_word)) {
+ return bytes_read;
+ }
+ memcpy(buffer, &data_word, left_over);
+ bytes_read += left_over;
+ }
+ return bytes_read;
#endif
}
diff --git a/libprocessgroup/processgroup.cpp b/libprocessgroup/processgroup.cpp
index 7c15429..eb66727 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -31,12 +31,15 @@
#include <chrono>
#include <memory>
#include <mutex>
+#include <thread>
#include <android-base/logging.h>
#include <private/android_filesystem_config.h>
#include <processgroup/processgroup.h>
+using namespace std::chrono_literals;
+
// Uncomment line below use memory cgroups for keeping track of (forked) PIDs
// #define USE_MEMCG 1
@@ -288,7 +291,7 @@
while ((processes = killProcessGroupOnce(uid, initialPid, signal)) > 0) {
LOG(VERBOSE) << "killed " << processes << " processes for processgroup " << initialPid;
if (retry > 0) {
- usleep(5 * 1000); // 5ms
+ std::this_thread::sleep_for(5ms);
--retry;
} else {
LOG(ERROR) << "failed to kill " << processes << " processes for processgroup "
diff --git a/libprocinfo/.clang-format b/libprocinfo/.clang-format
new file mode 100644
index 0000000..b8c6428
--- /dev/null
+++ b/libprocinfo/.clang-format
@@ -0,0 +1,14 @@
+BasedOnStyle: Google
+AllowShortBlocksOnASingleLine: false
+AllowShortFunctionsOnASingleLine: false
+
+ColumnLimit: 100
+CommentPragmas: NOLINT:.*
+DerivePointerAlignment: false
+IndentWidth: 2
+PointerAlignment: Left
+TabWidth: 2
+UseTab: Never
+PenaltyExcessCharacter: 32
+
+Cpp11BracedListStyle: false
diff --git a/libprocinfo/Android.bp b/libprocinfo/Android.bp
new file mode 100644
index 0000000..8e17f1b
--- /dev/null
+++ b/libprocinfo/Android.bp
@@ -0,0 +1,73 @@
+//
+// Copyright (C) 2015 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+libprocinfo_cppflags = [
+ "-Wall",
+ "-Wextra",
+ "-Werror",
+]
+
+cc_library {
+ name: "libprocinfo",
+ host_supported: true,
+ srcs: [
+ "process.cpp",
+ ],
+ cppflags: libprocinfo_cppflags,
+
+ local_include_dirs: ["include"],
+ export_include_dirs: ["include"],
+ shared_libs: ["libbase"],
+ target: {
+ darwin: {
+ enabled: false,
+ },
+ windows: {
+ enabled: false,
+ },
+ },
+}
+
+// Tests
+// ------------------------------------------------------------------------------
+cc_test {
+ name: "libprocinfo_test",
+ host_supported: true,
+ srcs: [
+ "process_test.cpp",
+ ],
+ target: {
+ darwin: {
+ enabled: false,
+ },
+ windows: {
+ enabled: false,
+ },
+ },
+
+ cppflags: libprocinfo_cppflags,
+ shared_libs: ["libbase", "libprocinfo"],
+
+ compile_multilib: "both",
+ multilib: {
+ lib32: {
+ suffix: "32",
+ },
+ lib64: {
+ suffix: "64",
+ },
+ },
+}
diff --git a/libprocinfo/include/procinfo/process.h b/libprocinfo/include/procinfo/process.h
new file mode 100644
index 0000000..fb140ff
--- /dev/null
+++ b/libprocinfo/include/procinfo/process.h
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <dirent.h>
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <memory>
+#include <string>
+#include <type_traits>
+
+#include <android-base/logging.h>
+#include <android-base/parseint.h>
+#include <android-base/unique_fd.h>
+
+namespace android {
+namespace procinfo {
+
+#if defined(__linux__)
+
+struct ProcessInfo {
+ std::string name;
+ pid_t tid;
+ pid_t pid;
+ pid_t ppid;
+ pid_t tracer;
+ uid_t uid;
+ uid_t gid;
+};
+
+// Parse the contents of /proc/<tid>/status into |process_info|.
+bool GetProcessInfo(pid_t tid, ProcessInfo* process_info);
+
+// Parse the contents of <fd>/status into |process_info|.
+// |fd| should be an fd pointing at a /proc/<pid> directory.
+bool GetProcessInfoFromProcPidFd(int fd, ProcessInfo* process_info);
+
+// Fetch the list of threads from a given process's /proc/<pid> directory.
+// |fd| should be an fd pointing at a /proc/<pid> directory.
+template <typename Collection>
+auto GetProcessTidsFromProcPidFd(int fd, Collection* out) ->
+ typename std::enable_if<sizeof(typename Collection::value_type) >= sizeof(pid_t), bool>::type {
+ out->clear();
+
+ int task_fd = openat(fd, "task", O_DIRECTORY | O_RDONLY | O_CLOEXEC);
+ std::unique_ptr<DIR, int (*)(DIR*)> dir(fdopendir(task_fd), closedir);
+ if (!dir) {
+ PLOG(ERROR) << "failed to open task directory";
+ return false;
+ }
+
+ struct dirent* dent;
+ while ((dent = readdir(dir.get()))) {
+ if (strcmp(dent->d_name, ".") != 0 && strcmp(dent->d_name, "..") != 0) {
+ pid_t tid;
+ if (!android::base::ParseInt(dent->d_name, &tid, 1, std::numeric_limits<pid_t>::max())) {
+ LOG(ERROR) << "failed to parse task id: " << dent->d_name;
+ return false;
+ }
+
+ out->insert(out->end(), tid);
+ }
+ }
+
+ return true;
+}
+
+template <typename Collection>
+auto GetProcessTids(pid_t pid, Collection* out) ->
+ typename std::enable_if<sizeof(typename Collection::value_type) >= sizeof(pid_t), bool>::type {
+ char task_path[PATH_MAX];
+ if (snprintf(task_path, PATH_MAX, "/proc/%d", pid) >= PATH_MAX) {
+ LOG(ERROR) << "task path overflow (pid = " << pid << ")";
+ return false;
+ }
+
+ android::base::unique_fd fd(open(task_path, O_DIRECTORY | O_RDONLY | O_CLOEXEC));
+ if (fd == -1) {
+ PLOG(ERROR) << "failed to open " << task_path;
+ return false;
+ }
+
+ return GetProcessTidsFromProcPidFd(fd.get(), out);
+}
+
+#endif
+
+} /* namespace procinfo */
+} /* namespace android */
diff --git a/libprocinfo/process.cpp b/libprocinfo/process.cpp
new file mode 100644
index 0000000..c513e16
--- /dev/null
+++ b/libprocinfo/process.cpp
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <procinfo/process.h>
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include <string>
+
+#include <android-base/unique_fd.h>
+
+using android::base::unique_fd;
+
+namespace android {
+namespace procinfo {
+
+bool GetProcessInfo(pid_t tid, ProcessInfo* process_info) {
+ char path[PATH_MAX];
+ snprintf(path, sizeof(path), "/proc/%d", tid);
+
+ unique_fd dirfd(open(path, O_DIRECTORY | O_RDONLY));
+ if (dirfd == -1) {
+ PLOG(ERROR) << "failed to open " << path;
+ return false;
+ }
+
+ return GetProcessInfoFromProcPidFd(dirfd.get(), process_info);
+}
+
+bool GetProcessInfoFromProcPidFd(int fd, ProcessInfo* process_info) {
+ int status_fd = openat(fd, "status", O_RDONLY | O_CLOEXEC);
+
+ if (status_fd == -1) {
+ PLOG(ERROR) << "failed to open status fd in GetProcessInfoFromProcPidFd";
+ return false;
+ }
+
+ std::unique_ptr<FILE, decltype(&fclose)> fp(fdopen(status_fd, "r"), fclose);
+ if (!fp) {
+ PLOG(ERROR) << "failed to open status file in GetProcessInfoFromProcPidFd";
+ close(status_fd);
+ return false;
+ }
+
+ int field_bitmap = 0;
+ static constexpr int finished_bitmap = 127;
+ char* line = nullptr;
+ size_t len = 0;
+
+ while (getline(&line, &len, fp.get()) != -1 && field_bitmap != finished_bitmap) {
+ char* tab = strchr(line, '\t');
+ if (tab == nullptr) {
+ continue;
+ }
+
+ size_t header_len = tab - line;
+ std::string header = std::string(line, header_len);
+ if (header == "Name:") {
+ std::string name = line + header_len + 1;
+
+ // line includes the trailing newline.
+ name.pop_back();
+ process_info->name = std::move(name);
+
+ field_bitmap |= 1;
+ } else if (header == "Pid:") {
+ process_info->tid = atoi(tab + 1);
+ field_bitmap |= 2;
+ } else if (header == "Tgid:") {
+ process_info->pid = atoi(tab + 1);
+ field_bitmap |= 4;
+ } else if (header == "PPid:") {
+ process_info->ppid = atoi(tab + 1);
+ field_bitmap |= 8;
+ } else if (header == "TracerPid:") {
+ process_info->tracer = atoi(tab + 1);
+ field_bitmap |= 16;
+ } else if (header == "Uid:") {
+ process_info->uid = atoi(tab + 1);
+ field_bitmap |= 32;
+ } else if (header == "Gid:") {
+ process_info->gid = atoi(tab + 1);
+ field_bitmap |= 64;
+ }
+ }
+
+ free(line);
+ return field_bitmap == finished_bitmap;
+}
+
+} /* namespace procinfo */
+} /* namespace android */
diff --git a/libprocinfo/process_test.cpp b/libprocinfo/process_test.cpp
new file mode 100644
index 0000000..5ffd236
--- /dev/null
+++ b/libprocinfo/process_test.cpp
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <procinfo/process.h>
+
+#include <fcntl.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <set>
+#include <thread>
+#include <vector>
+
+#include <gtest/gtest.h>
+
+#include <android-base/stringprintf.h>
+
+#if !defined(__BIONIC__)
+#include <syscall.h>
+static pid_t gettid() {
+ return syscall(__NR_gettid);
+}
+#endif
+
+TEST(process_info, process_info_smoke) {
+ android::procinfo::ProcessInfo self;
+ ASSERT_TRUE(android::procinfo::GetProcessInfo(gettid(), &self));
+ ASSERT_EQ(gettid(), self.tid);
+ ASSERT_EQ(getpid(), self.pid);
+ ASSERT_EQ(getppid(), self.ppid);
+ ASSERT_EQ(getuid(), self.uid);
+ ASSERT_EQ(getgid(), self.gid);
+}
+
+TEST(process_info, process_info_proc_pid_fd_smoke) {
+ android::procinfo::ProcessInfo self;
+ int fd = open(android::base::StringPrintf("/proc/%d", gettid()).c_str(), O_DIRECTORY | O_RDONLY);
+ ASSERT_NE(-1, fd);
+ ASSERT_TRUE(android::procinfo::GetProcessInfoFromProcPidFd(fd, &self));
+
+ // Process name is capped at 15 bytes.
+ ASSERT_EQ("libprocinfo_tes", self.name);
+ ASSERT_EQ(gettid(), self.tid);
+ ASSERT_EQ(getpid(), self.pid);
+ ASSERT_EQ(getppid(), self.ppid);
+ ASSERT_EQ(getuid(), self.uid);
+ ASSERT_EQ(getgid(), self.gid);
+ close(fd);
+}
+
+TEST(process_info, process_tids_smoke) {
+ pid_t main_tid = gettid();
+ std::thread([main_tid]() {
+ pid_t thread_tid = gettid();
+
+ {
+ std::vector<pid_t> vec;
+ ASSERT_TRUE(android::procinfo::GetProcessTids(getpid(), &vec));
+ ASSERT_EQ(1, std::count(vec.begin(), vec.end(), main_tid));
+ ASSERT_EQ(1, std::count(vec.begin(), vec.end(), thread_tid));
+ }
+
+ {
+ std::set<pid_t> set;
+ ASSERT_TRUE(android::procinfo::GetProcessTids(getpid(), &set));
+ ASSERT_EQ(1, std::count(set.begin(), set.end(), main_tid));
+ ASSERT_EQ(1, std::count(set.begin(), set.end(), thread_tid));
+ }
+ }).join();
+}