Merge "adbd: move jdwp listening logic into ART."
diff --git a/adb/daemon/usb.cpp b/adb/daemon/usb.cpp
index 1abae87..f4aa9fb 100644
--- a/adb/daemon/usb.cpp
+++ b/adb/daemon/usb.cpp
@@ -509,14 +509,16 @@
}
if (id.direction == TransferDirection::READ) {
- HandleRead(id, event.res);
+ if (!HandleRead(id, event.res)) {
+ return;
+ }
} else {
HandleWrite(id);
}
}
}
- void HandleRead(TransferId id, int64_t size) {
+ bool HandleRead(TransferId id, int64_t size) {
uint64_t read_idx = id.id % kUsbReadQueueDepth;
IoBlock* block = &read_requests_[read_idx];
block->pending = false;
@@ -526,7 +528,7 @@
if (block->id().id != needed_read_id_) {
LOG(VERBOSE) << "read " << block->id().id << " completed while waiting for "
<< needed_read_id_;
- return;
+ return true;
}
for (uint64_t id = needed_read_id_;; ++id) {
@@ -535,15 +537,22 @@
if (current_block->pending) {
break;
}
- ProcessRead(current_block);
+ if (!ProcessRead(current_block)) {
+ return false;
+ }
++needed_read_id_;
}
+
+ return true;
}
- void ProcessRead(IoBlock* block) {
+ bool ProcessRead(IoBlock* block) {
if (!block->payload->empty()) {
if (!incoming_header_.has_value()) {
- CHECK_EQ(sizeof(amessage), block->payload->size());
+ if (block->payload->size() != sizeof(amessage)) {
+ HandleError("received packet of unexpected length while reading header");
+ return false;
+ }
amessage msg;
memcpy(&msg, block->payload->data(), sizeof(amessage));
LOG(DEBUG) << "USB read:" << dump_header(&msg);
@@ -551,7 +560,10 @@
} else {
size_t bytes_left = incoming_header_->data_length - incoming_payload_.size();
Block payload = std::move(*block->payload);
- CHECK_LE(payload.size(), bytes_left);
+ if (block->payload->size() > bytes_left) {
+ HandleError("received too many bytes while waiting for payload");
+ return false;
+ }
incoming_payload_.append(std::make_unique<Block>(std::move(payload)));
}
@@ -570,6 +582,7 @@
PrepareReadBlock(block, block->id().id + kUsbReadQueueDepth);
SubmitRead(block);
+ return true;
}
bool SubmitRead(IoBlock* block) {
diff --git a/base/include/android-base/expected.h b/base/include/android-base/expected.h
index 08c9fb5..957a8a0 100644
--- a/base/include/android-base/expected.h
+++ b/base/include/android-base/expected.h
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+#pragma once
+
#include <algorithm>
#include <initializer_list>
#include <type_traits>
diff --git a/bootstat/bootstat.cpp b/bootstat/bootstat.cpp
index c7be00b..6936cc2 100644
--- a/bootstat/bootstat.cpp
+++ b/bootstat/bootstat.cpp
@@ -310,6 +310,7 @@
{"shutdown,userrequested,fastboot", 181},
{"shutdown,userrequested,recovery", 182},
{"reboot,unknown[0-9]*", 183},
+ {"reboot,longkey,.*", 184},
};
// Converts a string value representing the reason the system booted to an
diff --git a/debuggerd/debuggerd_test.cpp b/debuggerd/debuggerd_test.cpp
index 64df53e..1f0e420 100644
--- a/debuggerd/debuggerd_test.cpp
+++ b/debuggerd/debuggerd_test.cpp
@@ -243,9 +243,10 @@
void CrasherTest::AssertDeath(int signo) {
int status;
- pid_t pid = TIMEOUT(5, waitpid(crasher_pid, &status, 0));
+ pid_t pid = TIMEOUT(10, waitpid(crasher_pid, &status, 0));
if (pid != crasher_pid) {
- printf("failed to wait for crasher (pid %d)\n", crasher_pid);
+ printf("failed to wait for crasher (expected pid %d, return value %d): %s\n", crasher_pid, pid,
+ strerror(errno));
sleep(100);
FAIL() << "failed to wait for crasher: " << strerror(errno);
}
diff --git a/fs_mgr/Android.bp b/fs_mgr/Android.bp
index ffde114..3d3503c 100644
--- a/fs_mgr/Android.bp
+++ b/fs_mgr/Android.bp
@@ -35,6 +35,7 @@
export_include_dirs: ["include"],
include_dirs: ["system/vold"],
srcs: [
+ "file_wait.cpp",
"fs_mgr.cpp",
"fs_mgr_format.cpp",
"fs_mgr_verity.cpp",
diff --git a/fs_mgr/file_wait.cpp b/fs_mgr/file_wait.cpp
new file mode 100644
index 0000000..cbf6845
--- /dev/null
+++ b/fs_mgr/file_wait.cpp
@@ -0,0 +1,235 @@
+// Copyright (C) 2019 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 <fs_mgr/file_wait.h>
+
+#include <limits.h>
+#if defined(__linux__)
+#include <poll.h>
+#include <sys/inotify.h>
+#endif
+#if defined(WIN32)
+#include <io.h>
+#else
+#include <unistd.h>
+#endif
+
+#include <functional>
+#include <thread>
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+
+namespace android {
+namespace fs_mgr {
+
+using namespace std::literals;
+using android::base::unique_fd;
+
+bool PollForFile(const std::string& path, const std::chrono::milliseconds relative_timeout) {
+ auto start_time = std::chrono::steady_clock::now();
+
+ while (true) {
+ if (!access(path.c_str(), F_OK) || errno != ENOENT) return true;
+
+ std::this_thread::sleep_for(50ms);
+
+ auto now = std::chrono::steady_clock::now();
+ auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
+ if (time_elapsed > relative_timeout) return false;
+ }
+}
+
+bool PollForFileDeleted(const std::string& path, const std::chrono::milliseconds relative_timeout) {
+ auto start_time = std::chrono::steady_clock::now();
+
+ while (true) {
+ if (access(path.c_str(), F_OK) && errno == ENOENT) return true;
+
+ std::this_thread::sleep_for(50ms);
+
+ auto now = std::chrono::steady_clock::now();
+ auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
+ if (time_elapsed > relative_timeout) return false;
+ }
+}
+
+#if defined(__linux__)
+class OneShotInotify {
+ public:
+ OneShotInotify(const std::string& path, uint32_t mask,
+ const std::chrono::milliseconds relative_timeout);
+
+ bool Wait();
+
+ private:
+ bool CheckCompleted();
+ int64_t RemainingMs() const;
+ bool ConsumeEvents();
+
+ enum class Result { Success, Timeout, Error };
+ Result WaitImpl();
+
+ unique_fd inotify_fd_;
+ std::string path_;
+ uint32_t mask_;
+ std::chrono::time_point<std::chrono::steady_clock> start_time_;
+ std::chrono::milliseconds relative_timeout_;
+ bool finished_;
+};
+
+OneShotInotify::OneShotInotify(const std::string& path, uint32_t mask,
+ const std::chrono::milliseconds relative_timeout)
+ : path_(path),
+ mask_(mask),
+ start_time_(std::chrono::steady_clock::now()),
+ relative_timeout_(relative_timeout),
+ finished_(false) {
+ // If the condition is already met, don't bother creating an inotify.
+ if (CheckCompleted()) return;
+
+ unique_fd inotify_fd(inotify_init1(IN_CLOEXEC | IN_NONBLOCK));
+ if (inotify_fd < 0) {
+ PLOG(ERROR) << "inotify_init1 failed";
+ return;
+ }
+
+ std::string watch_path;
+ if (mask == IN_CREATE) {
+ watch_path = android::base::Dirname(path);
+ } else {
+ watch_path = path;
+ }
+ if (inotify_add_watch(inotify_fd, watch_path.c_str(), mask) < 0) {
+ PLOG(ERROR) << "inotify_add_watch failed";
+ return;
+ }
+
+ // It's possible the condition was met before the add_watch. Check for
+ // this and abort early if so.
+ if (CheckCompleted()) return;
+
+ inotify_fd_ = std::move(inotify_fd);
+}
+
+bool OneShotInotify::Wait() {
+ Result result = WaitImpl();
+ if (result == Result::Success) return true;
+ if (result == Result::Timeout) return false;
+
+ // Some kind of error with inotify occurred, so fallback to a poll.
+ std::chrono::milliseconds timeout(RemainingMs());
+ if (mask_ == IN_CREATE) {
+ return PollForFile(path_, timeout);
+ } else if (mask_ == IN_DELETE_SELF) {
+ return PollForFileDeleted(path_, timeout);
+ } else {
+ LOG(ERROR) << "Unknown inotify mask: " << mask_;
+ return false;
+ }
+}
+
+OneShotInotify::Result OneShotInotify::WaitImpl() {
+ // If the operation completed super early, we'll never have created an
+ // inotify instance.
+ if (finished_) return Result::Success;
+ if (inotify_fd_ < 0) return Result::Error;
+
+ while (true) {
+ auto remaining_ms = RemainingMs();
+ if (remaining_ms <= 0) return Result::Timeout;
+
+ struct pollfd event = {
+ .fd = inotify_fd_,
+ .events = POLLIN,
+ .revents = 0,
+ };
+ int rv = poll(&event, 1, static_cast<int>(remaining_ms));
+ if (rv <= 0) {
+ if (rv == 0 || errno == EINTR) {
+ continue;
+ }
+ PLOG(ERROR) << "poll for inotify failed";
+ return Result::Error;
+ }
+ if (event.revents & POLLERR) {
+ LOG(ERROR) << "error reading inotify for " << path_;
+ return Result::Error;
+ }
+
+ // Note that we don't bother checking what kind of event it is, since
+ // it's cheap enough to just see if the initial condition is satisified.
+ // If it's not, we consume all the events available and continue.
+ if (CheckCompleted()) return Result::Success;
+ if (!ConsumeEvents()) return Result::Error;
+ }
+}
+
+bool OneShotInotify::CheckCompleted() {
+ if (mask_ == IN_CREATE) {
+ finished_ = !access(path_.c_str(), F_OK) || errno != ENOENT;
+ } else if (mask_ == IN_DELETE_SELF) {
+ finished_ = access(path_.c_str(), F_OK) && errno == ENOENT;
+ } else {
+ LOG(ERROR) << "Unexpected mask: " << mask_;
+ }
+ return finished_;
+}
+
+bool OneShotInotify::ConsumeEvents() {
+ // According to the manpage, this is enough to read at least one event.
+ static constexpr size_t kBufferSize = sizeof(struct inotify_event) + NAME_MAX + 1;
+ char buffer[kBufferSize];
+
+ do {
+ ssize_t rv = TEMP_FAILURE_RETRY(read(inotify_fd_, buffer, sizeof(buffer)));
+ if (rv <= 0) {
+ if (rv == 0 || errno == EAGAIN) {
+ return true;
+ }
+ PLOG(ERROR) << "read inotify failed";
+ return false;
+ }
+ } while (true);
+}
+
+int64_t OneShotInotify::RemainingMs() const {
+ auto remaining = (std::chrono::steady_clock::now() - start_time_);
+ auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(remaining);
+ return (relative_timeout_ - elapsed).count();
+}
+#endif
+
+bool WaitForFile(const std::string& path, const std::chrono::milliseconds relative_timeout) {
+#if defined(__linux__)
+ OneShotInotify inotify(path, IN_CREATE, relative_timeout);
+ return inotify.Wait();
+#else
+ return PollForFile(path, relative_timeout);
+#endif
+}
+
+// Wait at most |relative_timeout| milliseconds for |path| to stop existing.
+bool WaitForFileDeleted(const std::string& path, const std::chrono::milliseconds relative_timeout) {
+#if defined(__linux__)
+ OneShotInotify inotify(path, IN_DELETE_SELF, relative_timeout);
+ return inotify.Wait();
+#else
+ return PollForFileDeleted(path, relative_timeout);
+#endif
+}
+
+} // namespace fs_mgr
+} // namespace android
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 410209b..259f800 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -56,6 +56,7 @@
#include <ext4_utils/ext4_utils.h>
#include <ext4_utils/wipe.h>
#include <fs_avb/fs_avb.h>
+#include <fs_mgr/file_wait.h>
#include <fs_mgr_overlayfs.h>
#include <libdm/dm.h>
#include <liblp/metadata_format.h>
@@ -116,28 +117,6 @@
FS_STAT_ENABLE_VERITY_FAILED = 0x80000,
};
-// TODO: switch to inotify()
-bool fs_mgr_wait_for_file(const std::string& filename,
- const std::chrono::milliseconds relative_timeout,
- FileWaitMode file_wait_mode) {
- auto start_time = std::chrono::steady_clock::now();
-
- while (true) {
- int rv = access(filename.c_str(), F_OK);
- if (file_wait_mode == FileWaitMode::Exists) {
- if (!rv || errno != ENOENT) return true;
- } else if (file_wait_mode == FileWaitMode::DoesNotExist) {
- if (rv && errno == ENOENT) return true;
- }
-
- std::this_thread::sleep_for(50ms);
-
- auto now = std::chrono::steady_clock::now();
- auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start_time);
- if (time_elapsed > relative_timeout) return false;
- }
-}
-
static void log_fs_stat(const std::string& blk_device, int fs_stat) {
if ((fs_stat & FS_STAT_IS_EXT4) == 0) return; // only log ext4
std::string msg =
@@ -929,7 +908,7 @@
public:
CheckpointManager(int needs_checkpoint = -1) : needs_checkpoint_(needs_checkpoint) {}
- bool Update(FstabEntry* entry) {
+ bool Update(FstabEntry* entry, const std::string& block_device = std::string()) {
if (!entry->fs_mgr_flags.checkpoint_blk && !entry->fs_mgr_flags.checkpoint_fs) {
return true;
}
@@ -948,7 +927,7 @@
return true;
}
- if (!UpdateCheckpointPartition(entry)) {
+ if (!UpdateCheckpointPartition(entry, block_device)) {
LERROR << "Could not set up checkpoint partition, skipping!";
return false;
}
@@ -978,7 +957,7 @@
}
private:
- bool UpdateCheckpointPartition(FstabEntry* entry) {
+ bool UpdateCheckpointPartition(FstabEntry* entry, const std::string& block_device) {
if (entry->fs_mgr_flags.checkpoint_fs) {
if (is_f2fs(entry->fs_type)) {
entry->fs_options += ",checkpoint=disable";
@@ -986,39 +965,43 @@
LERROR << entry->fs_type << " does not implement checkpoints.";
}
} else if (entry->fs_mgr_flags.checkpoint_blk) {
- unique_fd fd(TEMP_FAILURE_RETRY(open(entry->blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
- if (fd < 0) {
- PERROR << "Cannot open device " << entry->blk_device;
- return false;
- }
+ auto actual_block_device = block_device.empty() ? entry->blk_device : block_device;
+ if (fs_mgr_find_bow_device(actual_block_device).empty()) {
+ unique_fd fd(
+ TEMP_FAILURE_RETRY(open(entry->blk_device.c_str(), O_RDONLY | O_CLOEXEC)));
+ if (fd < 0) {
+ PERROR << "Cannot open device " << entry->blk_device;
+ return false;
+ }
- uint64_t size = get_block_device_size(fd) / 512;
- if (!size) {
- PERROR << "Cannot get device size";
- return false;
- }
+ uint64_t size = get_block_device_size(fd) / 512;
+ if (!size) {
+ PERROR << "Cannot get device size";
+ return false;
+ }
- android::dm::DmTable table;
- if (!table.AddTarget(
- std::make_unique<android::dm::DmTargetBow>(0, size, entry->blk_device))) {
- LERROR << "Failed to add bow target";
- return false;
- }
+ android::dm::DmTable table;
+ if (!table.AddTarget(std::make_unique<android::dm::DmTargetBow>(
+ 0, size, entry->blk_device))) {
+ LERROR << "Failed to add bow target";
+ return false;
+ }
- DeviceMapper& dm = DeviceMapper::Instance();
- if (!dm.CreateDevice("bow", table)) {
- PERROR << "Failed to create bow device";
- return false;
- }
+ DeviceMapper& dm = DeviceMapper::Instance();
+ if (!dm.CreateDevice("bow", table)) {
+ PERROR << "Failed to create bow device";
+ return false;
+ }
- std::string name;
- if (!dm.GetDmDevicePathByName("bow", &name)) {
- PERROR << "Failed to get bow device name";
- return false;
- }
+ std::string name;
+ if (!dm.GetDmDevicePathByName("bow", &name)) {
+ PERROR << "Failed to get bow device name";
+ return false;
+ }
- device_map_[name] = entry->blk_device;
- entry->blk_device = name;
+ device_map_[name] = entry->blk_device;
+ entry->blk_device = name;
+ }
}
return true;
}
@@ -1028,6 +1011,50 @@
std::map<std::string, std::string> device_map_;
};
+std::string fs_mgr_find_bow_device(const std::string& block_device) {
+ if (block_device.substr(0, 5) != "/dev/") {
+ LOG(ERROR) << "Expected block device, got " << block_device;
+ return std::string();
+ }
+
+ std::string sys_dir = std::string("/sys/") + block_device.substr(5);
+
+ for (;;) {
+ std::string name;
+ if (!android::base::ReadFileToString(sys_dir + "/dm/name", &name)) {
+ PLOG(ERROR) << block_device << " is not dm device";
+ return std::string();
+ }
+
+ if (name == "bow\n") return sys_dir;
+
+ std::string slaves = sys_dir + "/slaves";
+ std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(slaves.c_str()), closedir);
+ if (!directory) {
+ PLOG(ERROR) << "Can't open slave directory " << slaves;
+ return std::string();
+ }
+
+ int count = 0;
+ for (dirent* entry = readdir(directory.get()); entry; entry = readdir(directory.get())) {
+ if (entry->d_type != DT_LNK) continue;
+
+ if (count == 1) {
+ LOG(ERROR) << "Too many slaves in " << slaves;
+ return std::string();
+ }
+
+ ++count;
+ sys_dir = std::string("/sys/block/") + entry->d_name;
+ }
+
+ if (count != 1) {
+ LOG(ERROR) << "No slave in " << slaves;
+ return std::string();
+ }
+ }
+}
+
static bool IsMountPointMounted(const std::string& mount_point) {
// Check if this is already mounted.
Fstab fstab;
@@ -1103,8 +1130,7 @@
continue;
}
- if (current_entry.fs_mgr_flags.wait &&
- !fs_mgr_wait_for_file(current_entry.blk_device, 20s)) {
+ if (current_entry.fs_mgr_flags.wait && !WaitForFile(current_entry.blk_device, 20s)) {
LERROR << "Skipping '" << current_entry.blk_device << "' during mount_all";
continue;
}
@@ -1166,7 +1192,8 @@
}
encryptable = status;
if (status == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
- if (!call_vdc({"cryptfs", "encryptFstab", attempted_entry.mount_point})) {
+ if (!call_vdc({"cryptfs", "encryptFstab", attempted_entry.blk_device,
+ attempted_entry.mount_point})) {
LERROR << "Encryption failed";
return FS_MGR_MNTALL_FAIL;
}
@@ -1237,7 +1264,8 @@
encryptable = FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED;
} else if (mount_errno != EBUSY && mount_errno != EACCES &&
should_use_metadata_encryption(attempted_entry)) {
- if (!call_vdc({"cryptfs", "mountFstab", attempted_entry.mount_point})) {
+ if (!call_vdc({"cryptfs", "mountFstab", attempted_entry.blk_device,
+ attempted_entry.mount_point})) {
++error_count;
}
encryptable = FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED;
@@ -1367,13 +1395,13 @@
}
}
- if (!checkpoint_manager.Update(&fstab_entry)) {
+ if (!checkpoint_manager.Update(&fstab_entry, n_blk_device)) {
LERROR << "Could not set up checkpoint partition, skipping!";
continue;
}
// First check the filesystem if requested.
- if (fstab_entry.fs_mgr_flags.wait && !fs_mgr_wait_for_file(n_blk_device, 20s)) {
+ if (fstab_entry.fs_mgr_flags.wait && !WaitForFile(n_blk_device, 20s)) {
LERROR << "Skipping mounting '" << n_blk_device << "'";
continue;
}
@@ -1576,7 +1604,7 @@
fprintf(zram_fp.get(), "%" PRId64 "\n", entry.zram_size);
}
- if (entry.fs_mgr_flags.wait && !fs_mgr_wait_for_file(entry.blk_device, 20s)) {
+ if (entry.fs_mgr_flags.wait && !WaitForFile(entry.blk_device, 20s)) {
LERROR << "Skipping mkswap for '" << entry.blk_device << "'";
ret = false;
continue;
diff --git a/fs_mgr/fs_mgr_dm_linear.cpp b/fs_mgr/fs_mgr_dm_linear.cpp
index ee6ffdb..1f21a71 100644
--- a/fs_mgr/fs_mgr_dm_linear.cpp
+++ b/fs_mgr/fs_mgr_dm_linear.cpp
@@ -38,6 +38,7 @@
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
+#include <fs_mgr/file_wait.h>
#include <liblp/reader.h>
#include "fs_mgr_priv.h"
@@ -128,7 +129,7 @@
return false;
}
if (timeout_ms > std::chrono::milliseconds::zero()) {
- if (!fs_mgr_wait_for_file(*path, timeout_ms, FileWaitMode::Exists)) {
+ if (!WaitForFile(*path, timeout_ms)) {
DestroyLogicalPartition(name, {});
LERROR << "Timed out waiting for device path: " << *path;
return false;
@@ -202,7 +203,7 @@
if (!dm.DeleteDevice(name)) {
return false;
}
- if (!path.empty() && !fs_mgr_wait_for_file(path, timeout_ms, FileWaitMode::DoesNotExist)) {
+ if (!path.empty() && !WaitForFileDeleted(path, timeout_ms)) {
LERROR << "Timed out waiting for device path to unlink: " << path;
return false;
}
diff --git a/fs_mgr/fs_mgr_overlayfs.cpp b/fs_mgr/fs_mgr_overlayfs.cpp
index ed8cce6..05ca5fc 100644
--- a/fs_mgr/fs_mgr_overlayfs.cpp
+++ b/fs_mgr/fs_mgr_overlayfs.cpp
@@ -44,6 +44,7 @@
#include <android-base/unique_fd.h>
#include <ext4_utils/ext4_utils.h>
#include <fs_mgr.h>
+#include <fs_mgr/file_wait.h>
#include <fs_mgr_dm_linear.h>
#include <fs_mgr_overlayfs.h>
#include <fstab/fstab.h>
@@ -867,7 +868,7 @@
scratch_can_be_mounted = false;
auto scratch_device = fs_mgr_overlayfs_scratch_device();
if (fs_mgr_overlayfs_scratch_can_be_mounted(scratch_device) &&
- fs_mgr_wait_for_file(scratch_device, 10s)) {
+ WaitForFile(scratch_device, 10s)) {
const auto mount_type = fs_mgr_overlayfs_scratch_mount_type();
if (fs_mgr_overlayfs_mount_scratch(scratch_device, mount_type,
true /* readonly */)) {
diff --git a/fs_mgr/fs_mgr_priv.h b/fs_mgr/fs_mgr_priv.h
index c36fd3d..3a33cf3 100644
--- a/fs_mgr/fs_mgr_priv.h
+++ b/fs_mgr/fs_mgr_priv.h
@@ -88,12 +88,6 @@
using namespace std::chrono_literals;
-enum class FileWaitMode { Exists, DoesNotExist };
-
-bool fs_mgr_wait_for_file(const std::string& filename,
- const std::chrono::milliseconds relative_timeout,
- FileWaitMode wait_mode = FileWaitMode::Exists);
-
bool fs_mgr_set_blk_ro(const std::string& blockdev, bool readonly = true);
bool fs_mgr_update_for_slotselect(android::fs_mgr::Fstab* fstab);
bool fs_mgr_is_device_unlocked();
diff --git a/fs_mgr/fs_mgr_verity.cpp b/fs_mgr/fs_mgr_verity.cpp
index 1deb1ac..be8077b 100644
--- a/fs_mgr/fs_mgr_verity.cpp
+++ b/fs_mgr/fs_mgr_verity.cpp
@@ -35,6 +35,7 @@
#include <android-base/unique_fd.h>
#include <crypto_utils/android_pubkey.h>
#include <cutils/properties.h>
+#include <fs_mgr/file_wait.h>
#include <libdm/dm.h>
#include <logwrap/logwrap.h>
#include <openssl/obj_mac.h>
@@ -529,7 +530,7 @@
}
// make sure we've set everything up properly
- if (wait_for_verity_dev && !fs_mgr_wait_for_file(entry->blk_device, 1s)) {
+ if (wait_for_verity_dev && !WaitForFile(entry->blk_device, 1s)) {
goto out;
}
diff --git a/fs_mgr/include/fs_mgr.h b/fs_mgr/include/fs_mgr.h
index 88b2f8f..bdec7be 100644
--- a/fs_mgr/include/fs_mgr.h
+++ b/fs_mgr/include/fs_mgr.h
@@ -104,3 +104,7 @@
// fs_mgr_umount_all() is the reverse of fs_mgr_mount_all. In particular,
// it destroys verity devices from device mapper after the device is unmounted.
int fs_mgr_umount_all(android::fs_mgr::Fstab* fstab);
+
+// Finds the dm_bow device on which this block device is stacked, or returns
+// empty string
+std::string fs_mgr_find_bow_device(const std::string& block_device);
diff --git a/fs_mgr/include/fs_mgr/file_wait.h b/fs_mgr/include/fs_mgr/file_wait.h
new file mode 100644
index 0000000..74d160e
--- /dev/null
+++ b/fs_mgr/include/fs_mgr/file_wait.h
@@ -0,0 +1,34 @@
+// Copyright (C) 2019 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 <chrono>
+#include <string>
+
+namespace android {
+namespace fs_mgr {
+
+// Wait at most |relative_timeout| milliseconds for |path| to exist. dirname(path)
+// must already exist. For example, to wait on /dev/block/dm-6, /dev/block must
+// be a valid directory.
+bool WaitForFile(const std::string& path, const std::chrono::milliseconds relative_timeout);
+
+// Wait at most |relative_timeout| milliseconds for |path| to stop existing.
+// Note that this only returns true if the inode itself no longer exists, i.e.,
+// all outstanding file descriptors have been closed.
+bool WaitForFileDeleted(const std::string& path, const std::chrono::milliseconds relative_timeout);
+
+} // namespace fs_mgr
+} // namespace android
diff --git a/fs_mgr/libdm/Android.bp b/fs_mgr/libdm/Android.bp
index c8c2d83..21255df 100644
--- a/fs_mgr/libdm/Android.bp
+++ b/fs_mgr/libdm/Android.bp
@@ -46,6 +46,7 @@
static_libs: [
"libdm",
"libbase",
+ "libfs_mgr",
"liblog",
],
srcs: [
diff --git a/fs_mgr/libdm/dm.cpp b/fs_mgr/libdm/dm.cpp
index c2917a4..d54b6ef 100644
--- a/fs_mgr/libdm/dm.cpp
+++ b/fs_mgr/libdm/dm.cpp
@@ -302,6 +302,26 @@
return true;
}
+bool DeviceMapper::GetDeviceNumber(const std::string& name, dev_t* dev) {
+ struct dm_ioctl io;
+ InitIo(&io, name);
+ if (ioctl(fd_, DM_DEV_STATUS, &io) < 0) {
+ PLOG(WARNING) << "DM_DEV_STATUS failed for " << name;
+ return false;
+ }
+ *dev = io.dev;
+ return true;
+}
+
+bool DeviceMapper::GetDeviceString(const std::string& name, std::string* dev) {
+ dev_t num;
+ if (!GetDeviceNumber(name, &num)) {
+ return false;
+ }
+ *dev = std::to_string(major(num)) + ":" + std::to_string(minor(num));
+ return true;
+}
+
bool DeviceMapper::GetTableStatus(const std::string& name, std::vector<TargetInfo>* table) {
return GetTable(name, 0, table);
}
@@ -368,5 +388,13 @@
}
}
+std::string DeviceMapper::GetTargetType(const struct dm_target_spec& spec) {
+ if (const void* p = memchr(spec.target_type, '\0', sizeof(spec.target_type))) {
+ ptrdiff_t length = reinterpret_cast<const char*>(p) - spec.target_type;
+ return std::string{spec.target_type, static_cast<size_t>(length)};
+ }
+ return std::string{spec.target_type, sizeof(spec.target_type)};
+}
+
} // namespace dm
} // namespace android
diff --git a/fs_mgr/libdm/dm_test.cpp b/fs_mgr/libdm/dm_test.cpp
index dc47c33..c5881dd 100644
--- a/fs_mgr/libdm/dm_test.cpp
+++ b/fs_mgr/libdm/dm_test.cpp
@@ -132,8 +132,8 @@
// Define a 2-sector device, with each sector mapping to the first sector
// of one of our loop devices.
DmTable table;
- ASSERT_TRUE(table.AddTarget(make_unique<DmTargetLinear>(0, 1, loop_a.device(), 0)));
- ASSERT_TRUE(table.AddTarget(make_unique<DmTargetLinear>(1, 1, loop_b.device(), 0)));
+ ASSERT_TRUE(table.Emplace<DmTargetLinear>(0, 1, loop_a.device(), 0));
+ ASSERT_TRUE(table.Emplace<DmTargetLinear>(1, 1, loop_b.device(), 0));
ASSERT_TRUE(table.valid());
TempDevice dev("libdm-test-dm-linear", table);
@@ -141,6 +141,16 @@
ASSERT_FALSE(dev.path().empty());
ASSERT_TRUE(dev.WaitForUdev());
+ auto& dm = DeviceMapper::Instance();
+
+ dev_t dev_number;
+ ASSERT_TRUE(dm.GetDeviceNumber(dev.name(), &dev_number));
+ ASSERT_NE(dev_number, 0);
+
+ std::string dev_string;
+ ASSERT_TRUE(dm.GetDeviceString(dev.name(), &dev_string));
+ ASSERT_FALSE(dev_string.empty());
+
// Note: a scope is needed to ensure that there are no open descriptors
// when we go to close the device.
{
@@ -157,7 +167,6 @@
}
// Test GetTableStatus.
- DeviceMapper& dm = DeviceMapper::Instance();
vector<DeviceMapper::TargetInfo> targets;
ASSERT_TRUE(dm.GetTableStatus(dev.name(), &targets));
ASSERT_EQ(targets.size(), 2);
@@ -170,6 +179,10 @@
EXPECT_EQ(targets[1].spec.sector_start, 1);
EXPECT_EQ(targets[1].spec.length, 1);
+ // Test GetTargetType().
+ EXPECT_EQ(DeviceMapper::GetTargetType(targets[0].spec), std::string{"linear"});
+ EXPECT_EQ(DeviceMapper::GetTargetType(targets[1].spec), std::string{"linear"});
+
// Normally the TestDevice destructor would delete this, but at least one
// test should ensure that device deletion works.
ASSERT_TRUE(dev.Destroy());
diff --git a/fs_mgr/libdm/include/libdm/dm.h b/fs_mgr/libdm/include/libdm/dm.h
index d7e8aa9..afcb090 100644
--- a/fs_mgr/libdm/include/libdm/dm.h
+++ b/fs_mgr/libdm/include/libdm/dm.h
@@ -20,6 +20,7 @@
#include <fcntl.h>
#include <linux/dm-ioctl.h>
#include <linux/kdev_t.h>
+#include <linux/types.h>
#include <stdint.h>
#include <sys/sysmacros.h>
#include <unistd.h>
@@ -111,6 +112,13 @@
// parameter is not set.
bool GetDmDevicePathByName(const std::string& name, std::string* path);
+ // Returns the dev_t for the named device-mapper node.
+ bool GetDeviceNumber(const std::string& name, dev_t* dev);
+
+ // Returns a major:minor string for the named device-mapper node, that can
+ // be used as inputs to DmTargets that take a block device.
+ bool GetDeviceString(const std::string& name, std::string* dev);
+
// The only way to create a DeviceMapper object.
static DeviceMapper& Instance();
@@ -136,6 +144,8 @@
// mapper device from the kernel.
bool GetTableInfo(const std::string& name, std::vector<TargetInfo>* table);
+ static std::string GetTargetType(const struct dm_target_spec& spec);
+
private:
// Maximum possible device mapper targets registered in the kernel.
// This is only used to read the list of targets from kernel so we allocate
diff --git a/fs_mgr/libdm/include/libdm/loop_control.h b/fs_mgr/libdm/include/libdm/loop_control.h
index e6e83f4..6b4c2d8 100644
--- a/fs_mgr/libdm/include/libdm/loop_control.h
+++ b/fs_mgr/libdm/include/libdm/loop_control.h
@@ -35,6 +35,9 @@
// Detach the loop device given by 'loopdev' from the attached backing file.
bool Detach(const std::string& loopdev) const;
+ // Enable Direct I/O on a loop device. This requires kernel 4.9+.
+ static bool EnableDirectIo(int fd);
+
LoopControl(const LoopControl&) = delete;
LoopControl& operator=(const LoopControl&) = delete;
LoopControl& operator=(LoopControl&&) = default;
diff --git a/fs_mgr/libdm/loop_control.cpp b/fs_mgr/libdm/loop_control.cpp
index 0beb1a6..16bf4b0 100644
--- a/fs_mgr/libdm/loop_control.cpp
+++ b/fs_mgr/libdm/loop_control.cpp
@@ -91,6 +91,27 @@
return true;
}
+bool LoopControl::EnableDirectIo(int fd) {
+#if !defined(LOOP_SET_BLOCK_SIZE)
+ static constexpr int LOOP_SET_BLOCK_SIZE = 0x4C09;
+#endif
+#if !defined(LOOP_SET_DIRECT_IO)
+ static constexpr int LOOP_SET_DIRECT_IO = 0x4C08;
+#endif
+
+ // Note: the block size has to be >= the logical block size of the underlying
+ // block device, *not* the filesystem block size.
+ if (ioctl(fd, LOOP_SET_BLOCK_SIZE, 4096)) {
+ PLOG(ERROR) << "Could not set loop device block size";
+ return false;
+ }
+ if (ioctl(fd, LOOP_SET_DIRECT_IO, 1)) {
+ PLOG(ERROR) << "Could not set loop direct IO";
+ return false;
+ }
+ return true;
+}
+
LoopDevice::LoopDevice(int fd, bool auto_close) : fd_(fd), owns_fd_(auto_close) {
Init();
}
diff --git a/fs_mgr/libfiemap_writer/fiemap_writer.cpp b/fs_mgr/libfiemap_writer/fiemap_writer.cpp
index f064436..0a3ba6c 100644
--- a/fs_mgr/libfiemap_writer/fiemap_writer.cpp
+++ b/fs_mgr/libfiemap_writer/fiemap_writer.cpp
@@ -89,6 +89,31 @@
return true;
}
+static bool ValidateDmTarget(const DeviceMapper::TargetInfo& target) {
+ const auto& entry = target.spec;
+ if (entry.sector_start != 0) {
+ LOG(INFO) << "Stopping at target with non-zero starting sector";
+ return false;
+ }
+
+ auto target_type = DeviceMapper::GetTargetType(entry);
+ if (target_type == "bow" || target_type == "default-key" || target_type == "crypt") {
+ return true;
+ }
+ if (target_type == "linear") {
+ auto pieces = android::base::Split(target.data, " ");
+ if (pieces[1] != "0") {
+ LOG(INFO) << "Stopping at complex linear target with non-zero starting sector: "
+ << pieces[1];
+ return false;
+ }
+ return true;
+ }
+
+ LOG(INFO) << "Stopping at complex target type " << target_type;
+ return false;
+}
+
static bool DeviceMapperStackPop(const std::string& bdev, std::string* bdev_raw) {
*bdev_raw = bdev;
@@ -128,15 +153,7 @@
LOG(INFO) << "Stopping at complex table for " << dm_name << " at " << bdev;
return true;
}
- const auto& entry = table[0].spec;
- std::string target_type(std::string(entry.target_type, sizeof(entry.target_type)).c_str());
- if (target_type != "bow" && target_type != "default-key" && target_type != "crypt") {
- LOG(INFO) << "Stopping at complex target-type " << target_type << " for " << dm_name
- << " at " << bdev;
- return true;
- }
- if (entry.sector_start != 0) {
- LOG(INFO) << "Stopping at target-type with non-zero starting sector";
+ if (!ValidateDmTarget(table[0])) {
return true;
}
diff --git a/fs_mgr/liblp/partition_opener.cpp b/fs_mgr/liblp/partition_opener.cpp
index 3b12213..cc4a882 100644
--- a/fs_mgr/liblp/partition_opener.cpp
+++ b/fs_mgr/liblp/partition_opener.cpp
@@ -64,6 +64,12 @@
PERROR << __PRETTY_FUNCTION__ << "BLKALIGNOFF failed on " << block_device;
return false;
}
+ // The kernel can return -1 here when misaligned devices are stacked (i.e.
+ // device-mapper).
+ if (alignment_offset == -1) {
+ alignment_offset = 0;
+ }
+
int logical_block_size;
if (ioctl(fd, BLKSSZGET, &logical_block_size) < 0) {
PERROR << __PRETTY_FUNCTION__ << "BLKSSZGET failed on " << block_device;
diff --git a/fs_mgr/tests/Android.bp b/fs_mgr/tests/Android.bp
index eb9f525..83668e9 100644
--- a/fs_mgr/tests/Android.bp
+++ b/fs_mgr/tests/Android.bp
@@ -25,6 +25,7 @@
"libfstab",
],
srcs: [
+ "file_wait_test.cpp",
"fs_mgr_test.cpp",
],
diff --git a/fs_mgr/tests/file_wait_test.cpp b/fs_mgr/tests/file_wait_test.cpp
new file mode 100644
index 0000000..cc8b143
--- /dev/null
+++ b/fs_mgr/tests/file_wait_test.cpp
@@ -0,0 +1,91 @@
+// Copyright (C) 2019 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 <chrono>
+#include <string>
+#include <thread>
+
+#include <android-base/file.h>
+#include <android-base/unique_fd.h>
+#include <fs_mgr/file_wait.h>
+#include <gtest/gtest.h>
+
+using namespace std::literals;
+using android::base::unique_fd;
+using android::fs_mgr::WaitForFile;
+using android::fs_mgr::WaitForFileDeleted;
+
+class FileWaitTest : public ::testing::Test {
+ protected:
+ void SetUp() override {
+ const ::testing::TestInfo* tinfo = ::testing::UnitTest::GetInstance()->current_test_info();
+ test_file_ = temp_dir_.path + "/"s + tinfo->name();
+ }
+
+ void TearDown() override { unlink(test_file_.c_str()); }
+
+ TemporaryDir temp_dir_;
+ std::string test_file_;
+};
+
+TEST_F(FileWaitTest, FileExists) {
+ unique_fd fd(open(test_file_.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0700));
+ ASSERT_GE(fd, 0);
+
+ ASSERT_TRUE(WaitForFile(test_file_, 500ms));
+ ASSERT_FALSE(WaitForFileDeleted(test_file_, 500ms));
+}
+
+TEST_F(FileWaitTest, FileDoesNotExist) {
+ ASSERT_FALSE(WaitForFile(test_file_, 500ms));
+ ASSERT_TRUE(WaitForFileDeleted(test_file_, 500ms));
+}
+
+TEST_F(FileWaitTest, CreateAsync) {
+ std::thread thread([this] {
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+ unique_fd fd(open(test_file_.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0700));
+ });
+ EXPECT_TRUE(WaitForFile(test_file_, 3s));
+ thread.join();
+}
+
+TEST_F(FileWaitTest, CreateOtherAsync) {
+ std::thread thread([this] {
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+ unique_fd fd(open(test_file_.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0700));
+ });
+ EXPECT_FALSE(WaitForFile(test_file_ + ".wontexist", 2s));
+ thread.join();
+}
+
+TEST_F(FileWaitTest, DeleteAsync) {
+ // Note: need to close the file, otherwise inotify considers it not deleted.
+ {
+ unique_fd fd(open(test_file_.c_str(), O_CREAT | O_TRUNC | O_RDWR, 0700));
+ ASSERT_GE(fd, 0);
+ }
+
+ std::thread thread([this] {
+ std::this_thread::sleep_for(std::chrono::seconds(1));
+ unlink(test_file_.c_str());
+ });
+ EXPECT_TRUE(WaitForFileDeleted(test_file_, 3s));
+ thread.join();
+}
+
+TEST_F(FileWaitTest, BadPath) {
+ ASSERT_FALSE(WaitForFile("/this/path/does/not/exist", 5ms));
+ EXPECT_EQ(errno, ENOENT);
+}
diff --git a/gatekeeperd/Android.bp b/gatekeeperd/Android.bp
index 2b7db79..778e08c 100644
--- a/gatekeeperd/Android.bp
+++ b/gatekeeperd/Android.bp
@@ -23,8 +23,6 @@
"-Wunused",
],
srcs: [
- "SoftGateKeeperDevice.cpp",
- "IGateKeeperService.cpp",
"gatekeeperd.cpp",
],
@@ -43,9 +41,44 @@
"libhidltransport",
"libhwbinder",
"android.hardware.gatekeeper@1.0",
+ "libgatekeeper_aidl",
],
static_libs: ["libscrypt_static"],
include_dirs: ["external/scrypt/lib/crypto"],
init_rc: ["gatekeeperd.rc"],
}
+
+filegroup {
+ name: "gatekeeper_aidl",
+ srcs: [
+ "binder/android/service/gatekeeper/IGateKeeperService.aidl",
+ ],
+ path: "binder",
+}
+
+cc_library_shared {
+ name: "libgatekeeper_aidl",
+ srcs: [
+ ":gatekeeper_aidl",
+ "GateKeeperResponse.cpp",
+ ],
+ aidl: {
+ export_aidl_headers: true,
+ include_dirs: [
+ "system/core/gatekeeperd/binder",
+ "frameworks/base/core/java/",
+ ],
+ },
+ export_include_dirs: ["include"],
+ shared_libs: [
+ "libbase",
+ "libbinder",
+ "libcutils",
+ "liblog",
+ "libutils",
+ ],
+ export_shared_lib_headers: [
+ "libbinder",
+ ],
+}
diff --git a/gatekeeperd/GateKeeperResponse.cpp b/gatekeeperd/GateKeeperResponse.cpp
new file mode 100644
index 0000000..ca0c98f
--- /dev/null
+++ b/gatekeeperd/GateKeeperResponse.cpp
@@ -0,0 +1,83 @@
+/*
+**
+** Copyright 2019, 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.
+*/
+
+#define LOG_TAG "gatekeeperd"
+
+#include <gatekeeper/GateKeeperResponse.h>
+
+#include <binder/Parcel.h>
+
+#include <android-base/logging.h>
+
+namespace android {
+namespace service {
+namespace gatekeeper {
+
+status_t GateKeeperResponse::readFromParcel(const Parcel* in) {
+ if (in == nullptr) {
+ LOG(ERROR) << "readFromParcel got null in parameter";
+ return BAD_VALUE;
+ }
+ timeout_ = 0;
+ should_reenroll_ = false;
+ payload_ = {};
+ response_code_ = ResponseCode(in->readInt32());
+ if (response_code_ == ResponseCode::OK) {
+ should_reenroll_ = in->readInt32();
+ ssize_t length = in->readInt32();
+ if (length > 0) {
+ length = in->readInt32();
+ const uint8_t* buf = reinterpret_cast<const uint8_t*>(in->readInplace(length));
+ if (buf == nullptr) {
+ LOG(ERROR) << "readInplace returned null buffer for length " << length;
+ return BAD_VALUE;
+ }
+ payload_.resize(length);
+ std::copy(buf, buf + length, payload_.data());
+ }
+ } else if (response_code_ == ResponseCode::RETRY) {
+ timeout_ = in->readInt32();
+ }
+ return NO_ERROR;
+}
+status_t GateKeeperResponse::writeToParcel(Parcel* out) const {
+ if (out == nullptr) {
+ LOG(ERROR) << "writeToParcel got null out parameter";
+ return BAD_VALUE;
+ }
+ out->writeInt32(int32_t(response_code_));
+ if (response_code_ == ResponseCode::OK) {
+ out->writeInt32(should_reenroll_);
+ out->writeInt32(payload_.size());
+ if (payload_.size() != 0) {
+ out->writeInt32(payload_.size());
+ uint8_t* buf = reinterpret_cast<uint8_t*>(out->writeInplace(payload_.size()));
+ if (buf == nullptr) {
+ LOG(ERROR) << "writeInplace returned null buffer for length " << payload_.size();
+ return BAD_VALUE;
+ }
+ std::copy(payload_.begin(), payload_.end(), buf);
+ }
+ } else if (response_code_ == ResponseCode::RETRY) {
+ out->writeInt32(timeout_);
+ }
+ return NO_ERROR;
+}
+
+} // namespace gatekeeper
+} // namespace service
+} // namespace android
diff --git a/gatekeeperd/IGateKeeperService.cpp b/gatekeeperd/IGateKeeperService.cpp
deleted file mode 100644
index 43d5708..0000000
--- a/gatekeeperd/IGateKeeperService.cpp
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright 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.
-*/
-
-#define LOG_TAG "GateKeeperService"
-#include <utils/Log.h>
-
-#include "IGateKeeperService.h"
-
-namespace android {
-
-const android::String16 IGateKeeperService::descriptor("android.service.gatekeeper.IGateKeeperService");
-const android::String16& IGateKeeperService::getInterfaceDescriptor() const {
- return IGateKeeperService::descriptor;
-}
-
-status_t BnGateKeeperService::onTransact(
- uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
- switch(code) {
- case ENROLL: {
- CHECK_INTERFACE(IGateKeeperService, data, reply);
- uint32_t uid = data.readInt32();
-
- ssize_t currentPasswordHandleSize = data.readInt32();
- const uint8_t *currentPasswordHandle =
- static_cast<const uint8_t *>(data.readInplace(currentPasswordHandleSize));
- if (!currentPasswordHandle) currentPasswordHandleSize = 0;
-
- ssize_t currentPasswordSize = data.readInt32();
- const uint8_t *currentPassword =
- static_cast<const uint8_t *>(data.readInplace(currentPasswordSize));
- if (!currentPassword) currentPasswordSize = 0;
-
- ssize_t desiredPasswordSize = data.readInt32();
- const uint8_t *desiredPassword =
- static_cast<const uint8_t *>(data.readInplace(desiredPasswordSize));
- if (!desiredPassword) desiredPasswordSize = 0;
-
- uint8_t *out = NULL;
- uint32_t outSize = 0;
- int ret = enroll(uid, currentPasswordHandle, currentPasswordHandleSize,
- currentPassword, currentPasswordSize, desiredPassword,
- desiredPasswordSize, &out, &outSize);
-
- reply->writeNoException();
- reply->writeInt32(1);
- if (ret == 0 && outSize > 0 && out != NULL) {
- reply->writeInt32(GATEKEEPER_RESPONSE_OK);
- reply->writeInt32(0);
- reply->writeInt32(outSize);
- reply->writeInt32(outSize);
- void *buf = reply->writeInplace(outSize);
- memcpy(buf, out, outSize);
- delete[] out;
- } else if (ret > 0) {
- reply->writeInt32(GATEKEEPER_RESPONSE_RETRY);
- reply->writeInt32(ret);
- } else {
- reply->writeInt32(GATEKEEPER_RESPONSE_ERROR);
- }
- return OK;
- }
- case VERIFY: {
- CHECK_INTERFACE(IGateKeeperService, data, reply);
- uint32_t uid = data.readInt32();
- ssize_t currentPasswordHandleSize = data.readInt32();
- const uint8_t *currentPasswordHandle =
- static_cast<const uint8_t *>(data.readInplace(currentPasswordHandleSize));
- if (!currentPasswordHandle) currentPasswordHandleSize = 0;
-
- ssize_t currentPasswordSize = data.readInt32();
- const uint8_t *currentPassword =
- static_cast<const uint8_t *>(data.readInplace(currentPasswordSize));
- if (!currentPassword) currentPasswordSize = 0;
-
- bool request_reenroll = false;
- int ret = verify(uid, (uint8_t *) currentPasswordHandle,
- currentPasswordHandleSize, (uint8_t *) currentPassword, currentPasswordSize,
- &request_reenroll);
-
- reply->writeNoException();
- reply->writeInt32(1);
- if (ret == 0) {
- reply->writeInt32(GATEKEEPER_RESPONSE_OK);
- reply->writeInt32(request_reenroll ? 1 : 0);
- reply->writeInt32(0); // no payload returned from this call
- } else if (ret > 0) {
- reply->writeInt32(GATEKEEPER_RESPONSE_RETRY);
- reply->writeInt32(ret);
- } else {
- reply->writeInt32(GATEKEEPER_RESPONSE_ERROR);
- }
- return OK;
- }
- case VERIFY_CHALLENGE: {
- CHECK_INTERFACE(IGateKeeperService, data, reply);
- uint32_t uid = data.readInt32();
- uint64_t challenge = data.readInt64();
- ssize_t currentPasswordHandleSize = data.readInt32();
- const uint8_t *currentPasswordHandle =
- static_cast<const uint8_t *>(data.readInplace(currentPasswordHandleSize));
- if (!currentPasswordHandle) currentPasswordHandleSize = 0;
-
- ssize_t currentPasswordSize = data.readInt32();
- const uint8_t *currentPassword =
- static_cast<const uint8_t *>(data.readInplace(currentPasswordSize));
- if (!currentPassword) currentPasswordSize = 0;
-
-
- uint8_t *out = NULL;
- uint32_t outSize = 0;
- bool request_reenroll = false;
- int ret = verifyChallenge(uid, challenge, (uint8_t *) currentPasswordHandle,
- currentPasswordHandleSize, (uint8_t *) currentPassword, currentPasswordSize,
- &out, &outSize, &request_reenroll);
- reply->writeNoException();
- reply->writeInt32(1);
- if (ret == 0 && outSize > 0 && out != NULL) {
- reply->writeInt32(GATEKEEPER_RESPONSE_OK);
- reply->writeInt32(request_reenroll ? 1 : 0);
- reply->writeInt32(outSize);
- reply->writeInt32(outSize);
- void *buf = reply->writeInplace(outSize);
- memcpy(buf, out, outSize);
- delete[] out;
- } else if (ret > 0) {
- reply->writeInt32(GATEKEEPER_RESPONSE_RETRY);
- reply->writeInt32(ret);
- } else {
- reply->writeInt32(GATEKEEPER_RESPONSE_ERROR);
- }
- return OK;
- }
- case GET_SECURE_USER_ID: {
- CHECK_INTERFACE(IGateKeeperService, data, reply);
- uint32_t uid = data.readInt32();
- uint64_t sid = getSecureUserId(uid);
- reply->writeNoException();
- reply->writeInt64(sid);
- return OK;
- }
- case CLEAR_SECURE_USER_ID: {
- CHECK_INTERFACE(IGateKeeperService, data, reply);
- uint32_t uid = data.readInt32();
- clearSecureUserId(uid);
- reply->writeNoException();
- return OK;
- }
- case REPORT_DEVICE_SETUP_COMPLETE: {
- CHECK_INTERFACE(IGateKeeperService, data, reply);
- reportDeviceSetupComplete();
- reply->writeNoException();
- return OK;
- }
- default:
- return BBinder::onTransact(code, data, reply, flags);
- }
-};
-
-
-}; // namespace android
diff --git a/gatekeeperd/IGateKeeperService.h b/gatekeeperd/IGateKeeperService.h
deleted file mode 100644
index 2816efc..0000000
--- a/gatekeeperd/IGateKeeperService.h
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * 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.
- */
-
-#ifndef IGATEKEEPER_SERVICE_H_
-#define IGATEKEEPER_SERVICE_H_
-
-#include <binder/IInterface.h>
-#include <binder/Parcel.h>
-
-namespace android {
-
-/*
- * This must be kept manually in sync with frameworks/base's IGateKeeperService.aidl
- */
-class IGateKeeperService : public IInterface {
-public:
- enum {
- ENROLL = IBinder::FIRST_CALL_TRANSACTION + 0,
- VERIFY = IBinder::FIRST_CALL_TRANSACTION + 1,
- VERIFY_CHALLENGE = IBinder::FIRST_CALL_TRANSACTION + 2,
- GET_SECURE_USER_ID = IBinder::FIRST_CALL_TRANSACTION + 3,
- CLEAR_SECURE_USER_ID = IBinder::FIRST_CALL_TRANSACTION + 4,
- REPORT_DEVICE_SETUP_COMPLETE = IBinder::FIRST_CALL_TRANSACTION + 5,
- };
-
- enum {
- GATEKEEPER_RESPONSE_OK = 0,
- GATEKEEPER_RESPONSE_RETRY = 1,
- GATEKEEPER_RESPONSE_ERROR = -1,
- };
-
- // DECLARE_META_INTERFACE - C++ client interface not needed
- static const android::String16 descriptor;
- virtual const android::String16& getInterfaceDescriptor() const;
- IGateKeeperService() {}
- virtual ~IGateKeeperService() {}
-
- /**
- * Enrolls a password with the GateKeeper. Returns 0 on success, negative on failure.
- * Returns:
- * - 0 on success
- * - A timestamp T > 0 if the call has failed due to throttling and should not
- * be reattempted until T milliseconds have elapsed
- * - -1 on failure
- */
- virtual int enroll(uint32_t uid,
- const uint8_t *current_password_handle, uint32_t current_password_handle_length,
- const uint8_t *current_password, uint32_t current_password_length,
- const uint8_t *desired_password, uint32_t desired_password_length,
- uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length) = 0;
-
- /**
- * Verifies a password previously enrolled with the GateKeeper.
- * Returns:
- * - 0 on success
- * - A timestamp T > 0 if the call has failed due to throttling and should not
- * be reattempted until T milliseconds have elapsed
- * - -1 on failure
- */
- virtual int verify(uint32_t uid, const uint8_t *enrolled_password_handle,
- uint32_t enrolled_password_handle_length,
- const uint8_t *provided_password, uint32_t provided_password_length,
- bool *request_reenroll) = 0;
-
- /**
- * Verifies a password previously enrolled with the GateKeeper.
- * Returns:
- * - 0 on success
- * - A timestamp T > 0 if the call has failed due to throttling and should not
- * be reattempted until T milliseconds have elapsed
- * - -1 on failure
- */
- virtual int verifyChallenge(uint32_t uid, uint64_t challenge,
- const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
- const uint8_t *provided_password, uint32_t provided_password_length,
- uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll) = 0;
- /**
- * Returns the secure user ID for the provided android user
- */
- virtual uint64_t getSecureUserId(uint32_t uid) = 0;
-
- /**
- * Clears the secure user ID associated with the user.
- */
- virtual void clearSecureUserId(uint32_t uid) = 0;
-
- /**
- * Notifies gatekeeper that device setup has been completed and any potentially still existing
- * state from before a factory reset can be cleaned up (if it has not been already).
- */
- virtual void reportDeviceSetupComplete() = 0;
-};
-
-// ----------------------------------------------------------------------------
-
-class BnGateKeeperService: public BnInterface<IGateKeeperService> {
-public:
- virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply,
- uint32_t flags = 0);
-};
-
-} // namespace android
-
-#endif
-
diff --git a/gatekeeperd/SoftGateKeeper.h b/gatekeeperd/SoftGateKeeper.h
deleted file mode 100644
index 2f4f4d7..0000000
--- a/gatekeeperd/SoftGateKeeper.h
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright 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.
- *
- */
-
-#ifndef SOFT_GATEKEEPER_H_
-#define SOFT_GATEKEEPER_H_
-
-extern "C" {
-#include <openssl/rand.h>
-#include <openssl/sha.h>
-
-#include <crypto_scrypt.h>
-}
-
-#include <android-base/memory.h>
-#include <gatekeeper/gatekeeper.h>
-
-#include <iostream>
-#include <unordered_map>
-#include <memory>
-
-namespace gatekeeper {
-
-struct fast_hash_t {
- uint64_t salt;
- uint8_t digest[SHA256_DIGEST_LENGTH];
-};
-
-class SoftGateKeeper : public GateKeeper {
-public:
- static const uint32_t SIGNATURE_LENGTH_BYTES = 32;
-
- // scrypt params
- static const uint64_t N = 16384;
- static const uint32_t r = 8;
- static const uint32_t p = 1;
-
- static const int MAX_UINT_32_CHARS = 11;
-
- SoftGateKeeper() {
- key_.reset(new uint8_t[SIGNATURE_LENGTH_BYTES]);
- memset(key_.get(), 0, SIGNATURE_LENGTH_BYTES);
- }
-
- virtual ~SoftGateKeeper() {
- }
-
- virtual bool GetAuthTokenKey(const uint8_t **auth_token_key,
- uint32_t *length) const {
- if (auth_token_key == NULL || length == NULL) return false;
- uint8_t *auth_token_key_copy = new uint8_t[SIGNATURE_LENGTH_BYTES];
- memcpy(auth_token_key_copy, key_.get(), SIGNATURE_LENGTH_BYTES);
-
- *auth_token_key = auth_token_key_copy;
- *length = SIGNATURE_LENGTH_BYTES;
- return true;
- }
-
- virtual void GetPasswordKey(const uint8_t **password_key, uint32_t *length) {
- if (password_key == NULL || length == NULL) return;
- uint8_t *password_key_copy = new uint8_t[SIGNATURE_LENGTH_BYTES];
- memcpy(password_key_copy, key_.get(), SIGNATURE_LENGTH_BYTES);
-
- *password_key = password_key_copy;
- *length = SIGNATURE_LENGTH_BYTES;
- }
-
- virtual void ComputePasswordSignature(uint8_t *signature, uint32_t signature_length,
- const uint8_t *, uint32_t, const uint8_t *password,
- uint32_t password_length, salt_t salt) const {
- if (signature == NULL) return;
- crypto_scrypt(password, password_length, reinterpret_cast<uint8_t *>(&salt),
- sizeof(salt), N, r, p, signature, signature_length);
- }
-
- virtual void GetRandom(void *random, uint32_t requested_length) const {
- if (random == NULL) return;
- RAND_pseudo_bytes((uint8_t *) random, requested_length);
- }
-
- virtual void ComputeSignature(uint8_t *signature, uint32_t signature_length,
- const uint8_t *, uint32_t, const uint8_t *, const uint32_t) const {
- if (signature == NULL) return;
- memset(signature, 0, signature_length);
- }
-
- virtual uint64_t GetMillisecondsSinceBoot() const {
- struct timespec time;
- int res = clock_gettime(CLOCK_BOOTTIME, &time);
- if (res < 0) return 0;
- return (time.tv_sec * 1000) + (time.tv_nsec / 1000 / 1000);
- }
-
- virtual bool IsHardwareBacked() const {
- return false;
- }
-
- virtual bool GetFailureRecord(uint32_t uid, secure_id_t user_id, failure_record_t *record,
- bool /* secure */) {
- failure_record_t *stored = &failure_map_[uid];
- if (user_id != stored->secure_user_id) {
- stored->secure_user_id = user_id;
- stored->last_checked_timestamp = 0;
- stored->failure_counter = 0;
- }
- memcpy(record, stored, sizeof(*record));
- return true;
- }
-
- virtual bool ClearFailureRecord(uint32_t uid, secure_id_t user_id, bool /* secure */) {
- failure_record_t *stored = &failure_map_[uid];
- stored->secure_user_id = user_id;
- stored->last_checked_timestamp = 0;
- stored->failure_counter = 0;
- return true;
- }
-
- virtual bool WriteFailureRecord(uint32_t uid, failure_record_t *record, bool /* secure */) {
- failure_map_[uid] = *record;
- return true;
- }
-
- fast_hash_t ComputeFastHash(const SizedBuffer &password, uint64_t salt) {
- fast_hash_t fast_hash;
- size_t digest_size = password.length + sizeof(salt);
- std::unique_ptr<uint8_t[]> digest(new uint8_t[digest_size]);
- memcpy(digest.get(), &salt, sizeof(salt));
- memcpy(digest.get() + sizeof(salt), password.buffer.get(), password.length);
-
- SHA256(digest.get(), digest_size, (uint8_t *) &fast_hash.digest);
-
- fast_hash.salt = salt;
- return fast_hash;
- }
-
- bool VerifyFast(const fast_hash_t &fast_hash, const SizedBuffer &password) {
- fast_hash_t computed = ComputeFastHash(password, fast_hash.salt);
- return memcmp(computed.digest, fast_hash.digest, SHA256_DIGEST_LENGTH) == 0;
- }
-
- bool DoVerify(const password_handle_t *expected_handle, const SizedBuffer &password) {
- uint64_t user_id = android::base::get_unaligned<secure_id_t>(&expected_handle->user_id);
- FastHashMap::const_iterator it = fast_hash_map_.find(user_id);
- if (it != fast_hash_map_.end() && VerifyFast(it->second, password)) {
- return true;
- } else {
- if (GateKeeper::DoVerify(expected_handle, password)) {
- uint64_t salt;
- GetRandom(&salt, sizeof(salt));
- fast_hash_map_[user_id] = ComputeFastHash(password, salt);
- return true;
- }
- }
-
- return false;
- }
-
-private:
-
- typedef std::unordered_map<uint32_t, failure_record_t> FailureRecordMap;
- typedef std::unordered_map<uint64_t, fast_hash_t> FastHashMap;
-
- std::unique_ptr<uint8_t[]> key_;
- FailureRecordMap failure_map_;
- FastHashMap fast_hash_map_;
-};
-}
-
-#endif // SOFT_GATEKEEPER_H_
diff --git a/gatekeeperd/SoftGateKeeperDevice.cpp b/gatekeeperd/SoftGateKeeperDevice.cpp
deleted file mode 100644
index f5e2ce6..0000000
--- a/gatekeeperd/SoftGateKeeperDevice.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * 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.
- */
-#include "SoftGateKeeper.h"
-#include "SoftGateKeeperDevice.h"
-
-namespace android {
-
-int SoftGateKeeperDevice::enroll(uint32_t uid,
- const uint8_t *current_password_handle, uint32_t current_password_handle_length,
- const uint8_t *current_password, uint32_t current_password_length,
- const uint8_t *desired_password, uint32_t desired_password_length,
- uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length) {
-
- if (enrolled_password_handle == NULL || enrolled_password_handle_length == NULL ||
- desired_password == NULL || desired_password_length == 0)
- return -EINVAL;
-
- // Current password and current password handle go together
- if (current_password_handle == NULL || current_password_handle_length == 0 ||
- current_password == NULL || current_password_length == 0) {
- current_password_handle = NULL;
- current_password_handle_length = 0;
- current_password = NULL;
- current_password_length = 0;
- }
-
- SizedBuffer desired_password_buffer(desired_password_length);
- memcpy(desired_password_buffer.buffer.get(), desired_password, desired_password_length);
-
- SizedBuffer current_password_handle_buffer(current_password_handle_length);
- if (current_password_handle) {
- memcpy(current_password_handle_buffer.buffer.get(), current_password_handle,
- current_password_handle_length);
- }
-
- SizedBuffer current_password_buffer(current_password_length);
- if (current_password) {
- memcpy(current_password_buffer.buffer.get(), current_password, current_password_length);
- }
-
- EnrollRequest request(uid, ¤t_password_handle_buffer, &desired_password_buffer,
- ¤t_password_buffer);
- EnrollResponse response;
-
- impl_->Enroll(request, &response);
-
- if (response.error == ERROR_RETRY) {
- return response.retry_timeout;
- } else if (response.error != ERROR_NONE) {
- return -EINVAL;
- }
-
- *enrolled_password_handle = response.enrolled_password_handle.buffer.release();
- *enrolled_password_handle_length = response.enrolled_password_handle.length;
- return 0;
-}
-
-int SoftGateKeeperDevice::verify(uint32_t uid,
- uint64_t challenge, const uint8_t *enrolled_password_handle,
- uint32_t enrolled_password_handle_length, const uint8_t *provided_password,
- uint32_t provided_password_length, uint8_t **auth_token, uint32_t *auth_token_length,
- bool *request_reenroll) {
-
- if (enrolled_password_handle == NULL ||
- provided_password == NULL) {
- return -EINVAL;
- }
-
- SizedBuffer password_handle_buffer(enrolled_password_handle_length);
- memcpy(password_handle_buffer.buffer.get(), enrolled_password_handle,
- enrolled_password_handle_length);
- SizedBuffer provided_password_buffer(provided_password_length);
- memcpy(provided_password_buffer.buffer.get(), provided_password, provided_password_length);
-
- VerifyRequest request(uid, challenge, &password_handle_buffer, &provided_password_buffer);
- VerifyResponse response;
-
- impl_->Verify(request, &response);
-
- if (response.error == ERROR_RETRY) {
- return response.retry_timeout;
- } else if (response.error != ERROR_NONE) {
- return -EINVAL;
- }
-
- if (auth_token != NULL && auth_token_length != NULL) {
- *auth_token = response.auth_token.buffer.release();
- *auth_token_length = response.auth_token.length;
- }
-
- if (request_reenroll != NULL) {
- *request_reenroll = response.request_reenroll;
- }
-
- return 0;
-}
-} // namespace android
diff --git a/gatekeeperd/SoftGateKeeperDevice.h b/gatekeeperd/SoftGateKeeperDevice.h
deleted file mode 100644
index e3dc068..0000000
--- a/gatekeeperd/SoftGateKeeperDevice.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright 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.
- */
-
-#ifndef SOFT_GATEKEEPER_DEVICE_H_
-#define SOFT_GATEKEEPER_DEVICE_H_
-
-#include "SoftGateKeeper.h"
-
-#include <memory>
-
-using namespace gatekeeper;
-
-namespace android {
-
-/**
- * Software based GateKeeper implementation
- */
-class SoftGateKeeperDevice {
-public:
- SoftGateKeeperDevice() {
- impl_.reset(new SoftGateKeeper());
- }
-
- // Wrappers to translate the gatekeeper HAL API to the Kegyuard Messages API.
-
- /**
- * Enrolls password_payload, which should be derived from a user selected pin or password,
- * with the authentication factor private key used only for enrolling authentication
- * factor data.
- *
- * Returns: 0 on success or an error code less than 0 on error.
- * On error, enrolled_password_handle will not be allocated.
- */
- int enroll(uint32_t uid,
- const uint8_t *current_password_handle, uint32_t current_password_handle_length,
- const uint8_t *current_password, uint32_t current_password_length,
- const uint8_t *desired_password, uint32_t desired_password_length,
- uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length);
-
- /**
- * Verifies provided_password matches enrolled_password_handle.
- *
- * Implementations of this module may retain the result of this call
- * to attest to the recency of authentication.
- *
- * On success, writes the address of a verification token to auth_token,
- * usable to attest password verification to other trusted services. Clients
- * may pass NULL for this value.
- *
- * Returns: 0 on success or an error code less than 0 on error
- * On error, verification token will not be allocated
- */
- int verify(uint32_t uid, uint64_t challenge,
- const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
- const uint8_t *provided_password, uint32_t provided_password_length,
- uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll);
-private:
- std::unique_ptr<SoftGateKeeper> impl_;
-};
-
-} // namespace gatekeeper
-
-#endif //SOFT_GATEKEEPER_DEVICE_H_
diff --git a/gatekeeperd/binder/android/service/gatekeeper/GateKeeperResponse.aidl b/gatekeeperd/binder/android/service/gatekeeper/GateKeeperResponse.aidl
new file mode 100644
index 0000000..097bb54
--- /dev/null
+++ b/gatekeeperd/binder/android/service/gatekeeper/GateKeeperResponse.aidl
@@ -0,0 +1,24 @@
+/*
+ * 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.
+ */
+
+package android.service.gatekeeper;
+
+/**
+ * Response object for a GateKeeper verification request.
+ * @hide
+ */
+parcelable GateKeeperResponse cpp_header "gatekeeper/GateKeeperResponse.h";
+
diff --git a/gatekeeperd/binder/android/service/gatekeeper/IGateKeeperService.aidl b/gatekeeperd/binder/android/service/gatekeeper/IGateKeeperService.aidl
new file mode 100644
index 0000000..57adaba
--- /dev/null
+++ b/gatekeeperd/binder/android/service/gatekeeper/IGateKeeperService.aidl
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+
+package android.service.gatekeeper;
+
+import android.service.gatekeeper.GateKeeperResponse;
+
+/**
+ * Interface for communication with GateKeeper, the
+ * secure password storage daemon.
+ *
+ * This must be kept manually in sync with system/core/gatekeeperd
+ * until AIDL can generate both C++ and Java bindings.
+ *
+ * @hide
+ */
+interface IGateKeeperService {
+ /**
+ * Enrolls a password, returning the handle to the enrollment to be stored locally.
+ * @param uid The Android user ID associated to this enrollment
+ * @param currentPasswordHandle The previously enrolled handle, or null if none
+ * @param currentPassword The previously enrolled plaintext password, or null if none.
+ * If provided, must verify against the currentPasswordHandle.
+ * @param desiredPassword The new desired password, for which a handle will be returned
+ * upon success.
+ * @return an EnrollResponse or null on failure
+ */
+ GateKeeperResponse enroll(int uid, in @nullable byte[] currentPasswordHandle,
+ in @nullable byte[] currentPassword, in byte[] desiredPassword);
+
+ /**
+ * Verifies an enrolled handle against a provided, plaintext blob.
+ * @param uid The Android user ID associated to this enrollment
+ * @param enrolledPasswordHandle The handle against which the provided password will be
+ * verified.
+ * @param The plaintext blob to verify against enrolledPassword.
+ * @return a VerifyResponse, or null on failure.
+ */
+ GateKeeperResponse verify(int uid, in byte[] enrolledPasswordHandle, in byte[] providedPassword);
+
+ /**
+ * Verifies an enrolled handle against a provided, plaintext blob.
+ * @param uid The Android user ID associated to this enrollment
+ * @param challenge a challenge to authenticate agaisnt the device credential. If successful
+ * authentication occurs, this value will be written to the returned
+ * authentication attestation.
+ * @param enrolledPasswordHandle The handle against which the provided password will be
+ * verified.
+ * @param The plaintext blob to verify against enrolledPassword.
+ * @return a VerifyResponse with an attestation, or null on failure.
+ */
+ GateKeeperResponse verifyChallenge(int uid, long challenge, in byte[] enrolledPasswordHandle,
+ in byte[] providedPassword);
+
+ /**
+ * Retrieves the secure identifier for the user with the provided Android ID,
+ * or 0 if none is found.
+ * @param uid the Android user id
+ */
+ long getSecureUserId(int uid);
+
+ /**
+ * Clears secure user id associated with the provided Android ID.
+ * Must be called when password is set to NONE.
+ * @param uid the Android user id.
+ */
+ void clearSecureUserId(int uid);
+
+ /**
+ * Notifies gatekeeper that device setup has been completed and any potentially still existing
+ * state from before a factory reset can be cleaned up (if it has not been already).
+ */
+ void reportDeviceSetupComplete();
+}
diff --git a/gatekeeperd/gatekeeperd.cpp b/gatekeeperd/gatekeeperd.cpp
index 8700c34..1d65b1c 100644
--- a/gatekeeperd/gatekeeperd.cpp
+++ b/gatekeeperd/gatekeeperd.cpp
@@ -16,7 +16,8 @@
#define LOG_TAG "gatekeeperd"
-#include "IGateKeeperService.h"
+#include <android/service/gatekeeper/BnGateKeeperService.h>
+#include <gatekeeper/GateKeeperResponse.h>
#include <errno.h>
#include <fcntl.h>
@@ -41,8 +42,6 @@
#include <utils/Log.h>
#include <utils/String16.h>
-#include "SoftGateKeeperDevice.h"
-
#include <hidl/HidlSupport.h>
#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
@@ -52,6 +51,11 @@
using android::hardware::gatekeeper::V1_0::GatekeeperResponse;
using android::hardware::Return;
+using ::android::binder::Status;
+using ::android::service::gatekeeper::BnGateKeeperService;
+using GKResponse = ::android::service::gatekeeper::GateKeeperResponse;
+using GKResponseCode = ::android::service::gatekeeper::ResponseCode;
+
namespace android {
static const String16 KEYGUARD_PERMISSION("android.permission.ACCESS_KEYGUARD_SECURE_STORAGE");
@@ -64,9 +68,8 @@
hw_device = IGatekeeper::getService();
is_running_gsi = android::base::GetBoolProperty(android::gsi::kGsiBootedProp, false);
- if (hw_device == nullptr) {
- ALOGW("falling back to software GateKeeper");
- soft_device.reset(new SoftGateKeeperDevice());
+ if (!hw_device) {
+ LOG(ERROR) << "Could not find Gatekeeper device, which makes me very sad.";
}
}
@@ -92,7 +95,7 @@
if (mark_cold_boot() && !is_running_gsi) {
ALOGI("cold boot: clearing state");
- if (hw_device != nullptr) {
+ if (hw_device) {
hw_device->deleteAllUsers([](const GatekeeperResponse &){});
}
}
@@ -154,16 +157,16 @@
return uid;
}
- virtual int enroll(uint32_t uid,
- const uint8_t *current_password_handle, uint32_t current_password_handle_length,
- const uint8_t *current_password, uint32_t current_password_length,
- const uint8_t *desired_password, uint32_t desired_password_length,
- uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length) {
+#define GK_ERROR *gkResponse = GKResponse::error(), Status::ok()
+
+ Status enroll(int32_t uid, const std::unique_ptr<std::vector<uint8_t>>& currentPasswordHandle,
+ const std::unique_ptr<std::vector<uint8_t>>& currentPassword,
+ const std::vector<uint8_t>& desiredPassword, GKResponse* gkResponse) override {
IPCThreadState* ipc = IPCThreadState::self();
const int calling_pid = ipc->getCallingPid();
const int calling_uid = ipc->getCallingUid();
if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
- return PERMISSION_DENIED;
+ return GK_ERROR;
}
// Make sure to clear any state from before factory reset as soon as a credential is
@@ -171,225 +174,189 @@
clear_state_if_needed();
// need a desired password to enroll
- if (desired_password_length == 0) return -EINVAL;
+ if (desiredPassword.size() == 0) return GK_ERROR;
- int ret;
- if (hw_device != nullptr) {
- const gatekeeper::password_handle_t *handle =
- reinterpret_cast<const gatekeeper::password_handle_t *>(current_password_handle);
+ if (!hw_device) {
+ LOG(ERROR) << "has no HAL to talk to";
+ return GK_ERROR;
+ }
- if (handle != NULL && handle->version != 0 && !handle->hardware_backed) {
- // handle is being re-enrolled from a software version. HAL probably won't accept
- // the handle as valid, so we nullify it and enroll from scratch
- current_password_handle = NULL;
- current_password_handle_length = 0;
- current_password = NULL;
- current_password_length = 0;
+ android::hardware::hidl_vec<uint8_t> curPwdHandle;
+ android::hardware::hidl_vec<uint8_t> curPwd;
+
+ if (currentPasswordHandle && currentPassword) {
+ if (currentPasswordHandle->size() != sizeof(gatekeeper::password_handle_t)) {
+ LOG(INFO) << "Password handle has wrong length";
+ return GK_ERROR;
}
+ curPwdHandle.setToExternal(const_cast<uint8_t*>(currentPasswordHandle->data()),
+ currentPasswordHandle->size());
+ curPwd.setToExternal(const_cast<uint8_t*>(currentPassword->data()),
+ currentPassword->size());
+ }
- android::hardware::hidl_vec<uint8_t> curPwdHandle;
- curPwdHandle.setToExternal(const_cast<uint8_t*>(current_password_handle),
- current_password_handle_length);
- android::hardware::hidl_vec<uint8_t> curPwd;
- curPwd.setToExternal(const_cast<uint8_t*>(current_password),
- current_password_length);
- android::hardware::hidl_vec<uint8_t> newPwd;
- newPwd.setToExternal(const_cast<uint8_t*>(desired_password),
- desired_password_length);
+ android::hardware::hidl_vec<uint8_t> newPwd;
+ newPwd.setToExternal(const_cast<uint8_t*>(desiredPassword.data()), desiredPassword.size());
- uint32_t hw_uid = adjust_uid(uid);
- Return<void> hwRes = hw_device->enroll(hw_uid, curPwdHandle, curPwd, newPwd,
- [&ret, enrolled_password_handle, enrolled_password_handle_length]
- (const GatekeeperResponse &rsp) {
- ret = static_cast<int>(rsp.code); // propagate errors
- if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
- if (enrolled_password_handle != nullptr &&
- enrolled_password_handle_length != nullptr) {
- *enrolled_password_handle = new uint8_t[rsp.data.size()];
- *enrolled_password_handle_length = rsp.data.size();
- memcpy(*enrolled_password_handle, rsp.data.data(),
- *enrolled_password_handle_length);
+ uint32_t hw_uid = adjust_uid(uid);
+ Return<void> hwRes = hw_device->enroll(
+ hw_uid, curPwdHandle, curPwd, newPwd, [&gkResponse](const GatekeeperResponse& rsp) {
+ if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
+ *gkResponse = GKResponse::ok({rsp.data.begin(), rsp.data.end()});
+ } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT &&
+ rsp.timeout > 0) {
+ *gkResponse = GKResponse::retry(rsp.timeout);
+ } else {
+ *gkResponse = GKResponse::error();
}
- ret = 0; // all success states are reported as 0
- } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT && rsp.timeout > 0) {
- ret = rsp.timeout;
- }
- });
- if (!hwRes.isOk()) {
- ALOGE("enroll transaction failed\n");
- ret = -1;
+ });
+ if (!hwRes.isOk()) {
+ LOG(ERROR) << "enroll transaction failed";
+ return GK_ERROR;
+ }
+
+ if (gkResponse->response_code() == GKResponseCode::OK && !gkResponse->should_reenroll()) {
+ if (gkResponse->payload().size() != sizeof(gatekeeper::password_handle_t)) {
+ LOG(ERROR) << "HAL returned password handle of invalid length "
+ << gkResponse->payload().size();
+ return GK_ERROR;
}
- } else {
- ret = soft_device->enroll(uid,
- current_password_handle, current_password_handle_length,
- current_password, current_password_length,
- desired_password, desired_password_length,
- enrolled_password_handle, enrolled_password_handle_length);
- }
- if (ret == GATEKEEPER_RESPONSE_OK && (*enrolled_password_handle == nullptr ||
- *enrolled_password_handle_length != sizeof(password_handle_t))) {
- ret = GATEKEEPER_RESPONSE_ERROR;
- ALOGE("HAL: password_handle=%p size_of_handle=%" PRIu32 "\n",
- *enrolled_password_handle, *enrolled_password_handle_length);
- }
-
- if (ret == GATEKEEPER_RESPONSE_OK) {
- gatekeeper::password_handle_t *handle =
- reinterpret_cast<gatekeeper::password_handle_t *>(*enrolled_password_handle);
+ const gatekeeper::password_handle_t* handle =
+ reinterpret_cast<const gatekeeper::password_handle_t*>(
+ gkResponse->payload().data());
store_sid(uid, handle->user_id);
- bool rr;
+ GKResponse verifyResponse;
// immediately verify this password so we don't ask the user to enter it again
// if they just created it.
- verify(uid, *enrolled_password_handle, sizeof(password_handle_t), desired_password,
- desired_password_length, &rr);
+ auto status = verify(uid, gkResponse->payload(), desiredPassword, &verifyResponse);
+ if (!status.isOk() || verifyResponse.response_code() != GKResponseCode::OK) {
+ LOG(ERROR) << "Failed to verify password after enrolling";
+ }
}
- return ret;
+ return Status::ok();
}
- virtual int verify(uint32_t uid,
- const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
- const uint8_t *provided_password, uint32_t provided_password_length, bool *request_reenroll) {
- uint8_t *auth_token = nullptr;
- uint32_t auth_token_length;
- int ret = verifyChallenge(uid, 0, enrolled_password_handle, enrolled_password_handle_length,
- provided_password, provided_password_length,
- &auth_token, &auth_token_length, request_reenroll);
- delete [] auth_token;
- return ret;
+ Status verify(int32_t uid, const ::std::vector<uint8_t>& enrolledPasswordHandle,
+ const ::std::vector<uint8_t>& providedPassword, GKResponse* gkResponse) override {
+ return verifyChallenge(uid, 0 /* challenge */, enrolledPasswordHandle, providedPassword,
+ gkResponse);
}
- virtual int verifyChallenge(uint32_t uid, uint64_t challenge,
- const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
- const uint8_t *provided_password, uint32_t provided_password_length,
- uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll) {
+ Status verifyChallenge(int32_t uid, int64_t challenge,
+ const std::vector<uint8_t>& enrolledPasswordHandle,
+ const std::vector<uint8_t>& providedPassword,
+ GKResponse* gkResponse) override {
IPCThreadState* ipc = IPCThreadState::self();
const int calling_pid = ipc->getCallingPid();
const int calling_uid = ipc->getCallingUid();
if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
- return PERMISSION_DENIED;
+ return GK_ERROR;
}
// can't verify if we're missing either param
- if ((enrolled_password_handle_length | provided_password_length) == 0)
- return -EINVAL;
+ if (enrolledPasswordHandle.size() == 0 || providedPassword.size() == 0) return GK_ERROR;
- int ret;
- if (hw_device != nullptr) {
- const gatekeeper::password_handle_t *handle =
- reinterpret_cast<const gatekeeper::password_handle_t *>(enrolled_password_handle);
- // handle version 0 does not have hardware backed flag, and thus cannot be upgraded to
- // a HAL if there was none before
- if (handle->version == 0 || handle->hardware_backed) {
- uint32_t hw_uid = adjust_uid(uid);
- android::hardware::hidl_vec<uint8_t> curPwdHandle;
- curPwdHandle.setToExternal(const_cast<uint8_t*>(enrolled_password_handle),
- enrolled_password_handle_length);
- android::hardware::hidl_vec<uint8_t> enteredPwd;
- enteredPwd.setToExternal(const_cast<uint8_t*>(provided_password),
- provided_password_length);
- Return<void> hwRes = hw_device->verify(hw_uid, challenge, curPwdHandle, enteredPwd,
- [&ret, request_reenroll, auth_token, auth_token_length]
- (const GatekeeperResponse &rsp) {
- ret = static_cast<int>(rsp.code); // propagate errors
- if (auth_token != nullptr && auth_token_length != nullptr &&
- rsp.code >= GatekeeperStatusCode::STATUS_OK) {
- *auth_token = new uint8_t[rsp.data.size()];
- *auth_token_length = rsp.data.size();
- memcpy(*auth_token, rsp.data.data(), *auth_token_length);
- if (request_reenroll != nullptr) {
- *request_reenroll = (rsp.code == GatekeeperStatusCode::STATUS_REENROLL);
- }
- ret = 0; // all success states are reported as 0
- } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT &&
- rsp.timeout > 0) {
- ret = rsp.timeout;
+ if (!hw_device) return GK_ERROR;
+
+ if (enrolledPasswordHandle.size() != sizeof(gatekeeper::password_handle_t)) {
+ LOG(INFO) << "Password handle has wrong length";
+ return GK_ERROR;
+ }
+ const gatekeeper::password_handle_t* handle =
+ reinterpret_cast<const gatekeeper::password_handle_t*>(
+ enrolledPasswordHandle.data());
+
+ uint32_t hw_uid = adjust_uid(uid);
+ android::hardware::hidl_vec<uint8_t> curPwdHandle;
+ curPwdHandle.setToExternal(const_cast<uint8_t*>(enrolledPasswordHandle.data()),
+ enrolledPasswordHandle.size());
+ android::hardware::hidl_vec<uint8_t> enteredPwd;
+ enteredPwd.setToExternal(const_cast<uint8_t*>(providedPassword.data()),
+ providedPassword.size());
+
+ Return<void> hwRes = hw_device->verify(
+ hw_uid, challenge, curPwdHandle, enteredPwd,
+ [&gkResponse](const GatekeeperResponse& rsp) {
+ if (rsp.code >= GatekeeperStatusCode::STATUS_OK) {
+ *gkResponse = GKResponse::ok(
+ {rsp.data.begin(), rsp.data.end()},
+ rsp.code == GatekeeperStatusCode::STATUS_REENROLL /* reenroll */);
+ } else if (rsp.code == GatekeeperStatusCode::ERROR_RETRY_TIMEOUT) {
+ *gkResponse = GKResponse::retry(rsp.timeout);
+ } else {
+ *gkResponse = GKResponse::error();
}
});
- if (!hwRes.isOk()) {
- ALOGE("verify transaction failed\n");
- ret = -1;
- }
- } else {
- // upgrade scenario, a HAL has been added to this device where there was none before
- SoftGateKeeperDevice soft_dev;
- ret = soft_dev.verify(uid, challenge,
- enrolled_password_handle, enrolled_password_handle_length,
- provided_password, provided_password_length, auth_token, auth_token_length,
- request_reenroll);
- if (ret == 0) {
- // success! re-enroll with HAL
- *request_reenroll = true;
+ if (!hwRes.isOk()) {
+ LOG(ERROR) << "verify transaction failed";
+ return GK_ERROR;
+ }
+
+ if (gkResponse->response_code() == GKResponseCode::OK) {
+ if (gkResponse->payload().size() != 0) {
+ sp<IServiceManager> sm = defaultServiceManager();
+ sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
+ sp<security::keystore::IKeystoreService> service =
+ interface_cast<security::keystore::IKeystoreService>(binder);
+
+ if (service) {
+ int result = 0;
+ auto binder_result = service->addAuthToken(gkResponse->payload(), &result);
+ if (!binder_result.isOk() ||
+ !keystore::KeyStoreServiceReturnCode(result).isOk()) {
+ LOG(ERROR) << "Failure sending auth token to KeyStore: " << result;
+ }
+ } else {
+ LOG(ERROR) << "Cannot deliver auth token. Unable to communicate with Keystore.";
}
}
- } else {
- ret = soft_device->verify(uid, challenge,
- enrolled_password_handle, enrolled_password_handle_length,
- provided_password, provided_password_length, auth_token, auth_token_length,
- request_reenroll);
+
+ maybe_store_sid(uid, handle->user_id);
}
- if (ret == 0 && *auth_token != NULL && *auth_token_length > 0) {
- // TODO: cache service?
- sp<IServiceManager> sm = defaultServiceManager();
- sp<IBinder> binder = sm->getService(String16("android.security.keystore"));
- sp<security::keystore::IKeystoreService> service =
- interface_cast<security::keystore::IKeystoreService>(binder);
- if (service != NULL) {
- std::vector<uint8_t> auth_token_vector(*auth_token,
- (*auth_token) + *auth_token_length);
- int result = 0;
- auto binder_result = service->addAuthToken(auth_token_vector, &result);
- if (!binder_result.isOk() || !keystore::KeyStoreServiceReturnCode(result).isOk()) {
- ALOGE("Failure sending auth token to KeyStore: %" PRId32, result);
- }
- } else {
- ALOGE("Unable to communicate with KeyStore");
- }
- }
-
- if (ret == 0) {
- maybe_store_sid(uid, reinterpret_cast<const gatekeeper::password_handle_t *>(
- enrolled_password_handle)->user_id);
- }
-
- return ret;
+ return Status::ok();
}
- virtual uint64_t getSecureUserId(uint32_t uid) { return read_sid(uid); }
+ Status getSecureUserId(int32_t uid, int64_t* sid) override {
+ *sid = read_sid(uid);
+ return Status::ok();
+ }
- virtual void clearSecureUserId(uint32_t uid) {
+ Status clearSecureUserId(int32_t uid) override {
IPCThreadState* ipc = IPCThreadState::self();
const int calling_pid = ipc->getCallingPid();
const int calling_uid = ipc->getCallingUid();
if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
- return;
+ return Status::ok();
}
clear_sid(uid);
- if (hw_device != nullptr) {
+ if (hw_device) {
uint32_t hw_uid = adjust_uid(uid);
hw_device->deleteUser(hw_uid, [] (const GatekeeperResponse &){});
}
+ return Status::ok();
}
- virtual void reportDeviceSetupComplete() {
+ Status reportDeviceSetupComplete() override {
IPCThreadState* ipc = IPCThreadState::self();
const int calling_pid = ipc->getCallingPid();
const int calling_uid = ipc->getCallingUid();
if (!PermissionCache::checkPermission(KEYGUARD_PERMISSION, calling_pid, calling_uid)) {
ALOGE("%s: permission denied for [%d:%d]", __func__, calling_pid, calling_uid);
- return;
+ return Status::ok();
}
clear_state_if_needed();
+ return Status::ok();
}
- virtual status_t dump(int fd, const Vector<String16> &) {
+ status_t dump(int fd, const Vector<String16>&) override {
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
@@ -410,7 +377,6 @@
private:
sp<IGatekeeper> hw_device;
- std::unique_ptr<SoftGateKeeperDevice> soft_device;
bool clear_state_if_needed_done;
bool is_running_gsi;
diff --git a/gatekeeperd/include/gatekeeper/GateKeeperResponse.h b/gatekeeperd/include/gatekeeper/GateKeeperResponse.h
new file mode 100644
index 0000000..99fff02
--- /dev/null
+++ b/gatekeeperd/include/gatekeeper/GateKeeperResponse.h
@@ -0,0 +1,85 @@
+/*
+**
+** Copyright 2019, 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.
+*/
+
+#ifndef GATEKEEPERD_INCLUDE_GATEKEEPER_GATEKEEPERRESPONSE_H_
+#define GATEKEEPERD_INCLUDE_GATEKEEPER_GATEKEEPERRESPONSE_H_
+
+#include <binder/Parcelable.h>
+
+namespace android {
+namespace service {
+namespace gatekeeper {
+
+enum class ResponseCode : int32_t {
+ ERROR = -1,
+ OK = 0,
+ RETRY = 1,
+};
+
+class GateKeeperResponse : public ::android::Parcelable {
+ GateKeeperResponse(ResponseCode response_code, int32_t timeout = 0,
+ std::vector<uint8_t> payload = {}, bool should_reenroll = false)
+ : response_code_(response_code),
+ timeout_(timeout),
+ payload_(std::move(payload)),
+ should_reenroll_(should_reenroll) {}
+
+ public:
+ GateKeeperResponse() = default;
+ GateKeeperResponse(GateKeeperResponse&&) = default;
+ GateKeeperResponse(const GateKeeperResponse&) = default;
+ GateKeeperResponse& operator=(GateKeeperResponse&&) = default;
+
+ static GateKeeperResponse error() { return GateKeeperResponse(ResponseCode::ERROR); }
+ static GateKeeperResponse retry(int32_t timeout) {
+ return GateKeeperResponse(ResponseCode::RETRY, timeout);
+ }
+ static GateKeeperResponse ok(std::vector<uint8_t> payload, bool reenroll = false) {
+ return GateKeeperResponse(ResponseCode::OK, 0, std::move(payload), reenroll);
+ }
+
+ status_t readFromParcel(const Parcel* in) override;
+ status_t writeToParcel(Parcel* out) const override;
+
+ const std::vector<uint8_t>& payload() const { return payload_; }
+
+ void payload(std::vector<uint8_t> payload) { payload_ = payload; }
+
+ ResponseCode response_code() const { return response_code_; }
+
+ void response_code(ResponseCode response_code) { response_code_ = response_code; }
+
+ bool should_reenroll() const { return should_reenroll_; }
+
+ void should_reenroll(bool should_reenroll) { should_reenroll_ = should_reenroll; }
+
+ int32_t timeout() const { return timeout_; }
+
+ void timeout(int32_t timeout) { timeout_ = timeout; }
+
+ private:
+ ResponseCode response_code_;
+ int32_t timeout_;
+ std::vector<uint8_t> payload_;
+ bool should_reenroll_;
+};
+
+} // namespace gatekeeper
+} // namespace service
+} // namespace android
+
+#endif // GATEKEEPERD_INCLUDE_GATEKEEPER_GATEKEEPERRESPONSE_H_
diff --git a/gatekeeperd/tests/Android.bp b/gatekeeperd/tests/Android.bp
deleted file mode 100644
index d4cf93b..0000000
--- a/gatekeeperd/tests/Android.bp
+++ /dev/null
@@ -1,34 +0,0 @@
-//
-// 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.
-//
-
-cc_test {
- name: "gatekeeperd-unit-tests",
-
- cflags: [
- "-g",
- "-Wall",
- "-Werror",
- "-Wno-missing-field-initializers",
- ],
- shared_libs: [
- "libgatekeeper",
- "libcrypto",
- "libbase",
- ],
- static_libs: ["libscrypt_static"],
- include_dirs: ["external/scrypt/lib/crypto"],
- srcs: ["gatekeeper_test.cpp"],
-}
diff --git a/gatekeeperd/tests/gatekeeper_test.cpp b/gatekeeperd/tests/gatekeeper_test.cpp
deleted file mode 100644
index 100375f..0000000
--- a/gatekeeperd/tests/gatekeeper_test.cpp
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * Copyright 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.
- */
-
-#include <arpa/inet.h>
-#include <iostream>
-
-#include <gtest/gtest.h>
-#include <hardware/hw_auth_token.h>
-
-#include "../SoftGateKeeper.h"
-
-using ::gatekeeper::SizedBuffer;
-using ::testing::Test;
-using ::gatekeeper::EnrollRequest;
-using ::gatekeeper::EnrollResponse;
-using ::gatekeeper::VerifyRequest;
-using ::gatekeeper::VerifyResponse;
-using ::gatekeeper::SoftGateKeeper;
-using ::gatekeeper::secure_id_t;
-
-static void do_enroll(SoftGateKeeper &gatekeeper, EnrollResponse *response) {
- SizedBuffer password;
-
- password.buffer.reset(new uint8_t[16]);
- password.length = 16;
- memset(password.buffer.get(), 0, 16);
- EnrollRequest request(0, NULL, &password, NULL);
-
- gatekeeper.Enroll(request, response);
-}
-
-TEST(GateKeeperTest, EnrollSuccess) {
- SoftGateKeeper gatekeeper;
- EnrollResponse response;
- do_enroll(gatekeeper, &response);
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
-}
-
-TEST(GateKeeperTest, EnrollBogusData) {
- SoftGateKeeper gatekeeper;
- SizedBuffer password;
- EnrollResponse response;
-
- EnrollRequest request(0, NULL, &password, NULL);
-
- gatekeeper.Enroll(request, &response);
-
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_INVALID, response.error);
-}
-
-TEST(GateKeeperTest, VerifySuccess) {
- SoftGateKeeper gatekeeper;
- SizedBuffer provided_password;
- EnrollResponse enroll_response;
-
- provided_password.buffer.reset(new uint8_t[16]);
- provided_password.length = 16;
- memset(provided_password.buffer.get(), 0, 16);
-
- do_enroll(gatekeeper, &enroll_response);
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, enroll_response.error);
- VerifyRequest request(0, 1, &enroll_response.enrolled_password_handle,
- &provided_password);
- VerifyResponse response;
-
- gatekeeper.Verify(request, &response);
-
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
-
- hw_auth_token_t *auth_token =
- reinterpret_cast<hw_auth_token_t *>(response.auth_token.buffer.get());
-
- ASSERT_EQ((uint32_t) HW_AUTH_PASSWORD, ntohl(auth_token->authenticator_type));
- ASSERT_EQ((uint64_t) 1, auth_token->challenge);
- ASSERT_NE(~((uint32_t) 0), auth_token->timestamp);
- ASSERT_NE((uint64_t) 0, auth_token->user_id);
- ASSERT_NE((uint64_t) 0, auth_token->authenticator_id);
-}
-
-TEST(GateKeeperTest, TrustedReEnroll) {
- SoftGateKeeper gatekeeper;
- SizedBuffer provided_password;
- EnrollResponse enroll_response;
- SizedBuffer password_handle;
-
- // do_enroll enrolls an all 0 password
- provided_password.buffer.reset(new uint8_t[16]);
- provided_password.length = 16;
- memset(provided_password.buffer.get(), 0, 16);
- do_enroll(gatekeeper, &enroll_response);
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, enroll_response.error);
-
- // keep a copy of the handle
- password_handle.buffer.reset(new uint8_t[enroll_response.enrolled_password_handle.length]);
- password_handle.length = enroll_response.enrolled_password_handle.length;
- memcpy(password_handle.buffer.get(), enroll_response.enrolled_password_handle.buffer.get(),
- password_handle.length);
-
- // verify first password
- VerifyRequest request(0, 0, &enroll_response.enrolled_password_handle,
- &provided_password);
- VerifyResponse response;
- gatekeeper.Verify(request, &response);
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
- hw_auth_token_t *auth_token =
- reinterpret_cast<hw_auth_token_t *>(response.auth_token.buffer.get());
-
- secure_id_t secure_id = auth_token->user_id;
-
- // enroll new password
- provided_password.buffer.reset(new uint8_t[16]);
- provided_password.length = 16;
- memset(provided_password.buffer.get(), 0, 16);
- SizedBuffer password;
- password.buffer.reset(new uint8_t[16]);
- memset(password.buffer.get(), 1, 16);
- password.length = 16;
- EnrollRequest enroll_request(0, &password_handle, &password, &provided_password);
- gatekeeper.Enroll(enroll_request, &enroll_response);
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, enroll_response.error);
-
- // verify new password
- password.buffer.reset(new uint8_t[16]);
- memset(password.buffer.get(), 1, 16);
- password.length = 16;
- VerifyRequest new_request(0, 0, &enroll_response.enrolled_password_handle,
- &password);
- gatekeeper.Verify(new_request, &response);
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
- ASSERT_EQ(secure_id,
- reinterpret_cast<hw_auth_token_t *>(response.auth_token.buffer.get())->user_id);
-}
-
-
-TEST(GateKeeperTest, UntrustedReEnroll) {
- SoftGateKeeper gatekeeper;
- SizedBuffer provided_password;
- EnrollResponse enroll_response;
-
- // do_enroll enrolls an all 0 password
- provided_password.buffer.reset(new uint8_t[16]);
- provided_password.length = 16;
- memset(provided_password.buffer.get(), 0, 16);
- do_enroll(gatekeeper, &enroll_response);
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, enroll_response.error);
-
- // verify first password
- VerifyRequest request(0, 0, &enroll_response.enrolled_password_handle,
- &provided_password);
- VerifyResponse response;
- gatekeeper.Verify(request, &response);
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
- hw_auth_token_t *auth_token =
- reinterpret_cast<hw_auth_token_t *>(response.auth_token.buffer.get());
-
- secure_id_t secure_id = auth_token->user_id;
-
- // enroll new password
- SizedBuffer password;
- password.buffer.reset(new uint8_t[16]);
- memset(password.buffer.get(), 1, 16);
- password.length = 16;
- EnrollRequest enroll_request(0, NULL, &password, NULL);
- gatekeeper.Enroll(enroll_request, &enroll_response);
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, enroll_response.error);
-
- // verify new password
- password.buffer.reset(new uint8_t[16]);
- memset(password.buffer.get(), 1, 16);
- password.length = 16;
- VerifyRequest new_request(0, 0, &enroll_response.enrolled_password_handle,
- &password);
- gatekeeper.Verify(new_request, &response);
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_NONE, response.error);
- ASSERT_NE(secure_id,
- reinterpret_cast<hw_auth_token_t *>(response.auth_token.buffer.get())->user_id);
-}
-
-
-TEST(GateKeeperTest, VerifyBogusData) {
- SoftGateKeeper gatekeeper;
- SizedBuffer provided_password;
- SizedBuffer password_handle;
- VerifyResponse response;
-
- VerifyRequest request(0, 0, &provided_password, &password_handle);
-
- gatekeeper.Verify(request, &response);
-
- ASSERT_EQ(::gatekeeper::gatekeeper_error_t::ERROR_INVALID, response.error);
-}
diff --git a/init/Android.bp b/init/Android.bp
index fa0a35c..6bc581d 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -63,6 +63,7 @@
"libavb",
"libc++fs",
"libcgrouprc_format",
+ "libmodprobe",
"libprotobuf-cpp-lite",
"libpropertyinfoserializer",
"libpropertyinfoparser",
@@ -127,6 +128,8 @@
"selabel.cpp",
"selinux.cpp",
"service.cpp",
+ "service_list.cpp",
+ "service_parser.cpp",
"service_utils.cpp",
"sigchld_handler.cpp",
"subcontext.cpp",
@@ -254,11 +257,12 @@
"import_parser.cpp",
"host_import_parser.cpp",
"host_init_verifier.cpp",
- "host_init_stubs.cpp",
"parser.cpp",
"rlimit_parser.cpp",
"tokenizer.cpp",
"service.cpp",
+ "service_list.cpp",
+ "service_parser.cpp",
"service_utils.cpp",
"subcontext.cpp",
"subcontext.proto",
diff --git a/init/Android.mk b/init/Android.mk
index 0a3e8c7..b24f757 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -110,6 +110,7 @@
libdexfile_support \
libunwindstack \
libbacktrace \
+ libmodprobe \
LOCAL_SANITIZE := signed-integer-overflow
# First stage init is weird: it may start without stdout/stderr, and no /proc.
diff --git a/init/README.md b/init/README.md
index 6868378..8179bff 100644
--- a/init/README.md
+++ b/init/README.md
@@ -196,9 +196,9 @@
`interface <interface name> <instance name>`
> Associates this service with a list of the HIDL services that it provides. The interface name
- must be a fully-qualified name and not a value name. This is used to allow hwservicemanager to
- lazily start services. When multiple interfaces are served, this tag should be used multiple
- times.
+ must be a fully-qualified name and not a value name. For instance, this is used to allow
+ hwservicemanager to lazily start services. When multiple interfaces are served, this tag should
+ be used multiple times.
For example: interface vendor.foo.bar@1.0::IBaz default
`ioprio <class> <priority>`
diff --git a/init/builtins.cpp b/init/builtins.cpp
index 44cac4b..cc84aa0 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -63,7 +63,6 @@
#include "action_manager.h"
#include "bootchart.h"
-#include "host_init_stubs.h"
#include "init.h"
#include "mount_namespace.h"
#include "parser.h"
@@ -73,6 +72,7 @@
#include "selabel.h"
#include "selinux.h"
#include "service.h"
+#include "service_list.h"
#include "subcontext.h"
#include "util.h"
@@ -88,6 +88,8 @@
namespace android {
namespace init {
+std::vector<std::string> late_import_paths;
+
static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s;
static Result<void> reboot_into_recovery(const std::vector<std::string>& options) {
@@ -588,7 +590,12 @@
if (!ReadFstabFromFile(fstab_file, &fstab)) {
return Error() << "Could not read fstab";
}
- auto mount_fstab_return_code = fs_mgr_mount_all(&fstab, mount_mode);
+
+ auto mount_fstab_return_code =
+ CallFunctionAndHandleProperties(fs_mgr_mount_all, &fstab, mount_mode);
+ if (!mount_fstab_return_code) {
+ return Error() << "Could not call fs_mgr_mount_all(): " << mount_fstab_return_code.error();
+ }
property_set(prop_name, std::to_string(t.duration().count()));
if (import_rc && SelinuxGetVendorAndroidVersion() <= __ANDROID_API_Q__) {
@@ -599,7 +606,7 @@
if (queue_event) {
/* queue_fs_event will queue event based on mount_fstab return code
* and return processed return code*/
- auto queue_fs_result = queue_fs_event(mount_fstab_return_code);
+ auto queue_fs_result = queue_fs_event(*mount_fstab_return_code);
if (!queue_fs_result) {
return Error() << "queue_fs_event() failed: " << queue_fs_result.error();
}
@@ -615,8 +622,13 @@
return Error() << "Could not read fstab";
}
- if (auto result = fs_mgr_umount_all(&fstab); result != 0) {
- return Error() << "umount_fstab() failed " << result;
+ auto result = CallFunctionAndHandleProperties(fs_mgr_umount_all, &fstab);
+ if (!result) {
+ return Error() << "Could not call fs_mgr_mount_all() " << result.error();
+ }
+
+ if (*result != 0) {
+ return Error() << "fs_mgr_mount_all() failed: " << *result;
}
return {};
}
@@ -627,8 +639,13 @@
return Error() << "Could not read fstab '" << args[1] << "'";
}
- if (!fs_mgr_swapon_all(fstab)) {
- return Error() << "fs_mgr_swapon_all() failed";
+ auto result = CallFunctionAndHandleProperties(fs_mgr_swapon_all, fstab);
+ if (!result) {
+ return Error() << "Could not call fs_mgr_swapon_all() " << result.error();
+ }
+
+ if (*result == 0) {
+ return Error() << "fs_mgr_swapon_all() failed.";
}
return {};
diff --git a/init/builtins.h b/init/builtins.h
index 5db0d1c..7bbf6aa 100644
--- a/init/builtins.h
+++ b/init/builtins.h
@@ -40,6 +40,8 @@
const Map& map() const override;
};
+extern std::vector<std::string> late_import_paths;
+
} // namespace init
} // namespace android
diff --git a/init/devices.cpp b/init/devices.cpp
index 5e760d0..e8e6cd7 100644
--- a/init/devices.cpp
+++ b/init/devices.cpp
@@ -39,10 +39,6 @@
#include "selabel.h"
#include "util.h"
-#ifdef _INIT_INIT_H
-#error "Do not include init.h in files used by ueventd; it will expose init's globals"
-#endif
-
using namespace std::chrono_literals;
using android::base::Basename;
diff --git a/init/first_stage_init.cpp b/init/first_stage_init.cpp
index 5d64f41..17387e2 100644
--- a/init/first_stage_init.cpp
+++ b/init/first_stage_init.cpp
@@ -33,6 +33,7 @@
#include <android-base/chrono_utils.h>
#include <android-base/file.h>
#include <android-base/logging.h>
+#include <modprobe/modprobe.h>
#include <private/android_filesystem_config.h>
#include "debug_ramdisk.h"
@@ -192,6 +193,11 @@
old_root_dir.reset();
}
+ Modprobe m({"/lib/modules"});
+ if (!m.LoadListedModules()) {
+ LOG(FATAL) << "Failed to load kernel modules";
+ }
+
if (ForceNormalBoot()) {
mkdir("/first_stage_ramdisk", 0755);
// SwitchRoot() must be called with a mount point as the target, so we bind mount the
diff --git a/init/host_init_stubs.cpp b/init/host_init_stubs.cpp
deleted file mode 100644
index b85e54a..0000000
--- a/init/host_init_stubs.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2018 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 "host_init_stubs.h"
-
-#include <android-base/properties.h>
-
-// unistd.h
-int setgroups(size_t __size, const gid_t* __list) {
- return 0;
-}
-
-namespace android {
-namespace init {
-
-// init.h
-std::string default_console = "/dev/console";
-
-// property_service.h
-bool CanReadProperty(const std::string& source_context, const std::string& name) {
- return true;
-}
-uint32_t SetProperty(const std::string& key, const std::string& value) {
- android::base::SetProperty(key, value);
- return 0;
-}
-uint32_t (*property_set)(const std::string& name, const std::string& value) = SetProperty;
-uint32_t HandlePropertySet(const std::string&, const std::string&, const std::string&, const ucred&,
- std::string*) {
- return 0;
-}
-
-// selinux.h
-int SelinuxGetVendorAndroidVersion() {
- return 10000;
-}
-void SelabelInitialize() {}
-
-bool SelabelLookupFileContext(const std::string& key, int type, std::string* result) {
- return false;
-}
-
-} // namespace init
-} // namespace android
diff --git a/init/host_init_stubs.h b/init/host_init_stubs.h
index f6e9676..7c0544a 100644
--- a/init/host_init_stubs.h
+++ b/init/host_init_stubs.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _INIT_HOST_INIT_STUBS_H
-#define _INIT_HOST_INIT_STUBS_H
+#pragma once
#include <stddef.h>
#include <sys/socket.h>
@@ -23,26 +22,30 @@
#include <string>
+#include <android-base/properties.h>
+
// android/api-level.h
#define __ANDROID_API_P__ 28
// sys/system_properties.h
#define PROP_VALUE_MAX 92
-// unistd.h
-int setgroups(size_t __size, const gid_t* __list);
-
namespace android {
namespace init {
-// init.h
-extern std::string default_console;
-
// property_service.h
-bool CanReadProperty(const std::string& source_context, const std::string& name);
-extern uint32_t (*property_set)(const std::string& name, const std::string& value);
-uint32_t HandlePropertySet(const std::string& name, const std::string& value,
- const std::string& source_context, const ucred& cr, std::string* error);
+inline bool CanReadProperty(const std::string&, const std::string&) {
+ return true;
+}
+inline uint32_t SetProperty(const std::string& key, const std::string& value) {
+ android::base::SetProperty(key, value);
+ return 0;
+}
+inline uint32_t (*property_set)(const std::string& name, const std::string& value) = SetProperty;
+inline uint32_t HandlePropertySet(const std::string&, const std::string&, const std::string&,
+ const ucred&, std::string*) {
+ return 0;
+}
// reboot_utils.h
inline void SetFatalRebootTarget() {}
@@ -50,12 +53,16 @@
abort();
}
+// selabel.h
+inline void SelabelInitialize() {}
+inline bool SelabelLookupFileContext(const std::string&, int, std::string*) {
+ return false;
+}
+
// selinux.h
-int SelinuxGetVendorAndroidVersion();
-void SelabelInitialize();
-bool SelabelLookupFileContext(const std::string& key, int type, std::string* result);
+inline int SelinuxGetVendorAndroidVersion() {
+ return 10000;
+}
} // namespace init
} // namespace android
-
-#endif
diff --git a/init/host_init_verifier.cpp b/init/host_init_verifier.cpp
index cb861f3..9323aa0 100644
--- a/init/host_init_verifier.cpp
+++ b/init/host_init_verifier.cpp
@@ -15,11 +15,13 @@
//
#include <errno.h>
+#include <getopt.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
+#include <iterator>
#include <string>
#include <vector>
@@ -36,6 +38,8 @@
#include "parser.h"
#include "result.h"
#include "service.h"
+#include "service_list.h"
+#include "service_parser.h"
#define EXCLUDE_FS_CONFIG_STRUCTURES
#include "generated_android_ids.h"
@@ -46,9 +50,9 @@
using android::base::ReadFileToString;
using android::base::Split;
-static std::string passwd_file;
+static std::vector<std::string> passwd_files;
-static std::vector<std::pair<std::string, int>> GetVendorPasswd() {
+static std::vector<std::pair<std::string, int>> GetVendorPasswd(const std::string& passwd_file) {
std::string passwd;
if (!ReadFileToString(passwd_file, &passwd)) {
return {};
@@ -70,6 +74,16 @@
return result;
}
+static std::vector<std::pair<std::string, int>> GetVendorPasswd() {
+ std::vector<std::pair<std::string, int>> result;
+ for (const auto& passwd_file : passwd_files) {
+ auto individual_result = GetVendorPasswd(passwd_file);
+ std::move(individual_result.begin(), individual_result.end(),
+ std::back_insert_iterator(result));
+ }
+ return result;
+}
+
passwd* getpwnam(const char* login) { // NOLINT: implementing bad function.
// This isn't thread safe, but that's okay for our purposes.
static char static_name[32] = "";
@@ -124,17 +138,50 @@
#include "generated_stub_builtin_function_map.h"
+void PrintUsage() {
+ std::cout << "usage: host_init_verifier [-p FILE] <init rc file>\n"
+ "\n"
+ "Tests an init script for correctness\n"
+ "\n"
+ "-p FILE\tSearch this passwd file for users and groups\n"
+ << std::endl;
+}
+
int main(int argc, char** argv) {
android::base::InitLogging(argv, &android::base::StdioLogger);
android::base::SetMinimumLogSeverity(android::base::ERROR);
- if (argc != 2 && argc != 3) {
- LOG(ERROR) << "Usage: " << argv[0] << " <init rc file> [passwd file]";
- return EXIT_FAILURE;
+ while (true) {
+ static const struct option long_options[] = {
+ {"help", no_argument, nullptr, 'h'},
+ {nullptr, 0, nullptr, 0},
+ };
+
+ int arg = getopt_long(argc, argv, "p:", long_options, nullptr);
+
+ if (arg == -1) {
+ break;
+ }
+
+ switch (arg) {
+ case 'h':
+ PrintUsage();
+ return EXIT_FAILURE;
+ case 'p':
+ passwd_files.emplace_back(optarg);
+ break;
+ default:
+ std::cerr << "getprop: getopt returned invalid result: " << arg << std::endl;
+ return EXIT_FAILURE;
+ }
}
- if (argc == 3) {
- passwd_file = argv[2];
+ argc -= optind;
+ argv += optind;
+
+ if (argc != 1) {
+ PrintUsage();
+ return EXIT_FAILURE;
}
const BuiltinFunctionMap function_map;
@@ -146,12 +193,12 @@
parser.AddSectionParser("on", std::make_unique<ActionParser>(&am, nullptr));
parser.AddSectionParser("import", std::make_unique<HostImportParser>());
- if (!parser.ParseConfigFileInsecure(argv[1])) {
- LOG(ERROR) << "Failed to open init rc script '" << argv[1] << "'";
+ if (!parser.ParseConfigFileInsecure(*argv)) {
+ LOG(ERROR) << "Failed to open init rc script '" << *argv << "'";
return EXIT_FAILURE;
}
if (parser.parse_error_count() > 0) {
- LOG(ERROR) << "Failed to parse init script '" << argv[1] << "' with "
+ LOG(ERROR) << "Failed to parse init script '" << *argv << "' with "
<< parser.parse_error_count() << " errors";
return EXIT_FAILURE;
}
diff --git a/init/init.cpp b/init/init.cpp
index 1412e4a..b6911e5 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -28,9 +28,11 @@
#include <sys/types.h>
#include <unistd.h>
+#include <functional>
#include <map>
#include <memory>
#include <optional>
+#include <vector>
#include <android-base/chrono_utils.h>
#include <android-base/file.h>
@@ -54,6 +56,7 @@
#include "action_parser.h"
#include "boringssl_self_test.h"
+#include "builtins.h"
#include "epoll.h"
#include "first_stage_init.h"
#include "first_stage_mount.h"
@@ -67,6 +70,8 @@
#include "security.h"
#include "selabel.h"
#include "selinux.h"
+#include "service.h"
+#include "service_parser.h"
#include "sigchld_handler.h"
#include "util.h"
@@ -88,8 +93,6 @@
static char qemu[32];
-std::string default_console = "/dev/console";
-
static int signal_fd = -1;
static std::unique_ptr<Timer> waiting_for_prop(nullptr);
@@ -100,8 +103,6 @@
static bool do_shutdown = false;
static bool load_debug_prop = false;
-std::vector<std::string> late_import_paths;
-
static std::vector<Subcontext>* subcontexts;
void DumpState() {
@@ -198,6 +199,14 @@
if (property_triggers_enabled) ActionManager::GetInstance().QueuePropertyChange(name, value);
+ // We always record how long init waited for ueventd to tell us cold boot finished.
+ // If we aren't waiting on this property, it means that ueventd finished before we even started
+ // to wait.
+ if (name == kColdBootDoneProp) {
+ auto time_waited = waiting_for_prop ? waiting_for_prop->duration().count() : 0;
+ property_set("ro.boottime.init.cold_boot_wait", std::to_string(time_waited));
+ }
+
if (waiting_for_prop) {
if (wait_prop_name == name && wait_prop_value == value) {
LOG(INFO) << "Wait for property '" << wait_prop_name << "=" << wait_prop_value
@@ -331,31 +340,10 @@
}
static Result<void> wait_for_coldboot_done_action(const BuiltinArguments& args) {
- Timer t;
-
- LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "...";
-
- // Historically we had a 1s timeout here because we weren't otherwise
- // tracking boot time, and many OEMs made their sepolicy regular
- // expressions too expensive (http://b/19899875).
-
- // Now we're tracking boot time, just log the time taken to a system
- // property. We still panic if it takes more than a minute though,
- // because any build that slow isn't likely to boot at all, and we'd
- // rather any test lab devices fail back to the bootloader.
- if (wait_for_file(COLDBOOT_DONE, 60s) < 0) {
- LOG(FATAL) << "Timed out waiting for " COLDBOOT_DONE;
+ if (!start_waiting_for_property(kColdBootDoneProp, "true")) {
+ LOG(FATAL) << "Could not wait for '" << kColdBootDoneProp << "'";
}
- property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration().count()));
- return {};
-}
-
-static Result<void> console_init_action(const BuiltinArguments& args) {
- std::string console = GetProperty("ro.boot.console", "");
- if (!console.empty()) {
- default_console = "/dev/" + console;
- }
return {};
}
@@ -765,7 +753,6 @@
return {};
},
"KeychordInit");
- am.QueueBuiltinAction(console_init_action, "console_init");
// Trigger all the boot actions to get us started.
am.QueueEventTrigger("init");
diff --git a/init/init.h b/init/init.h
index 90ead0e..cfc28f1 100644
--- a/init/init.h
+++ b/init/init.h
@@ -14,29 +14,20 @@
* limitations under the License.
*/
-#ifndef _INIT_INIT_H
-#define _INIT_INIT_H
+#pragma once
#include <sys/types.h>
-#include <functional>
#include <string>
-#include <vector>
#include "action.h"
#include "action_manager.h"
#include "parser.h"
-#include "service.h"
+#include "service_list.h"
namespace android {
namespace init {
-// Note: These globals are *only* valid in init, so they should not be used in ueventd
-// or any files that may be included in ueventd, such as devices.cpp and util.cpp.
-// TODO: Have an Init class and remove all globals.
-extern std::string default_console;
-extern std::vector<std::string> late_import_paths;
-
Parser CreateParser(ActionManager& action_manager, ServiceList& service_list);
Parser CreateServiceOnlyParser(ServiceList& service_list);
@@ -54,5 +45,3 @@
} // namespace init
} // namespace android
-
-#endif /* _INIT_INIT_H */
diff --git a/init/init_test.cpp b/init/init_test.cpp
index 18c2b38..1bcc5ef 100644
--- a/init/init_test.cpp
+++ b/init/init_test.cpp
@@ -27,6 +27,8 @@
#include "keyword_map.h"
#include "parser.h"
#include "service.h"
+#include "service_list.h"
+#include "service_parser.h"
#include "test_function_map.h"
#include "util.h"
diff --git a/init/modalias_handler.cpp b/init/modalias_handler.cpp
index a511156..07b05d8 100644
--- a/init/modalias_handler.cpp
+++ b/init/modalias_handler.cpp
@@ -16,147 +16,20 @@
#include "modalias_handler.h"
-#include <fnmatch.h>
-#include <sys/syscall.h>
-
-#include <algorithm>
-#include <functional>
#include <string>
#include <vector>
-#include <android-base/chrono_utils.h>
-#include <android-base/logging.h>
-#include <android-base/unique_fd.h>
-
-#include "parser.h"
+#include <modprobe/modprobe.h>
namespace android {
namespace init {
-Result<void> ModaliasHandler::ParseDepCallback(std::vector<std::string>&& args) {
- std::vector<std::string> deps;
-
- // Set first item as our modules path
- std::string::size_type pos = args[0].find(':');
- if (pos != std::string::npos) {
- deps.emplace_back(args[0].substr(0, pos));
- } else {
- return Error() << "dependency lines must start with name followed by ':'";
- }
-
- // Remaining items are dependencies of our module
- for (auto arg = args.begin() + 1; arg != args.end(); ++arg) {
- deps.push_back(*arg);
- }
-
- // Key is striped module name to match names in alias file
- std::size_t start = args[0].find_last_of('/');
- std::size_t end = args[0].find(".ko:");
- if ((end - start) <= 1) return Error() << "malformed dependency line";
- auto mod_name = args[0].substr(start + 1, (end - start) - 1);
- // module names can have '-', but their file names will have '_'
- std::replace(mod_name.begin(), mod_name.end(), '-', '_');
- this->module_deps_[mod_name] = deps;
-
- return {};
-}
-
-Result<void> ModaliasHandler::ParseAliasCallback(std::vector<std::string>&& args) {
- auto it = args.begin();
- const std::string& type = *it++;
-
- if (type != "alias") {
- return Error() << "we only handle alias lines, got: " << type;
- }
-
- if (args.size() != 3) {
- return Error() << "alias lines must have 3 entries";
- }
-
- std::string& alias = *it++;
- std::string& module_name = *it++;
- this->module_aliases_.emplace_back(alias, module_name);
-
- return {};
-}
-
-ModaliasHandler::ModaliasHandler() {
- using namespace std::placeholders;
-
- static const std::string base_paths[] = {
- "/vendor/lib/modules/",
- "/lib/modules/",
- "/odm/lib/modules/",
- };
-
- Parser alias_parser;
- auto alias_callback = std::bind(&ModaliasHandler::ParseAliasCallback, this, _1);
- alias_parser.AddSingleLineParser("alias", alias_callback);
- for (const auto& base_path : base_paths) alias_parser.ParseConfig(base_path + "modules.alias");
-
- Parser dep_parser;
- auto dep_callback = std::bind(&ModaliasHandler::ParseDepCallback, this, _1);
- dep_parser.AddSingleLineParser("", dep_callback);
- for (const auto& base_path : base_paths) dep_parser.ParseConfig(base_path + "modules.dep");
-}
-
-Result<void> ModaliasHandler::Insmod(const std::string& path_name, const std::string& args) {
- base::unique_fd fd(
- TEMP_FAILURE_RETRY(open(path_name.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
- if (fd == -1) return ErrnoError() << "Could not open module '" << path_name << "'";
-
- int ret = syscall(__NR_finit_module, fd.get(), args.c_str(), 0);
- if (ret != 0) {
- if (errno == EEXIST) {
- // Module already loaded
- return {};
- }
- return ErrnoError() << "Failed to insmod '" << path_name << "' with args '" << args << "'";
- }
-
- LOG(INFO) << "Loaded kernel module " << path_name;
- return {};
-}
-
-Result<void> ModaliasHandler::InsmodWithDeps(const std::string& module_name,
- const std::string& args) {
- if (module_name.empty()) {
- return Error() << "Need valid module name";
- }
-
- auto it = module_deps_.find(module_name);
- if (it == module_deps_.end()) {
- return Error() << "Module '" << module_name << "' not in dependency file";
- }
- auto& dependencies = it->second;
-
- // load module dependencies in reverse order
- for (auto dep = dependencies.rbegin(); dep != dependencies.rend() - 1; ++dep) {
- if (auto result = Insmod(*dep, ""); !result) return result;
- }
-
- // load target module itself with args
- return Insmod(dependencies[0], args);
-}
+ModaliasHandler::ModaliasHandler(const std::vector<std::string>& base_paths)
+ : modprobe_(base_paths) {}
void ModaliasHandler::HandleUevent(const Uevent& uevent) {
if (uevent.modalias.empty()) return;
-
- for (const auto& [alias, module] : module_aliases_) {
- if (fnmatch(alias.c_str(), uevent.modalias.c_str(), 0) != 0) continue; // Keep looking
-
- LOG(DEBUG) << "Loading kernel module '" << module << "' for alias '" << uevent.modalias
- << "'";
-
- if (auto result = InsmodWithDeps(module, ""); !result) {
- LOG(ERROR) << "Cannot load module: " << result.error();
- // try another one since there may be another match
- continue;
- }
-
- // loading was successful
- return;
- }
+ modprobe_.LoadWithAliases(uevent.modalias, true);
}
} // namespace init
diff --git a/init/modalias_handler.h b/init/modalias_handler.h
index 7d0afde..ce89a05 100644
--- a/init/modalias_handler.h
+++ b/init/modalias_handler.h
@@ -17,10 +17,10 @@
#pragma once
#include <string>
-#include <unordered_map>
#include <vector>
-#include "result.h"
+#include <modprobe/modprobe.h>
+
#include "uevent.h"
#include "uevent_handler.h"
@@ -29,20 +29,13 @@
class ModaliasHandler : public UeventHandler {
public:
- ModaliasHandler();
+ ModaliasHandler(const std::vector<std::string>&);
virtual ~ModaliasHandler() = default;
void HandleUevent(const Uevent& uevent) override;
private:
- Result<void> InsmodWithDeps(const std::string& module_name, const std::string& args);
- Result<void> Insmod(const std::string& path_name, const std::string& args);
-
- Result<void> ParseDepCallback(std::vector<std::string>&& args);
- Result<void> ParseAliasCallback(std::vector<std::string>&& args);
-
- std::vector<std::pair<std::string, std::string>> module_aliases_;
- std::unordered_map<std::string, std::vector<std::string>> module_deps_;
+ Modprobe modprobe_;
};
} // namespace init
diff --git a/init/property_service.cpp b/init/property_service.cpp
index 14bb819..1520c9f 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -39,6 +39,7 @@
#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
#include <sys/_system_properties.h>
+#include <atomic>
#include <map>
#include <memory>
#include <mutex>
@@ -52,6 +53,7 @@
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
#include <property_info_parser/property_info_parser.h>
#include <property_info_serializer/property_info_serializer.h>
#include <selinux/android.h>
@@ -59,7 +61,6 @@
#include <selinux/selinux.h>
#include "debug_ramdisk.h"
-#include "epoll.h"
#include "init.h"
#include "persistent_properties.h"
#include "property_type.h"
@@ -76,6 +77,7 @@
using android::base::StringPrintf;
using android::base::Timer;
using android::base::Trim;
+using android::base::unique_fd;
using android::base::WriteStringToFile;
using android::properties::BuildTrie;
using android::properties::ParsePropertyInfoFile;
@@ -1006,5 +1008,42 @@
}
}
+Result<int> CallFunctionAndHandlePropertiesImpl(const std::function<int()>& f) {
+ unique_fd reader;
+ unique_fd writer;
+ if (!Socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, &reader, &writer)) {
+ return ErrnoError() << "Could not create socket pair";
+ }
+
+ int result = 0;
+ std::atomic<bool> end = false;
+ auto thread = std::thread{[&f, &result, &end, &writer] {
+ result = f();
+ end = true;
+ send(writer, "1", 1, 0);
+ }};
+
+ Epoll epoll;
+ if (auto result = epoll.Open(); !result) {
+ return Error() << "Could not create epoll: " << result.error();
+ }
+ if (auto result = epoll.RegisterHandler(property_set_fd, handle_property_set_fd); !result) {
+ return Error() << "Could not register epoll handler for property fd: " << result.error();
+ }
+
+ // No-op function, just used to break from loop.
+ if (auto result = epoll.RegisterHandler(reader, [] {}); !result) {
+ return Error() << "Could not register epoll handler for ending thread:" << result.error();
+ }
+
+ while (!end) {
+ epoll.Wait({});
+ }
+
+ thread.join();
+
+ return result;
+}
+
} // namespace init
} // namespace android
diff --git a/init/property_service.h b/init/property_service.h
index 7f9f844..dc47b4d 100644
--- a/init/property_service.h
+++ b/init/property_service.h
@@ -18,9 +18,11 @@
#include <sys/socket.h>
+#include <functional>
#include <string>
#include "epoll.h"
+#include "result.h"
namespace android {
namespace init {
@@ -37,5 +39,13 @@
void load_persist_props();
void StartPropertyService(Epoll* epoll);
+template <typename F, typename... Args>
+Result<int> CallFunctionAndHandleProperties(F&& f, Args&&... args) {
+ Result<int> CallFunctionAndHandlePropertiesImpl(const std::function<int()>& f);
+
+ auto func = [&] { return f(args...); };
+ return CallFunctionAndHandlePropertiesImpl(func);
+}
+
} // namespace init
} // namespace android
diff --git a/init/reboot.cpp b/init/reboot.cpp
index eaba3cc..d9d885c 100644
--- a/init/reboot.cpp
+++ b/init/reboot.cpp
@@ -55,6 +55,7 @@
#include "property_service.h"
#include "reboot_utils.h"
#include "service.h"
+#include "service_list.h"
#include "sigchld_handler.h"
#define PROC_SYSRQ "/proc/sysrq-trigger"
diff --git a/init/service.cpp b/init/service.cpp
index 4fe374c..cd08f3d 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -18,11 +18,9 @@
#include <fcntl.h>
#include <inttypes.h>
-#include <linux/input.h>
#include <linux/securebits.h>
#include <sched.h>
#include <sys/prctl.h>
-#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <termios.h>
@@ -30,27 +28,20 @@
#include <android-base/file.h>
#include <android-base/logging.h>
-#include <android-base/parseint.h>
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
-#include <hidl-util/FQName.h>
#include <processgroup/processgroup.h>
#include <selinux/selinux.h>
-#include <system/thread_defs.h>
-#include "rlimit_parser.h"
+#include "service_list.h"
#include "util.h"
#if defined(__ANDROID__)
#include <ApexProperties.sysprop.h>
-#include <android/api-level.h>
-#include <sys/system_properties.h>
-#include "init.h"
#include "mount_namespace.h"
#include "property_service.h"
-#include "selinux.h"
#else
#include "host_init_stubs.h"
#endif
@@ -58,8 +49,6 @@
using android::base::boot_clock;
using android::base::GetProperty;
using android::base::Join;
-using android::base::ParseInt;
-using android::base::Split;
using android::base::StartsWith;
using android::base::StringPrintf;
using android::base::WriteStringToFile;
@@ -315,450 +304,6 @@
[] (const auto& info) { LOG(INFO) << *info; });
}
-Result<void> Service::ParseCapabilities(std::vector<std::string>&& args) {
- capabilities_ = 0;
-
- if (!CapAmbientSupported()) {
- return Error()
- << "capabilities requested but the kernel does not support ambient capabilities";
- }
-
- unsigned int last_valid_cap = GetLastValidCap();
- if (last_valid_cap >= capabilities_->size()) {
- LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
- }
-
- for (size_t i = 1; i < args.size(); i++) {
- const std::string& arg = args[i];
- int res = LookupCap(arg);
- if (res < 0) {
- return Errorf("invalid capability '{}'", arg);
- }
- unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
- if (cap > last_valid_cap) {
- return Errorf("capability '{}' not supported by the kernel", arg);
- }
- (*capabilities_)[cap] = true;
- }
- return {};
-}
-
-Result<void> Service::ParseClass(std::vector<std::string>&& args) {
- classnames_ = std::set<std::string>(args.begin() + 1, args.end());
- return {};
-}
-
-Result<void> Service::ParseConsole(std::vector<std::string>&& args) {
- flags_ |= SVC_CONSOLE;
- proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
- return {};
-}
-
-Result<void> Service::ParseCritical(std::vector<std::string>&& args) {
- flags_ |= SVC_CRITICAL;
- return {};
-}
-
-Result<void> Service::ParseDisabled(std::vector<std::string>&& args) {
- flags_ |= SVC_DISABLED;
- flags_ |= SVC_RC_DISABLED;
- return {};
-}
-
-Result<void> Service::ParseEnterNamespace(std::vector<std::string>&& args) {
- if (args[1] != "net") {
- return Error() << "Init only supports entering network namespaces";
- }
- if (!namespaces_.namespaces_to_enter.empty()) {
- return Error() << "Only one network namespace may be entered";
- }
- // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
- // present. Therefore, they also require mount namespaces.
- namespaces_.flags |= CLONE_NEWNS;
- namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
- return {};
-}
-
-Result<void> Service::ParseGroup(std::vector<std::string>&& args) {
- auto gid = DecodeUid(args[1]);
- if (!gid) {
- return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
- }
- proc_attr_.gid = *gid;
-
- for (std::size_t n = 2; n < args.size(); n++) {
- gid = DecodeUid(args[n]);
- if (!gid) {
- return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
- }
- proc_attr_.supp_gids.emplace_back(*gid);
- }
- return {};
-}
-
-Result<void> Service::ParsePriority(std::vector<std::string>&& args) {
- proc_attr_.priority = 0;
- if (!ParseInt(args[1], &proc_attr_.priority,
- static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
- static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
- return Errorf("process priority value must be range {} - {}", ANDROID_PRIORITY_HIGHEST,
- ANDROID_PRIORITY_LOWEST);
- }
- return {};
-}
-
-Result<void> Service::ParseInterface(std::vector<std::string>&& args) {
- const std::string& interface_name = args[1];
- const std::string& instance_name = args[2];
-
- FQName fq_name;
- if (!FQName::parse(interface_name, &fq_name)) {
- return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
- }
-
- if (!fq_name.isFullyQualified()) {
- return Error() << "Interface name not fully-qualified '" << interface_name << "'";
- }
-
- if (fq_name.isValidValueName()) {
- return Error() << "Interface name must not be a value name '" << interface_name << "'";
- }
-
- const std::string fullname = interface_name + "/" + instance_name;
-
- for (const auto& svc : ServiceList::GetInstance()) {
- if (svc->interfaces().count(fullname) > 0) {
- return Error() << "Interface '" << fullname << "' redefined in " << name()
- << " but is already defined by " << svc->name();
- }
- }
-
- interfaces_.insert(fullname);
-
- return {};
-}
-
-Result<void> Service::ParseIoprio(std::vector<std::string>&& args) {
- if (!ParseInt(args[2], &proc_attr_.ioprio_pri, 0, 7)) {
- return Error() << "priority value must be range 0 - 7";
- }
-
- if (args[1] == "rt") {
- proc_attr_.ioprio_class = IoSchedClass_RT;
- } else if (args[1] == "be") {
- proc_attr_.ioprio_class = IoSchedClass_BE;
- } else if (args[1] == "idle") {
- proc_attr_.ioprio_class = IoSchedClass_IDLE;
- } else {
- return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
- }
-
- return {};
-}
-
-Result<void> Service::ParseKeycodes(std::vector<std::string>&& args) {
- auto it = args.begin() + 1;
- if (args.size() == 2 && StartsWith(args[1], "$")) {
- std::string expanded;
- if (!expand_props(args[1], &expanded)) {
- return Error() << "Could not expand property '" << args[1] << "'";
- }
-
- // If the property is not set, it defaults to none, in which case there are no keycodes
- // for this service.
- if (expanded == "none") {
- return {};
- }
-
- args = Split(expanded, ",");
- it = args.begin();
- }
-
- for (; it != args.end(); ++it) {
- int code;
- if (ParseInt(*it, &code, 0, KEY_MAX)) {
- for (auto& key : keycodes_) {
- if (key == code) return Error() << "duplicate keycode: " << *it;
- }
- keycodes_.insert(std::upper_bound(keycodes_.begin(), keycodes_.end(), code), code);
- } else {
- return Error() << "invalid keycode: " << *it;
- }
- }
- return {};
-}
-
-Result<void> Service::ParseOneshot(std::vector<std::string>&& args) {
- flags_ |= SVC_ONESHOT;
- return {};
-}
-
-Result<void> Service::ParseOnrestart(std::vector<std::string>&& args) {
- args.erase(args.begin());
- int line = onrestart_.NumCommands() + 1;
- if (auto result = onrestart_.AddCommand(std::move(args), line); !result) {
- return Error() << "cannot add Onrestart command: " << result.error();
- }
- return {};
-}
-
-Result<void> Service::ParseNamespace(std::vector<std::string>&& args) {
- for (size_t i = 1; i < args.size(); i++) {
- if (args[i] == "pid") {
- namespaces_.flags |= CLONE_NEWPID;
- // PID namespaces require mount namespaces.
- namespaces_.flags |= CLONE_NEWNS;
- } else if (args[i] == "mnt") {
- namespaces_.flags |= CLONE_NEWNS;
- } else {
- return Error() << "namespace must be 'pid' or 'mnt'";
- }
- }
- return {};
-}
-
-Result<void> Service::ParseOomScoreAdjust(std::vector<std::string>&& args) {
- if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
- return Error() << "oom_score_adjust value must be in range -1000 - +1000";
- }
- return {};
-}
-
-Result<void> Service::ParseOverride(std::vector<std::string>&& args) {
- override_ = true;
- return {};
-}
-
-Result<void> Service::ParseMemcgSwappiness(std::vector<std::string>&& args) {
- if (!ParseInt(args[1], &swappiness_, 0)) {
- return Error() << "swappiness value must be equal or greater than 0";
- }
- return {};
-}
-
-Result<void> Service::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
- if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
- return Error() << "limit_in_bytes value must be equal or greater than 0";
- }
- return {};
-}
-
-Result<void> Service::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
- if (!ParseInt(args[1], &limit_percent_, 0)) {
- return Error() << "limit_percent value must be equal or greater than 0";
- }
- return {};
-}
-
-Result<void> Service::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
- limit_property_ = std::move(args[1]);
- return {};
-}
-
-Result<void> Service::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
- if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
- return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
- }
- return {};
-}
-
-Result<void> Service::ParseProcessRlimit(std::vector<std::string>&& args) {
- auto rlimit = ParseRlimit(args);
- if (!rlimit) return rlimit.error();
-
- proc_attr_.rlimits.emplace_back(*rlimit);
- return {};
-}
-
-Result<void> Service::ParseRestartPeriod(std::vector<std::string>&& args) {
- int period;
- if (!ParseInt(args[1], &period, 5)) {
- return Error() << "restart_period value must be an integer >= 5";
- }
- restart_period_ = std::chrono::seconds(period);
- return {};
-}
-
-Result<void> Service::ParseSeclabel(std::vector<std::string>&& args) {
- seclabel_ = std::move(args[1]);
- return {};
-}
-
-Result<void> Service::ParseSigstop(std::vector<std::string>&& args) {
- sigstop_ = true;
- return {};
-}
-
-Result<void> Service::ParseSetenv(std::vector<std::string>&& args) {
- environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
- return {};
-}
-
-Result<void> Service::ParseShutdown(std::vector<std::string>&& args) {
- if (args[1] == "critical") {
- flags_ |= SVC_SHUTDOWN_CRITICAL;
- return {};
- }
- return Error() << "Invalid shutdown option";
-}
-
-Result<void> Service::ParseTimeoutPeriod(std::vector<std::string>&& args) {
- int period;
- if (!ParseInt(args[1], &period, 1)) {
- return Error() << "timeout_period value must be an integer >= 1";
- }
- timeout_period_ = std::chrono::seconds(period);
- return {};
-}
-
-template <typename T>
-Result<void> Service::AddDescriptor(std::vector<std::string>&& args) {
- int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
- Result<uid_t> uid = 0;
- Result<gid_t> gid = 0;
- std::string context = args.size() > 6 ? args[6] : "";
-
- if (args.size() > 4) {
- uid = DecodeUid(args[4]);
- if (!uid) {
- return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
- }
- }
-
- if (args.size() > 5) {
- gid = DecodeUid(args[5]);
- if (!gid) {
- return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
- }
- }
-
- auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
-
- auto old =
- std::find_if(descriptors_.begin(), descriptors_.end(),
- [&descriptor] (const auto& other) { return descriptor.get() == other.get(); });
-
- if (old != descriptors_.end()) {
- return Error() << "duplicate descriptor " << args[1] << " " << args[2];
- }
-
- descriptors_.emplace_back(std::move(descriptor));
- return {};
-}
-
-// name type perm [ uid gid context ]
-Result<void> Service::ParseSocket(std::vector<std::string>&& args) {
- if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
- !StartsWith(args[2], "seqpacket")) {
- return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
- }
- return AddDescriptor<SocketInfo>(std::move(args));
-}
-
-// name type perm [ uid gid context ]
-Result<void> Service::ParseFile(std::vector<std::string>&& args) {
- if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
- return Error() << "file type must be 'r', 'w' or 'rw'";
- }
- std::string expanded;
- if (!expand_props(args[1], &expanded)) {
- return Error() << "Could not expand property in file path '" << args[1] << "'";
- }
- args[1] = std::move(expanded);
- if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
- return Error() << "file name must not be relative";
- }
- return AddDescriptor<FileInfo>(std::move(args));
-}
-
-Result<void> Service::ParseUser(std::vector<std::string>&& args) {
- auto uid = DecodeUid(args[1]);
- if (!uid) {
- return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
- }
- proc_attr_.uid = *uid;
- return {};
-}
-
-Result<void> Service::ParseWritepid(std::vector<std::string>&& args) {
- args.erase(args.begin());
- writepid_files_ = std::move(args);
- return {};
-}
-
-Result<void> Service::ParseUpdatable(std::vector<std::string>&& args) {
- updatable_ = true;
- return {};
-}
-
-class Service::OptionParserMap : public KeywordMap<OptionParser> {
- public:
- OptionParserMap() {}
-
- private:
- const Map& map() const override;
-};
-
-const Service::OptionParserMap::Map& Service::OptionParserMap::map() const {
- constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
- // clang-format off
- static const Map option_parsers = {
- {"capabilities",
- {0, kMax, &Service::ParseCapabilities}},
- {"class", {1, kMax, &Service::ParseClass}},
- {"console", {0, 1, &Service::ParseConsole}},
- {"critical", {0, 0, &Service::ParseCritical}},
- {"disabled", {0, 0, &Service::ParseDisabled}},
- {"enter_namespace",
- {2, 2, &Service::ParseEnterNamespace}},
- {"file", {2, 2, &Service::ParseFile}},
- {"group", {1, NR_SVC_SUPP_GIDS + 1, &Service::ParseGroup}},
- {"interface", {2, 2, &Service::ParseInterface}},
- {"ioprio", {2, 2, &Service::ParseIoprio}},
- {"keycodes", {1, kMax, &Service::ParseKeycodes}},
- {"memcg.limit_in_bytes",
- {1, 1, &Service::ParseMemcgLimitInBytes}},
- {"memcg.limit_percent",
- {1, 1, &Service::ParseMemcgLimitPercent}},
- {"memcg.limit_property",
- {1, 1, &Service::ParseMemcgLimitProperty}},
- {"memcg.soft_limit_in_bytes",
- {1, 1, &Service::ParseMemcgSoftLimitInBytes}},
- {"memcg.swappiness",
- {1, 1, &Service::ParseMemcgSwappiness}},
- {"namespace", {1, 2, &Service::ParseNamespace}},
- {"oneshot", {0, 0, &Service::ParseOneshot}},
- {"onrestart", {1, kMax, &Service::ParseOnrestart}},
- {"oom_score_adjust",
- {1, 1, &Service::ParseOomScoreAdjust}},
- {"override", {0, 0, &Service::ParseOverride}},
- {"priority", {1, 1, &Service::ParsePriority}},
- {"restart_period",
- {1, 1, &Service::ParseRestartPeriod}},
- {"rlimit", {3, 3, &Service::ParseProcessRlimit}},
- {"seclabel", {1, 1, &Service::ParseSeclabel}},
- {"setenv", {2, 2, &Service::ParseSetenv}},
- {"shutdown", {1, 1, &Service::ParseShutdown}},
- {"sigstop", {0, 0, &Service::ParseSigstop}},
- {"socket", {3, 6, &Service::ParseSocket}},
- {"timeout_period",
- {1, 1, &Service::ParseTimeoutPeriod}},
- {"updatable", {0, 0, &Service::ParseUpdatable}},
- {"user", {1, 1, &Service::ParseUser}},
- {"writepid", {1, kMax, &Service::ParseWritepid}},
- };
- // clang-format on
- return option_parsers;
-}
-
-Result<void> Service::ParseLine(std::vector<std::string>&& args) {
- static const OptionParserMap parser_map;
- auto parser = parser_map.FindFunction(args);
-
- if (!parser) return parser.error();
-
- return std::invoke(*parser, this, std::move(args));
-}
Result<void> Service::ExecStart() {
if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
@@ -813,7 +358,7 @@
bool needs_console = (flags_ & SVC_CONSOLE);
if (needs_console) {
if (proc_attr_.console.empty()) {
- proc_attr_.console = default_console;
+ proc_attr_.console = "/dev/" + GetProperty("ro.boot.console", "console");
}
// Make sure that open call succeeds to ensure a console driver is
@@ -1072,17 +617,6 @@
}
}
-ServiceList::ServiceList() {}
-
-ServiceList& ServiceList::GetInstance() {
- static ServiceList instance;
- return instance;
-}
-
-void ServiceList::AddService(std::unique_ptr<Service> service) {
- services_.emplace_back(std::move(service));
-}
-
std::unique_ptr<Service> Service::MakeTemporaryOneshotService(const std::vector<std::string>& args) {
// Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
// SECLABEL can be a - to denote default
@@ -1147,139 +681,5 @@
nullptr, str_args);
}
-// Shutdown services in the opposite order that they were started.
-const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
- std::vector<Service*> shutdown_services;
- for (const auto& service : services_) {
- if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
- }
- std::sort(shutdown_services.begin(), shutdown_services.end(),
- [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
- return shutdown_services;
-}
-
-void ServiceList::RemoveService(const Service& svc) {
- auto svc_it = std::find_if(services_.begin(), services_.end(),
- [&svc] (const std::unique_ptr<Service>& s) {
- return svc.name() == s->name();
- });
- if (svc_it == services_.end()) {
- return;
- }
-
- services_.erase(svc_it);
-}
-
-void ServiceList::DumpState() const {
- for (const auto& s : services_) {
- s->DumpState();
- }
-}
-
-void ServiceList::MarkPostData() {
- post_data_ = true;
-}
-
-bool ServiceList::IsPostData() {
- return post_data_;
-}
-
-void ServiceList::MarkServicesUpdate() {
- services_update_finished_ = true;
-
- // start the delayed services
- for (const auto& name : delayed_service_names_) {
- Service* service = FindService(name);
- if (service == nullptr) {
- LOG(ERROR) << "delayed service '" << name << "' could not be found.";
- continue;
- }
- if (auto result = service->Start(); !result) {
- LOG(ERROR) << result.error().message();
- }
- }
- delayed_service_names_.clear();
-}
-
-void ServiceList::DelayService(const Service& service) {
- if (services_update_finished_) {
- LOG(ERROR) << "Cannot delay the start of service '" << service.name()
- << "' because all services are already updated. Ignoring.";
- return;
- }
- delayed_service_names_.emplace_back(service.name());
-}
-
-Result<void> ServiceParser::ParseSection(std::vector<std::string>&& args,
- const std::string& filename, int line) {
- if (args.size() < 3) {
- return Error() << "services must have a name and a program";
- }
-
- const std::string& name = args[1];
- if (!IsValidName(name)) {
- return Error() << "invalid service name '" << name << "'";
- }
-
- filename_ = filename;
-
- Subcontext* restart_action_subcontext = nullptr;
- if (subcontexts_) {
- for (auto& subcontext : *subcontexts_) {
- if (StartsWith(filename, subcontext.path_prefix())) {
- restart_action_subcontext = &subcontext;
- break;
- }
- }
- }
-
- std::vector<std::string> str_args(args.begin() + 2, args.end());
-
- if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
- if (str_args[0] == "/sbin/watchdogd") {
- str_args[0] = "/system/bin/watchdogd";
- }
- }
-
- service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
- return {};
-}
-
-Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
- return service_ ? service_->ParseLine(std::move(args)) : Result<void>{};
-}
-
-Result<void> ServiceParser::EndSection() {
- if (service_) {
- Service* old_service = service_list_->FindService(service_->name());
- if (old_service) {
- if (!service_->is_override()) {
- return Error() << "ignored duplicate definition of service '" << service_->name()
- << "'";
- }
-
- if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
- return Error() << "cannot update a non-updatable service '" << service_->name()
- << "' with a config in APEX";
- }
-
- service_list_->RemoveService(*old_service);
- old_service = nullptr;
- }
-
- service_list_->AddService(std::move(service_));
- }
-
- return {};
-}
-
-bool ServiceParser::IsValidName(const std::string& name) const {
- // Property names can be any length, but may only contain certain characters.
- // Property values can contain any characters, but may only be a certain length.
- // (The latter restriction is needed because `start` and `stop` work by writing
- // the service name to the "ctl.start" and "ctl.stop" properties.)
- return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
-}
-
} // namespace init
} // namespace android
diff --git a/init/service.h b/init/service.h
index b4356c8..78f94ce 100644
--- a/init/service.h
+++ b/init/service.h
@@ -14,11 +14,9 @@
* limitations under the License.
*/
-#ifndef _INIT_SERVICE_H
-#define _INIT_SERVICE_H
+#pragma once
#include <signal.h>
-#include <sys/resource.h>
#include <sys/types.h>
#include <chrono>
@@ -64,6 +62,8 @@
namespace init {
class Service {
+ friend class ServiceParser;
+
public:
Service(const std::string& name, Subcontext* subcontext_for_restart_commands,
const std::vector<std::string>& args);
@@ -76,7 +76,6 @@
static std::unique_ptr<Service> MakeTemporaryOneshotService(const std::vector<std::string>& args);
bool IsRunning() { return (flags_ & SVC_RUNNING) != 0; }
- Result<void> ParseLine(std::vector<std::string>&& args);
Result<void> ExecStart();
Result<void> Start();
Result<void> StartIfNotDisabled();
@@ -130,51 +129,11 @@
bool is_post_data() const { return post_data_; }
private:
- using OptionParser = Result<void> (Service::*)(std::vector<std::string>&& args);
- class OptionParserMap;
-
void NotifyStateChange(const std::string& new_state) const;
void StopOrReset(int how);
void KillProcessGroup(int signal);
void SetProcessAttributesAndCaps();
- Result<void> ParseCapabilities(std::vector<std::string>&& args);
- Result<void> ParseClass(std::vector<std::string>&& args);
- Result<void> ParseConsole(std::vector<std::string>&& args);
- Result<void> ParseCritical(std::vector<std::string>&& args);
- Result<void> ParseDisabled(std::vector<std::string>&& args);
- Result<void> ParseEnterNamespace(std::vector<std::string>&& args);
- Result<void> ParseGroup(std::vector<std::string>&& args);
- Result<void> ParsePriority(std::vector<std::string>&& args);
- Result<void> ParseInterface(std::vector<std::string>&& args);
- Result<void> ParseIoprio(std::vector<std::string>&& args);
- Result<void> ParseKeycodes(std::vector<std::string>&& args);
- Result<void> ParseOneshot(std::vector<std::string>&& args);
- Result<void> ParseOnrestart(std::vector<std::string>&& args);
- Result<void> ParseOomScoreAdjust(std::vector<std::string>&& args);
- Result<void> ParseOverride(std::vector<std::string>&& args);
- Result<void> ParseMemcgLimitInBytes(std::vector<std::string>&& args);
- Result<void> ParseMemcgLimitPercent(std::vector<std::string>&& args);
- Result<void> ParseMemcgLimitProperty(std::vector<std::string>&& args);
- Result<void> ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args);
- Result<void> ParseMemcgSwappiness(std::vector<std::string>&& args);
- Result<void> ParseNamespace(std::vector<std::string>&& args);
- Result<void> ParseProcessRlimit(std::vector<std::string>&& args);
- Result<void> ParseRestartPeriod(std::vector<std::string>&& args);
- Result<void> ParseSeclabel(std::vector<std::string>&& args);
- Result<void> ParseSetenv(std::vector<std::string>&& args);
- Result<void> ParseShutdown(std::vector<std::string>&& args);
- Result<void> ParseSigstop(std::vector<std::string>&& args);
- Result<void> ParseSocket(std::vector<std::string>&& args);
- Result<void> ParseTimeoutPeriod(std::vector<std::string>&& args);
- Result<void> ParseFile(std::vector<std::string>&& args);
- Result<void> ParseUser(std::vector<std::string>&& args);
- Result<void> ParseWritepid(std::vector<std::string>&& args);
- Result<void> ParseUpdatable(std::vector<std::string>&& args);
-
- template <typename T>
- Result<void> AddDescriptor(std::vector<std::string>&& args);
-
static unsigned long next_start_order_;
static bool is_exec_service_running_;
@@ -238,79 +197,5 @@
bool running_at_post_data_reset_ = false;
};
-class ServiceList {
- public:
- static ServiceList& GetInstance();
-
- // Exposed for testing
- ServiceList();
-
- void AddService(std::unique_ptr<Service> service);
- void RemoveService(const Service& svc);
-
- template <typename T, typename F = decltype(&Service::name)>
- Service* FindService(T value, F function = &Service::name) const {
- auto svc = std::find_if(services_.begin(), services_.end(),
- [&function, &value](const std::unique_ptr<Service>& s) {
- return std::invoke(function, s) == value;
- });
- if (svc != services_.end()) {
- return svc->get();
- }
- return nullptr;
- }
-
- Service* FindInterface(const std::string& interface_name) {
- for (const auto& svc : services_) {
- if (svc->interfaces().count(interface_name) > 0) {
- return svc.get();
- }
- }
-
- return nullptr;
- }
-
- void DumpState() const;
-
- auto begin() const { return services_.begin(); }
- auto end() const { return services_.end(); }
- const std::vector<std::unique_ptr<Service>>& services() const { return services_; }
- const std::vector<Service*> services_in_shutdown_order() const;
-
- void MarkPostData();
- bool IsPostData();
- void MarkServicesUpdate();
- bool IsServicesUpdated() const { return services_update_finished_; }
- void DelayService(const Service& service);
-
- private:
- std::vector<std::unique_ptr<Service>> services_;
-
- bool post_data_ = false;
- bool services_update_finished_ = false;
- std::vector<std::string> delayed_service_names_;
-};
-
-class ServiceParser : public SectionParser {
- public:
- ServiceParser(ServiceList* service_list, std::vector<Subcontext>* subcontexts)
- : service_list_(service_list), subcontexts_(subcontexts), service_(nullptr) {}
- Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
- int line) override;
- Result<void> ParseLineSection(std::vector<std::string>&& args, int line) override;
- Result<void> EndSection() override;
- void EndFile() override { filename_ = ""; }
-
- private:
- bool IsValidName(const std::string& name) const;
-
- ServiceList* service_list_;
- std::vector<Subcontext>* subcontexts_;
- std::unique_ptr<Service> service_;
- std::string filename_;
-};
-
} // namespace init
} // namespace android
-
-#endif
diff --git a/init/service_list.cpp b/init/service_list.cpp
new file mode 100644
index 0000000..3a48183
--- /dev/null
+++ b/init/service_list.cpp
@@ -0,0 +1,98 @@
+/*
+ * Copyright (C) 2019 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 "service_list.h"
+
+#include <android-base/logging.h>
+
+namespace android {
+namespace init {
+
+ServiceList::ServiceList() {}
+
+ServiceList& ServiceList::GetInstance() {
+ static ServiceList instance;
+ return instance;
+}
+
+void ServiceList::AddService(std::unique_ptr<Service> service) {
+ services_.emplace_back(std::move(service));
+}
+
+// Shutdown services in the opposite order that they were started.
+const std::vector<Service*> ServiceList::services_in_shutdown_order() const {
+ std::vector<Service*> shutdown_services;
+ for (const auto& service : services_) {
+ if (service->start_order() > 0) shutdown_services.emplace_back(service.get());
+ }
+ std::sort(shutdown_services.begin(), shutdown_services.end(),
+ [](const auto& a, const auto& b) { return a->start_order() > b->start_order(); });
+ return shutdown_services;
+}
+
+void ServiceList::RemoveService(const Service& svc) {
+ auto svc_it = std::find_if(
+ services_.begin(), services_.end(),
+ [&svc](const std::unique_ptr<Service>& s) { return svc.name() == s->name(); });
+ if (svc_it == services_.end()) {
+ return;
+ }
+
+ services_.erase(svc_it);
+}
+
+void ServiceList::DumpState() const {
+ for (const auto& s : services_) {
+ s->DumpState();
+ }
+}
+
+void ServiceList::MarkPostData() {
+ post_data_ = true;
+}
+
+bool ServiceList::IsPostData() {
+ return post_data_;
+}
+
+void ServiceList::MarkServicesUpdate() {
+ services_update_finished_ = true;
+
+ // start the delayed services
+ for (const auto& name : delayed_service_names_) {
+ Service* service = FindService(name);
+ if (service == nullptr) {
+ LOG(ERROR) << "delayed service '" << name << "' could not be found.";
+ continue;
+ }
+ if (auto result = service->Start(); !result) {
+ LOG(ERROR) << result.error().message();
+ }
+ }
+ delayed_service_names_.clear();
+}
+
+void ServiceList::DelayService(const Service& service) {
+ if (services_update_finished_) {
+ LOG(ERROR) << "Cannot delay the start of service '" << service.name()
+ << "' because all services are already updated. Ignoring.";
+ return;
+ }
+ delayed_service_names_.emplace_back(service.name());
+}
+
+} // namespace init
+} // namespace android
diff --git a/init/service_list.h b/init/service_list.h
new file mode 100644
index 0000000..2136a21
--- /dev/null
+++ b/init/service_list.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2019 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 <memory>
+#include <vector>
+
+#include "service.h"
+
+namespace android {
+namespace init {
+
+class ServiceList {
+ public:
+ static ServiceList& GetInstance();
+
+ // Exposed for testing
+ ServiceList();
+
+ void AddService(std::unique_ptr<Service> service);
+ void RemoveService(const Service& svc);
+
+ template <typename T, typename F = decltype(&Service::name)>
+ Service* FindService(T value, F function = &Service::name) const {
+ auto svc = std::find_if(services_.begin(), services_.end(),
+ [&function, &value](const std::unique_ptr<Service>& s) {
+ return std::invoke(function, s) == value;
+ });
+ if (svc != services_.end()) {
+ return svc->get();
+ }
+ return nullptr;
+ }
+
+ Service* FindInterface(const std::string& interface_name) {
+ for (const auto& svc : services_) {
+ if (svc->interfaces().count(interface_name) > 0) {
+ return svc.get();
+ }
+ }
+
+ return nullptr;
+ }
+
+ void DumpState() const;
+
+ auto begin() const { return services_.begin(); }
+ auto end() const { return services_.end(); }
+ const std::vector<std::unique_ptr<Service>>& services() const { return services_; }
+ const std::vector<Service*> services_in_shutdown_order() const;
+
+ void MarkPostData();
+ bool IsPostData();
+ void MarkServicesUpdate();
+ bool IsServicesUpdated() const { return services_update_finished_; }
+ void DelayService(const Service& service);
+
+ private:
+ std::vector<std::unique_ptr<Service>> services_;
+
+ bool post_data_ = false;
+ bool services_update_finished_ = false;
+ std::vector<std::string> delayed_service_names_;
+};
+
+} // namespace init
+} // namespace android
diff --git a/init/service_parser.cpp b/init/service_parser.cpp
new file mode 100644
index 0000000..33ed050
--- /dev/null
+++ b/init/service_parser.cpp
@@ -0,0 +1,567 @@
+/*
+ * Copyright (C) 2019 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 "service_parser.h"
+
+#include <linux/input.h>
+
+#include <android-base/logging.h>
+#include <android-base/parseint.h>
+#include <android-base/strings.h>
+#include <hidl-util/FQName.h>
+#include <system/thread_defs.h>
+
+#include "rlimit_parser.h"
+#include "util.h"
+
+#if defined(__ANDROID__)
+#include <android/api-level.h>
+#include <sys/system_properties.h>
+
+#include "selinux.h"
+#else
+#include "host_init_stubs.h"
+#endif
+
+using android::base::ParseInt;
+using android::base::Split;
+using android::base::StartsWith;
+
+namespace android {
+namespace init {
+
+Result<void> ServiceParser::ParseCapabilities(std::vector<std::string>&& args) {
+ service_->capabilities_ = 0;
+
+ if (!CapAmbientSupported()) {
+ return Error()
+ << "capabilities requested but the kernel does not support ambient capabilities";
+ }
+
+ unsigned int last_valid_cap = GetLastValidCap();
+ if (last_valid_cap >= service_->capabilities_->size()) {
+ LOG(WARNING) << "last valid run-time capability is larger than CAP_LAST_CAP";
+ }
+
+ for (size_t i = 1; i < args.size(); i++) {
+ const std::string& arg = args[i];
+ int res = LookupCap(arg);
+ if (res < 0) {
+ return Errorf("invalid capability '{}'", arg);
+ }
+ unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
+ if (cap > last_valid_cap) {
+ return Errorf("capability '{}' not supported by the kernel", arg);
+ }
+ (*service_->capabilities_)[cap] = true;
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParseClass(std::vector<std::string>&& args) {
+ service_->classnames_ = std::set<std::string>(args.begin() + 1, args.end());
+ return {};
+}
+
+Result<void> ServiceParser::ParseConsole(std::vector<std::string>&& args) {
+ service_->flags_ |= SVC_CONSOLE;
+ service_->proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
+ return {};
+}
+
+Result<void> ServiceParser::ParseCritical(std::vector<std::string>&& args) {
+ service_->flags_ |= SVC_CRITICAL;
+ return {};
+}
+
+Result<void> ServiceParser::ParseDisabled(std::vector<std::string>&& args) {
+ service_->flags_ |= SVC_DISABLED;
+ service_->flags_ |= SVC_RC_DISABLED;
+ return {};
+}
+
+Result<void> ServiceParser::ParseEnterNamespace(std::vector<std::string>&& args) {
+ if (args[1] != "net") {
+ return Error() << "Init only supports entering network namespaces";
+ }
+ if (!service_->namespaces_.namespaces_to_enter.empty()) {
+ return Error() << "Only one network namespace may be entered";
+ }
+ // Network namespaces require that /sys is remounted, otherwise the old adapters will still be
+ // present. Therefore, they also require mount namespaces.
+ service_->namespaces_.flags |= CLONE_NEWNS;
+ service_->namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
+ return {};
+}
+
+Result<void> ServiceParser::ParseGroup(std::vector<std::string>&& args) {
+ auto gid = DecodeUid(args[1]);
+ if (!gid) {
+ return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
+ }
+ service_->proc_attr_.gid = *gid;
+
+ for (std::size_t n = 2; n < args.size(); n++) {
+ gid = DecodeUid(args[n]);
+ if (!gid) {
+ return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
+ }
+ service_->proc_attr_.supp_gids.emplace_back(*gid);
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParsePriority(std::vector<std::string>&& args) {
+ service_->proc_attr_.priority = 0;
+ if (!ParseInt(args[1], &service_->proc_attr_.priority,
+ static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
+ static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
+ return Errorf("process priority value must be range {} - {}", ANDROID_PRIORITY_HIGHEST,
+ ANDROID_PRIORITY_LOWEST);
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParseInterface(std::vector<std::string>&& args) {
+ const std::string& interface_name = args[1];
+ const std::string& instance_name = args[2];
+
+ FQName fq_name;
+ if (!FQName::parse(interface_name, &fq_name)) {
+ return Error() << "Invalid fully-qualified name for interface '" << interface_name << "'";
+ }
+
+ if (!fq_name.isFullyQualified()) {
+ return Error() << "Interface name not fully-qualified '" << interface_name << "'";
+ }
+
+ if (fq_name.isValidValueName()) {
+ return Error() << "Interface name must not be a value name '" << interface_name << "'";
+ }
+
+ const std::string fullname = interface_name + "/" + instance_name;
+
+ for (const auto& svc : *service_list_) {
+ if (svc->interfaces().count(fullname) > 0) {
+ return Error() << "Interface '" << fullname << "' redefined in " << service_->name()
+ << " but is already defined by " << svc->name();
+ }
+ }
+
+ service_->interfaces_.insert(fullname);
+
+ return {};
+}
+
+Result<void> ServiceParser::ParseIoprio(std::vector<std::string>&& args) {
+ if (!ParseInt(args[2], &service_->proc_attr_.ioprio_pri, 0, 7)) {
+ return Error() << "priority value must be range 0 - 7";
+ }
+
+ if (args[1] == "rt") {
+ service_->proc_attr_.ioprio_class = IoSchedClass_RT;
+ } else if (args[1] == "be") {
+ service_->proc_attr_.ioprio_class = IoSchedClass_BE;
+ } else if (args[1] == "idle") {
+ service_->proc_attr_.ioprio_class = IoSchedClass_IDLE;
+ } else {
+ return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
+ }
+
+ return {};
+}
+
+Result<void> ServiceParser::ParseKeycodes(std::vector<std::string>&& args) {
+ auto it = args.begin() + 1;
+ if (args.size() == 2 && StartsWith(args[1], "$")) {
+ std::string expanded;
+ if (!expand_props(args[1], &expanded)) {
+ return Error() << "Could not expand property '" << args[1] << "'";
+ }
+
+ // If the property is not set, it defaults to none, in which case there are no keycodes
+ // for this service.
+ if (expanded == "none") {
+ return {};
+ }
+
+ args = Split(expanded, ",");
+ it = args.begin();
+ }
+
+ for (; it != args.end(); ++it) {
+ int code;
+ if (ParseInt(*it, &code, 0, KEY_MAX)) {
+ for (auto& key : service_->keycodes_) {
+ if (key == code) return Error() << "duplicate keycode: " << *it;
+ }
+ service_->keycodes_.insert(
+ std::upper_bound(service_->keycodes_.begin(), service_->keycodes_.end(), code),
+ code);
+ } else {
+ return Error() << "invalid keycode: " << *it;
+ }
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParseOneshot(std::vector<std::string>&& args) {
+ service_->flags_ |= SVC_ONESHOT;
+ return {};
+}
+
+Result<void> ServiceParser::ParseOnrestart(std::vector<std::string>&& args) {
+ args.erase(args.begin());
+ int line = service_->onrestart_.NumCommands() + 1;
+ if (auto result = service_->onrestart_.AddCommand(std::move(args), line); !result) {
+ return Error() << "cannot add Onrestart command: " << result.error();
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParseNamespace(std::vector<std::string>&& args) {
+ for (size_t i = 1; i < args.size(); i++) {
+ if (args[i] == "pid") {
+ service_->namespaces_.flags |= CLONE_NEWPID;
+ // PID namespaces require mount namespaces.
+ service_->namespaces_.flags |= CLONE_NEWNS;
+ } else if (args[i] == "mnt") {
+ service_->namespaces_.flags |= CLONE_NEWNS;
+ } else {
+ return Error() << "namespace must be 'pid' or 'mnt'";
+ }
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParseOomScoreAdjust(std::vector<std::string>&& args) {
+ if (!ParseInt(args[1], &service_->oom_score_adjust_, -1000, 1000)) {
+ return Error() << "oom_score_adjust value must be in range -1000 - +1000";
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParseOverride(std::vector<std::string>&& args) {
+ service_->override_ = true;
+ return {};
+}
+
+Result<void> ServiceParser::ParseMemcgSwappiness(std::vector<std::string>&& args) {
+ if (!ParseInt(args[1], &service_->swappiness_, 0)) {
+ return Error() << "swappiness value must be equal or greater than 0";
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
+ if (!ParseInt(args[1], &service_->limit_in_bytes_, 0)) {
+ return Error() << "limit_in_bytes value must be equal or greater than 0";
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
+ if (!ParseInt(args[1], &service_->limit_percent_, 0)) {
+ return Error() << "limit_percent value must be equal or greater than 0";
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
+ service_->limit_property_ = std::move(args[1]);
+ return {};
+}
+
+Result<void> ServiceParser::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
+ if (!ParseInt(args[1], &service_->soft_limit_in_bytes_, 0)) {
+ return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
+ }
+ return {};
+}
+
+Result<void> ServiceParser::ParseProcessRlimit(std::vector<std::string>&& args) {
+ auto rlimit = ParseRlimit(args);
+ if (!rlimit) return rlimit.error();
+
+ service_->proc_attr_.rlimits.emplace_back(*rlimit);
+ return {};
+}
+
+Result<void> ServiceParser::ParseRestartPeriod(std::vector<std::string>&& args) {
+ int period;
+ if (!ParseInt(args[1], &period, 5)) {
+ return Error() << "restart_period value must be an integer >= 5";
+ }
+ service_->restart_period_ = std::chrono::seconds(period);
+ return {};
+}
+
+Result<void> ServiceParser::ParseSeclabel(std::vector<std::string>&& args) {
+ service_->seclabel_ = std::move(args[1]);
+ return {};
+}
+
+Result<void> ServiceParser::ParseSigstop(std::vector<std::string>&& args) {
+ service_->sigstop_ = true;
+ return {};
+}
+
+Result<void> ServiceParser::ParseSetenv(std::vector<std::string>&& args) {
+ service_->environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
+ return {};
+}
+
+Result<void> ServiceParser::ParseShutdown(std::vector<std::string>&& args) {
+ if (args[1] == "critical") {
+ service_->flags_ |= SVC_SHUTDOWN_CRITICAL;
+ return {};
+ }
+ return Error() << "Invalid shutdown option";
+}
+
+Result<void> ServiceParser::ParseTimeoutPeriod(std::vector<std::string>&& args) {
+ int period;
+ if (!ParseInt(args[1], &period, 1)) {
+ return Error() << "timeout_period value must be an integer >= 1";
+ }
+ service_->timeout_period_ = std::chrono::seconds(period);
+ return {};
+}
+
+template <typename T>
+Result<void> ServiceParser::AddDescriptor(std::vector<std::string>&& args) {
+ int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
+ Result<uid_t> uid = 0;
+ Result<gid_t> gid = 0;
+ std::string context = args.size() > 6 ? args[6] : "";
+
+ if (args.size() > 4) {
+ uid = DecodeUid(args[4]);
+ if (!uid) {
+ return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
+ }
+ }
+
+ if (args.size() > 5) {
+ gid = DecodeUid(args[5]);
+ if (!gid) {
+ return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
+ }
+ }
+
+ auto descriptor = std::make_unique<T>(args[1], args[2], *uid, *gid, perm, context);
+
+ auto old = std::find_if(
+ service_->descriptors_.begin(), service_->descriptors_.end(),
+ [&descriptor](const auto& other) { return descriptor.get() == other.get(); });
+
+ if (old != service_->descriptors_.end()) {
+ return Error() << "duplicate descriptor " << args[1] << " " << args[2];
+ }
+
+ service_->descriptors_.emplace_back(std::move(descriptor));
+ return {};
+}
+
+// name type perm [ uid gid context ]
+Result<void> ServiceParser::ParseSocket(std::vector<std::string>&& args) {
+ if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
+ !StartsWith(args[2], "seqpacket")) {
+ return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
+ }
+ return AddDescriptor<SocketInfo>(std::move(args));
+}
+
+// name type perm [ uid gid context ]
+Result<void> ServiceParser::ParseFile(std::vector<std::string>&& args) {
+ if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
+ return Error() << "file type must be 'r', 'w' or 'rw'";
+ }
+ std::string expanded;
+ if (!expand_props(args[1], &expanded)) {
+ return Error() << "Could not expand property in file path '" << args[1] << "'";
+ }
+ args[1] = std::move(expanded);
+ if ((args[1][0] != '/') || (args[1].find("../") != std::string::npos)) {
+ return Error() << "file name must not be relative";
+ }
+ return AddDescriptor<FileInfo>(std::move(args));
+}
+
+Result<void> ServiceParser::ParseUser(std::vector<std::string>&& args) {
+ auto uid = DecodeUid(args[1]);
+ if (!uid) {
+ return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
+ }
+ service_->proc_attr_.uid = *uid;
+ return {};
+}
+
+Result<void> ServiceParser::ParseWritepid(std::vector<std::string>&& args) {
+ args.erase(args.begin());
+ service_->writepid_files_ = std::move(args);
+ return {};
+}
+
+Result<void> ServiceParser::ParseUpdatable(std::vector<std::string>&& args) {
+ service_->updatable_ = true;
+ return {};
+}
+
+class ServiceParser::OptionParserMap : public KeywordMap<OptionParser> {
+ public:
+ OptionParserMap() {}
+
+ private:
+ const Map& map() const override;
+};
+
+const ServiceParser::OptionParserMap::Map& ServiceParser::OptionParserMap::map() const {
+ constexpr std::size_t kMax = std::numeric_limits<std::size_t>::max();
+ // clang-format off
+ static const Map option_parsers = {
+ {"capabilities",
+ {0, kMax, &ServiceParser::ParseCapabilities}},
+ {"class", {1, kMax, &ServiceParser::ParseClass}},
+ {"console", {0, 1, &ServiceParser::ParseConsole}},
+ {"critical", {0, 0, &ServiceParser::ParseCritical}},
+ {"disabled", {0, 0, &ServiceParser::ParseDisabled}},
+ {"enter_namespace",
+ {2, 2, &ServiceParser::ParseEnterNamespace}},
+ {"file", {2, 2, &ServiceParser::ParseFile}},
+ {"group", {1, NR_SVC_SUPP_GIDS + 1, &ServiceParser::ParseGroup}},
+ {"interface", {2, 2, &ServiceParser::ParseInterface}},
+ {"ioprio", {2, 2, &ServiceParser::ParseIoprio}},
+ {"keycodes", {1, kMax, &ServiceParser::ParseKeycodes}},
+ {"memcg.limit_in_bytes",
+ {1, 1, &ServiceParser::ParseMemcgLimitInBytes}},
+ {"memcg.limit_percent",
+ {1, 1, &ServiceParser::ParseMemcgLimitPercent}},
+ {"memcg.limit_property",
+ {1, 1, &ServiceParser::ParseMemcgLimitProperty}},
+ {"memcg.soft_limit_in_bytes",
+ {1, 1, &ServiceParser::ParseMemcgSoftLimitInBytes}},
+ {"memcg.swappiness",
+ {1, 1, &ServiceParser::ParseMemcgSwappiness}},
+ {"namespace", {1, 2, &ServiceParser::ParseNamespace}},
+ {"oneshot", {0, 0, &ServiceParser::ParseOneshot}},
+ {"onrestart", {1, kMax, &ServiceParser::ParseOnrestart}},
+ {"oom_score_adjust",
+ {1, 1, &ServiceParser::ParseOomScoreAdjust}},
+ {"override", {0, 0, &ServiceParser::ParseOverride}},
+ {"priority", {1, 1, &ServiceParser::ParsePriority}},
+ {"restart_period",
+ {1, 1, &ServiceParser::ParseRestartPeriod}},
+ {"rlimit", {3, 3, &ServiceParser::ParseProcessRlimit}},
+ {"seclabel", {1, 1, &ServiceParser::ParseSeclabel}},
+ {"setenv", {2, 2, &ServiceParser::ParseSetenv}},
+ {"shutdown", {1, 1, &ServiceParser::ParseShutdown}},
+ {"sigstop", {0, 0, &ServiceParser::ParseSigstop}},
+ {"socket", {3, 6, &ServiceParser::ParseSocket}},
+ {"timeout_period",
+ {1, 1, &ServiceParser::ParseTimeoutPeriod}},
+ {"updatable", {0, 0, &ServiceParser::ParseUpdatable}},
+ {"user", {1, 1, &ServiceParser::ParseUser}},
+ {"writepid", {1, kMax, &ServiceParser::ParseWritepid}},
+ };
+ // clang-format on
+ return option_parsers;
+}
+
+Result<void> ServiceParser::ParseSection(std::vector<std::string>&& args,
+ const std::string& filename, int line) {
+ if (args.size() < 3) {
+ return Error() << "services must have a name and a program";
+ }
+
+ const std::string& name = args[1];
+ if (!IsValidName(name)) {
+ return Error() << "invalid service name '" << name << "'";
+ }
+
+ filename_ = filename;
+
+ Subcontext* restart_action_subcontext = nullptr;
+ if (subcontexts_) {
+ for (auto& subcontext : *subcontexts_) {
+ if (StartsWith(filename, subcontext.path_prefix())) {
+ restart_action_subcontext = &subcontext;
+ break;
+ }
+ }
+ }
+
+ std::vector<std::string> str_args(args.begin() + 2, args.end());
+
+ if (SelinuxGetVendorAndroidVersion() <= __ANDROID_API_P__) {
+ if (str_args[0] == "/sbin/watchdogd") {
+ str_args[0] = "/system/bin/watchdogd";
+ }
+ }
+
+ service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
+ return {};
+}
+
+Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
+ if (!service_) {
+ return {};
+ }
+
+ static const OptionParserMap parser_map;
+ auto parser = parser_map.FindFunction(args);
+
+ if (!parser) return parser.error();
+
+ return std::invoke(*parser, this, std::move(args));
+}
+
+Result<void> ServiceParser::EndSection() {
+ if (!service_) {
+ return {};
+ }
+
+ Service* old_service = service_list_->FindService(service_->name());
+ if (old_service) {
+ if (!service_->is_override()) {
+ return Error() << "ignored duplicate definition of service '" << service_->name()
+ << "'";
+ }
+
+ if (StartsWith(filename_, "/apex/") && !old_service->is_updatable()) {
+ return Error() << "cannot update a non-updatable service '" << service_->name()
+ << "' with a config in APEX";
+ }
+
+ service_list_->RemoveService(*old_service);
+ old_service = nullptr;
+ }
+
+ service_list_->AddService(std::move(service_));
+
+ return {};
+}
+
+bool ServiceParser::IsValidName(const std::string& name) const {
+ // Property names can be any length, but may only contain certain characters.
+ // Property values can contain any characters, but may only be a certain length.
+ // (The latter restriction is needed because `start` and `stop` work by writing
+ // the service name to the "ctl.start" and "ctl.stop" properties.)
+ return IsLegalPropertyName("init.svc." + name) && name.size() <= PROP_VALUE_MAX;
+}
+
+} // namespace init
+} // namespace android
diff --git a/init/service_parser.h b/init/service_parser.h
new file mode 100644
index 0000000..0a5b291
--- /dev/null
+++ b/init/service_parser.h
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2019 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 <vector>
+
+#include "parser.h"
+#include "service.h"
+#include "service_list.h"
+#include "subcontext.h"
+
+namespace android {
+namespace init {
+
+class ServiceParser : public SectionParser {
+ public:
+ ServiceParser(ServiceList* service_list, std::vector<Subcontext>* subcontexts)
+ : service_list_(service_list), subcontexts_(subcontexts), service_(nullptr) {}
+ Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
+ int line) override;
+ Result<void> ParseLineSection(std::vector<std::string>&& args, int line) override;
+ Result<void> EndSection() override;
+ void EndFile() override { filename_ = ""; }
+
+ private:
+ using OptionParser = Result<void> (ServiceParser::*)(std::vector<std::string>&& args);
+ class OptionParserMap;
+
+ Result<void> ParseCapabilities(std::vector<std::string>&& args);
+ Result<void> ParseClass(std::vector<std::string>&& args);
+ Result<void> ParseConsole(std::vector<std::string>&& args);
+ Result<void> ParseCritical(std::vector<std::string>&& args);
+ Result<void> ParseDisabled(std::vector<std::string>&& args);
+ Result<void> ParseEnterNamespace(std::vector<std::string>&& args);
+ Result<void> ParseGroup(std::vector<std::string>&& args);
+ Result<void> ParsePriority(std::vector<std::string>&& args);
+ Result<void> ParseInterface(std::vector<std::string>&& args);
+ Result<void> ParseIoprio(std::vector<std::string>&& args);
+ Result<void> ParseKeycodes(std::vector<std::string>&& args);
+ Result<void> ParseOneshot(std::vector<std::string>&& args);
+ Result<void> ParseOnrestart(std::vector<std::string>&& args);
+ Result<void> ParseOomScoreAdjust(std::vector<std::string>&& args);
+ Result<void> ParseOverride(std::vector<std::string>&& args);
+ Result<void> ParseMemcgLimitInBytes(std::vector<std::string>&& args);
+ Result<void> ParseMemcgLimitPercent(std::vector<std::string>&& args);
+ Result<void> ParseMemcgLimitProperty(std::vector<std::string>&& args);
+ Result<void> ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args);
+ Result<void> ParseMemcgSwappiness(std::vector<std::string>&& args);
+ Result<void> ParseNamespace(std::vector<std::string>&& args);
+ Result<void> ParseProcessRlimit(std::vector<std::string>&& args);
+ Result<void> ParseRestartPeriod(std::vector<std::string>&& args);
+ Result<void> ParseSeclabel(std::vector<std::string>&& args);
+ Result<void> ParseSetenv(std::vector<std::string>&& args);
+ Result<void> ParseShutdown(std::vector<std::string>&& args);
+ Result<void> ParseSigstop(std::vector<std::string>&& args);
+ Result<void> ParseSocket(std::vector<std::string>&& args);
+ Result<void> ParseTimeoutPeriod(std::vector<std::string>&& args);
+ Result<void> ParseFile(std::vector<std::string>&& args);
+ Result<void> ParseUser(std::vector<std::string>&& args);
+ Result<void> ParseWritepid(std::vector<std::string>&& args);
+ Result<void> ParseUpdatable(std::vector<std::string>&& args);
+
+ template <typename T>
+ Result<void> AddDescriptor(std::vector<std::string>&& args);
+
+ bool IsValidName(const std::string& name) const;
+
+ ServiceList* service_list_;
+ std::vector<Subcontext>* subcontexts_;
+ std::unique_ptr<Service> service_;
+ std::string filename_;
+};
+
+} // namespace init
+} // namespace android
diff --git a/init/sigchld_handler.cpp b/init/sigchld_handler.cpp
index 987b2f9..c9a09cd 100644
--- a/init/sigchld_handler.cpp
+++ b/init/sigchld_handler.cpp
@@ -30,6 +30,7 @@
#include "init.h"
#include "service.h"
+#include "service_list.h"
using android::base::StringPrintf;
using android::base::boot_clock;
diff --git a/init/ueventd.cpp b/init/ueventd.cpp
index d700c46..3b9de0f 100644
--- a/init/ueventd.cpp
+++ b/init/ueventd.cpp
@@ -214,7 +214,7 @@
WaitForSubProcesses();
- close(open(COLDBOOT_DONE, O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
+ android::base::SetProperty(kColdBootDoneProp, "true");
LOG(INFO) << "Coldboot took " << cold_boot_timer.duration().count() / 1000.0f << " seconds";
}
@@ -251,11 +251,12 @@
std::move(ueventd_configuration.firmware_directories)));
if (ueventd_configuration.enable_modalias_handling) {
- uevent_handlers.emplace_back(std::make_unique<ModaliasHandler>());
+ std::vector<std::string> base_paths = {"/odm/lib/modules", "/vendor/lib/modules"};
+ uevent_handlers.emplace_back(std::make_unique<ModaliasHandler>(base_paths));
}
UeventListener uevent_listener(ueventd_configuration.uevent_socket_rcvbuf_size);
- if (access(COLDBOOT_DONE, F_OK) != 0) {
+ if (!android::base::GetBoolProperty(kColdBootDoneProp, false)) {
ColdBoot cold_boot(uevent_listener, uevent_handlers);
cold_boot.Run();
}
diff --git a/init/util.cpp b/init/util.cpp
index 14acaa2..2b34242 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -46,10 +46,6 @@
#include "host_init_stubs.h"
#endif
-#ifdef _INIT_INIT_H
-#error "Do not include init.h in files used by ueventd; it will expose init's globals"
-#endif
-
using android::base::boot_clock;
using namespace std::literals::string_literals;
diff --git a/init/util.h b/init/util.h
index 770084b..1929cb5 100644
--- a/init/util.h
+++ b/init/util.h
@@ -30,14 +30,14 @@
#include "result.h"
-#define COLDBOOT_DONE "/dev/.coldboot_done"
-
using android::base::boot_clock;
using namespace std::chrono_literals;
namespace android {
namespace init {
+static const char kColdBootDoneProp[] = "ro.cold_boot_done";
+
int CreateSocket(const char* name, int type, bool passcred, mode_t perm, uid_t uid, gid_t gid,
const char* socketcon);
diff --git a/libcutils/fs_config.cpp b/libcutils/fs_config.cpp
index 6606030..897a169 100644
--- a/libcutils/fs_config.cpp
+++ b/libcutils/fs_config.cpp
@@ -39,6 +39,8 @@
#include <private/android_filesystem_config.h>
#include <utils/Compat.h>
+#include "fs_config.h"
+
#ifndef O_BINARY
#define O_BINARY 0
#endif
@@ -46,20 +48,8 @@
using android::base::EndsWith;
using android::base::StartsWith;
-// My kingdom for <endian.h>
-static inline uint16_t get2LE(const uint8_t* src) {
- return src[0] | (src[1] << 8);
-}
-
-static inline uint64_t get8LE(const uint8_t* src) {
- uint32_t low, high;
-
- low = src[0] | (src[1] << 8) | (src[2] << 16) | (src[3] << 24);
- high = src[4] | (src[5] << 8) | (src[6] << 16) | (src[7] << 24);
- return ((uint64_t)high << 32) | (uint64_t)low;
-}
-
#define ALIGN(x, alignment) (((x) + ((alignment)-1)) & ~((alignment)-1))
+#define CAP_MASK_LONG(cap_name) (1ULL << (cap_name))
// Rules for directories.
// These rules are applied based on "first match", so they
@@ -333,7 +323,7 @@
while (TEMP_FAILURE_RETRY(read(fd, &header, sizeof(header))) == sizeof(header)) {
char* prefix;
- uint16_t host_len = get2LE((const uint8_t*)&header.len);
+ uint16_t host_len = header.len;
ssize_t len, remainder = host_len - sizeof(header);
if (remainder <= 0) {
ALOGE("%s len is corrupted", conf[which][dir]);
@@ -358,10 +348,10 @@
if (fs_config_cmp(dir, prefix, len, path, plen)) {
free(prefix);
close(fd);
- *uid = get2LE((const uint8_t*)&(header.uid));
- *gid = get2LE((const uint8_t*)&(header.gid));
- *mode = (*mode & (~07777)) | get2LE((const uint8_t*)&(header.mode));
- *capabilities = get8LE((const uint8_t*)&(header.capabilities));
+ *uid = header.uid;
+ *gid = header.gid;
+ *mode = (*mode & (~07777)) | header.mode;
+ *capabilities = header.capabilities;
return;
}
free(prefix);
@@ -379,21 +369,3 @@
*mode = (*mode & (~07777)) | pc->mode;
*capabilities = pc->capabilities;
}
-
-ssize_t fs_config_generate(char* buffer, size_t length, const struct fs_path_config* pc) {
- struct fs_path_config_from_file* p = (struct fs_path_config_from_file*)buffer;
- size_t len = ALIGN(sizeof(*p) + strlen(pc->prefix) + 1, sizeof(uint64_t));
-
- if ((length < len) || (len > UINT16_MAX)) {
- return -ENOSPC;
- }
- memset(p, 0, len);
- uint16_t host_len = len;
- p->len = get2LE((const uint8_t*)&host_len);
- p->mode = get2LE((const uint8_t*)&(pc->mode));
- p->uid = get2LE((const uint8_t*)&(pc->uid));
- p->gid = get2LE((const uint8_t*)&(pc->gid));
- p->capabilities = get8LE((const uint8_t*)&(pc->capabilities));
- strcpy(p->prefix, pc->prefix);
- return len;
-}
diff --git a/libcutils/fs_config.h b/libcutils/fs_config.h
new file mode 100644
index 0000000..66ad48b
--- /dev/null
+++ b/libcutils/fs_config.h
@@ -0,0 +1,37 @@
+/*
+ * Copyright (C) 2019 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 <stdint.h>
+
+// Binary format for the runtime <partition>/etc/fs_config_(dirs|files) filesystem override files.
+struct fs_path_config_from_file {
+ uint16_t len;
+ uint16_t mode;
+ uint16_t uid;
+ uint16_t gid;
+ uint64_t capabilities;
+ char prefix[];
+} __attribute__((__aligned__(sizeof(uint64_t))));
+
+struct fs_path_config {
+ unsigned mode;
+ unsigned uid;
+ unsigned gid;
+ uint64_t capabilities;
+ const char* prefix;
+};
diff --git a/libcutils/fs_config_test.cpp b/libcutils/fs_config_test.cpp
index c26315f..9627152 100644
--- a/libcutils/fs_config_test.cpp
+++ b/libcutils/fs_config_test.cpp
@@ -25,7 +25,8 @@
#include <android-base/strings.h>
#include <private/android_filesystem_config.h>
-#include <private/fs_config.h>
+
+#include "fs_config.h"
extern const fs_path_config* __for_testing_only__android_dirs;
extern const fs_path_config* __for_testing_only__android_files;
diff --git a/libcutils/include/private/fs_config.h b/libcutils/include/private/fs_config.h
index 8926491..8a9a1ff 100644
--- a/libcutils/include/private/fs_config.h
+++ b/libcutils/include/private/fs_config.h
@@ -19,44 +19,17 @@
** by the device side of adb.
*/
-#ifndef _LIBS_CUTILS_PRIVATE_FS_CONFIG_H
-#define _LIBS_CUTILS_PRIVATE_FS_CONFIG_H
+#pragma once
#include <stdint.h>
#include <sys/cdefs.h>
-#include <sys/types.h>
#if defined(__BIONIC__)
#include <linux/capability.h>
#else // defined(__BIONIC__)
-#include "android_filesystem_capability.h"
+#include <private/android_filesystem_capability.h>
#endif // defined(__BIONIC__)
-#define CAP_MASK_LONG(cap_name) (1ULL << (cap_name))
-
-/*
- * binary format for the runtime <partition>/etc/fs_config_(dirs|files)
- * filesystem override files.
- */
-
-/* The following structure is stored little endian */
-struct fs_path_config_from_file {
- uint16_t len;
- uint16_t mode;
- uint16_t uid;
- uint16_t gid;
- uint64_t capabilities;
- char prefix[];
-} __attribute__((__aligned__(sizeof(uint64_t))));
-
-struct fs_path_config {
- unsigned mode;
- unsigned uid;
- unsigned gid;
- uint64_t capabilities;
- const char* prefix;
-};
-
/* Rules for directories and files has moved to system/code/libcutils/fs_config.c */
__BEGIN_DECLS
@@ -74,8 +47,4 @@
void fs_config(const char* path, int dir, const char* target_out_path, unsigned* uid, unsigned* gid,
unsigned* mode, uint64_t* capabilities);
-ssize_t fs_config_generate(char* buffer, size_t length, const struct fs_path_config* pc);
-
__END_DECLS
-
-#endif /* _LIBS_CUTILS_PRIVATE_FS_CONFIG_H */
diff --git a/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp b/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp
index 0851fb3..9a80c82 100644
--- a/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp
+++ b/libmeminfo/libdmabufinfo/tools/dmabuf_dump.cpp
@@ -17,16 +17,17 @@
#include <dirent.h>
#include <errno.h>
#include <inttypes.h>
+#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
-#include <iostream>
#include <fstream>
+#include <iostream>
+#include <map>
+#include <set>
#include <sstream>
#include <string>
#include <vector>
-#include <map>
-#include <set>
#include <android-base/stringprintf.h>
#include <dmabufinfo/dmabufinfo.h>
@@ -43,7 +44,7 @@
exit(exit_status);
}
-static std::string GetProcessBaseName(pid_t pid) {
+static std::string GetProcessComm(const pid_t pid) {
std::string pid_path = android::base::StringPrintf("/proc/%d/comm", pid);
std::ifstream in{pid_path};
if (!in) return std::string("N/A");
@@ -53,85 +54,76 @@
return line;
}
-static void AddPidsToSet(const std::unordered_map<pid_t, int>& map, std::set<pid_t>* set)
-{
- for (auto it = map.begin(); it != map.end(); ++it)
- set->insert(it->first);
+static void AddPidsToSet(const std::unordered_map<pid_t, int>& map, std::set<pid_t>* set) {
+ for (auto it = map.begin(); it != map.end(); ++it) set->insert(it->first);
}
static void PrintDmaBufInfo(const std::vector<DmaBuffer>& bufs) {
- std::set<pid_t> pid_set;
- std::map<pid_t, int> pid_column;
-
if (bufs.empty()) {
- std::cout << "dmabuf info not found ¯\\_(ツ)_/¯" << std::endl;
+ printf("dmabuf info not found ¯\\_(ツ)_/¯\n");
return;
}
// Find all unique pids in the input vector, create a set
+ std::set<pid_t> pid_set;
for (int i = 0; i < bufs.size(); i++) {
AddPidsToSet(bufs[i].fdrefs(), &pid_set);
AddPidsToSet(bufs[i].maprefs(), &pid_set);
}
- int pid_count = 0;
-
- std::cout << "\t\t\t\t\t\t";
-
- // Create a map to convert each unique pid into a column number
- for (auto it = pid_set.begin(); it != pid_set.end(); ++it, ++pid_count) {
- pid_column.insert(std::make_pair(*it, pid_count));
- std::cout << ::android::base::StringPrintf("[pid: % 4d]\t", *it);
+ // Format the header string spaced and separated with '|'
+ printf(" Dmabuf Inode | Size | Ref Counts |");
+ for (auto pid : pid_set) {
+ printf("%16s:%-5d |", GetProcessComm(pid).c_str(), pid);
}
+ printf("\n");
- std::cout << std::endl << "\t\t\t\t\t\t";
+ // holds per-process dmabuf size in kB
+ std::map<pid_t, uint64_t> per_pid_size = {};
+ uint64_t dmabuf_total_size = 0;
- for (auto it = pid_set.begin(); it != pid_set.end(); ++it) {
- std::cout << ::android::base::StringPrintf("%16s",
- GetProcessBaseName(*it).c_str());
- }
+ // Iterate through all dmabufs and collect per-process sizes, refs
+ for (auto& buf : bufs) {
+ printf("%16ju |%13" PRIu64 " kB |%16" PRIu64 " |", static_cast<uintmax_t>(buf.inode()),
+ buf.size() / 1024, buf.total_refs());
+ // Iterate through each process to find out per-process references for each buffer,
+ // gather total size used by each process etc.
+ for (pid_t pid : pid_set) {
+ int pid_refs = 0;
+ if (buf.fdrefs().count(pid) == 1) {
+ // Get the total number of ref counts the process is holding
+ // on this buffer. We don't differentiate between mmap or fd.
+ pid_refs += buf.fdrefs().at(pid);
+ if (buf.maprefs().count(pid) == 1) {
+ pid_refs += buf.maprefs().at(pid);
+ }
+ }
- std::cout << std::endl << "\tinode\t\tsize\t\tcount\t";
- for (int i = 0; i < pid_count; i++) {
- std::cout << "fd\tmap\t";
- }
- std::cout << std::endl;
-
- auto fds = std::make_unique<int[]>(pid_count);
- auto maps = std::make_unique<int[]>(pid_count);
- auto pss = std::make_unique<long[]>(pid_count);
-
- memset(pss.get(), 0, sizeof(long) * pid_count);
-
- for (auto buf = bufs.begin(); buf != bufs.end(); ++buf) {
-
- std::cout << ::android::base::StringPrintf("%16lu\t%10" PRIu64 "\t%" PRIu64 "\t",
- buf->inode(),buf->size(), buf->count());
-
- memset(fds.get(), 0, sizeof(int) * pid_count);
- memset(maps.get(), 0, sizeof(int) * pid_count);
-
- for (auto it = buf->fdrefs().begin(); it != buf->fdrefs().end(); ++it) {
- fds[pid_column[it->first]] = it->second;
- pss[pid_column[it->first]] += buf->size() * it->second / buf->count();
+ if (pid_refs) {
+ // Add up the per-pid total size. Note that if a buffer is mapped
+ // in 2 different processes, the size will be shown as mapped or opened
+ // in both processes. This is intended for visibility.
+ //
+ // If one wants to get the total *unique* dma buffers, they can simply
+ // sum the size of all dma bufs shown by the tool
+ per_pid_size[pid] += buf.size() / 1024;
+ printf("%17d refs |", pid_refs);
+ } else {
+ printf("%22s |", "--");
+ }
}
-
- for (auto it = buf->maprefs().begin(); it != buf->maprefs().end(); ++it) {
- maps[pid_column[it->first]] = it->second;
- pss[pid_column[it->first]] += buf->size() * it->second / buf->count();
- }
-
- for (int i = 0; i < pid_count; i++) {
- std::cout << ::android::base::StringPrintf("%d\t%d\t", fds[i], maps[i]);
- }
- std::cout << std::endl;
+ dmabuf_total_size += buf.size() / 1024;
+ printf("\n");
}
- std::cout << "-----------------------------------------" << std::endl;
- std::cout << "PSS ";
- for (int i = 0; i < pid_count; i++) {
- std::cout << ::android::base::StringPrintf("%15ldK", pss[i] / 1024);
+
+ printf("------------------------------------\n");
+ printf("%-16s %13" PRIu64 " kB |%16s |", "TOTALS", dmabuf_total_size, "n/a");
+ for (auto pid : pid_set) {
+ printf("%19" PRIu64 " kB |", per_pid_size[pid]);
}
- std::cout << std::endl;
+ printf("\n");
+
+ return;
}
int main(int argc, char* argv[]) {
@@ -142,8 +134,7 @@
if (argc > 1) {
if (sscanf(argv[1], "%d", &pid) == 1) {
show_all = false;
- }
- else {
+ } else {
usage(EXIT_FAILURE);
}
}
@@ -178,8 +169,7 @@
exit(EXIT_FAILURE);
}
}
+
PrintDmaBufInfo(bufs);
return 0;
}
-
-
diff --git a/libmeminfo/pageacct.cpp b/libmeminfo/pageacct.cpp
index 0a26c08..cb17af8 100644
--- a/libmeminfo/pageacct.cpp
+++ b/libmeminfo/pageacct.cpp
@@ -81,7 +81,8 @@
if (!InitPageAcct()) return false;
}
- if (pread64(kpageflags_fd_, flags, sizeof(uint64_t), pfn * sizeof(uint64_t)) < 0) {
+ if (pread64(kpageflags_fd_, flags, sizeof(uint64_t), pfn * sizeof(uint64_t)) !=
+ sizeof(uint64_t)) {
PLOG(ERROR) << "Failed to read page flags for page " << pfn;
return false;
}
@@ -95,7 +96,8 @@
if (!InitPageAcct()) return false;
}
- if (pread64(kpagecount_fd_, mapcount, sizeof(uint64_t), pfn * sizeof(uint64_t)) < 0) {
+ if (pread64(kpagecount_fd_, mapcount, sizeof(uint64_t), pfn * sizeof(uint64_t)) !=
+ sizeof(uint64_t)) {
PLOG(ERROR) << "Failed to read map count for page " << pfn;
return false;
}
@@ -130,7 +132,7 @@
off64_t offset = pfn_to_idle_bitmap_offset(pfn);
uint64_t idle_bits;
- if (pread64(pageidle_fd_, &idle_bits, sizeof(uint64_t), offset) < 0) {
+ if (pread64(pageidle_fd_, &idle_bits, sizeof(uint64_t), offset) != sizeof(uint64_t)) {
PLOG(ERROR) << "Failed to read page idle bitmap for page " << pfn;
return -errno;
}
diff --git a/libmeminfo/procmeminfo.cpp b/libmeminfo/procmeminfo.cpp
index 934d65c..caf6e86 100644
--- a/libmeminfo/procmeminfo.cpp
+++ b/libmeminfo/procmeminfo.cpp
@@ -27,6 +27,7 @@
#include <memory>
#include <string>
#include <utility>
+#include <vector>
#include <android-base/file.h>
#include <android-base/logging.h>
@@ -278,68 +279,89 @@
bool ProcMemInfo::ReadVmaStats(int pagemap_fd, Vma& vma, bool get_wss, bool use_pageidle) {
PageAcct& pinfo = PageAcct::Instance();
- uint64_t pagesz = getpagesize();
- uint64_t num_pages = (vma.end - vma.start) / pagesz;
-
- std::unique_ptr<uint64_t[]> pg_frames(new uint64_t[num_pages]);
- uint64_t first = vma.start / pagesz;
- if (pread64(pagemap_fd, pg_frames.get(), num_pages * sizeof(uint64_t),
- first * sizeof(uint64_t)) < 0) {
- PLOG(ERROR) << "Failed to read page frames from page map for pid: " << pid_;
+ if (get_wss && use_pageidle && !pinfo.InitPageAcct(true)) {
+ LOG(ERROR) << "Failed to init idle page accounting";
return false;
}
- if (get_wss && use_pageidle) {
- if (!pinfo.InitPageAcct(true)) {
- LOG(ERROR) << "Failed to init idle page accounting";
- return false;
- }
- }
+ uint64_t pagesz = getpagesize();
+ size_t num_pages = (vma.end - vma.start) / pagesz;
+ size_t first_page = vma.start / pagesz;
- std::unique_ptr<uint64_t[]> pg_flags(new uint64_t[num_pages]);
- std::unique_ptr<uint64_t[]> pg_counts(new uint64_t[num_pages]);
- for (uint64_t i = 0; i < num_pages; ++i) {
+ std::vector<uint64_t> page_cache;
+ size_t cur_page_cache_index = 0;
+ size_t num_in_page_cache = 0;
+ size_t num_leftover_pages = num_pages;
+ for (size_t cur_page = first_page; cur_page < first_page + num_pages; ++cur_page) {
if (!get_wss) {
vma.usage.vss += pagesz;
}
- uint64_t p = pg_frames[i];
- if (!PAGE_PRESENT(p) && !PAGE_SWAPPED(p)) continue;
- if (PAGE_SWAPPED(p)) {
+ // Cache page map data.
+ if (cur_page_cache_index == num_in_page_cache) {
+ static constexpr size_t kMaxPages = 2048;
+ num_leftover_pages -= num_in_page_cache;
+ if (num_leftover_pages > kMaxPages) {
+ num_in_page_cache = kMaxPages;
+ } else {
+ num_in_page_cache = num_leftover_pages;
+ }
+ page_cache.resize(num_in_page_cache);
+ size_t total_bytes = page_cache.size() * sizeof(uint64_t);
+ ssize_t bytes = pread64(pagemap_fd, page_cache.data(), total_bytes,
+ cur_page * sizeof(uint64_t));
+ if (bytes != total_bytes) {
+ if (bytes == -1) {
+ PLOG(ERROR) << "Failed to read page data at offset "
+ << cur_page * sizeof(uint64_t);
+ } else {
+ LOG(ERROR) << "Failed to read page data at offset "
+ << cur_page * sizeof(uint64_t) << " read bytes " << sizeof(uint64_t)
+ << " expected bytes " << bytes;
+ }
+ return false;
+ }
+ cur_page_cache_index = 0;
+ }
+
+ uint64_t page_info = page_cache[cur_page_cache_index++];
+ if (!PAGE_PRESENT(page_info) && !PAGE_SWAPPED(page_info)) continue;
+
+ if (PAGE_SWAPPED(page_info)) {
vma.usage.swap += pagesz;
- swap_offsets_.emplace_back(PAGE_SWAP_OFFSET(p));
+ swap_offsets_.emplace_back(PAGE_SWAP_OFFSET(page_info));
continue;
}
- uint64_t page_frame = PAGE_PFN(p);
- if (!pinfo.PageFlags(page_frame, &pg_flags[i])) {
+ uint64_t page_frame = PAGE_PFN(page_info);
+ uint64_t cur_page_flags;
+ if (!pinfo.PageFlags(page_frame, &cur_page_flags)) {
LOG(ERROR) << "Failed to get page flags for " << page_frame << " in process " << pid_;
swap_offsets_.clear();
return false;
}
// skip unwanted pages from the count
- if ((pg_flags[i] & pgflags_mask_) != pgflags_) continue;
+ if ((cur_page_flags & pgflags_mask_) != pgflags_) continue;
- if (!pinfo.PageMapCount(page_frame, &pg_counts[i])) {
+ uint64_t cur_page_counts;
+ if (!pinfo.PageMapCount(page_frame, &cur_page_counts)) {
LOG(ERROR) << "Failed to get page count for " << page_frame << " in process " << pid_;
swap_offsets_.clear();
return false;
}
// Page was unmapped between the presence check at the beginning of the loop and here.
- if (pg_counts[i] == 0) {
- pg_frames[i] = 0;
- pg_flags[i] = 0;
+ if (cur_page_counts == 0) {
continue;
}
- bool is_dirty = !!(pg_flags[i] & (1 << KPF_DIRTY));
- bool is_private = (pg_counts[i] == 1);
+ bool is_dirty = !!(cur_page_flags & (1 << KPF_DIRTY));
+ bool is_private = (cur_page_counts == 1);
// Working set
if (get_wss) {
bool is_referenced = use_pageidle ? (pinfo.IsPageIdle(page_frame) == 1)
- : !!(pg_flags[i] & (1 << KPF_REFERENCED));
+ : !!(cur_page_flags & (1 << KPF_REFERENCED));
if (!is_referenced) {
continue;
}
@@ -351,7 +373,7 @@
vma.usage.rss += pagesz;
vma.usage.uss += is_private ? pagesz : 0;
- vma.usage.pss += pagesz / pg_counts[i];
+ vma.usage.pss += pagesz / cur_page_counts;
if (is_private) {
vma.usage.private_dirty += is_dirty ? pagesz : 0;
vma.usage.private_clean += is_dirty ? 0 : pagesz;
diff --git a/libmeminfo/tools/procrank.cpp b/libmeminfo/tools/procrank.cpp
index cb3757d..1e44ff9 100644
--- a/libmeminfo/tools/procrank.cpp
+++ b/libmeminfo/tools/procrank.cpp
@@ -348,7 +348,7 @@
auto rss_sort = [](ProcessRecord& a, ProcessRecord& b) {
MemUsage stats_a = show_wss ? a.Wss() : a.Usage();
MemUsage stats_b = show_wss ? b.Wss() : b.Usage();
- return reverse_sort ? stats_a.rss < stats_b.pss : stats_a.pss > stats_b.pss;
+ return reverse_sort ? stats_a.rss < stats_b.rss : stats_a.rss > stats_b.rss;
};
auto vss_sort = [](ProcessRecord& a, ProcessRecord& b) {
diff --git a/libmodprobe/Android.bp b/libmodprobe/Android.bp
new file mode 100644
index 0000000..a2824d1
--- /dev/null
+++ b/libmodprobe/Android.bp
@@ -0,0 +1,30 @@
+cc_library_static {
+ name: "libmodprobe",
+ cflags: [
+ "-Werror",
+ ],
+ recovery_available: true,
+ srcs: [
+ "libmodprobe.cpp",
+ "libmodprobe_ext.cpp",
+ ],
+ shared_libs: [
+ "libbase",
+ ],
+ export_include_dirs: ["include/"],
+}
+
+cc_test {
+ name: "libmodprobe_tests",
+ cflags: ["-Werror"],
+ shared_libs: [
+ "libbase",
+ ],
+ local_include_dirs: ["include/"],
+ srcs: [
+ "libmodprobe_test.cpp",
+ "libmodprobe.cpp",
+ "libmodprobe_ext_test.cpp",
+ ],
+ test_suites: ["device-tests"],
+}
diff --git a/libmodprobe/include/modprobe/modprobe.h b/libmodprobe/include/modprobe/modprobe.h
new file mode 100644
index 0000000..0ec766a
--- /dev/null
+++ b/libmodprobe/include/modprobe/modprobe.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2018 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 <string>
+#include <unordered_map>
+#include <vector>
+
+class Modprobe {
+ public:
+ Modprobe(const std::vector<std::string>&);
+
+ bool LoadListedModules();
+ bool LoadWithAliases(const std::string& module_name, bool strict);
+
+ private:
+ std::string MakeCanonical(const std::string& module_path);
+ bool InsmodWithDeps(const std::string& module_name);
+ bool Insmod(const std::string& path_name);
+ std::vector<std::string> GetDependencies(const std::string& module);
+ bool ModuleExists(const std::string& module_name);
+
+ bool ParseDepCallback(const std::string& base_path, const std::vector<std::string>& args);
+ bool ParseAliasCallback(const std::vector<std::string>& args);
+ bool ParseSoftdepCallback(const std::vector<std::string>& args);
+ bool ParseLoadCallback(const std::vector<std::string>& args);
+ bool ParseOptionsCallback(const std::vector<std::string>& args);
+ void ParseCfg(const std::string& cfg, std::function<bool(const std::vector<std::string>&)> f);
+
+ std::vector<std::pair<std::string, std::string>> module_aliases_;
+ std::unordered_map<std::string, std::vector<std::string>> module_deps_;
+ std::vector<std::pair<std::string, std::string>> module_pre_softdep_;
+ std::vector<std::pair<std::string, std::string>> module_post_softdep_;
+ std::vector<std::string> module_load_;
+ std::unordered_map<std::string, std::string> module_options_;
+};
diff --git a/libmodprobe/libmodprobe.cpp b/libmodprobe/libmodprobe.cpp
new file mode 100644
index 0000000..01cf2e3
--- /dev/null
+++ b/libmodprobe/libmodprobe.cpp
@@ -0,0 +1,321 @@
+/*
+ * Copyright (C) 2018 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 <modprobe/modprobe.h>
+
+#include <fnmatch.h>
+#include <sys/stat.h>
+#include <sys/syscall.h>
+
+#include <algorithm>
+#include <set>
+#include <string>
+#include <vector>
+
+#include <android-base/chrono_utils.h>
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+
+std::string Modprobe::MakeCanonical(const std::string& module_path) {
+ auto start = module_path.find_last_of('/');
+ if (start == std::string::npos) {
+ start = 0;
+ } else {
+ start += 1;
+ }
+ auto end = module_path.size();
+ if (android::base::EndsWith(module_path, ".ko")) {
+ end -= 3;
+ }
+ if ((end - start) <= 1) {
+ LOG(ERROR) << "malformed module name: " << module_path;
+ return "";
+ }
+ std::string module_name = module_path.substr(start, end - start);
+ // module names can have '-', but their file names will have '_'
+ std::replace(module_name.begin(), module_name.end(), '-', '_');
+ return module_name;
+}
+
+bool Modprobe::ParseDepCallback(const std::string& base_path,
+ const std::vector<std::string>& args) {
+ std::vector<std::string> deps;
+ std::string prefix = "";
+
+ // Set first item as our modules path
+ std::string::size_type pos = args[0].find(':');
+ if (args[0][0] != '/') {
+ prefix = base_path + "/";
+ }
+ if (pos != std::string::npos) {
+ deps.emplace_back(prefix + args[0].substr(0, pos));
+ } else {
+ LOG(ERROR) << "dependency lines must start with name followed by ':'";
+ }
+
+ // Remaining items are dependencies of our module
+ for (auto arg = args.begin() + 1; arg != args.end(); ++arg) {
+ if ((*arg)[0] != '/') {
+ prefix = base_path + "/";
+ } else {
+ prefix = "";
+ }
+ deps.push_back(prefix + *arg);
+ }
+
+ std::string canonical_name = MakeCanonical(args[0].substr(0, pos));
+ if (canonical_name.empty()) {
+ return false;
+ }
+ this->module_deps_[canonical_name] = deps;
+
+ return true;
+}
+
+bool Modprobe::ParseAliasCallback(const std::vector<std::string>& args) {
+ auto it = args.begin();
+ const std::string& type = *it++;
+
+ if (type != "alias") {
+ LOG(ERROR) << "non-alias line encountered in modules.alias, found " << type;
+ return false;
+ }
+
+ if (args.size() != 3) {
+ LOG(ERROR) << "alias lines in modules.alias must have 3 entries, not " << args.size();
+ return false;
+ }
+
+ const std::string& alias = *it++;
+ const std::string& module_name = *it++;
+ this->module_aliases_.emplace_back(alias, module_name);
+
+ return true;
+}
+
+bool Modprobe::ParseSoftdepCallback(const std::vector<std::string>& args) {
+ auto it = args.begin();
+ const std::string& type = *it++;
+ std::string state = "";
+
+ if (type != "softdep") {
+ LOG(ERROR) << "non-softdep line encountered in modules.softdep, found " << type;
+ return false;
+ }
+
+ if (args.size() < 4) {
+ LOG(ERROR) << "softdep lines in modules.softdep must have at least 4 entries";
+ return false;
+ }
+
+ const std::string& module = *it++;
+ while (it != args.end()) {
+ const std::string& token = *it++;
+ if (token == "pre:" || token == "post:") {
+ state = token;
+ continue;
+ }
+ if (state == "") {
+ LOG(ERROR) << "malformed modules.softdep at token " << token;
+ return false;
+ }
+ if (state == "pre:") {
+ this->module_pre_softdep_.emplace_back(module, token);
+ } else {
+ this->module_post_softdep_.emplace_back(module, token);
+ }
+ }
+
+ return true;
+}
+
+bool Modprobe::ParseLoadCallback(const std::vector<std::string>& args) {
+ auto it = args.begin();
+ const std::string& module = *it++;
+
+ const std::string& canonical_name = MakeCanonical(module);
+ if (canonical_name.empty()) {
+ return false;
+ }
+ this->module_load_.emplace_back(canonical_name);
+
+ return true;
+}
+
+bool Modprobe::ParseOptionsCallback(const std::vector<std::string>& args) {
+ auto it = args.begin();
+ const std::string& type = *it++;
+
+ if (type != "options") {
+ LOG(ERROR) << "non-options line encountered in modules.options";
+ return false;
+ }
+
+ if (args.size() < 2) {
+ LOG(ERROR) << "lines in modules.options must have at least 2 entries, not " << args.size();
+ return false;
+ }
+
+ const std::string& module = *it++;
+ std::string options = "";
+
+ const std::string& canonical_name = MakeCanonical(module);
+ if (canonical_name.empty()) {
+ return false;
+ }
+
+ while (it != args.end()) {
+ options += *it++;
+ if (it != args.end()) {
+ options += " ";
+ }
+ }
+
+ auto [unused, inserted] = this->module_options_.emplace(canonical_name, options);
+ if (!inserted) {
+ LOG(ERROR) << "multiple options lines present for module " << module;
+ return false;
+ }
+ return true;
+}
+
+void Modprobe::ParseCfg(const std::string& cfg,
+ std::function<bool(const std::vector<std::string>&)> f) {
+ std::string cfg_contents;
+ if (!android::base::ReadFileToString(cfg, &cfg_contents, false)) {
+ return;
+ }
+
+ std::vector<std::string> lines = android::base::Split(cfg_contents, "\n");
+ for (const std::string line : lines) {
+ if (line.empty() || line[0] == '#') {
+ continue;
+ }
+ const std::vector<std::string> args = android::base::Split(line, " ");
+ if (args.empty()) continue;
+ f(args);
+ }
+ return;
+}
+
+Modprobe::Modprobe(const std::vector<std::string>& base_paths) {
+ using namespace std::placeholders;
+
+ for (const auto& base_path : base_paths) {
+ auto alias_callback = std::bind(&Modprobe::ParseAliasCallback, this, _1);
+ ParseCfg(base_path + "/modules.alias", alias_callback);
+
+ auto dep_callback = std::bind(&Modprobe::ParseDepCallback, this, base_path, _1);
+ ParseCfg(base_path + "/modules.dep", dep_callback);
+
+ auto softdep_callback = std::bind(&Modprobe::ParseSoftdepCallback, this, _1);
+ ParseCfg(base_path + "/modules.softdep", softdep_callback);
+
+ auto load_callback = std::bind(&Modprobe::ParseLoadCallback, this, _1);
+ ParseCfg(base_path + "/modules.load", load_callback);
+
+ auto options_callback = std::bind(&Modprobe::ParseOptionsCallback, this, _1);
+ ParseCfg(base_path + "/modules.options", options_callback);
+ }
+}
+
+std::vector<std::string> Modprobe::GetDependencies(const std::string& module) {
+ auto it = module_deps_.find(module);
+ if (it == module_deps_.end()) {
+ return {};
+ }
+ return it->second;
+}
+
+bool Modprobe::InsmodWithDeps(const std::string& module_name) {
+ if (module_name.empty()) {
+ LOG(ERROR) << "Need valid module name, given: " << module_name;
+ return false;
+ }
+
+ auto dependencies = GetDependencies(module_name);
+ if (dependencies.empty()) {
+ LOG(ERROR) << "Module " << module_name << " not in dependency file";
+ return false;
+ }
+
+ // load module dependencies in reverse order
+ for (auto dep = dependencies.rbegin(); dep != dependencies.rend() - 1; ++dep) {
+ const std::string& canonical_name = MakeCanonical(*dep);
+ if (canonical_name.empty()) {
+ return false;
+ }
+ if (!LoadWithAliases(canonical_name, true)) {
+ return false;
+ }
+ }
+
+ // try to load soft pre-dependencies
+ for (const auto& [module, softdep] : module_pre_softdep_) {
+ if (module_name == module) {
+ LoadWithAliases(softdep, false);
+ }
+ }
+
+ // load target module itself with args
+ if (!Insmod(dependencies[0])) {
+ return false;
+ }
+
+ // try to load soft post-dependencies
+ for (const auto& [module, softdep] : module_post_softdep_) {
+ if (module_name == module) {
+ LoadWithAliases(softdep, false);
+ }
+ }
+
+ return true;
+}
+
+bool Modprobe::LoadWithAliases(const std::string& module_name, bool strict) {
+ std::set<std::string> modules_to_load = {module_name};
+ bool module_loaded = false;
+
+ // use aliases to expand list of modules to load (multiple modules
+ // may alias themselves to the requested name)
+ for (const auto& [alias, aliased_module] : module_aliases_) {
+ if (fnmatch(alias.c_str(), module_name.c_str(), 0) != 0) continue;
+ modules_to_load.emplace(aliased_module);
+ }
+
+ // attempt to load all modules aliased to this name
+ for (const auto& module : modules_to_load) {
+ if (!ModuleExists(module)) continue;
+ if (InsmodWithDeps(module)) module_loaded = true;
+ }
+
+ if (strict && !module_loaded) {
+ LOG(ERROR) << "LoadWithAliases did not find a module for " << module_name;
+ return false;
+ }
+ return true;
+}
+
+bool Modprobe::LoadListedModules() {
+ for (const auto& module : module_load_) {
+ if (!LoadWithAliases(module, true)) {
+ return false;
+ }
+ }
+ return true;
+}
diff --git a/libmodprobe/libmodprobe_ext.cpp b/libmodprobe/libmodprobe_ext.cpp
new file mode 100644
index 0000000..5f3a04d
--- /dev/null
+++ b/libmodprobe/libmodprobe_ext.cpp
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2018 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 <sys/stat.h>
+#include <sys/syscall.h>
+
+#include <android-base/logging.h>
+#include <android-base/unique_fd.h>
+
+#include <modprobe/modprobe.h>
+
+bool Modprobe::Insmod(const std::string& path_name) {
+ android::base::unique_fd fd(
+ TEMP_FAILURE_RETRY(open(path_name.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
+ if (fd == -1) {
+ LOG(ERROR) << "Could not open module '" << path_name << "'";
+ return false;
+ }
+
+ std::string options = "";
+ auto options_iter = module_options_.find(MakeCanonical(path_name));
+ if (options_iter != module_options_.end()) {
+ options = options_iter->second;
+ }
+
+ LOG(INFO) << "Loading module " << path_name << " with args \"" << options << "\"";
+ int ret = syscall(__NR_finit_module, fd.get(), options.c_str(), 0);
+ if (ret != 0) {
+ if (errno == EEXIST) {
+ // Module already loaded
+ return true;
+ }
+ LOG(ERROR) << "Failed to insmod '" << path_name << "' with args '" << options << "'";
+ return false;
+ }
+
+ LOG(INFO) << "Loaded kernel module " << path_name;
+ return true;
+}
+
+bool Modprobe::ModuleExists(const std::string& module_name) {
+ struct stat fileStat;
+ auto deps = GetDependencies(module_name);
+ if (deps.empty()) {
+ // missing deps can happen in the case of an alias
+ return false;
+ }
+ if (stat(deps.front().c_str(), &fileStat)) {
+ return false;
+ }
+ if (!S_ISREG(fileStat.st_mode)) {
+ return false;
+ }
+ return true;
+}
diff --git a/libmodprobe/libmodprobe_ext_test.cpp b/libmodprobe/libmodprobe_ext_test.cpp
new file mode 100644
index 0000000..0f073cb
--- /dev/null
+++ b/libmodprobe/libmodprobe_ext_test.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2019 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 <sys/stat.h>
+#include <sys/syscall.h>
+
+#include <string>
+#include <vector>
+
+#include <android-base/logging.h>
+#include <android-base/strings.h>
+#include <android-base/unique_fd.h>
+#include <gtest/gtest.h>
+
+#include <modprobe/modprobe.h>
+
+#include "libmodprobe_test.h"
+
+bool Modprobe::Insmod(const std::string& path_name) {
+ auto deps = GetDependencies(MakeCanonical(path_name));
+ if (deps.empty()) {
+ return false;
+ }
+ if (std::find(test_modules.begin(), test_modules.end(), deps.front()) == test_modules.end()) {
+ return false;
+ }
+ for (auto it = modules_loaded.begin(); it != modules_loaded.end(); ++it) {
+ if (android::base::StartsWith(*it, path_name)) {
+ return true;
+ }
+ }
+ std::string options;
+ auto options_iter = module_options_.find(MakeCanonical(path_name));
+ if (options_iter != module_options_.end()) {
+ options = " " + options_iter->second;
+ }
+ modules_loaded.emplace_back(path_name + options);
+ return true;
+}
+
+bool Modprobe::ModuleExists(const std::string& module_name) {
+ auto deps = GetDependencies(module_name);
+ if (deps.empty()) {
+ // missing deps can happen in the case of an alias
+ return false;
+ }
+ return std::find(test_modules.begin(), test_modules.end(), deps.front()) != test_modules.end();
+}
diff --git a/libmodprobe/libmodprobe_test.cpp b/libmodprobe/libmodprobe_test.cpp
new file mode 100644
index 0000000..481658d
--- /dev/null
+++ b/libmodprobe/libmodprobe_test.cpp
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2019 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 <functional>
+
+#include <android-base/file.h>
+#include <android-base/macros.h>
+#include <android-base/unique_fd.h>
+#include <gtest/gtest.h>
+
+#include <modprobe/modprobe.h>
+
+#include "libmodprobe_test.h"
+
+// Used by libmodprobe_ext_test to check if requested modules are present.
+std::vector<std::string> test_modules;
+
+// Used by libmodprobe_ext_test to report which modules would have been loaded.
+std::vector<std::string> modules_loaded;
+
+TEST(libmodprobe, Test) {
+ test_modules = {
+ "/test1.ko", "/test2.ko", "/test3.ko", "/test4.ko", "/test5.ko",
+ "/test6.ko", "/test7.ko", "/test8.ko", "/test9.ko", "/test10.ko",
+ "/test11.ko", "/test12.ko", "/test13.ko", "/test14.ko", "/test15.ko",
+ };
+
+ std::vector<std::string> expected_modules_loaded = {
+ "/test14.ko",
+ "/test15.ko",
+ "/test3.ko",
+ "/test4.ko",
+ "/test1.ko",
+ "/test6.ko",
+ "/test2.ko",
+ "/test5.ko",
+ "/test8.ko",
+ "/test7.ko param1=4",
+ "/test9.ko param_x=1 param_y=2 param_z=3",
+ "/test10.ko",
+ "/test12.ko",
+ "/test11.ko",
+ "/test13.ko",
+ };
+
+ const std::string modules_dep =
+ "test1.ko:\n"
+ "test2.ko:\n"
+ "test3.ko:\n"
+ "test4.ko: test3.ko\n"
+ "test5.ko: test2.ko test6.ko\n"
+ "test6.ko:\n"
+ "test7.ko:\n"
+ "test8.ko:\n"
+ "test9.ko:\n"
+ "test10.ko:\n"
+ "test11.ko:\n"
+ "test12.ko:\n"
+ "test13.ko:\n"
+ "test14.ko:\n"
+ "test15.ko:\n";
+
+ const std::string modules_softdep =
+ "softdep test7 pre: test8\n"
+ "softdep test9 post: test10\n"
+ "softdep test11 pre: test12 post: test13\n"
+ "softdep test3 pre: test141516\n";
+
+ const std::string modules_alias =
+ "# Aliases extracted from modules themselves.\n"
+ "\n"
+ "alias test141516 test14\n"
+ "alias test141516 test15\n"
+ "alias test141516 test16\n";
+
+ const std::string modules_options =
+ "options test7.ko param1=4\n"
+ "options test9.ko param_x=1 param_y=2 param_z=3\n"
+ "options test100.ko param_1=1\n";
+
+ const std::string modules_load =
+ "test4.ko\n"
+ "test1.ko\n"
+ "test3.ko\n"
+ "test5.ko\n"
+ "test7.ko\n"
+ "test9.ko\n"
+ "test11.ko\n";
+
+ TemporaryDir dir;
+ ASSERT_TRUE(android::base::WriteStringToFile(
+ modules_alias, std::string(dir.path) + "/modules.alias", 0600, getuid(), getgid()));
+
+ ASSERT_TRUE(android::base::WriteStringToFile(
+ modules_dep, std::string(dir.path) + "/modules.dep", 0600, getuid(), getgid()));
+ ASSERT_TRUE(android::base::WriteStringToFile(
+ modules_softdep, std::string(dir.path) + "/modules.softdep", 0600, getuid(), getgid()));
+ ASSERT_TRUE(android::base::WriteStringToFile(
+ modules_options, std::string(dir.path) + "/modules.options", 0600, getuid(), getgid()));
+ ASSERT_TRUE(android::base::WriteStringToFile(
+ modules_load, std::string(dir.path) + "/modules.load", 0600, getuid(), getgid()));
+
+ for (auto i = test_modules.begin(); i != test_modules.end(); ++i) {
+ *i = dir.path + *i;
+ }
+
+ Modprobe m({dir.path});
+ EXPECT_TRUE(m.LoadListedModules());
+
+ GTEST_LOG_(INFO) << "Expected modules loaded (in order):";
+ for (auto i = expected_modules_loaded.begin(); i != expected_modules_loaded.end(); ++i) {
+ *i = dir.path + *i;
+ GTEST_LOG_(INFO) << "\"" << *i << "\"";
+ }
+ GTEST_LOG_(INFO) << "Actual modules loaded (in order):";
+ for (auto i = modules_loaded.begin(); i != modules_loaded.end(); ++i) {
+ GTEST_LOG_(INFO) << "\"" << *i << "\"";
+ }
+
+ EXPECT_TRUE(modules_loaded == expected_modules_loaded);
+}
diff --git a/libmodprobe/libmodprobe_test.h b/libmodprobe/libmodprobe_test.h
new file mode 100644
index 0000000..a001b69
--- /dev/null
+++ b/libmodprobe/libmodprobe_test.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright (C) 2019 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 <string>
+#include <vector>
+
+extern std::vector<std::string> test_modules;
+extern std::vector<std::string> modules_loaded;
diff --git a/libprocessgroup/cgroup_map.cpp b/libprocessgroup/cgroup_map.cpp
index 9797d76..20ae2be 100644
--- a/libprocessgroup/cgroup_map.cpp
+++ b/libprocessgroup/cgroup_map.cpp
@@ -67,11 +67,14 @@
return controller_ != nullptr;
}
-bool CgroupController::IsUsable() const {
+bool CgroupController::IsUsable() {
if (!HasValue()) return false;
- static bool enabled = (access(GetProcsFilePath("", 0, 0).c_str(), F_OK) == 0);
- return enabled;
+ if (state_ == UNKNOWN) {
+ state_ = access(GetProcsFilePath("", 0, 0).c_str(), F_OK) == 0 ? USABLE : MISSING;
+ }
+
+ return state_ == USABLE;
}
std::string CgroupController::GetTasksFilePath(const std::string& rel_path) const {
diff --git a/libprocessgroup/cgroup_map.h b/libprocessgroup/cgroup_map.h
index 9350412..427d71b 100644
--- a/libprocessgroup/cgroup_map.h
+++ b/libprocessgroup/cgroup_map.h
@@ -31,20 +31,28 @@
class CgroupController {
public:
// Does not own controller
- explicit CgroupController(const ACgroupController* controller) : controller_(controller) {}
+ explicit CgroupController(const ACgroupController* controller)
+ : controller_(controller), state_(UNKNOWN) {}
uint32_t version() const;
const char* name() const;
const char* path() const;
bool HasValue() const;
- bool IsUsable() const;
+ bool IsUsable();
std::string GetTasksFilePath(const std::string& path) const;
std::string GetProcsFilePath(const std::string& path, uid_t uid, pid_t pid) const;
bool GetTaskGroup(int tid, std::string* group) const;
private:
+ enum ControllerState {
+ UNKNOWN = 0,
+ USABLE = 1,
+ MISSING = 2,
+ };
+
const ACgroupController* controller_ = nullptr;
+ ControllerState state_;
};
class CgroupMap {
diff --git a/libprocessgroup/include/processgroup/processgroup.h b/libprocessgroup/include/processgroup/processgroup.h
index 7e6bf45..f73ec2d 100644
--- a/libprocessgroup/include/processgroup/processgroup.h
+++ b/libprocessgroup/include/processgroup/processgroup.h
@@ -39,6 +39,11 @@
bool UsePerAppMemcg();
+// Drop the fd cache of cgroup path. It is used for when resource caching is enabled and a process
+// loses the access to the path, the access checking (See SetCgroupAction::EnableResourceCaching)
+// should be active again. E.g. Zygote specialization for child process.
+void DropTaskProfilesResourceCaching();
+
// Return 0 and removes the cgroup if there are no longer any processes in it.
// Returns -1 in the case of an error occurring or if there are processes still running
// even after retrying for up to 200ms.
diff --git a/libprocessgroup/processgroup.cpp b/libprocessgroup/processgroup.cpp
index d3ac26b..7c191be 100644
--- a/libprocessgroup/processgroup.cpp
+++ b/libprocessgroup/processgroup.cpp
@@ -111,6 +111,10 @@
return memcg_supported;
}
+void DropTaskProfilesResourceCaching() {
+ TaskProfiles::GetInstance().DropResourceCaching();
+}
+
bool SetProcessProfiles(uid_t uid, pid_t pid, const std::vector<std::string>& profiles,
bool use_fd_cache) {
const TaskProfiles& tp = TaskProfiles::GetInstance();
diff --git a/libprocessgroup/task_profiles.cpp b/libprocessgroup/task_profiles.cpp
index edc316a..aee5f0c 100644
--- a/libprocessgroup/task_profiles.cpp
+++ b/libprocessgroup/task_profiles.cpp
@@ -173,6 +173,15 @@
fd_ = std::move(fd);
}
+void SetCgroupAction::DropResourceCaching() {
+ std::lock_guard<std::mutex> lock(fd_mutex_);
+ if (fd_ == FDS_NOT_CACHED) {
+ return;
+ }
+
+ fd_.reset(FDS_NOT_CACHED);
+}
+
bool SetCgroupAction::AddTidToCgroup(int tid, int fd) {
if (tid <= 0) {
return true;
@@ -292,6 +301,24 @@
res_cached_ = true;
}
+void TaskProfile::DropResourceCaching() {
+ if (!res_cached_) {
+ return;
+ }
+
+ for (auto& element : elements_) {
+ element->DropResourceCaching();
+ }
+
+ res_cached_ = false;
+}
+
+void TaskProfiles::DropResourceCaching() const {
+ for (auto& iter : profiles_) {
+ iter.second->DropResourceCaching();
+ }
+}
+
TaskProfiles& TaskProfiles::GetInstance() {
// Deliberately leak this object to avoid a race between destruction on
// process exit and concurrent access from another thread.
diff --git a/libprocessgroup/task_profiles.h b/libprocessgroup/task_profiles.h
index 77bac2d..891d5b5 100644
--- a/libprocessgroup/task_profiles.h
+++ b/libprocessgroup/task_profiles.h
@@ -51,6 +51,7 @@
virtual bool ExecuteForTask(int) const { return false; };
virtual void EnableResourceCaching() {}
+ virtual void DropResourceCaching() {}
};
// Profile actions
@@ -114,6 +115,7 @@
virtual bool ExecuteForProcess(uid_t uid, pid_t pid) const;
virtual bool ExecuteForTask(int tid) const;
virtual void EnableResourceCaching();
+ virtual void DropResourceCaching();
const CgroupController* controller() const { return &controller_; }
std::string path() const { return path_; }
@@ -145,6 +147,7 @@
bool ExecuteForProcess(uid_t uid, pid_t pid) const;
bool ExecuteForTask(int tid) const;
void EnableResourceCaching();
+ void DropResourceCaching();
private:
bool res_cached_;
@@ -158,6 +161,7 @@
TaskProfile* GetProfile(const std::string& name) const;
const ProfileAttribute* GetAttribute(const std::string& name) const;
+ void DropResourceCaching() const;
private:
std::map<std::string, std::unique_ptr<TaskProfile>> profiles_;
diff --git a/libunwindstack/MapInfo.cpp b/libunwindstack/MapInfo.cpp
index 1c0f1e6..5b30a4d 100644
--- a/libunwindstack/MapInfo.cpp
+++ b/libunwindstack/MapInfo.cpp
@@ -300,7 +300,7 @@
std::string MapInfo::GetBuildID() {
uintptr_t id = build_id.load();
- if (build_id != 0) {
+ if (id != 0) {
return *reinterpret_cast<std::string*>(id);
}
diff --git a/libunwindstack/tests/ArmExidxDecodeTest.cpp b/libunwindstack/tests/ArmExidxDecodeTest.cpp
index 5f3d1ea..7b1dd92 100644
--- a/libunwindstack/tests/ArmExidxDecodeTest.cpp
+++ b/libunwindstack/tests/ArmExidxDecodeTest.cpp
@@ -1662,7 +1662,7 @@
ASSERT_EQ(0x10U, (*exidx_->regs())[15]);
}
-INSTANTIATE_TEST_CASE_P(, ArmExidxDecodeTest,
- ::testing::Values("logging", "register_logging", "no_logging"));
+INSTANTIATE_TEST_SUITE_P(, ArmExidxDecodeTest,
+ ::testing::Values("logging", "register_logging", "no_logging"));
} // namespace unwindstack
diff --git a/libunwindstack/tests/DwarfCfaLogTest.cpp b/libunwindstack/tests/DwarfCfaLogTest.cpp
index bb2e8f0..9dd0cdd 100644
--- a/libunwindstack/tests/DwarfCfaLogTest.cpp
+++ b/libunwindstack/tests/DwarfCfaLogTest.cpp
@@ -66,7 +66,7 @@
DwarfCie cie_;
DwarfFde fde_;
};
-TYPED_TEST_CASE_P(DwarfCfaLogTest);
+TYPED_TEST_SUITE_P(DwarfCfaLogTest);
// NOTE: All class variable references have to be prefaced with this->.
@@ -763,17 +763,17 @@
ASSERT_EQ("", GetFakeLogBuf());
}
-REGISTER_TYPED_TEST_CASE_P(DwarfCfaLogTest, cfa_illegal, cfa_nop, cfa_offset, cfa_offset_extended,
- cfa_offset_extended_sf, cfa_restore, cfa_restore_extended, cfa_set_loc,
- cfa_advance_loc, cfa_advance_loc1, cfa_advance_loc2, cfa_advance_loc4,
- cfa_undefined, cfa_same, cfa_register, cfa_state,
- cfa_state_cfa_offset_restore, cfa_def_cfa, cfa_def_cfa_sf,
- cfa_def_cfa_register, cfa_def_cfa_offset, cfa_def_cfa_offset_sf,
- cfa_def_cfa_expression, cfa_expression, cfa_val_offset,
- cfa_val_offset_sf, cfa_val_expression, cfa_gnu_args_size,
- cfa_gnu_negative_offset_extended, cfa_register_override);
+REGISTER_TYPED_TEST_SUITE_P(DwarfCfaLogTest, cfa_illegal, cfa_nop, cfa_offset, cfa_offset_extended,
+ cfa_offset_extended_sf, cfa_restore, cfa_restore_extended, cfa_set_loc,
+ cfa_advance_loc, cfa_advance_loc1, cfa_advance_loc2, cfa_advance_loc4,
+ cfa_undefined, cfa_same, cfa_register, cfa_state,
+ cfa_state_cfa_offset_restore, cfa_def_cfa, cfa_def_cfa_sf,
+ cfa_def_cfa_register, cfa_def_cfa_offset, cfa_def_cfa_offset_sf,
+ cfa_def_cfa_expression, cfa_expression, cfa_val_offset,
+ cfa_val_offset_sf, cfa_val_expression, cfa_gnu_args_size,
+ cfa_gnu_negative_offset_extended, cfa_register_override);
typedef ::testing::Types<uint32_t, uint64_t> DwarfCfaLogTestTypes;
-INSTANTIATE_TYPED_TEST_CASE_P(, DwarfCfaLogTest, DwarfCfaLogTestTypes);
+INSTANTIATE_TYPED_TEST_SUITE_P(, DwarfCfaLogTest, DwarfCfaLogTestTypes);
} // namespace unwindstack
diff --git a/libunwindstack/tests/DwarfCfaTest.cpp b/libunwindstack/tests/DwarfCfaTest.cpp
index 7395b04..dd71490 100644
--- a/libunwindstack/tests/DwarfCfaTest.cpp
+++ b/libunwindstack/tests/DwarfCfaTest.cpp
@@ -64,7 +64,7 @@
DwarfCie cie_;
DwarfFde fde_;
};
-TYPED_TEST_CASE_P(DwarfCfaTest);
+TYPED_TEST_SUITE_P(DwarfCfaTest);
// NOTE: All test class variables need to be referenced as this->.
@@ -952,16 +952,17 @@
ASSERT_EQ("", GetFakeLogBuf());
}
-REGISTER_TYPED_TEST_CASE_P(DwarfCfaTest, cfa_illegal, cfa_nop, cfa_offset, cfa_offset_extended,
- cfa_offset_extended_sf, cfa_restore, cfa_restore_extended, cfa_set_loc,
- cfa_advance_loc1, cfa_advance_loc2, cfa_advance_loc4, cfa_undefined,
- cfa_same, cfa_register, cfa_state, cfa_state_cfa_offset_restore,
- cfa_def_cfa, cfa_def_cfa_sf, cfa_def_cfa_register, cfa_def_cfa_offset,
- cfa_def_cfa_offset_sf, cfa_def_cfa_expression, cfa_expression,
- cfa_val_offset, cfa_val_offset_sf, cfa_val_expression, cfa_gnu_args_size,
- cfa_gnu_negative_offset_extended, cfa_register_override);
+REGISTER_TYPED_TEST_SUITE_P(DwarfCfaTest, cfa_illegal, cfa_nop, cfa_offset, cfa_offset_extended,
+ cfa_offset_extended_sf, cfa_restore, cfa_restore_extended, cfa_set_loc,
+ cfa_advance_loc1, cfa_advance_loc2, cfa_advance_loc4, cfa_undefined,
+ cfa_same, cfa_register, cfa_state, cfa_state_cfa_offset_restore,
+ cfa_def_cfa, cfa_def_cfa_sf, cfa_def_cfa_register, cfa_def_cfa_offset,
+ cfa_def_cfa_offset_sf, cfa_def_cfa_expression, cfa_expression,
+ cfa_val_offset, cfa_val_offset_sf, cfa_val_expression,
+ cfa_gnu_args_size, cfa_gnu_negative_offset_extended,
+ cfa_register_override);
typedef ::testing::Types<uint32_t, uint64_t> DwarfCfaTestTypes;
-INSTANTIATE_TYPED_TEST_CASE_P(, DwarfCfaTest, DwarfCfaTestTypes);
+INSTANTIATE_TYPED_TEST_SUITE_P(, DwarfCfaTest, DwarfCfaTestTypes);
} // namespace unwindstack
diff --git a/libunwindstack/tests/DwarfDebugFrameTest.cpp b/libunwindstack/tests/DwarfDebugFrameTest.cpp
index 120bd73..2b36f17 100644
--- a/libunwindstack/tests/DwarfDebugFrameTest.cpp
+++ b/libunwindstack/tests/DwarfDebugFrameTest.cpp
@@ -44,7 +44,7 @@
MemoryFake memory_;
DwarfDebugFrame<TypeParam>* debug_frame_ = nullptr;
};
-TYPED_TEST_CASE_P(DwarfDebugFrameTest);
+TYPED_TEST_SUITE_P(DwarfDebugFrameTest);
// NOTE: All test class variables need to be referenced as this->.
@@ -812,7 +812,7 @@
EXPECT_EQ(0xb50U, fde->pc_end);
}
-REGISTER_TYPED_TEST_CASE_P(
+REGISTER_TYPED_TEST_SUITE_P(
DwarfDebugFrameTest, GetFdes32, GetFdes32_after_GetFdeFromPc, GetFdes32_not_in_section,
GetFdeFromPc32, GetFdeFromPc32_reverse, GetFdeFromPc32_not_in_section, GetFdes64,
GetFdes64_after_GetFdeFromPc, GetFdes64_not_in_section, GetFdeFromPc64, GetFdeFromPc64_reverse,
@@ -825,6 +825,6 @@
GetFdeFromOffset64_lsda_address, GetFdeFromPc_interleaved);
typedef ::testing::Types<uint32_t, uint64_t> DwarfDebugFrameTestTypes;
-INSTANTIATE_TYPED_TEST_CASE_P(, DwarfDebugFrameTest, DwarfDebugFrameTestTypes);
+INSTANTIATE_TYPED_TEST_SUITE_P(, DwarfDebugFrameTest, DwarfDebugFrameTestTypes);
} // namespace unwindstack
diff --git a/libunwindstack/tests/DwarfEhFrameTest.cpp b/libunwindstack/tests/DwarfEhFrameTest.cpp
index 9cac6e8..4792fb5 100644
--- a/libunwindstack/tests/DwarfEhFrameTest.cpp
+++ b/libunwindstack/tests/DwarfEhFrameTest.cpp
@@ -42,7 +42,7 @@
MemoryFake memory_;
DwarfEhFrame<TypeParam>* eh_frame_ = nullptr;
};
-TYPED_TEST_CASE_P(DwarfEhFrameTest);
+TYPED_TEST_SUITE_P(DwarfEhFrameTest);
// NOTE: All test class variables need to be referenced as this->.
@@ -125,9 +125,9 @@
EXPECT_EQ(1U, cie->return_address_register);
}
-REGISTER_TYPED_TEST_CASE_P(DwarfEhFrameTest, GetFdeCieFromOffset32, GetFdeCieFromOffset64);
+REGISTER_TYPED_TEST_SUITE_P(DwarfEhFrameTest, GetFdeCieFromOffset32, GetFdeCieFromOffset64);
typedef ::testing::Types<uint32_t, uint64_t> DwarfEhFrameTestTypes;
-INSTANTIATE_TYPED_TEST_CASE_P(, DwarfEhFrameTest, DwarfEhFrameTestTypes);
+INSTANTIATE_TYPED_TEST_SUITE_P(, DwarfEhFrameTest, DwarfEhFrameTestTypes);
} // namespace unwindstack
diff --git a/libunwindstack/tests/DwarfEhFrameWithHdrTest.cpp b/libunwindstack/tests/DwarfEhFrameWithHdrTest.cpp
index be9e721..78608e3 100644
--- a/libunwindstack/tests/DwarfEhFrameWithHdrTest.cpp
+++ b/libunwindstack/tests/DwarfEhFrameWithHdrTest.cpp
@@ -73,7 +73,7 @@
MemoryFake memory_;
TestDwarfEhFrameWithHdr<TypeParam>* eh_frame_ = nullptr;
};
-TYPED_TEST_CASE_P(DwarfEhFrameWithHdrTest);
+TYPED_TEST_SUITE_P(DwarfEhFrameWithHdrTest);
// NOTE: All test class variables need to be referenced as this->.
@@ -446,14 +446,14 @@
ASSERT_EQ(nullptr, this->eh_frame_->GetFdeFromPc(0x800));
}
-REGISTER_TYPED_TEST_CASE_P(DwarfEhFrameWithHdrTest, Init, Init_non_zero_load_bias, GetFdes,
- GetFdeInfoFromIndex_expect_cache_fail, GetFdeInfoFromIndex_read_pcrel,
- GetFdeInfoFromIndex_read_datarel, GetFdeInfoFromIndex_cached,
- GetFdeOffsetFromPc_verify, GetFdeOffsetFromPc_index_fail,
- GetFdeOffsetFromPc_fail_fde_count, GetFdeOffsetFromPc_search,
- GetCieFde32, GetCieFde64, GetFdeFromPc_fde_not_found);
+REGISTER_TYPED_TEST_SUITE_P(DwarfEhFrameWithHdrTest, Init, Init_non_zero_load_bias, GetFdes,
+ GetFdeInfoFromIndex_expect_cache_fail, GetFdeInfoFromIndex_read_pcrel,
+ GetFdeInfoFromIndex_read_datarel, GetFdeInfoFromIndex_cached,
+ GetFdeOffsetFromPc_verify, GetFdeOffsetFromPc_index_fail,
+ GetFdeOffsetFromPc_fail_fde_count, GetFdeOffsetFromPc_search,
+ GetCieFde32, GetCieFde64, GetFdeFromPc_fde_not_found);
typedef ::testing::Types<uint32_t, uint64_t> DwarfEhFrameWithHdrTestTypes;
-INSTANTIATE_TYPED_TEST_CASE_P(, DwarfEhFrameWithHdrTest, DwarfEhFrameWithHdrTestTypes);
+INSTANTIATE_TYPED_TEST_SUITE_P(, DwarfEhFrameWithHdrTest, DwarfEhFrameWithHdrTestTypes);
} // namespace unwindstack
diff --git a/libunwindstack/tests/DwarfOpLogTest.cpp b/libunwindstack/tests/DwarfOpLogTest.cpp
index 3f09dd8..f4ade5d 100644
--- a/libunwindstack/tests/DwarfOpLogTest.cpp
+++ b/libunwindstack/tests/DwarfOpLogTest.cpp
@@ -48,7 +48,7 @@
std::unique_ptr<DwarfMemory> mem_;
std::unique_ptr<DwarfOp<TypeParam>> op_;
};
-TYPED_TEST_CASE_P(DwarfOpLogTest);
+TYPED_TEST_SUITE_P(DwarfOpLogTest);
TYPED_TEST_P(DwarfOpLogTest, multiple_ops) {
// Multi operation opcodes.
@@ -65,9 +65,9 @@
ASSERT_EQ(expected, lines);
}
-REGISTER_TYPED_TEST_CASE_P(DwarfOpLogTest, multiple_ops);
+REGISTER_TYPED_TEST_SUITE_P(DwarfOpLogTest, multiple_ops);
typedef ::testing::Types<uint32_t, uint64_t> DwarfOpLogTestTypes;
-INSTANTIATE_TYPED_TEST_CASE_P(, DwarfOpLogTest, DwarfOpLogTestTypes);
+INSTANTIATE_TYPED_TEST_SUITE_P(, DwarfOpLogTest, DwarfOpLogTestTypes);
} // namespace unwindstack
diff --git a/libunwindstack/tests/DwarfOpTest.cpp b/libunwindstack/tests/DwarfOpTest.cpp
index d424d5f..0898ec0 100644
--- a/libunwindstack/tests/DwarfOpTest.cpp
+++ b/libunwindstack/tests/DwarfOpTest.cpp
@@ -48,7 +48,7 @@
std::unique_ptr<DwarfMemory> mem_;
std::unique_ptr<DwarfOp<TypeParam>> op_;
};
-TYPED_TEST_CASE_P(DwarfOpTest);
+TYPED_TEST_SUITE_P(DwarfOpTest);
TYPED_TEST_P(DwarfOpTest, decode) {
// Memory error.
@@ -1571,15 +1571,16 @@
EXPECT_FALSE(this->op_->dex_pc_set());
}
-REGISTER_TYPED_TEST_CASE_P(DwarfOpTest, decode, eval, illegal_opcode, not_implemented, op_addr,
- op_deref, op_deref_size, const_unsigned, const_signed, const_uleb,
- const_sleb, op_dup, op_drop, op_over, op_pick, op_swap, op_rot, op_abs,
- op_and, op_div, op_minus, op_mod, op_mul, op_neg, op_not, op_or, op_plus,
- op_plus_uconst, op_shl, op_shr, op_shra, op_xor, op_bra,
- compare_opcode_stack_error, compare_opcodes, op_skip, op_lit, op_reg,
- op_regx, op_breg, op_breg_invalid_register, op_bregx, op_nop, is_dex_pc);
+REGISTER_TYPED_TEST_SUITE_P(DwarfOpTest, decode, eval, illegal_opcode, not_implemented, op_addr,
+ op_deref, op_deref_size, const_unsigned, const_signed, const_uleb,
+ const_sleb, op_dup, op_drop, op_over, op_pick, op_swap, op_rot, op_abs,
+ op_and, op_div, op_minus, op_mod, op_mul, op_neg, op_not, op_or,
+ op_plus, op_plus_uconst, op_shl, op_shr, op_shra, op_xor, op_bra,
+ compare_opcode_stack_error, compare_opcodes, op_skip, op_lit, op_reg,
+ op_regx, op_breg, op_breg_invalid_register, op_bregx, op_nop,
+ is_dex_pc);
typedef ::testing::Types<uint32_t, uint64_t> DwarfOpTestTypes;
-INSTANTIATE_TYPED_TEST_CASE_P(, DwarfOpTest, DwarfOpTestTypes);
+INSTANTIATE_TYPED_TEST_SUITE_P(, DwarfOpTest, DwarfOpTestTypes);
} // namespace unwindstack
diff --git a/libunwindstack/tests/DwarfSectionImplTest.cpp b/libunwindstack/tests/DwarfSectionImplTest.cpp
index 46f555a..b386ef4 100644
--- a/libunwindstack/tests/DwarfSectionImplTest.cpp
+++ b/libunwindstack/tests/DwarfSectionImplTest.cpp
@@ -68,7 +68,7 @@
MemoryFake memory_;
TestDwarfSectionImpl<TypeParam>* section_ = nullptr;
};
-TYPED_TEST_CASE_P(DwarfSectionImplTest);
+TYPED_TEST_SUITE_P(DwarfSectionImplTest);
// NOTE: All test class variables need to be referenced as this->.
@@ -571,18 +571,18 @@
ASSERT_EQ("", GetFakeLogBuf());
}
-REGISTER_TYPED_TEST_CASE_P(DwarfSectionImplTest, GetCieFromOffset_fail_should_not_cache,
- GetFdeFromOffset_fail_should_not_cache, Eval_cfa_expr_eval_fail,
- Eval_cfa_expr_no_stack, Eval_cfa_expr_is_register, Eval_cfa_expr,
- Eval_cfa_val_expr, Eval_bad_regs, Eval_no_cfa, Eval_cfa_bad,
- Eval_cfa_register_prev, Eval_cfa_register_from_value,
- Eval_double_indirection, Eval_register_reference_chain, Eval_dex_pc,
- Eval_invalid_register, Eval_different_reg_locations,
- Eval_return_address_undefined, Eval_pc_zero, Eval_return_address,
- Eval_ignore_large_reg_loc, Eval_reg_expr, Eval_reg_val_expr,
- GetCfaLocationInfo_cie_not_cached, GetCfaLocationInfo_cie_cached, Log);
+REGISTER_TYPED_TEST_SUITE_P(DwarfSectionImplTest, GetCieFromOffset_fail_should_not_cache,
+ GetFdeFromOffset_fail_should_not_cache, Eval_cfa_expr_eval_fail,
+ Eval_cfa_expr_no_stack, Eval_cfa_expr_is_register, Eval_cfa_expr,
+ Eval_cfa_val_expr, Eval_bad_regs, Eval_no_cfa, Eval_cfa_bad,
+ Eval_cfa_register_prev, Eval_cfa_register_from_value,
+ Eval_double_indirection, Eval_register_reference_chain, Eval_dex_pc,
+ Eval_invalid_register, Eval_different_reg_locations,
+ Eval_return_address_undefined, Eval_pc_zero, Eval_return_address,
+ Eval_ignore_large_reg_loc, Eval_reg_expr, Eval_reg_val_expr,
+ GetCfaLocationInfo_cie_not_cached, GetCfaLocationInfo_cie_cached, Log);
typedef ::testing::Types<uint32_t, uint64_t> DwarfSectionImplTestTypes;
-INSTANTIATE_TYPED_TEST_CASE_P(, DwarfSectionImplTest, DwarfSectionImplTestTypes);
+INSTANTIATE_TYPED_TEST_SUITE_P(, DwarfSectionImplTest, DwarfSectionImplTestTypes);
} // namespace unwindstack
diff --git a/libunwindstack/tests/ElfCacheTest.cpp b/libunwindstack/tests/ElfCacheTest.cpp
index 07fd6f6..5735858 100644
--- a/libunwindstack/tests/ElfCacheTest.cpp
+++ b/libunwindstack/tests/ElfCacheTest.cpp
@@ -31,7 +31,7 @@
class ElfCacheTest : public ::testing::Test {
protected:
- static void SetUpTestCase() { memory_.reset(new MemoryFake); }
+ static void SetUpTestSuite() { memory_.reset(new MemoryFake); }
void SetUp() override { Elf::SetCachingEnabled(true); }
diff --git a/libunwindstack/tests/MapInfoCreateMemoryTest.cpp b/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
index 6be8bdc..5b4ca7c 100644
--- a/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
+++ b/libunwindstack/tests/MapInfoCreateMemoryTest.cpp
@@ -58,7 +58,7 @@
ASSERT_TRUE(android::base::WriteFully(fd, buffer.data(), buffer.size()));
}
- static void SetUpTestCase() {
+ static void SetUpTestSuite() {
std::vector<uint8_t> buffer(12288, 0);
memcpy(buffer.data(), ELFMAG, SELFMAG);
buffer[EI_CLASS] = ELFCLASS32;
diff --git a/libunwindstack/tests/MemoryOfflineBufferTest.cpp b/libunwindstack/tests/MemoryOfflineBufferTest.cpp
index c62c53d..9531708 100644
--- a/libunwindstack/tests/MemoryOfflineBufferTest.cpp
+++ b/libunwindstack/tests/MemoryOfflineBufferTest.cpp
@@ -30,7 +30,7 @@
memory_.reset(new MemoryOfflineBuffer(buffer_.data(), kStart, kEnd));
}
- static void SetUpTestCase() {
+ static void SetUpTestSuite() {
buffer_.resize(kLength);
for (size_t i = 0; i < kLength; i++) {
buffer_[i] = i % 189;
diff --git a/libunwindstack/tests/RegsIterateTest.cpp b/libunwindstack/tests/RegsIterateTest.cpp
index 9a27dbd..7e36953 100644
--- a/libunwindstack/tests/RegsIterateTest.cpp
+++ b/libunwindstack/tests/RegsIterateTest.cpp
@@ -236,7 +236,7 @@
}
using RegTypes = ::testing::Types<RegsArm, RegsArm64, RegsX86, RegsX86_64, RegsMips, RegsMips64>;
-TYPED_TEST_CASE(RegsIterateTest, RegTypes);
+TYPED_TEST_SUITE(RegsIterateTest, RegTypes);
TYPED_TEST(RegsIterateTest, iterate) {
std::vector<Register> expected = ExpectedRegisters<TypeParam>();
diff --git a/libunwindstack/tests/SymbolsTest.cpp b/libunwindstack/tests/SymbolsTest.cpp
index b40a253..ae3c349 100644
--- a/libunwindstack/tests/SymbolsTest.cpp
+++ b/libunwindstack/tests/SymbolsTest.cpp
@@ -55,7 +55,7 @@
MemoryFake memory_;
};
-TYPED_TEST_CASE_P(SymbolsTest);
+TYPED_TEST_SUITE_P(SymbolsTest);
TYPED_TEST_P(SymbolsTest, function_bounds_check) {
Symbols symbols(0x1000, sizeof(TypeParam), sizeof(TypeParam), 0x2000, 0x100);
@@ -362,11 +362,11 @@
EXPECT_EQ(4U, offset);
}
-REGISTER_TYPED_TEST_CASE_P(SymbolsTest, function_bounds_check, no_symbol, multiple_entries,
- multiple_entries_nonstandard_size, symtab_value_out_of_bounds,
- symtab_read_cached, get_global);
+REGISTER_TYPED_TEST_SUITE_P(SymbolsTest, function_bounds_check, no_symbol, multiple_entries,
+ multiple_entries_nonstandard_size, symtab_value_out_of_bounds,
+ symtab_read_cached, get_global);
typedef ::testing::Types<Elf32_Sym, Elf64_Sym> SymbolsTestTypes;
-INSTANTIATE_TYPED_TEST_CASE_P(, SymbolsTest, SymbolsTestTypes);
+INSTANTIATE_TYPED_TEST_SUITE_P(, SymbolsTest, SymbolsTestTypes);
} // namespace unwindstack
diff --git a/libunwindstack/tests/UnwinderTest.cpp b/libunwindstack/tests/UnwinderTest.cpp
index 1463167..ef1950c 100644
--- a/libunwindstack/tests/UnwinderTest.cpp
+++ b/libunwindstack/tests/UnwinderTest.cpp
@@ -54,7 +54,7 @@
}
}
- static void SetUpTestCase() {
+ static void SetUpTestSuite() {
maps_.reset(new Maps);
ElfFake* elf = new ElfFake(new MemoryFake);
diff --git a/libziparchive/include/ziparchive/zip_archive.h b/libziparchive/include/ziparchive/zip_archive.h
index 463851c..e3ac114 100644
--- a/libziparchive/include/ziparchive/zip_archive.h
+++ b/libziparchive/include/ziparchive/zip_archive.h
@@ -36,30 +36,6 @@
kCompressDeflated = 8, // standard deflate
};
-// TODO: remove this when everyone's moved over to std::string.
-struct ZipString {
- const uint8_t* name;
- uint16_t name_length;
-
- ZipString() {}
-
- explicit ZipString(std::string_view entry_name);
-
- bool operator==(const ZipString& rhs) const {
- return name && (name_length == rhs.name_length) && (memcmp(name, rhs.name, name_length) == 0);
- }
-
- bool StartsWith(const ZipString& prefix) const {
- return name && (name_length >= prefix.name_length) &&
- (memcmp(name, prefix.name, prefix.name_length) == 0);
- }
-
- bool EndsWith(const ZipString& suffix) const {
- return name && (name_length >= suffix.name_length) &&
- (memcmp(name + name_length - suffix.name_length, suffix.name, suffix.name_length) == 0);
- }
-};
-
/*
* Represents information about a zip entry in a zip file.
*/
@@ -191,8 +167,6 @@
*/
int32_t Next(void* cookie, ZipEntry* data, std::string* name);
int32_t Next(void* cookie, ZipEntry* data, std::string_view* name);
-// TODO: remove this when everyone's moved over to std::string/std::string_view.
-int32_t Next(void* cookie, ZipEntry* data, ZipString* name);
/*
* End iteration over all entries of a zip file and frees the memory allocated
diff --git a/libziparchive/include/ziparchive/zip_writer.h b/libziparchive/include/ziparchive/zip_writer.h
index bd44fdb..a2a0dbf 100644
--- a/libziparchive/include/ziparchive/zip_writer.h
+++ b/libziparchive/include/ziparchive/zip_writer.h
@@ -21,6 +21,7 @@
#include <memory>
#include <string>
+#include <string_view>
#include <vector>
#include "android-base/macros.h"
@@ -101,7 +102,7 @@
* Subsequent calls to WriteBytes(const void*, size_t) will add data to this entry.
* Returns 0 on success, and an error value < 0 on failure.
*/
- int32_t StartEntry(const char* path, size_t flags);
+ int32_t StartEntry(std::string_view path, size_t flags);
/**
* Starts a new zip entry with the given path and flags, where the
@@ -111,17 +112,17 @@
* Subsequent calls to WriteBytes(const void*, size_t) will add data to this entry.
* Returns 0 on success, and an error value < 0 on failure.
*/
- int32_t StartAlignedEntry(const char* path, size_t flags, uint32_t alignment);
+ int32_t StartAlignedEntry(std::string_view path, size_t flags, uint32_t alignment);
/**
* Same as StartEntry(const char*, size_t), but sets a last modified time for the entry.
*/
- int32_t StartEntryWithTime(const char* path, size_t flags, time_t time);
+ int32_t StartEntryWithTime(std::string_view path, size_t flags, time_t time);
/**
* Same as StartAlignedEntry(const char*, size_t), but sets a last modified time for the entry.
*/
- int32_t StartAlignedEntryWithTime(const char* path, size_t flags, time_t time, uint32_t alignment);
+ int32_t StartAlignedEntryWithTime(std::string_view path, size_t flags, time_t time, uint32_t alignment);
/**
* Writes bytes to the zip file for the previously started zip entry.
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index e966295..c95b035 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -47,6 +47,7 @@
#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
#include <android-base/mapped_file.h>
#include <android-base/memory.h>
+#include <android-base/strings.h>
#include <android-base/utf8.h>
#include <log/log.h>
#include "zlib.h"
@@ -101,25 +102,8 @@
return val;
}
-static uint32_t ComputeHash(const ZipString& name) {
- return static_cast<uint32_t>(std::hash<std::string_view>{}(
- std::string_view(reinterpret_cast<const char*>(name.name), name.name_length)));
-}
-
-static bool isZipStringEqual(const uint8_t* start, const ZipString& zip_string,
- const ZipStringOffset& zip_string_offset) {
- const ZipString from_offset = zip_string_offset.GetZipString(start);
- return from_offset == zip_string;
-}
-
-/**
- * Returns offset of ZipString#name from the start of the central directory in the memory map.
- * For valid ZipStrings contained in the zip archive mmap, 0 < offset < 0xffffff.
- */
-static inline uint32_t GetOffset(const uint8_t* name, const uint8_t* start) {
- CHECK_GT(name, start);
- CHECK_LT(name, start + 0xffffff);
- return static_cast<uint32_t>(name - start);
+static uint32_t ComputeHash(std::string_view name) {
+ return static_cast<uint32_t>(std::hash<std::string_view>{}(name));
}
/*
@@ -127,19 +111,19 @@
* valid range.
*/
static int64_t EntryToIndex(const ZipStringOffset* hash_table, const uint32_t hash_table_size,
- const ZipString& name, const uint8_t* start) {
+ std::string_view name, const uint8_t* start) {
const uint32_t hash = ComputeHash(name);
// NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
uint32_t ent = hash & (hash_table_size - 1);
while (hash_table[ent].name_offset != 0) {
- if (isZipStringEqual(start, name, hash_table[ent])) {
+ if (hash_table[ent].ToStringView(start) == name) {
return ent;
}
ent = (ent + 1) & (hash_table_size - 1);
}
- ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
+ ALOGV("Zip: Unable to find entry %.*s", static_cast<int>(name.size()), name.data());
return kEntryNotFound;
}
@@ -147,7 +131,7 @@
* Add a new entry to the hash table.
*/
static int32_t AddToHash(ZipStringOffset* hash_table, const uint32_t hash_table_size,
- const ZipString& name, const uint8_t* start) {
+ std::string_view name, const uint8_t* start) {
const uint64_t hash = ComputeHash(name);
uint32_t ent = hash & (hash_table_size - 1);
@@ -156,15 +140,18 @@
* Further, we guarantee that the hashtable size is not 0.
*/
while (hash_table[ent].name_offset != 0) {
- if (isZipStringEqual(start, name, hash_table[ent])) {
- // We've found a duplicate entry. We don't accept it
- ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
+ if (hash_table[ent].ToStringView(start) == name) {
+ // We've found a duplicate entry. We don't accept duplicates.
+ ALOGW("Zip: Found duplicate entry %.*s", static_cast<int>(name.size()), name.data());
return kDuplicateEntry;
}
ent = (ent + 1) & (hash_table_size - 1);
}
- hash_table[ent].name_offset = GetOffset(name.name, start);
- hash_table[ent].name_length = name.name_length;
+
+ // `name` has already been validated before entry.
+ const char* start_char = reinterpret_cast<const char*>(start);
+ hash_table[ent].name_offset = static_cast<uint32_t>(name.data() - start_char);
+ hash_table[ent].name_length = static_cast<uint16_t>(name.size());
return 0;
}
@@ -366,7 +353,7 @@
reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
if (archive->hash_table == nullptr) {
ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
- archive->hash_table_size, sizeof(ZipString));
+ archive->hash_table_size, sizeof(ZipStringOffset));
return -1;
}
@@ -404,21 +391,19 @@
const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
if (file_name + file_name_length > cd_end) {
- ALOGW(
- "Zip: file name boundary exceeds the central directory range, file_name_length: "
- "%" PRIx16 ", cd_length: %zu",
- file_name_length, cd_length);
+ ALOGW("Zip: file name for entry %" PRIu16
+ " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
+ i, file_name_length, cd_length);
return -1;
}
- /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
+ // Check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters.
if (!IsValidEntryName(file_name, file_name_length)) {
+ ALOGW("Zip: invalid file name at entry %" PRIu16, i);
return -1;
}
- /* add the CDE filename to the hash table */
- ZipString entry_name;
- entry_name.name = file_name;
- entry_name.name_length = file_name_length;
+ // Add the CDE filename to the hash table.
+ std::string_view entry_name{reinterpret_cast<const char*>(file_name), file_name_length};
const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
archive->central_directory.GetBasePtr());
if (add_result != 0) {
@@ -539,15 +524,13 @@
// Recover the start of the central directory entry from the filename
// pointer. The filename is the first entry past the fixed-size data,
// so we can just subtract back from that.
- const ZipString from_offset =
- archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
- const uint8_t* ptr = from_offset.name;
+ const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
+ const uint8_t* ptr = base_ptr + archive->hash_table[ent].name_offset;
ptr -= sizeof(CentralDirectoryRecord);
// This is the base of our mmapped region, we have to sanity check that
// the name that's in the hash table is a pointer to a location within
// this mapped region.
- const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
ALOGW("Zip: Invalid entry pointer");
return kInvalidOffset;
@@ -639,26 +622,24 @@
// Check that the local file header name matches the declared
// name in the central directory.
- if (lfh->file_name_length == nameLen) {
- const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
- if (name_offset + lfh->file_name_length > cd_offset) {
- ALOGW("Zip: Invalid declared length");
- return kInvalidOffset;
- }
-
- std::vector<uint8_t> name_buf(nameLen);
- if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
- ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
- return kIoError;
- }
- const ZipString from_offset =
- archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
- if (memcmp(from_offset.name, name_buf.data(), nameLen)) {
- return kInconsistentInformation;
- }
-
- } else {
- ALOGW("Zip: lfh name did not match central directory.");
+ if (lfh->file_name_length != nameLen) {
+ ALOGW("Zip: lfh name length did not match central directory");
+ return kInconsistentInformation;
+ }
+ const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
+ if (name_offset + lfh->file_name_length > cd_offset) {
+ ALOGW("Zip: lfh name has invalid declared length");
+ return kInvalidOffset;
+ }
+ std::vector<uint8_t> name_buf(nameLen);
+ if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
+ ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
+ return kIoError;
+ }
+ const std::string_view entry_name =
+ archive->hash_table[ent].ToStringView(archive->central_directory.GetBasePtr());
+ if (memcmp(entry_name.data(), name_buf.data(), nameLen) != 0) {
+ ALOGW("Zip: lfh name did not match central directory");
return kInconsistentInformation;
}
@@ -691,21 +672,13 @@
struct IterationHandle {
ZipArchive* archive;
- std::string prefix_holder;
- ZipString prefix;
-
- std::string suffix_holder;
- ZipString suffix;
+ std::string prefix;
+ std::string suffix;
uint32_t position = 0;
- IterationHandle(ZipArchive* archive, const std::string_view in_prefix,
- const std::string_view in_suffix)
- : archive(archive),
- prefix_holder(in_prefix),
- prefix(prefix_holder),
- suffix_holder(in_suffix),
- suffix(suffix_holder) {}
+ IterationHandle(ZipArchive* archive, std::string_view in_prefix, std::string_view in_suffix)
+ : archive(archive), prefix(in_prefix), suffix(in_suffix) {}
};
int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
@@ -737,8 +710,8 @@
return kInvalidEntryName;
}
- const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size,
- ZipString(entryName), archive->central_directory.GetBasePtr());
+ const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
+ archive->central_directory.GetBasePtr());
if (ent < 0) {
ALOGV("Zip: Could not find entry %.*s", static_cast<int>(entryName.size()), entryName.data());
return static_cast<int32_t>(ent); // kEntryNotFound is safe to truncate.
@@ -757,15 +730,6 @@
}
int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
- ZipString zs;
- int32_t result = Next(cookie, data, &zs);
- if (result == 0 && name) {
- *name = std::string_view(reinterpret_cast<const char*>(zs.name), zs.name_length);
- }
- return result;
-}
-
-int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
if (handle == NULL) {
ALOGW("Zip: Null ZipArchiveHandle");
@@ -782,16 +746,14 @@
const uint32_t hash_table_length = archive->hash_table_size;
const ZipStringOffset* hash_table = archive->hash_table;
for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
- const ZipString from_offset =
- hash_table[i].GetZipString(archive->central_directory.GetBasePtr());
- if (hash_table[i].name_offset != 0 &&
- (handle->prefix.name_length == 0 || from_offset.StartsWith(handle->prefix)) &&
- (handle->suffix.name_length == 0 || from_offset.EndsWith(handle->suffix))) {
+ const std::string_view entry_name =
+ hash_table[i].ToStringView(archive->central_directory.GetBasePtr());
+ if (hash_table[i].name_offset != 0 && (android::base::StartsWith(entry_name, handle->prefix) &&
+ android::base::EndsWith(entry_name, handle->suffix))) {
handle->position = (i + 1);
const int error = FindEntry(archive, i, data);
- if (!error) {
- name->name = from_offset.name;
- name->name_length = hash_table[i].name_length;
+ if (!error && name) {
+ *name = entry_name;
}
return error;
}
@@ -1159,13 +1121,6 @@
return archive->mapped_zip.GetFileDescriptor();
}
-ZipString::ZipString(std::string_view entry_name)
- : name(reinterpret_cast<const uint8_t*>(entry_name.data())) {
- size_t len = entry_name.size();
- CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
- name_length = static_cast<uint16_t>(len);
-}
-
#if !defined(_WIN32)
class ProcessWriter : public zip_archive::Writer {
public:
diff --git a/libziparchive/zip_archive_benchmark.cpp b/libziparchive/zip_archive_benchmark.cpp
index 23ed408..09d3b8a 100644
--- a/libziparchive/zip_archive_benchmark.cpp
+++ b/libziparchive/zip_archive_benchmark.cpp
@@ -58,7 +58,7 @@
std::string_view name("thisFileNameDoesNotExist");
// Start the benchmark.
- while (state.KeepRunning()) {
+ for (auto _ : state) {
OpenArchive(temp_file->path, &handle);
FindEntry(handle, name, &data);
CloseArchive(handle);
@@ -73,7 +73,7 @@
ZipEntry data;
std::string name;
- while (state.KeepRunning()) {
+ for (auto _ : state) {
OpenArchive(temp_file->path, &handle);
StartIteration(handle, &iteration_cookie);
while (Next(iteration_cookie, &data, &name) == 0) {
@@ -84,4 +84,27 @@
}
BENCHMARK(Iterate_all_files);
+static void StartAlignedEntry(benchmark::State& state) {
+ TemporaryFile file;
+ FILE* fp = fdopen(file.fd, "w");
+
+ ZipWriter writer(fp);
+
+ auto alignment = uint32_t(state.range(0));
+ std::string name = "name";
+ int counter = 0;
+ for (auto _ : state) {
+ writer.StartAlignedEntry(name + std::to_string(counter++), 0, alignment);
+ state.PauseTiming();
+ writer.WriteBytes("hola", 4);
+ writer.FinishEntry();
+ state.ResumeTiming();
+ }
+
+ writer.Finish();
+ fclose(fp);
+}
+BENCHMARK(StartAlignedEntry)->Arg(2)->Arg(16)->Arg(1024)->Arg(4096);
+
+
BENCHMARK_MAIN();
diff --git a/libziparchive/zip_archive_private.h b/libziparchive/zip_archive_private.h
index 330a02a..30a1d72 100644
--- a/libziparchive/zip_archive_private.h
+++ b/libziparchive/zip_archive_private.h
@@ -137,22 +137,22 @@
};
/**
- * More space efficient string representation of strings in an mmaped zipped file than
- * std::string_view or ZipString. Using ZipString as an entry in the ZipArchive hashtable wastes
- * space. ZipString stores a pointer to a string (on 64 bit, 8 bytes) and the length to read from
- * that pointer, 2 bytes. Because of alignment, the structure consumes 16 bytes, wasting 6 bytes.
- * ZipStringOffset stores a 4 byte offset from a fixed location in the memory mapped file instead
- * of the entire address, consuming 8 bytes with alignment.
+ * More space efficient string representation of strings in an mmaped zipped
+ * file than std::string_view. Using std::string_view as an entry in the
+ * ZipArchive hash table wastes space. std::string_view stores a pointer to a
+ * string (on 64 bit, 8 bytes) and the length to read from that pointer,
+ * 2 bytes. Because of alignment, the structure consumes 16 bytes, wasting
+ * 6 bytes.
+ *
+ * ZipStringOffset stores a 4 byte offset from a fixed location in the memory
+ * mapped file instead of the entire address, consuming 8 bytes with alignment.
*/
struct ZipStringOffset {
uint32_t name_offset;
uint16_t name_length;
- const ZipString GetZipString(const uint8_t* start) const {
- ZipString zip_string;
- zip_string.name = start + name_offset;
- zip_string.name_length = name_length;
- return zip_string;
+ const std::string_view ToStringView(const uint8_t* start) const {
+ return std::string_view{reinterpret_cast<const char*>(start + name_offset), name_length};
}
};
diff --git a/libziparchive/zip_writer.cc b/libziparchive/zip_writer.cc
index ae9d145..198154b 100644
--- a/libziparchive/zip_writer.cc
+++ b/libziparchive/zip_writer.cc
@@ -130,7 +130,7 @@
return error_code;
}
-int32_t ZipWriter::StartEntry(const char* path, size_t flags) {
+int32_t ZipWriter::StartEntry(std::string_view path, size_t flags) {
uint32_t alignment = 0;
if (flags & kAlign32) {
flags &= ~kAlign32;
@@ -139,11 +139,11 @@
return StartAlignedEntryWithTime(path, flags, time_t(), alignment);
}
-int32_t ZipWriter::StartAlignedEntry(const char* path, size_t flags, uint32_t alignment) {
+int32_t ZipWriter::StartAlignedEntry(std::string_view path, size_t flags, uint32_t alignment) {
return StartAlignedEntryWithTime(path, flags, time_t(), alignment);
}
-int32_t ZipWriter::StartEntryWithTime(const char* path, size_t flags, time_t time) {
+int32_t ZipWriter::StartEntryWithTime(std::string_view path, size_t flags, time_t time) {
uint32_t alignment = 0;
if (flags & kAlign32) {
flags &= ~kAlign32;
@@ -198,7 +198,7 @@
dst->extra_field_length = src.padding_length;
}
-int32_t ZipWriter::StartAlignedEntryWithTime(const char* path, size_t flags, time_t time,
+int32_t ZipWriter::StartAlignedEntryWithTime(std::string_view path, size_t flags, time_t time,
uint32_t alignment) {
if (state_ != State::kWritingZip) {
return kInvalidState;
@@ -247,13 +247,24 @@
ExtractTimeAndDate(time, &file_entry.last_mod_time, &file_entry.last_mod_date);
off_t offset = current_offset_ + sizeof(LocalFileHeader) + file_entry.path.size();
- std::vector<char> zero_padding;
+ // prepare a pre-zeroed memory page in case when we need to pad some aligned data.
+ static constexpr auto kPageSize = 4096;
+ static constexpr char kSmallZeroPadding[kPageSize] = {};
+ // use this buffer if our preallocated one is too small
+ std::vector<char> zero_padding_big;
+ const char* zero_padding = nullptr;
+
if (alignment != 0 && (offset & (alignment - 1))) {
// Pad the extra field so the data will be aligned.
uint16_t padding = static_cast<uint16_t>(alignment - (offset % alignment));
file_entry.padding_length = padding;
offset += padding;
- zero_padding.resize(padding, 0);
+ if (padding <= std::size(kSmallZeroPadding)) {
+ zero_padding = kSmallZeroPadding;
+ } else {
+ zero_padding_big.resize(padding, 0);
+ zero_padding = zero_padding_big.data();
+ }
}
LocalFileHeader header = {};
@@ -265,11 +276,11 @@
return HandleError(kIoError);
}
- if (fwrite(path, sizeof(*path), file_entry.path.size(), file_) != file_entry.path.size()) {
+ if (fwrite(path.data(), 1, path.size(), file_) != path.size()) {
return HandleError(kIoError);
}
- if (file_entry.padding_length != 0 && fwrite(zero_padding.data(), 1, file_entry.padding_length,
+ if (file_entry.padding_length != 0 && fwrite(zero_padding, 1, file_entry.padding_length,
file_) != file_entry.padding_length) {
return HandleError(kIoError);
}
diff --git a/logd/tests/logd_test.cpp b/logd/tests/logd_test.cpp
index 447b067..b6c33d7 100644
--- a/logd/tests/logd_test.cpp
+++ b/logd/tests/logd_test.cpp
@@ -952,7 +952,7 @@
void __android_log_btwrite_multiple__helper(int count) {
#ifdef __ANDROID__
log_time ts(CLOCK_MONOTONIC);
-
+ usleep(100);
log_time ts1(CLOCK_MONOTONIC);
// We fork to create a unique pid for the submitted log messages
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 7cb0f66..3acf301 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -345,8 +345,11 @@
trigger early-boot
trigger boot
-on post-fs
+on early-fs
+ # Once metadata has been mounted, we'll need vold to deal with userdata checkpointing
start vold
+
+on post-fs
exec - system system -- /system/bin/vdc checkpoint markBootAttempt
# Once everything is setup, no need to modify /.
@@ -442,6 +445,7 @@
mkdir /data/apex 0750 root system
mkdir /data/apex/active 0750 root system
mkdir /data/apex/backup 0700 root system
+ mkdir /data/apex/hashtree 0700 root system
mkdir /data/apex/sessions 0700 root system
mkdir /data/app-staging 0750 system system
start apexd
diff --git a/trusty/gatekeeper/Android.bp b/trusty/gatekeeper/Android.bp
index 65b271a..1666cfb 100644
--- a/trusty/gatekeeper/Android.bp
+++ b/trusty/gatekeeper/Android.bp
@@ -1,4 +1,3 @@
-//
// Copyright (C) 2015 The Android Open-Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,14 +19,15 @@
// to only building on ARM if they include assembly. Individual makefiles
// are responsible for having their own logic, for fine-grained control.
-cc_library_shared {
- name: "gatekeeper.trusty",
+cc_binary {
+ name: "android.hardware.gatekeeper@1.0-service.trusty",
+ defaults: ["hidl_defaults"],
vendor: true,
-
relative_install_path: "hw",
+ init_rc: ["android.hardware.gatekeeper@1.0-service.trusty.rc"],
srcs: [
- "module.cpp",
+ "service.cpp",
"trusty_gatekeeper_ipc.c",
"trusty_gatekeeper.cpp",
],
@@ -39,10 +39,16 @@
],
shared_libs: [
+ "android.hardware.gatekeeper@1.0",
+ "libbase",
+ "libhidlbase",
+ "libhidltransport",
"libgatekeeper",
+ "libutils",
"liblog",
"libcutils",
"libtrusty",
],
- header_libs: ["libhardware_headers"],
+
+ vintf_fragments: ["android.hardware.gatekeeper@1.0-service.trusty.xml"],
}
diff --git a/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.rc b/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.rc
new file mode 100644
index 0000000..5413a6c
--- /dev/null
+++ b/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.rc
@@ -0,0 +1,4 @@
+service vendor.gatekeeper-1-0 /vendor/bin/hw/android.hardware.gatekeeper@1.0-service.trusty
+ class hal
+ user system
+ group system
diff --git a/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.xml b/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.xml
new file mode 100644
index 0000000..19714a8
--- /dev/null
+++ b/trusty/gatekeeper/android.hardware.gatekeeper@1.0-service.trusty.xml
@@ -0,0 +1,11 @@
+<manifest version="1.0" type="device">
+ <hal format="hidl">
+ <name>android.hardware.gatekeeper</name>
+ <transport>hwbinder</transport>
+ <version>1.0</version>
+ <interface>
+ <name>IGatekeeper</name>
+ <instance>default</instance>
+ </interface>
+ </hal>
+</manifest>
diff --git a/trusty/gatekeeper/module.cpp b/trusty/gatekeeper/module.cpp
deleted file mode 100644
index 0ee3c2f..0000000
--- a/trusty/gatekeeper/module.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * 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.
- */
-
-#include <hardware/hardware.h>
-
-#include <string.h>
-#include <errno.h>
-#include <stdlib.h>
-
-#include "trusty_gatekeeper.h"
-
-using gatekeeper::TrustyGateKeeperDevice;
-
-static int trusty_gatekeeper_open(const hw_module_t *module, const char *name,
- hw_device_t **device) {
-
- if (strcmp(name, HARDWARE_GATEKEEPER) != 0) {
- return -EINVAL;
- }
-
- TrustyGateKeeperDevice *gatekeeper = new TrustyGateKeeperDevice(module);
- if (gatekeeper == NULL) return -ENOMEM;
- *device = gatekeeper->hw_device();
-
- return 0;
-}
-
-static struct hw_module_methods_t gatekeeper_module_methods = {
- .open = trusty_gatekeeper_open,
-};
-
-struct gatekeeper_module HAL_MODULE_INFO_SYM __attribute__((visibility("default"))) = {
- .common = {
- .tag = HARDWARE_MODULE_TAG,
- .module_api_version = GATEKEEPER_MODULE_API_VERSION_0_1,
- .hal_api_version = HARDWARE_HAL_API_VERSION,
- .id = GATEKEEPER_HARDWARE_MODULE_ID,
- .name = "Trusty GateKeeper HAL",
- .author = "The Android Open Source Project",
- .methods = &gatekeeper_module_methods,
- .dso = 0,
- .reserved = {}
- },
-};
diff --git a/trusty/gatekeeper/service.cpp b/trusty/gatekeeper/service.cpp
new file mode 100644
index 0000000..c5ee488
--- /dev/null
+++ b/trusty/gatekeeper/service.cpp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2019 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.
+ */
+#define LOG_TAG "android.hardware.gatekeeper@1.0-service.trusty"
+
+#include <android-base/logging.h>
+#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
+
+#include <hidl/LegacySupport.h>
+
+#include "trusty_gatekeeper.h"
+
+// Generated HIDL files
+using android::hardware::gatekeeper::V1_0::IGatekeeper;
+using gatekeeper::TrustyGateKeeperDevice;
+
+int main() {
+ ::android::hardware::configureRpcThreadpool(1, true /* willJoinThreadpool */);
+ android::sp<TrustyGateKeeperDevice> gatekeeper(new TrustyGateKeeperDevice());
+ auto status = gatekeeper->registerAsService();
+ if (status != android::OK) {
+ LOG(FATAL) << "Could not register service for Gatekeeper 1.0 (trusty) (" << status << ")";
+ }
+
+ android::hardware::joinRpcThreadpool();
+ return -1; // Should never get here.
+}
diff --git a/trusty/gatekeeper/trusty_gatekeeper.cpp b/trusty/gatekeeper/trusty_gatekeeper.cpp
index b3fbfa9..d149664 100644
--- a/trusty/gatekeeper/trusty_gatekeeper.cpp
+++ b/trusty/gatekeeper/trusty_gatekeeper.cpp
@@ -16,147 +16,131 @@
#define LOG_TAG "TrustyGateKeeper"
-#include <assert.h>
-#include <errno.h>
-#include <stdio.h>
-
-#include <type_traits>
-
-#include <log/log.h>
+#include <android-base/logging.h>
+#include <limits>
#include "trusty_gatekeeper.h"
#include "trusty_gatekeeper_ipc.h"
#include "gatekeeper_ipc.h"
+using ::android::hardware::hidl_vec;
+using ::android::hardware::Return;
+using ::android::hardware::gatekeeper::V1_0::GatekeeperStatusCode;
+using ::gatekeeper::EnrollRequest;
+using ::gatekeeper::EnrollResponse;
+using ::gatekeeper::ERROR_INVALID;
+using ::gatekeeper::ERROR_MEMORY_ALLOCATION_FAILED;
+using ::gatekeeper::ERROR_NONE;
+using ::gatekeeper::ERROR_RETRY;
+using ::gatekeeper::SizedBuffer;
+using ::gatekeeper::VerifyRequest;
+using ::gatekeeper::VerifyResponse;
+
namespace gatekeeper {
-const uint32_t SEND_BUF_SIZE = 8192;
-const uint32_t RECV_BUF_SIZE = 8192;
+constexpr const uint32_t SEND_BUF_SIZE = 8192;
+constexpr const uint32_t RECV_BUF_SIZE = 8192;
-TrustyGateKeeperDevice::TrustyGateKeeperDevice(const hw_module_t *module) {
-#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
- static_assert(std::is_standard_layout<TrustyGateKeeperDevice>::value,
- "TrustyGateKeeperDevice must be standard layout");
- static_assert(offsetof(TrustyGateKeeperDevice, device_) == 0,
- "device_ must be the first member of TrustyGateKeeperDevice");
- static_assert(offsetof(TrustyGateKeeperDevice, device_.common) == 0,
- "common must be the first member of gatekeeper_device");
-#else
- assert(reinterpret_cast<gatekeeper_device_t *>(this) == &device_);
- assert(reinterpret_cast<hw_device_t *>(this) == &(device_.common));
-#endif
-
- memset(&device_, 0, sizeof(device_));
- device_.common.tag = HARDWARE_DEVICE_TAG;
- device_.common.version = 1;
- device_.common.module = const_cast<hw_module_t *>(module);
- device_.common.close = close_device;
-
- device_.enroll = enroll;
- device_.verify = verify;
- device_.delete_user = nullptr;
- device_.delete_all_users = nullptr;
-
+TrustyGateKeeperDevice::TrustyGateKeeperDevice() {
int rc = trusty_gatekeeper_connect();
if (rc < 0) {
- ALOGE("Error initializing trusty session: %d", rc);
+ LOG(ERROR) << "Error initializing trusty session: " << rc;
}
error_ = rc;
-
-}
-
-hw_device_t* TrustyGateKeeperDevice::hw_device() {
- return &device_.common;
-}
-
-int TrustyGateKeeperDevice::close_device(hw_device_t* dev) {
- delete reinterpret_cast<TrustyGateKeeperDevice *>(dev);
- return 0;
}
TrustyGateKeeperDevice::~TrustyGateKeeperDevice() {
trusty_gatekeeper_disconnect();
}
-int TrustyGateKeeperDevice::Enroll(uint32_t uid, const uint8_t *current_password_handle,
- uint32_t current_password_handle_length, const uint8_t *current_password,
- uint32_t current_password_length, const uint8_t *desired_password,
- uint32_t desired_password_length, uint8_t **enrolled_password_handle,
- uint32_t *enrolled_password_handle_length) {
-
- if (error_ != 0) {
- return error_;
- }
-
- SizedBuffer desired_password_buffer(desired_password_length);
- memcpy(desired_password_buffer.buffer.get(), desired_password, desired_password_length);
-
- SizedBuffer current_password_handle_buffer(current_password_handle_length);
- if (current_password_handle) {
- memcpy(current_password_handle_buffer.buffer.get(), current_password_handle,
- current_password_handle_length);
- }
-
- SizedBuffer current_password_buffer(current_password_length);
- if (current_password) {
- memcpy(current_password_buffer.buffer.get(), current_password, current_password_length);
- }
-
- EnrollRequest request(uid, ¤t_password_handle_buffer, &desired_password_buffer,
- ¤t_password_buffer);
- EnrollResponse response;
-
- gatekeeper_error_t error = Send(request, &response);
-
- if (error == ERROR_RETRY) {
- return response.retry_timeout;
- } else if (error != ERROR_NONE) {
- return -EINVAL;
- }
-
- *enrolled_password_handle = response.enrolled_password_handle.buffer.release();
- *enrolled_password_handle_length = response.enrolled_password_handle.length;
-
-
- return 0;
+SizedBuffer hidl_vec2sized_buffer(const hidl_vec<uint8_t>& vec) {
+ if (vec.size() == 0 || vec.size() > std::numeric_limits<uint32_t>::max()) return {};
+ auto dummy = new uint8_t[vec.size()];
+ std::copy(vec.begin(), vec.end(), dummy);
+ return {dummy, static_cast<uint32_t>(vec.size())};
}
-int TrustyGateKeeperDevice::Verify(uint32_t uid, uint64_t challenge,
- const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
- const uint8_t *provided_password, uint32_t provided_password_length,
- uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll) {
+Return<void> TrustyGateKeeperDevice::enroll(uint32_t uid,
+ const hidl_vec<uint8_t>& currentPasswordHandle,
+ const hidl_vec<uint8_t>& currentPassword,
+ const hidl_vec<uint8_t>& desiredPassword,
+ enroll_cb _hidl_cb) {
if (error_ != 0) {
- return error_;
+ _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+ return {};
}
- SizedBuffer password_handle_buffer(enrolled_password_handle_length);
- memcpy(password_handle_buffer.buffer.get(), enrolled_password_handle,
- enrolled_password_handle_length);
- SizedBuffer provided_password_buffer(provided_password_length);
- memcpy(provided_password_buffer.buffer.get(), provided_password, provided_password_length);
+ if (desiredPassword.size() == 0) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+ return {};
+ }
- VerifyRequest request(uid, challenge, &password_handle_buffer, &provided_password_buffer);
+ EnrollRequest request(uid, hidl_vec2sized_buffer(currentPasswordHandle),
+ hidl_vec2sized_buffer(desiredPassword),
+ hidl_vec2sized_buffer(currentPassword));
+ EnrollResponse response;
+ auto error = Send(request, &response);
+ if (error != ERROR_NONE) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+ } else if (response.error == ERROR_RETRY) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_RETRY_TIMEOUT, response.retry_timeout, {}});
+ } else if (response.error != ERROR_NONE) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+ } else {
+ hidl_vec<uint8_t> new_handle(response.enrolled_password_handle.Data<uint8_t>(),
+ response.enrolled_password_handle.Data<uint8_t>() +
+ response.enrolled_password_handle.size());
+ _hidl_cb({GatekeeperStatusCode::STATUS_OK, response.retry_timeout, new_handle});
+ }
+ return {};
+}
+
+Return<void> TrustyGateKeeperDevice::verify(
+ uint32_t uid, uint64_t challenge,
+ const ::android::hardware::hidl_vec<uint8_t>& enrolledPasswordHandle,
+ const ::android::hardware::hidl_vec<uint8_t>& providedPassword, verify_cb _hidl_cb) {
+ if (error_ != 0) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+ return {};
+ }
+
+ if (enrolledPasswordHandle.size() == 0) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+ return {};
+ }
+
+ VerifyRequest request(uid, challenge, hidl_vec2sized_buffer(enrolledPasswordHandle),
+ hidl_vec2sized_buffer(providedPassword));
VerifyResponse response;
- gatekeeper_error_t error = Send(request, &response);
+ auto error = Send(request, &response);
+ if (error != ERROR_NONE) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+ } else if (response.error == ERROR_RETRY) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_RETRY_TIMEOUT, response.retry_timeout, {}});
+ } else if (response.error != ERROR_NONE) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_GENERAL_FAILURE, 0, {}});
+ } else {
+ hidl_vec<uint8_t> auth_token(
+ response.auth_token.Data<uint8_t>(),
+ response.auth_token.Data<uint8_t>() + response.auth_token.size());
- if (error == ERROR_RETRY) {
- return response.retry_timeout;
- } else if (error != ERROR_NONE) {
- return -EINVAL;
+ _hidl_cb({response.request_reenroll ? GatekeeperStatusCode::STATUS_REENROLL
+ : GatekeeperStatusCode::STATUS_OK,
+ response.retry_timeout, auth_token});
}
+ return {};
+}
- if (auth_token != NULL && auth_token_length != NULL) {
- *auth_token = response.auth_token.buffer.release();
- *auth_token_length = response.auth_token.length;
- }
+Return<void> TrustyGateKeeperDevice::deleteUser(uint32_t /*uid*/, deleteUser_cb _hidl_cb) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_NOT_IMPLEMENTED, 0, {}});
+ return {};
+}
- if (request_reenroll != NULL) {
- *request_reenroll = response.request_reenroll;
- }
-
- return 0;
+Return<void> TrustyGateKeeperDevice::deleteAllUsers(deleteAllUsers_cb _hidl_cb) {
+ _hidl_cb({GatekeeperStatusCode::ERROR_NOT_IMPLEMENTED, 0, {}});
+ return {};
}
gatekeeper_error_t TrustyGateKeeperDevice::Send(uint32_t command, const GateKeeperMessage& request,
@@ -172,7 +156,7 @@
uint32_t response_size = RECV_BUF_SIZE;
int rc = trusty_gatekeeper_call(command, send_buf, request_size, recv_buf, &response_size);
if (rc < 0) {
- ALOGE("error (%d) calling gatekeeper TA", rc);
+ LOG(ERROR) << "error (" << rc << ") calling gatekeeper TA";
return ERROR_INVALID;
}
@@ -182,51 +166,4 @@
return response->Deserialize(payload, payload + response_size);
}
-static inline TrustyGateKeeperDevice *convert_device(const gatekeeper_device *dev) {
- return reinterpret_cast<TrustyGateKeeperDevice *>(const_cast<gatekeeper_device *>(dev));
-}
-
-/* static */
-int TrustyGateKeeperDevice::enroll(const struct gatekeeper_device *dev, uint32_t uid,
- const uint8_t *current_password_handle, uint32_t current_password_handle_length,
- const uint8_t *current_password, uint32_t current_password_length,
- const uint8_t *desired_password, uint32_t desired_password_length,
- uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length) {
-
- if (dev == NULL ||
- enrolled_password_handle == NULL || enrolled_password_handle_length == NULL ||
- desired_password == NULL || desired_password_length == 0)
- return -EINVAL;
-
- // Current password and current password handle go together
- if (current_password_handle == NULL || current_password_handle_length == 0 ||
- current_password == NULL || current_password_length == 0) {
- current_password_handle = NULL;
- current_password_handle_length = 0;
- current_password = NULL;
- current_password_length = 0;
- }
-
- return convert_device(dev)->Enroll(uid, current_password_handle, current_password_handle_length,
- current_password, current_password_length, desired_password, desired_password_length,
- enrolled_password_handle, enrolled_password_handle_length);
-
-}
-
-/* static */
-int TrustyGateKeeperDevice::verify(const struct gatekeeper_device *dev, uint32_t uid,
- uint64_t challenge, const uint8_t *enrolled_password_handle,
- uint32_t enrolled_password_handle_length, const uint8_t *provided_password,
- uint32_t provided_password_length, uint8_t **auth_token, uint32_t *auth_token_length,
- bool *request_reenroll) {
-
- if (dev == NULL || enrolled_password_handle == NULL ||
- provided_password == NULL) {
- return -EINVAL;
- }
-
- return convert_device(dev)->Verify(uid, challenge, enrolled_password_handle,
- enrolled_password_handle_length, provided_password, provided_password_length,
- auth_token, auth_token_length, request_reenroll);
-}
};
diff --git a/trusty/gatekeeper/trusty_gatekeeper.h b/trusty/gatekeeper/trusty_gatekeeper.h
index 2becc49..c0713f4 100644
--- a/trusty/gatekeeper/trusty_gatekeeper.h
+++ b/trusty/gatekeeper/trusty_gatekeeper.h
@@ -17,84 +17,34 @@
#ifndef TRUSTY_GATEKEEPER_H
#define TRUSTY_GATEKEEPER_H
-#include <hardware/gatekeeper.h>
+#include <android/hardware/gatekeeper/1.0/IGatekeeper.h>
+#include <hidl/Status.h>
+
+#include <memory>
+
#include <gatekeeper/gatekeeper_messages.h>
#include "gatekeeper_ipc.h"
namespace gatekeeper {
-class TrustyGateKeeperDevice {
- public:
-
- explicit TrustyGateKeeperDevice(const hw_module_t* module);
+class TrustyGateKeeperDevice : public ::android::hardware::gatekeeper::V1_0::IGatekeeper {
+ public:
+ explicit TrustyGateKeeperDevice();
~TrustyGateKeeperDevice();
-
- hw_device_t* hw_device();
-
/**
* Enrolls password_payload, which should be derived from a user selected pin or password,
* with the authentication factor private key used only for enrolling authentication
* factor data.
*
* Returns: 0 on success or an error code less than 0 on error.
- * On error, enrolled_password will not be allocated.
- */
- int Enroll(uint32_t uid, const uint8_t *current_password_handle,
- uint32_t current_password_handle_length, const uint8_t *current_password,
- uint32_t current_password_length, const uint8_t *desired_password,
- uint32_t desired_password_length, uint8_t **enrolled_password_handle,
- uint32_t *enrolled_password_handle_length);
-
- /**
- * Verifies provided_password matches expected_password after enrolling
- * with the authentication factor private key.
- *
- * Implementations of this module may retain the result of this call
- * to attest to the recency of authentication.
- *
- * On success, writes the address of a verification token to verification_token,
- *
- * Returns: 0 on success or an error code less than 0 on error
- * On error, verification token will not be allocated
- */
- int Verify(uint32_t uid, uint64_t challenge, const uint8_t *enrolled_password_handle,
- uint32_t enrolled_password_handle_length, const uint8_t *provided_password,
- uint32_t provided_password_length, uint8_t **auth_token, uint32_t *auth_token_length,
- bool *request_reenroll);
-
- private:
-
- gatekeeper_error_t Send(uint32_t command, const GateKeeperMessage& request,
- GateKeeperMessage* response);
-
- gatekeeper_error_t Send(const EnrollRequest& request, EnrollResponse *response) {
- return Send(GK_ENROLL, request, response);
- }
-
- gatekeeper_error_t Send(const VerifyRequest& request, VerifyResponse *response) {
- return Send(GK_VERIFY, request, response);
- }
-
- // Static methods interfacing the HAL API with the TrustyGateKeeper device
-
- /**
- * Enrolls desired_password, which should be derived from a user selected pin or password,
- * with the authentication factor private key used only for enrolling authentication
- * factor data.
- *
- * If there was already a password enrolled, it should be provided in
- * current_password_handle, along with the current password in current_password
- * that should validate against current_password_handle.
- *
- * Returns: 0 on success or an error code less than 0 on error.
* On error, enrolled_password_handle will not be allocated.
*/
- static int enroll(const struct gatekeeper_device *dev, uint32_t uid,
- const uint8_t *current_password_handle, uint32_t current_password_handle_length,
- const uint8_t *current_password, uint32_t current_password_length,
- const uint8_t *desired_password, uint32_t desired_password_length,
- uint8_t **enrolled_password_handle, uint32_t *enrolled_password_handle_length);
+ ::android::hardware::Return<void> enroll(
+ uint32_t uid, const ::android::hardware::hidl_vec<uint8_t>& currentPasswordHandle,
+ const ::android::hardware::hidl_vec<uint8_t>& currentPassword,
+ const ::android::hardware::hidl_vec<uint8_t>& desiredPassword,
+ enroll_cb _hidl_cb) override;
/**
* Verifies provided_password matches enrolled_password_handle.
@@ -109,18 +59,32 @@
* Returns: 0 on success or an error code less than 0 on error
* On error, verification token will not be allocated
*/
- static int verify(const struct gatekeeper_device *dev, uint32_t uid, uint64_t challenge,
- const uint8_t *enrolled_password_handle, uint32_t enrolled_password_handle_length,
- const uint8_t *provided_password, uint32_t provided_password_length,
- uint8_t **auth_token, uint32_t *auth_token_length, bool *request_reenroll);
+ ::android::hardware::Return<void> verify(
+ uint32_t uid, uint64_t challenge,
+ const ::android::hardware::hidl_vec<uint8_t>& enrolledPasswordHandle,
+ const ::android::hardware::hidl_vec<uint8_t>& providedPassword,
+ verify_cb _hidl_cb) override;
- static int close_device(hw_device_t* dev);
+ ::android::hardware::Return<void> deleteUser(uint32_t uid, deleteUser_cb _hidl_cb) override;
- gatekeeper_device device_;
+ ::android::hardware::Return<void> deleteAllUsers(deleteAllUsers_cb _hidl_cb) override;
+
+ private:
+ gatekeeper_error_t Send(uint32_t command, const GateKeeperMessage& request,
+ GateKeeperMessage* response);
+
+ gatekeeper_error_t Send(const EnrollRequest& request, EnrollResponse *response) {
+ return Send(GK_ENROLL, request, response);
+ }
+
+ gatekeeper_error_t Send(const VerifyRequest& request, VerifyResponse *response) {
+ return Send(GK_VERIFY, request, response);
+ }
+
int error_;
-
};
-}
+
+} // namespace gatekeeper
#endif
diff --git a/trusty/trusty-base.mk b/trusty/trusty-base.mk
index 445d3ce..fd8daa8 100644
--- a/trusty/trusty-base.mk
+++ b/trusty/trusty-base.mk
@@ -24,9 +24,7 @@
PRODUCT_PACKAGES += \
android.hardware.keymaster@4.0-service.trusty \
- android.hardware.gatekeeper@1.0-service \
- android.hardware.gatekeeper@1.0-impl \
- gatekeeper.trusty
+ android.hardware.gatekeeper@1.0-service.trusty
PRODUCT_PROPERTY_OVERRIDES += \
ro.hardware.keystore=trusty \
diff --git a/usbd/usbd.cpp b/usbd/usbd.cpp
index 191fb92..6e24d8e 100644
--- a/usbd/usbd.cpp
+++ b/usbd/usbd.cpp
@@ -24,8 +24,6 @@
#include <hidl/HidlTransportSupport.h>
-#define PERSISTENT_USB_CONFIG "persist.sys.usb.config"
-
using android::base::GetProperty;
using android::base::SetProperty;
using android::hardware::configureRpcThreadpool;
@@ -34,14 +32,15 @@
using android::hardware::Return;
int main(int /*argc*/, char** /*argv*/) {
- configureRpcThreadpool(1, true /*callerWillJoin*/);
+ if (GetProperty("ro.bootmode", "") == "charger") exit(0);
+ configureRpcThreadpool(1, true /*callerWillJoin*/);
android::sp<IUsbGadget> gadget = IUsbGadget::getService();
Return<void> ret;
if (gadget != nullptr) {
LOG(INFO) << "Usb HAL found.";
- std::string function = GetProperty(PERSISTENT_USB_CONFIG, "");
+ std::string function = GetProperty("persist.sys.usb.config", "");
if (function == "adb") {
LOG(INFO) << "peristent prop is adb";
SetProperty("ctl.start", "adbd");