Merge "Adding /data/local/traces for traceur app"
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
index 198c48b..be90d0f 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/tombstone.h
@@ -40,16 +40,16 @@
/* Creates a tombstone file and writes the crash dump to it. */
void engrave_tombstone(int tombstone_fd, BacktraceMap* map, const OpenFilesList* open_files,
pid_t pid, pid_t tid, const std::string& process_name,
- const std::map<pid_t, std::string>& threads, uintptr_t abort_msg_address,
+ const std::map<pid_t, std::string>& threads, uint64_t abort_msg_address,
std::string* amfd_data);
-void engrave_tombstone_ucontext(int tombstone_fd, uintptr_t abort_msg_address, siginfo_t* siginfo,
+void engrave_tombstone_ucontext(int tombstone_fd, uint64_t abort_msg_address, siginfo_t* siginfo,
ucontext_t* ucontext);
void engrave_tombstone(android::base::unique_fd output_fd, BacktraceMap* map,
unwindstack::Memory* process_memory,
const std::map<pid_t, ThreadInfo>& thread_info, pid_t target_thread,
- uintptr_t abort_msg_address, OpenFilesList* open_files,
+ uint64_t abort_msg_address, OpenFilesList* open_files,
std::string* amfd_data);
#endif // _DEBUGGERD_TOMBSTONE_H
diff --git a/debuggerd/libdebuggerd/include/libdebuggerd/utility.h b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
index c5abfe2..0f049fd 100644
--- a/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
+++ b/debuggerd/libdebuggerd/include/libdebuggerd/utility.h
@@ -68,7 +68,7 @@
class Memory;
}
-void dump_memory(log_t* log, unwindstack::Memory* backtrace, uintptr_t addr, const char* fmt, ...);
+void dump_memory(log_t* log, unwindstack::Memory* backtrace, uint64_t addr, const char* fmt, ...);
void read_with_default(const char* path, char* buf, size_t len, const char* default_value);
diff --git a/debuggerd/libdebuggerd/test/tombstone_test.cpp b/debuggerd/libdebuggerd/test/tombstone_test.cpp
index 1e3a10f..421ce43 100644
--- a/debuggerd/libdebuggerd/test/tombstone_test.cpp
+++ b/debuggerd/libdebuggerd/test/tombstone_test.cpp
@@ -437,9 +437,9 @@
map_mock_->AddMap(map);
#if defined(__LP64__)
- uintptr_t addr = 0x12345a534040UL;
+ uint64_t addr = 0x12345a534040UL;
#else
- uintptr_t addr = 0xf534040UL;
+ uint64_t addr = 0xf534040UL;
#endif
dump_all_maps(&log_, map_mock_.get(), nullptr, addr);
diff --git a/debuggerd/libdebuggerd/tombstone.cpp b/debuggerd/libdebuggerd/tombstone.cpp
index 89a125b..320e5db 100644
--- a/debuggerd/libdebuggerd/tombstone.cpp
+++ b/debuggerd/libdebuggerd/tombstone.cpp
@@ -127,7 +127,7 @@
}
static void dump_stack_segment(log_t* log, BacktraceMap* backtrace_map, Memory* process_memory,
- uintptr_t* sp, size_t words, int label) {
+ uint64_t* sp, size_t words, int label) {
// Read the data all at once.
word_t stack_data[words];
@@ -144,18 +144,18 @@
} else {
line += " ";
}
- line += StringPrintf("%" PRIPTR " %" PRIPTR, *sp, stack_data[i]);
+ line += StringPrintf("%" PRIPTR " %" PRIxPTR, *sp, stack_data[i]);
backtrace_map_t map;
backtrace_map->FillIn(stack_data[i], &map);
if (BacktraceMap::IsValid(map) && !map.name.empty()) {
line += " " + map.name;
- uintptr_t offset = 0;
+ uint64_t offset = 0;
std::string func_name = backtrace_map->GetFunctionName(stack_data[i], &offset);
if (!func_name.empty()) {
line += " (" + func_name;
if (offset) {
- line += StringPrintf("+%" PRIuPTR, offset);
+ line += StringPrintf("+%" PRIu64, offset);
}
line += ')';
}
@@ -185,7 +185,7 @@
first--;
// Dump a few words before the first frame.
- word_t sp = frames[first].sp - STACK_WORDS * sizeof(word_t);
+ uint64_t sp = frames[first].sp - STACK_WORDS * sizeof(word_t);
dump_stack_segment(log, backtrace_map, process_memory, &sp, STACK_WORDS, -1);
// Dump a few words from all successive frames.
@@ -213,19 +213,19 @@
}
}
-static std::string get_addr_string(uintptr_t addr) {
+static std::string get_addr_string(uint64_t addr) {
std::string addr_str;
#if defined(__LP64__)
addr_str = StringPrintf("%08x'%08x",
static_cast<uint32_t>(addr >> 32),
static_cast<uint32_t>(addr & 0xffffffff));
#else
- addr_str = StringPrintf("%08x", addr);
+ addr_str = StringPrintf("%08x", static_cast<uint32_t>(addr));
#endif
return addr_str;
}
-static void dump_abort_message(log_t* log, Memory* process_memory, uintptr_t address) {
+static void dump_abort_message(log_t* log, Memory* process_memory, uint64_t address) {
if (address == 0) {
return;
}
@@ -251,7 +251,7 @@
_LOG(log, logtype::HEADER, "Abort message: '%s'\n", msg);
}
-static void dump_all_maps(log_t* log, BacktraceMap* map, Memory* process_memory, uintptr_t addr) {
+static void dump_all_maps(log_t* log, BacktraceMap* map, Memory* process_memory, uint64_t addr) {
bool print_fault_address_marker = addr;
ScopedBacktraceMapIteratorLock lock(map);
@@ -301,7 +301,7 @@
} else {
line += '-';
}
- line += StringPrintf(" %8" PRIxPTR " %8" PRIxPTR, entry->offset, entry->end - entry->start);
+ line += StringPrintf(" %8" PRIx64 " %8" PRIx64, entry->offset, entry->end - entry->start);
bool space_needed = true;
if (entry->name.length() > 0) {
space_needed = false;
@@ -315,7 +315,7 @@
if (space_needed) {
line += ' ';
}
- line += StringPrintf(" (load bias 0x%" PRIxPTR ")", entry->load_bias);
+ line += StringPrintf(" (load bias 0x%" PRIx64 ")", entry->load_bias);
}
_LOG(log, logtype::MAPS, "%s\n", line.c_str());
}
@@ -335,9 +335,9 @@
const std::vector<std::pair<std::string, uint64_t>>& registers) {
std::string output;
for (auto& [name, value] : registers) {
- output += android::base::StringPrintf(" %-3s %0*" PRIxPTR, name.c_str(),
+ output += android::base::StringPrintf(" %-3s %0*" PRIx64, name.c_str(),
static_cast<int>(2 * sizeof(void*)),
- static_cast<uintptr_t>(value));
+ static_cast<uint64_t>(value));
}
_LOG(log, logtype::REGISTERS, " %s\n", output.c_str());
@@ -389,7 +389,7 @@
}
static bool dump_thread(log_t* log, BacktraceMap* map, Memory* process_memory,
- const ThreadInfo& thread_info, uintptr_t abort_msg_address,
+ const ThreadInfo& thread_info, uint64_t abort_msg_address,
bool primary_thread) {
UNUSED(process_memory);
log->current_tid = thread_info.tid;
@@ -425,10 +425,10 @@
if (primary_thread) {
dump_memory_and_code(log, process_memory, thread_info.registers.get());
if (map) {
- uintptr_t addr = 0;
+ uint64_t addr = 0;
siginfo_t* si = thread_info.siginfo;
if (signal_has_si_addr(si->si_signo, si->si_code)) {
- addr = reinterpret_cast<uintptr_t>(si->si_addr);
+ addr = reinterpret_cast<uint64_t>(si->si_addr);
}
dump_all_maps(log, map, process_memory, addr);
}
@@ -572,7 +572,7 @@
dump_log_file(log, pid, "main", tail);
}
-void engrave_tombstone_ucontext(int tombstone_fd, uintptr_t abort_msg_address, siginfo_t* siginfo,
+void engrave_tombstone_ucontext(int tombstone_fd, uint64_t abort_msg_address, siginfo_t* siginfo,
ucontext_t* ucontext) {
pid_t pid = getpid();
pid_t tid = gettid();
@@ -614,7 +614,7 @@
void engrave_tombstone(unique_fd output_fd, BacktraceMap* map, Memory* process_memory,
const std::map<pid_t, ThreadInfo>& threads, pid_t target_thread,
- uintptr_t abort_msg_address, OpenFilesList* open_files,
+ uint64_t abort_msg_address, OpenFilesList* open_files,
std::string* amfd_data) {
// don't copy log messages to tombstone unless this is a dev device
bool want_logs = android::base::GetBoolProperty("ro.debuggable", false);
diff --git a/debuggerd/libdebuggerd/utility.cpp b/debuggerd/libdebuggerd/utility.cpp
index 247d806..3ac98f5 100644
--- a/debuggerd/libdebuggerd/utility.cpp
+++ b/debuggerd/libdebuggerd/utility.cpp
@@ -124,7 +124,7 @@
#define MEMORY_BYTES_TO_DUMP 256
#define MEMORY_BYTES_PER_LINE 16
-void dump_memory(log_t* log, unwindstack::Memory* memory, uintptr_t addr, const char* fmt, ...) {
+void dump_memory(log_t* log, unwindstack::Memory* memory, uint64_t addr, const char* fmt, ...) {
std::string log_msg;
va_list ap;
va_start(ap, fmt);
@@ -159,7 +159,7 @@
bytes &= ~(sizeof(uintptr_t) - 1);
}
- uintptr_t start = 0;
+ uint64_t start = 0;
bool skip_2nd_read = false;
if (bytes == 0) {
// In this case, we might want to try another read at the beginning of
@@ -206,7 +206,7 @@
std::string ascii;
for (size_t i = 0; i < MEMORY_BYTES_PER_LINE / sizeof(uintptr_t); i++) {
if (current >= start && current + sizeof(uintptr_t) <= total_bytes) {
- android::base::StringAppendF(&logline, " %" PRIPTR, *data_ptr);
+ android::base::StringAppendF(&logline, " %" PRIPTR, static_cast<uint64_t>(*data_ptr));
// Fill out the ascii string from the data.
uint8_t* ptr = reinterpret_cast<uint8_t*>(data_ptr);
diff --git a/fastboot/bootimg_utils.cpp b/fastboot/bootimg_utils.cpp
index c1028ef..62a26b3 100644
--- a/fastboot/bootimg_utils.cpp
+++ b/fastboot/bootimg_utils.cpp
@@ -28,13 +28,15 @@
#include "bootimg_utils.h"
+#include "fastboot.h"
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-void bootimg_set_cmdline(boot_img_hdr* h, const char* cmdline)
-{
- strcpy((char*) h->cmdline, cmdline);
+void bootimg_set_cmdline(boot_img_hdr* h, const char* cmdline) {
+ if (strlen(cmdline) >= sizeof(h->cmdline)) die("command line too large: %zu", strlen(cmdline));
+ strcpy(reinterpret_cast<char*>(h->cmdline), cmdline);
}
boot_img_hdr* mkbootimg(void* kernel, int64_t kernel_size, off_t kernel_offset,
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 6175f59..536d64e 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -447,8 +447,11 @@
if (kdata == nullptr) die("cannot load '%s': %s", kernel.c_str(), strerror(errno));
// Is this actually a boot image?
+ if (ksize < static_cast<int64_t>(sizeof(boot_img_hdr))) {
+ die("cannot load '%s': too short", kernel.c_str());
+ }
if (!memcmp(kdata, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
- if (cmdline) bootimg_set_cmdline((boot_img_hdr*) kdata, cmdline);
+ if (cmdline) bootimg_set_cmdline(reinterpret_cast<boot_img_hdr*>(kdata), cmdline);
if (!ramdisk.empty()) die("cannot boot a boot.img *and* ramdisk");
diff --git a/init/Android.bp b/init/Android.bp
index 2fea359..0db7824 100644
--- a/init/Android.bp
+++ b/init/Android.bp
@@ -75,6 +75,7 @@
"persistent_properties.cpp",
"persistent_properties.proto",
"property_service.cpp",
+ "property_type.cpp",
"security.cpp",
"selinux.cpp",
"service.cpp",
@@ -178,6 +179,7 @@
"init_test.cpp",
"persistent_properties_test.cpp",
"property_service_test.cpp",
+ "property_type_test.cpp",
"result_test.cpp",
"rlimit_parser_test.cpp",
"service_test.cpp",
diff --git a/init/action.cpp b/init/action.cpp
index 16ecdcd..ba03e66 100644
--- a/init/action.cpp
+++ b/init/action.cpp
@@ -21,6 +21,7 @@
#include <android-base/properties.h>
#include <android-base/strings.h>
+#include "stable_properties.h"
#include "util.h"
using android::base::Join;
@@ -134,6 +135,25 @@
}
}
+static bool IsActionableProperty(Subcontext* subcontext, const std::string& prop_name) {
+ static bool enabled =
+ android::base::GetBoolProperty("ro.actionable_compatible_property.enabled", false);
+
+ if (subcontext == nullptr || !enabled) {
+ return true;
+ }
+
+ if (kExportedActionableProperties.count(prop_name) == 1) {
+ return true;
+ }
+ for (const auto& prefix : kPartnerPrefixes) {
+ if (android::base::StartsWith(prop_name, prefix)) {
+ return true;
+ }
+ }
+ return false;
+}
+
Result<Success> Action::ParsePropertyTrigger(const std::string& trigger) {
const static std::string prop_str("property:");
std::string prop_name(trigger.substr(prop_str.length()));
@@ -145,6 +165,10 @@
std::string prop_value(prop_name.substr(equal_pos + 1));
prop_name.erase(equal_pos);
+ if (!IsActionableProperty(subcontext_, prop_name)) {
+ return Error() << "unexported property tigger found: " << prop_name;
+ }
+
if (auto [it, inserted] = property_triggers_.emplace(prop_name, prop_value); !inserted) {
return Error() << "multiple property triggers found for same property";
}
diff --git a/init/property_service.cpp b/init/property_service.cpp
index 7aa94b0..79f7f25 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -58,6 +58,7 @@
#include "init.h"
#include "persistent_properties.h"
+#include "property_type.h"
#include "util.h"
using android::base::ReadFileToString;
@@ -95,14 +96,9 @@
LOG(FATAL) << "Failed to load serialized property info file";
}
}
-static bool check_mac_perms(const std::string& name, char* sctx, struct ucred* cr) {
- if (!sctx) {
- return false;
- }
-
- const char* target_context = nullptr;
- property_info_area->GetPropertyInfo(name.c_str(), &target_context, nullptr);
- if (target_context == nullptr) {
+static bool CheckMacPerms(const std::string& name, const char* target_context,
+ const char* source_context, struct ucred* cr) {
+ if (!target_context || !source_context) {
return false;
}
@@ -111,29 +107,12 @@
audit_data.name = name.c_str();
audit_data.cr = cr;
- bool has_access =
- (selinux_check_access(sctx, target_context, "property_service", "set", &audit_data) == 0);
+ bool has_access = (selinux_check_access(source_context, target_context, "property_service",
+ "set", &audit_data) == 0);
return has_access;
}
-static int check_control_mac_perms(const char *name, char *sctx, struct ucred *cr)
-{
- /*
- * Create a name prefix out of ctl.<service name>
- * The new prefix allows the use of the existing
- * property service backend labeling while avoiding
- * mislabels based on true property prefixes.
- */
- char ctl_name[PROP_VALUE_MAX+4];
- int ret = snprintf(ctl_name, sizeof(ctl_name), "ctl.%s", name);
-
- if (ret < 0 || (size_t) ret >= sizeof(ctl_name))
- return 0;
-
- return check_mac_perms(ctl_name, sctx, cr);
-}
-
bool is_legal_property_name(const std::string& name) {
size_t namelen = name.size();
@@ -422,52 +401,70 @@
struct ucred cr = socket.cred();
char* source_ctx = nullptr;
getpeercon(socket.socket(), &source_ctx);
+ std::string source_context = source_ctx;
+ freecon(source_ctx);
if (StartsWith(name, "ctl.")) {
- if (check_control_mac_perms(value.c_str(), source_ctx, &cr)) {
+ // ctl. properties have their name ctl.<action> and their value is the name of the service to
+ // apply that action to. Permissions for these actions are based on the service, so we must
+ // create a fake name of ctl.<service> to check permissions.
+ auto control_string = "ctl." + value;
+ const char* target_context = nullptr;
+ const char* type = nullptr;
+ property_info_area->GetPropertyInfo(control_string.c_str(), &target_context, &type);
+ if (!CheckMacPerms(control_string, target_context, source_context.c_str(), &cr)) {
+ LOG(ERROR) << "sys_prop(" << cmd_name << "): Unable to " << (name.c_str() + 4)
+ << " service ctl [" << value << "]"
+ << " uid:" << cr.uid << " gid:" << cr.gid << " pid:" << cr.pid;
+ if (!legacy_protocol) {
+ socket.SendUint32(PROP_ERROR_HANDLE_CONTROL_MESSAGE);
+ }
+ return;
+ }
+
handle_control_message(name.c_str() + 4, value.c_str());
if (!legacy_protocol) {
- socket.SendUint32(PROP_SUCCESS);
+ socket.SendUint32(PROP_SUCCESS);
}
- } else {
- LOG(ERROR) << "sys_prop(" << cmd_name << "): Unable to " << (name.c_str() + 4)
- << " service ctl [" << value << "]"
- << " uid:" << cr.uid
- << " gid:" << cr.gid
- << " pid:" << cr.pid;
- if (!legacy_protocol) {
- socket.SendUint32(PROP_ERROR_HANDLE_CONTROL_MESSAGE);
- }
- }
} else {
- if (check_mac_perms(name, source_ctx, &cr)) {
+ const char* target_context = nullptr;
+ const char* type = nullptr;
+ property_info_area->GetPropertyInfo(name.c_str(), &target_context, &type);
+ if (!CheckMacPerms(name, target_context, source_context.c_str(), &cr)) {
+ LOG(ERROR) << "sys_prop(" << cmd_name << "): permission denied uid:" << cr.uid
+ << " name:" << name;
+ if (!legacy_protocol) {
+ socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
+ }
+ return;
+ }
+ if (type == nullptr || !CheckType(type, value)) {
+ LOG(ERROR) << "sys_prop(" << cmd_name << "): type check failed, type: '"
+ << (type ?: "(null)") << "' value: '" << value << "'";
+ if (!legacy_protocol) {
+ socket.SendUint32(PROP_ERROR_INVALID_VALUE);
+ }
+ return;
+ }
// sys.powerctl is a special property that is used to make the device reboot. We want to log
// any process that sets this property to be able to accurately blame the cause of a shutdown.
if (name == "sys.powerctl") {
- std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
- std::string process_cmdline;
- std::string process_log_string;
- if (ReadFileToString(cmdline_path, &process_cmdline)) {
- // Since cmdline is null deliminated, .c_str() conveniently gives us just the process path.
- process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
- }
- LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
- << process_log_string;
+ std::string cmdline_path = StringPrintf("proc/%d/cmdline", cr.pid);
+ std::string process_cmdline;
+ std::string process_log_string;
+ if (ReadFileToString(cmdline_path, &process_cmdline)) {
+ // Since cmdline is null deliminated, .c_str() conveniently gives us just the process path.
+ process_log_string = StringPrintf(" (%s)", process_cmdline.c_str());
+ }
+ LOG(INFO) << "Received sys.powerctl='" << value << "' from pid: " << cr.pid
+ << process_log_string;
}
uint32_t result = property_set(name, value);
if (!legacy_protocol) {
- socket.SendUint32(result);
+ socket.SendUint32(result);
}
- } else {
- LOG(ERROR) << "sys_prop(" << cmd_name << "): permission denied uid:" << cr.uid << " name:" << name;
- if (!legacy_protocol) {
- socket.SendUint32(PROP_ERROR_PERMISSION_DENIED);
- }
- }
}
-
- freecon(source_ctx);
}
static void handle_property_set_fd() {
@@ -764,9 +761,10 @@
}
LoadPropertyInfoFromFile("/nonplat_property_contexts", &property_infos);
}
+
auto serialized_contexts = std::string();
auto error = std::string();
- if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "\\s*", &serialized_contexts,
+ if (!BuildTrie(property_infos, "u:object_r:default_prop:s0", "string", &serialized_contexts,
&error)) {
LOG(ERROR) << "Unable to serialize property contexts: " << error;
return;
diff --git a/init/property_type.cpp b/init/property_type.cpp
new file mode 100644
index 0000000..249b12b
--- /dev/null
+++ b/init/property_type.cpp
@@ -0,0 +1,81 @@
+//
+// Copyright (C) 2017 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 "property_type.h"
+
+#include <android-base/parsedouble.h>
+#include <android-base/parseint.h>
+#include <android-base/strings.h>
+
+using android::base::ParseDouble;
+using android::base::ParseInt;
+using android::base::ParseUint;
+using android::base::Split;
+
+namespace android {
+namespace init {
+
+bool CheckType(const std::string& type_string, const std::string& value) {
+ auto type_strings = Split(type_string, " ");
+ if (type_strings.empty()) {
+ return false;
+ }
+ auto type = type_strings[0];
+
+ if (type == "string") {
+ return true;
+ }
+ if (type == "bool") {
+ return value == "true" || value == "false" || value == "1" || value == "0";
+ }
+ if (type == "int") {
+ int64_t parsed;
+ return ParseInt(value, &parsed);
+ }
+ if (type == "uint") {
+ uint64_t parsed;
+ if (value.empty() || value.front() == '-') {
+ return false;
+ }
+ return ParseUint(value, &parsed);
+ }
+ if (type == "double") {
+ double parsed;
+ return ParseDouble(value.c_str(), &parsed);
+ }
+ if (type == "size") {
+ auto it = value.begin();
+ while (it != value.end() && isdigit(*it)) {
+ it++;
+ }
+ if (it == value.begin() || it == value.end() || (*it != 'g' && *it != 'k' && *it != 'm')) {
+ return false;
+ }
+ it++;
+ return it == value.end();
+ }
+ if (type == "enum") {
+ for (auto it = std::next(type_strings.begin()); it != type_strings.end(); ++it) {
+ if (*it == value) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+} // namespace init
+} // namespace android
diff --git a/init/property_type.h b/init/property_type.h
new file mode 100644
index 0000000..c889e16
--- /dev/null
+++ b/init/property_type.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2017 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 _INIT_PROPERTY_TYPE_H
+#define _INIT_PROPERTY_TYPE_H
+
+#include <string>
+
+namespace android {
+namespace init {
+
+bool CheckType(const std::string& type_string, const std::string& value);
+
+} // namespace init
+} // namespace android
+
+#endif
diff --git a/init/property_type_test.cpp b/init/property_type_test.cpp
new file mode 100644
index 0000000..068bccc
--- /dev/null
+++ b/init/property_type_test.cpp
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2017 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 "property_type.h"
+
+#include <gtest/gtest.h>
+
+namespace android {
+namespace init {
+
+TEST(property_type, CheckType_string) {
+ EXPECT_TRUE(CheckType("string", ""));
+ EXPECT_TRUE(CheckType("string", "-234"));
+ EXPECT_TRUE(CheckType("string", "234"));
+ EXPECT_TRUE(CheckType("string", "true"));
+ EXPECT_TRUE(CheckType("string", "false"));
+ EXPECT_TRUE(CheckType("string", "45645634563456345634563456"));
+ EXPECT_TRUE(CheckType("string", "some other string"));
+}
+
+TEST(property_type, CheckType_int) {
+ EXPECT_FALSE(CheckType("int", ""));
+ EXPECT_FALSE(CheckType("int", "abc"));
+ EXPECT_FALSE(CheckType("int", "-abc"));
+ EXPECT_TRUE(CheckType("int", "0"));
+ EXPECT_TRUE(CheckType("int", std::to_string(std::numeric_limits<int64_t>::min())));
+ EXPECT_TRUE(CheckType("int", std::to_string(std::numeric_limits<int64_t>::max())));
+ EXPECT_TRUE(CheckType("int", "123"));
+ EXPECT_TRUE(CheckType("int", "-123"));
+}
+
+TEST(property_type, CheckType_uint) {
+ EXPECT_FALSE(CheckType("uint", ""));
+ EXPECT_FALSE(CheckType("uint", "abc"));
+ EXPECT_FALSE(CheckType("uint", "-abc"));
+ EXPECT_TRUE(CheckType("uint", "0"));
+ EXPECT_TRUE(CheckType("uint", std::to_string(std::numeric_limits<uint64_t>::max())));
+ EXPECT_TRUE(CheckType("uint", "123"));
+ EXPECT_FALSE(CheckType("uint", "-123"));
+}
+
+TEST(property_type, CheckType_double) {
+ EXPECT_FALSE(CheckType("double", ""));
+ EXPECT_FALSE(CheckType("double", "abc"));
+ EXPECT_FALSE(CheckType("double", "-abc"));
+ EXPECT_TRUE(CheckType("double", "0.0"));
+ EXPECT_TRUE(CheckType("double", std::to_string(std::numeric_limits<double>::min())));
+ EXPECT_TRUE(CheckType("double", std::to_string(std::numeric_limits<double>::max())));
+ EXPECT_TRUE(CheckType("double", "123.1"));
+ EXPECT_TRUE(CheckType("double", "-123.1"));
+}
+
+TEST(property_type, CheckType_size) {
+ EXPECT_FALSE(CheckType("size", ""));
+ EXPECT_FALSE(CheckType("size", "ab"));
+ EXPECT_FALSE(CheckType("size", "abcd"));
+ EXPECT_FALSE(CheckType("size", "0"));
+
+ EXPECT_TRUE(CheckType("size", "512g"));
+ EXPECT_TRUE(CheckType("size", "512k"));
+ EXPECT_TRUE(CheckType("size", "512m"));
+
+ EXPECT_FALSE(CheckType("size", "512gggg"));
+ EXPECT_FALSE(CheckType("size", "512mgk"));
+ EXPECT_FALSE(CheckType("size", "g"));
+ EXPECT_FALSE(CheckType("size", "m"));
+}
+
+TEST(property_type, CheckType_enum) {
+ EXPECT_FALSE(CheckType("enum abc", ""));
+ EXPECT_FALSE(CheckType("enum abc", "ab"));
+ EXPECT_FALSE(CheckType("enum abc", "abcd"));
+ EXPECT_FALSE(CheckType("enum 123 456 789", "0"));
+
+ EXPECT_TRUE(CheckType("enum abc", "abc"));
+ EXPECT_TRUE(CheckType("enum 123 456 789", "123"));
+ EXPECT_TRUE(CheckType("enum 123 456 789", "456"));
+ EXPECT_TRUE(CheckType("enum 123 456 789", "789"));
+}
+
+} // namespace init
+} // namespace android
diff --git a/init/stable_properties.h b/init/stable_properties.h
new file mode 100644
index 0000000..8219838
--- /dev/null
+++ b/init/stable_properties.h
@@ -0,0 +1,46 @@
+/*
+ * 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.
+ */
+
+#ifndef _INIT_STABLE_PROPERTIES_H
+#define _INIT_STABLE_PROPERTIES_H
+
+#include <set>
+#include <string>
+
+namespace android {
+namespace init {
+
+static constexpr const char* kPartnerPrefixes[] = {
+ "init.svc.vendor.", "ro.vendor.", "persist.vendor.", "vendor.",
+ "init.svc.odm.", "ro.odm.", "persist.odm.", "odm.",
+};
+
+static const std::set<std::string> kExportedActionableProperties = {
+ "init.svc.zygote", "persist.bluetooth.btsnoopenable",
+ "persist.sys.crash_rcu", "persist.sys.zram_enabled",
+ "ro.boot.revision", "ro.bootmode",
+ "ro.build.type", "sys.boot_completed",
+ "sys.retaildemo.enabled", "sys.shutdown.requested",
+ "sys.usb.config", "sys.usb.configfs",
+ "sys.usb.ffs.mtp.ready", "sys.usb.ffs.ready",
+ "sys.user.0.ce_available", "sys.vdso",
+ "vts.native_server.on",
+};
+
+} // namespace init
+} // namespace android
+
+#endif
diff --git a/libbacktrace/Android.bp b/libbacktrace/Android.bp
index 9eaeae8..d9eed76 100644
--- a/libbacktrace/Android.bp
+++ b/libbacktrace/Android.bp
@@ -50,9 +50,6 @@
"BacktracePtrace.cpp",
"thread_utils.c",
"ThreadEntry.cpp",
- "UnwindCurrent.cpp",
- "UnwindMap.cpp",
- "UnwindPtrace.cpp",
"UnwindStack.cpp",
"UnwindStackMap.cpp",
]
diff --git a/libbacktrace/Backtrace.cpp b/libbacktrace/Backtrace.cpp
index 5bb6edc..1195e5f 100644
--- a/libbacktrace/Backtrace.cpp
+++ b/libbacktrace/Backtrace.cpp
@@ -30,8 +30,6 @@
#include <demangle.h>
#include "BacktraceLog.h"
-#include "UnwindCurrent.h"
-#include "UnwindPtrace.h"
#include "UnwindStack.h"
#include "thread_utils.h"
@@ -55,7 +53,7 @@
}
}
-std::string Backtrace::GetFunctionName(uintptr_t pc, uintptr_t* offset, const backtrace_map_t* map) {
+std::string Backtrace::GetFunctionName(uint64_t pc, uint64_t* offset, const backtrace_map_t* map) {
backtrace_map_t map_value;
if (map == nullptr) {
FillInMap(pc, &map_value);
@@ -68,7 +66,7 @@
return demangle(GetFunctionNameRaw(pc, offset).c_str());
}
-bool Backtrace::VerifyReadWordArgs(uintptr_t ptr, word_t* out_value) {
+bool Backtrace::VerifyReadWordArgs(uint64_t ptr, word_t* out_value) {
if (ptr & (sizeof(word_t)-1)) {
BACK_LOGW("invalid pointer %p", reinterpret_cast<void*>(ptr));
*out_value = static_cast<word_t>(-1);
@@ -105,12 +103,12 @@
// Special handling for non-zero offset maps, we need to print that
// information.
if (frame->map.offset != 0) {
- line += " (offset " + StringPrintf("0x%" PRIxPTR, frame->map.offset) + ")";
+ line += " (offset " + StringPrintf("0x%" PRIx64, frame->map.offset) + ")";
}
if (!frame->func_name.empty()) {
line += " (" + frame->func_name;
if (frame->func_offset) {
- line += StringPrintf("+%" PRIuPTR, frame->func_offset);
+ line += StringPrintf("+%" PRIu64, frame->func_offset);
}
line += ')';
}
@@ -118,7 +116,7 @@
return line;
}
-void Backtrace::FillInMap(uintptr_t pc, backtrace_map_t* map) {
+void Backtrace::FillInMap(uint64_t pc, backtrace_map_t* map) {
if (map_ != nullptr) {
map_->FillIn(pc, map);
}
diff --git a/libbacktrace/BacktraceCurrent.cpp b/libbacktrace/BacktraceCurrent.cpp
index 474d099..d61b281 100644
--- a/libbacktrace/BacktraceCurrent.cpp
+++ b/libbacktrace/BacktraceCurrent.cpp
@@ -36,7 +36,7 @@
#include "ThreadEntry.h"
#include "thread_utils.h"
-bool BacktraceCurrent::ReadWord(uintptr_t ptr, word_t* out_value) {
+bool BacktraceCurrent::ReadWord(uint64_t ptr, word_t* out_value) {
if (!VerifyReadWordArgs(ptr, out_value)) {
return false;
}
@@ -53,7 +53,7 @@
}
}
-size_t BacktraceCurrent::Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
+size_t BacktraceCurrent::Read(uint64_t addr, uint8_t* buffer, size_t bytes) {
backtrace_map_t map;
FillInMap(addr, &map);
if (!BacktraceMap::IsValid(map) || !(map.flags & PROT_READ)) {
diff --git a/libbacktrace/BacktraceCurrent.h b/libbacktrace/BacktraceCurrent.h
index 072ffd2..60a9117 100644
--- a/libbacktrace/BacktraceCurrent.h
+++ b/libbacktrace/BacktraceCurrent.h
@@ -40,9 +40,9 @@
BacktraceCurrent(pid_t pid, pid_t tid, BacktraceMap* map) : Backtrace(pid, tid, map) {}
virtual ~BacktraceCurrent() {}
- size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) override;
+ size_t Read(uint64_t addr, uint8_t* buffer, size_t bytes) override;
- bool ReadWord(uintptr_t ptr, word_t* out_value) override;
+ bool ReadWord(uint64_t ptr, word_t* out_value) override;
bool Unwind(size_t num_ignore_frames, ucontext_t* ucontext) override;
diff --git a/libbacktrace/BacktraceMap.cpp b/libbacktrace/BacktraceMap.cpp
index 0f1ae11..2a657b8 100644
--- a/libbacktrace/BacktraceMap.cpp
+++ b/libbacktrace/BacktraceMap.cpp
@@ -38,7 +38,7 @@
BacktraceMap::~BacktraceMap() {
}
-void BacktraceMap::FillIn(uintptr_t addr, backtrace_map_t* map) {
+void BacktraceMap::FillIn(uint64_t addr, backtrace_map_t* map) {
ScopedBacktraceMapIteratorLock lock(this);
for (auto it = begin(); it != end(); ++it) {
const backtrace_map_t* entry = *it;
diff --git a/libbacktrace/BacktraceOffline.cpp b/libbacktrace/BacktraceOffline.cpp
index 30845a2..a056716 100644
--- a/libbacktrace/BacktraceOffline.cpp
+++ b/libbacktrace/BacktraceOffline.cpp
@@ -57,7 +57,7 @@
uint64_t hdr_vaddr;
uint64_t vaddr;
uint64_t fde_table_offset;
- uintptr_t min_func_vaddr;
+ uint64_t min_func_vaddr;
std::vector<uint8_t> hdr_data;
std::vector<uint8_t> data;
};
@@ -221,8 +221,8 @@
frames_.resize(num_frames + 1);
backtrace_frame_data_t* frame = &frames_[num_frames];
frame->num = num_frames;
- frame->pc = static_cast<uintptr_t>(pc);
- frame->sp = static_cast<uintptr_t>(sp);
+ frame->pc = static_cast<uint64_t>(pc);
+ frame->sp = static_cast<uint64_t>(sp);
frame->stack_size = 0;
if (num_frames > 0) {
@@ -253,12 +253,12 @@
return true;
}
-bool BacktraceOffline::ReadWord(uintptr_t ptr, word_t* out_value) {
+bool BacktraceOffline::ReadWord(uint64_t ptr, word_t* out_value) {
size_t bytes_read = Read(ptr, reinterpret_cast<uint8_t*>(out_value), sizeof(word_t));
return bytes_read == sizeof(word_t);
}
-size_t BacktraceOffline::Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
+size_t BacktraceOffline::Read(uint64_t addr, uint8_t* buffer, size_t bytes) {
// Normally, libunwind needs stack information and call frame information to do remote unwinding.
// If call frame information is stored in .debug_frame, libunwind can read it from file
// by itself. If call frame information is stored in .eh_frame, we need to provide data in
@@ -386,9 +386,8 @@
proc_info->start_ip = *it;
proc_info->format = UNW_INFO_FORMAT_ARM_EXIDX;
proc_info->unwind_info = reinterpret_cast<void*>(
- static_cast<uintptr_t>(index * sizeof(ArmIdxEntry) +
- debug_frame->arm_exidx.exidx_vaddr +
- debug_frame->min_vaddr));
+ static_cast<uint64_t>(index * sizeof(ArmIdxEntry) + debug_frame->arm_exidx.exidx_vaddr +
+ debug_frame->min_vaddr));
eh_frame_hdr_space_.Clear();
eh_frame_space_.Clear();
// Prepare arm_exidx space and arm_extab space.
@@ -595,7 +594,7 @@
return result;
}
-std::string BacktraceOffline::GetFunctionNameRaw(uintptr_t, uintptr_t* offset) {
+std::string BacktraceOffline::GetFunctionNameRaw(uint64_t, uint64_t* offset) {
// We don't have enough information to support this. And it is expensive.
*offset = 0;
return "";
diff --git a/libbacktrace/BacktraceOffline.h b/libbacktrace/BacktraceOffline.h
index fcde379..e028cd8 100644
--- a/libbacktrace/BacktraceOffline.h
+++ b/libbacktrace/BacktraceOffline.h
@@ -57,9 +57,9 @@
bool Unwind(size_t num_ignore_frames, ucontext_t* context) override;
- bool ReadWord(uintptr_t ptr, word_t* out_value) override;
+ bool ReadWord(uint64_t ptr, word_t* out_value) override;
- size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) override;
+ size_t Read(uint64_t addr, uint8_t* buffer, size_t bytes) override;
bool FindProcInfo(unw_addr_space_t addr_space, uint64_t ip, unw_proc_info_t* proc_info,
int need_unwind_info);
@@ -67,7 +67,7 @@
bool ReadReg(size_t reg_index, uint64_t* value);
protected:
- std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) override;
+ std::string GetFunctionNameRaw(uint64_t pc, uint64_t* offset) override;
DebugFrameInfo* GetDebugFrameInFile(const std::string& filename);
bool cache_file_;
diff --git a/libbacktrace/BacktracePtrace.cpp b/libbacktrace/BacktracePtrace.cpp
index fd8b713..bf6b16f 100644
--- a/libbacktrace/BacktracePtrace.cpp
+++ b/libbacktrace/BacktracePtrace.cpp
@@ -31,7 +31,7 @@
#include "thread_utils.h"
#if !defined(__APPLE__)
-static bool PtraceRead(pid_t tid, uintptr_t addr, word_t* out_value) {
+static bool PtraceRead(pid_t tid, uint64_t addr, word_t* out_value) {
// ptrace() returns -1 and sets errno when the operation fails.
// To disambiguate -1 from a valid result, we clear errno beforehand.
errno = 0;
@@ -43,7 +43,7 @@
}
#endif
-bool BacktracePtrace::ReadWord(uintptr_t ptr, word_t* out_value) {
+bool BacktracePtrace::ReadWord(uint64_t ptr, word_t* out_value) {
#if defined(__APPLE__)
BACK_LOGW("MacOS does not support reading from another pid.");
return false;
@@ -62,7 +62,7 @@
#endif
}
-size_t BacktracePtrace::Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
+size_t BacktracePtrace::Read(uint64_t addr, uint8_t* buffer, size_t bytes) {
#if defined(__APPLE__)
BACK_LOGW("MacOS does not support reading from another pid.");
return 0;
diff --git a/libbacktrace/BacktracePtrace.h b/libbacktrace/BacktracePtrace.h
index d110b48..1ae3adf 100644
--- a/libbacktrace/BacktracePtrace.h
+++ b/libbacktrace/BacktracePtrace.h
@@ -29,9 +29,9 @@
BacktracePtrace(pid_t pid, pid_t tid, BacktraceMap* map) : Backtrace(pid, tid, map) {}
virtual ~BacktracePtrace() {}
- size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) override;
+ size_t Read(uint64_t addr, uint8_t* buffer, size_t bytes) override;
- bool ReadWord(uintptr_t ptr, word_t* out_value) override;
+ bool ReadWord(uint64_t ptr, word_t* out_value) override;
};
#endif // _LIBBACKTRACE_BACKTRACE_PTRACE_H
diff --git a/libbacktrace/UnwindCurrent.cpp b/libbacktrace/UnwindCurrent.cpp
deleted file mode 100644
index 3ccf13c..0000000
--- a/libbacktrace/UnwindCurrent.cpp
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2013 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 <stdint.h>
-#include <ucontext.h>
-
-#include <memory>
-#include <string>
-
-#define UNW_LOCAL_ONLY
-#include <libunwind.h>
-
-#include <android-base/logging.h>
-#include <backtrace/Backtrace.h>
-
-#include "BacktraceLog.h"
-#include "UnwindCurrent.h"
-
-std::string UnwindCurrent::GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) {
- if (!initialized_) {
- // If init local is not called, then trying to get a function name will
- // fail, so try to initialize first.
- std::unique_ptr<unw_cursor_t> cursor(new unw_cursor_t);
- if (unw_init_local(cursor.get(), &context_) < 0) {
- return "";
- }
- initialized_ = true;
- }
-
- *offset = 0;
- char buf[512];
- unw_word_t value;
- if (unw_get_proc_name_by_ip(unw_local_addr_space, pc, buf, sizeof(buf),
- &value, &context_) >= 0 && buf[0] != '\0') {
- *offset = static_cast<uintptr_t>(value);
- return buf;
- }
- return "";
-}
-
-void UnwindCurrent::GetUnwContextFromUcontext(const ucontext_t* ucontext) {
- unw_tdep_context_t* unw_context = reinterpret_cast<unw_tdep_context_t*>(&context_);
-
-#if defined(__arm__)
- unw_context->regs[0] = ucontext->uc_mcontext.arm_r0;
- unw_context->regs[1] = ucontext->uc_mcontext.arm_r1;
- unw_context->regs[2] = ucontext->uc_mcontext.arm_r2;
- unw_context->regs[3] = ucontext->uc_mcontext.arm_r3;
- unw_context->regs[4] = ucontext->uc_mcontext.arm_r4;
- unw_context->regs[5] = ucontext->uc_mcontext.arm_r5;
- unw_context->regs[6] = ucontext->uc_mcontext.arm_r6;
- unw_context->regs[7] = ucontext->uc_mcontext.arm_r7;
- unw_context->regs[8] = ucontext->uc_mcontext.arm_r8;
- unw_context->regs[9] = ucontext->uc_mcontext.arm_r9;
- unw_context->regs[10] = ucontext->uc_mcontext.arm_r10;
- unw_context->regs[11] = ucontext->uc_mcontext.arm_fp;
- unw_context->regs[12] = ucontext->uc_mcontext.arm_ip;
- unw_context->regs[13] = ucontext->uc_mcontext.arm_sp;
- unw_context->regs[14] = ucontext->uc_mcontext.arm_lr;
- unw_context->regs[15] = ucontext->uc_mcontext.arm_pc;
-#else
- unw_context->uc_mcontext = ucontext->uc_mcontext;
-#endif
-}
-
-bool UnwindCurrent::UnwindFromContext(size_t num_ignore_frames, ucontext_t* ucontext) {
- if (ucontext == nullptr) {
- int ret = unw_getcontext(&context_);
- if (ret < 0) {
- BACK_LOGW("unw_getcontext failed %d", ret);
- error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
- return false;
- }
- } else {
- GetUnwContextFromUcontext(ucontext);
- }
-
- // The cursor structure is pretty large, do not put it on the stack.
- std::unique_ptr<unw_cursor_t> cursor(new unw_cursor_t);
- int ret = unw_init_local(cursor.get(), &context_);
- if (ret < 0) {
- BACK_LOGW("unw_init_local failed %d", ret);
- error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
- return false;
- }
- initialized_ = true;
-
- size_t num_frames = 0;
- do {
- unw_word_t pc;
- ret = unw_get_reg(cursor.get(), UNW_REG_IP, &pc);
- if (ret < 0) {
- BACK_LOGW("Failed to read IP %d", ret);
- break;
- }
- unw_word_t sp;
- ret = unw_get_reg(cursor.get(), UNW_REG_SP, &sp);
- if (ret < 0) {
- BACK_LOGW("Failed to read SP %d", ret);
- break;
- }
-
- frames_.resize(num_frames+1);
- backtrace_frame_data_t* frame = &frames_.at(num_frames);
- frame->num = num_frames;
- frame->pc = static_cast<uintptr_t>(pc);
- frame->sp = static_cast<uintptr_t>(sp);
- frame->stack_size = 0;
-
- FillInMap(frame->pc, &frame->map);
- // Check to see if we should skip this frame because it's coming
- // from within the library, and we are doing a local unwind.
- if (ucontext != nullptr || num_frames != 0 || !DiscardFrame(*frame)) {
- if (num_ignore_frames == 0) {
- // GetFunctionName is an expensive call, only do it if we are
- // keeping the frame.
- frame->func_name = GetFunctionName(frame->pc, &frame->func_offset, &frame->map);
- if (num_frames > 0) {
- // Set the stack size for the previous frame.
- backtrace_frame_data_t* prev = &frames_.at(num_frames-1);
- prev->stack_size = frame->sp - prev->sp;
- }
- if (BacktraceMap::IsValid(frame->map)) {
- frame->rel_pc = frame->pc - frame->map.start + frame->map.load_bias;
- } else {
- frame->rel_pc = frame->pc;
- }
- num_frames++;
- } else {
- num_ignore_frames--;
- // Set the number of frames to zero to remove the frame added
- // above. By definition, if we still have frames to ignore
- // there should only be one frame in the vector.
- CHECK(num_frames == 0);
- frames_.resize(0);
- }
- }
- // If the pc is in a device map, then don't try to step.
- if (frame->map.flags & PROT_DEVICE_MAP) {
- break;
- }
- // Verify the sp is not in a device map too.
- backtrace_map_t map;
- FillInMap(frame->sp, &map);
- if (map.flags & PROT_DEVICE_MAP) {
- break;
- }
- ret = unw_step (cursor.get());
- } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);
-
- return true;
-}
diff --git a/libbacktrace/UnwindCurrent.h b/libbacktrace/UnwindCurrent.h
deleted file mode 100644
index 3656104..0000000
--- a/libbacktrace/UnwindCurrent.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2013 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 _LIBBACKTRACE_UNWIND_CURRENT_H
-#define _LIBBACKTRACE_UNWIND_CURRENT_H
-
-#include <stdint.h>
-#include <sys/types.h>
-#include <ucontext.h>
-
-#include <string>
-
-#include <backtrace/Backtrace.h>
-#include <backtrace/BacktraceMap.h>
-
-#include "BacktraceCurrent.h"
-
-#define UNW_LOCAL_ONLY
-#include <libunwind.h>
-
-class UnwindCurrent : public BacktraceCurrent {
- public:
- UnwindCurrent(pid_t pid, pid_t tid, BacktraceMap* map) : BacktraceCurrent(pid, tid, map) {}
- virtual ~UnwindCurrent() {}
-
- std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) override;
-
- private:
- void GetUnwContextFromUcontext(const ucontext_t* ucontext);
-
- bool UnwindFromContext(size_t num_ignore_frames, ucontext_t* ucontext) override;
-
- unw_context_t context_;
-
- bool initialized_ = false;
-};
-
-#endif // _LIBBACKTRACE_UNWIND_CURRENT_H
diff --git a/libbacktrace/UnwindMap.cpp b/libbacktrace/UnwindMap.cpp
index 3cab0d1..798c769 100644
--- a/libbacktrace/UnwindMap.cpp
+++ b/libbacktrace/UnwindMap.cpp
@@ -134,7 +134,7 @@
return (map_created_ = (unw_map_local_create() == 0)) && GenerateMap();;
}
-void UnwindMapLocal::FillIn(uintptr_t addr, backtrace_map_t* map) {
+void UnwindMapLocal::FillIn(uint64_t addr, backtrace_map_t* map) {
BacktraceMap::FillIn(addr, map);
if (!IsValid(*map)) {
// Check to see if the underlying map changed and regenerate the map
diff --git a/libbacktrace/UnwindMap.h b/libbacktrace/UnwindMap.h
index 6ffdafd..15544e8 100644
--- a/libbacktrace/UnwindMap.h
+++ b/libbacktrace/UnwindMap.h
@@ -55,7 +55,7 @@
bool Build() override;
- void FillIn(uintptr_t addr, backtrace_map_t* map) override;
+ void FillIn(uint64_t addr, backtrace_map_t* map) override;
void LockIterator() override { pthread_rwlock_rdlock(&map_lock_); }
void UnlockIterator() override { pthread_rwlock_unlock(&map_lock_); }
diff --git a/libbacktrace/UnwindPtrace.cpp b/libbacktrace/UnwindPtrace.cpp
deleted file mode 100644
index 2155b8a..0000000
--- a/libbacktrace/UnwindPtrace.cpp
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (C) 2013 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 <stdint.h>
-#include <sys/types.h>
-#include <ucontext.h>
-
-#include <libunwind.h>
-#include <libunwind-ptrace.h>
-
-#include <backtrace/Backtrace.h>
-#include <backtrace/BacktraceMap.h>
-
-#include "BacktraceLog.h"
-#include "UnwindMap.h"
-#include "UnwindPtrace.h"
-
-UnwindPtrace::UnwindPtrace(pid_t pid, pid_t tid, BacktraceMap* map)
- : BacktracePtrace(pid, tid, map), addr_space_(nullptr), upt_info_(nullptr) {
-}
-
-UnwindPtrace::~UnwindPtrace() {
- if (upt_info_) {
- _UPT_destroy(upt_info_);
- upt_info_ = nullptr;
- }
-
- if (addr_space_) {
- // Remove the map from the address space before destroying it.
- // It will be freed in the UnwindMap destructor.
- unw_map_set(addr_space_, nullptr);
-
- unw_destroy_addr_space(addr_space_);
- addr_space_ = nullptr;
- }
-}
-
-bool UnwindPtrace::Init() {
- if (upt_info_) {
- return true;
- }
-
- if (addr_space_) {
- // If somehow the addr_space_ gets initialized but upt_info_ doesn't,
- // then that indicates there is some kind of failure.
- return false;
- }
-
- addr_space_ = unw_create_addr_space(&_UPT_accessors, 0);
- if (!addr_space_) {
- BACK_LOGW("unw_create_addr_space failed.");
- error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
- return false;
- }
-
- UnwindMap* map = static_cast<UnwindMap*>(GetMap());
- unw_map_set(addr_space_, map->GetMapCursor());
-
- upt_info_ = reinterpret_cast<struct UPT_info*>(_UPT_create(Tid()));
- if (!upt_info_) {
- BACK_LOGW("Failed to create upt info.");
- error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
- return false;
- }
-
- return true;
-}
-
-bool UnwindPtrace::Unwind(size_t num_ignore_frames, ucontext_t* ucontext) {
- if (GetMap() == nullptr) {
- // Without a map object, we can't do anything.
- error_.error_code = BACKTRACE_UNWIND_ERROR_MAP_MISSING;
- return false;
- }
-
- error_.error_code = BACKTRACE_UNWIND_NO_ERROR;
-
- if (ucontext) {
- BACK_LOGW("Unwinding from a specified context not supported yet.");
- error_.error_code = BACKTRACE_UNWIND_ERROR_UNSUPPORTED_OPERATION;
- return false;
- }
-
- if (!Init()) {
- return false;
- }
-
- unw_cursor_t cursor;
- int ret = unw_init_remote(&cursor, addr_space_, upt_info_);
- if (ret < 0) {
- BACK_LOGW("unw_init_remote failed %d", ret);
- error_.error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
- return false;
- }
-
- size_t num_frames = 0;
- do {
- unw_word_t pc;
- ret = unw_get_reg(&cursor, UNW_REG_IP, &pc);
- if (ret < 0) {
- BACK_LOGW("Failed to read IP %d", ret);
- break;
- }
- unw_word_t sp;
- ret = unw_get_reg(&cursor, UNW_REG_SP, &sp);
- if (ret < 0) {
- BACK_LOGW("Failed to read SP %d", ret);
- break;
- }
-
- if (num_ignore_frames == 0) {
- frames_.resize(num_frames+1);
- backtrace_frame_data_t* frame = &frames_.at(num_frames);
- frame->num = num_frames;
- frame->pc = static_cast<uintptr_t>(pc);
- frame->sp = static_cast<uintptr_t>(sp);
- frame->stack_size = 0;
-
- if (num_frames > 0) {
- backtrace_frame_data_t* prev = &frames_.at(num_frames-1);
- prev->stack_size = frame->sp - prev->sp;
- }
-
- FillInMap(frame->pc, &frame->map);
- if (BacktraceMap::IsValid(frame->map)) {
- frame->rel_pc = frame->pc - frame->map.start + frame->map.load_bias;
- } else {
- frame->rel_pc = frame->pc;
- }
-
- frame->func_name = GetFunctionName(frame->pc, &frame->func_offset, &frame->map);
-
- num_frames++;
- // If the pc is in a device map, then don't try to step.
- if (frame->map.flags & PROT_DEVICE_MAP) {
- break;
- }
- } else {
- // If the pc is in a device map, then don't try to step.
- backtrace_map_t map;
- FillInMap(pc, &map);
- if (map.flags & PROT_DEVICE_MAP) {
- break;
- }
- num_ignore_frames--;
- }
- // Verify the sp is not in a device map.
- backtrace_map_t map;
- FillInMap(sp, &map);
- if (map.flags & PROT_DEVICE_MAP) {
- break;
- }
- ret = unw_step (&cursor);
- } while (ret > 0 && num_frames < MAX_BACKTRACE_FRAMES);
-
- return true;
-}
-
-std::string UnwindPtrace::GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) {
- if (!Init()) {
- return "";
- }
-
- *offset = 0;
- char buf[512];
- unw_word_t value;
- if (unw_get_proc_name_by_ip(addr_space_, pc, buf, sizeof(buf), &value,
- upt_info_) >= 0 && buf[0] != '\0') {
- *offset = static_cast<uintptr_t>(value);
- return buf;
- }
- return "";
-}
diff --git a/libbacktrace/UnwindPtrace.h b/libbacktrace/UnwindPtrace.h
deleted file mode 100644
index 4688110..0000000
--- a/libbacktrace/UnwindPtrace.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2013 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 _LIBBACKTRACE_UNWIND_PTRACE_H
-#define _LIBBACKTRACE_UNWIND_PTRACE_H
-
-#include <stdint.h>
-#include <sys/types.h>
-
-#include <string>
-
-#ifdef UNW_LOCAL_ONLY
-#undef UNW_LOCAL_ONLY
-#endif
-#include <libunwind.h>
-
-#include "BacktracePtrace.h"
-
-class UnwindPtrace : public BacktracePtrace {
- public:
- UnwindPtrace(pid_t pid, pid_t tid, BacktraceMap* map);
- virtual ~UnwindPtrace();
-
- bool Unwind(size_t num_ignore_frames, ucontext_t* ucontext) override;
-
- std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) override;
-
- private:
- bool Init();
-
- unw_addr_space_t addr_space_;
- struct UPT_info* upt_info_;
-};
-
-#endif // _LIBBACKTRACE_UNWIND_PTRACE_H
diff --git a/libbacktrace/UnwindStack.cpp b/libbacktrace/UnwindStack.cpp
index b0345a1..bbfbdda 100644
--- a/libbacktrace/UnwindStack.cpp
+++ b/libbacktrace/UnwindStack.cpp
@@ -70,6 +70,7 @@
back_frame->rel_pc = frame->rel_pc;
back_frame->pc = frame->pc;
back_frame->sp = frame->sp;
+ back_frame->dex_pc = frame->dex_pc;
back_frame->func_name = demangle(frame->function_name.c_str());
back_frame->func_offset = frame->function_offset;
@@ -88,7 +89,7 @@
UnwindStackCurrent::UnwindStackCurrent(pid_t pid, pid_t tid, BacktraceMap* map)
: BacktraceCurrent(pid, tid, map) {}
-std::string UnwindStackCurrent::GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) {
+std::string UnwindStackCurrent::GetFunctionNameRaw(uint64_t pc, uint64_t* offset) {
return GetMap()->GetFunctionName(pc, offset);
}
@@ -111,7 +112,7 @@
UnwindStackPtrace::UnwindStackPtrace(pid_t pid, pid_t tid, BacktraceMap* map)
: BacktracePtrace(pid, tid, map), memory_(pid) {}
-std::string UnwindStackPtrace::GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) {
+std::string UnwindStackPtrace::GetFunctionNameRaw(uint64_t pc, uint64_t* offset) {
return GetMap()->GetFunctionName(pc, offset);
}
@@ -127,6 +128,6 @@
return Backtrace::Unwind(regs.get(), GetMap(), &frames_, num_ignore_frames, nullptr);
}
-size_t UnwindStackPtrace::Read(uintptr_t addr, uint8_t* buffer, size_t bytes) {
+size_t UnwindStackPtrace::Read(uint64_t addr, uint8_t* buffer, size_t bytes) {
return memory_.Read(addr, buffer, bytes);
}
diff --git a/libbacktrace/UnwindStack.h b/libbacktrace/UnwindStack.h
index ee2a706..498ad4e 100644
--- a/libbacktrace/UnwindStack.h
+++ b/libbacktrace/UnwindStack.h
@@ -32,7 +32,7 @@
UnwindStackCurrent(pid_t pid, pid_t tid, BacktraceMap* map);
virtual ~UnwindStackCurrent() = default;
- std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) override;
+ std::string GetFunctionNameRaw(uint64_t pc, uint64_t* offset) override;
bool UnwindFromContext(size_t num_ignore_frames, ucontext_t* ucontext) override;
};
@@ -44,9 +44,9 @@
bool Unwind(size_t num_ignore_frames, ucontext_t* context) override;
- std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset);
+ std::string GetFunctionNameRaw(uint64_t pc, uint64_t* offset);
- size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) override;
+ size_t Read(uint64_t addr, uint8_t* buffer, size_t bytes) override;
private:
unwindstack::MemoryRemote memory_;
diff --git a/libbacktrace/UnwindStackMap.cpp b/libbacktrace/UnwindStackMap.cpp
index 93406dc..60c7952 100644
--- a/libbacktrace/UnwindStackMap.cpp
+++ b/libbacktrace/UnwindStackMap.cpp
@@ -57,7 +57,7 @@
map.end = map_info->end;
map.offset = map_info->offset;
// Set to -1 so that it is demand loaded.
- map.load_bias = static_cast<uintptr_t>(-1);
+ map.load_bias = static_cast<uint64_t>(-1);
map.flags = map_info->flags;
map.name = map_info->name;
@@ -67,9 +67,9 @@
return true;
}
-void UnwindStackMap::FillIn(uintptr_t addr, backtrace_map_t* map) {
+void UnwindStackMap::FillIn(uint64_t addr, backtrace_map_t* map) {
BacktraceMap::FillIn(addr, map);
- if (map->load_bias != static_cast<uintptr_t>(-1)) {
+ if (map->load_bias != static_cast<uint64_t>(-1)) {
return;
}
@@ -93,7 +93,7 @@
return map_info->GetLoadBias(process_memory_);
}
-std::string UnwindStackMap::GetFunctionName(uintptr_t pc, uintptr_t* offset) {
+std::string UnwindStackMap::GetFunctionName(uint64_t pc, uint64_t* offset) {
*offset = 0;
unwindstack::Maps* maps = stack_maps();
diff --git a/libbacktrace/UnwindStackMap.h b/libbacktrace/UnwindStackMap.h
index 12c5909..6b98809 100644
--- a/libbacktrace/UnwindStackMap.h
+++ b/libbacktrace/UnwindStackMap.h
@@ -33,9 +33,9 @@
bool Build() override;
- void FillIn(uintptr_t addr, backtrace_map_t* map) override;
+ void FillIn(uint64_t addr, backtrace_map_t* map) override;
- virtual std::string GetFunctionName(uintptr_t pc, uintptr_t* offset) override;
+ virtual std::string GetFunctionName(uint64_t pc, uint64_t* offset) override;
virtual std::shared_ptr<unwindstack::Memory> GetProcessMemory() override final;
unwindstack::Maps* stack_maps() { return stack_maps_.get(); }
diff --git a/libbacktrace/backtrace_offline_test.cpp b/libbacktrace/backtrace_offline_test.cpp
index e92bc61..e2a7441 100644
--- a/libbacktrace/backtrace_offline_test.cpp
+++ b/libbacktrace/backtrace_offline_test.cpp
@@ -75,20 +75,20 @@
struct FunctionSymbol {
std::string name;
- uintptr_t start;
- uintptr_t end;
+ uint64_t start;
+ uint64_t end;
};
static std::vector<FunctionSymbol> GetFunctionSymbols() {
std::vector<FunctionSymbol> symbols = {
{"unknown_start", 0, 0},
- {"test_level_one", reinterpret_cast<uintptr_t>(&test_level_one), 0},
- {"test_level_two", reinterpret_cast<uintptr_t>(&test_level_two), 0},
- {"test_level_three", reinterpret_cast<uintptr_t>(&test_level_three), 0},
- {"test_level_four", reinterpret_cast<uintptr_t>(&test_level_four), 0},
- {"test_recursive_call", reinterpret_cast<uintptr_t>(&test_recursive_call), 0},
- {"test_get_context_and_wait", reinterpret_cast<uintptr_t>(&test_get_context_and_wait), 0},
- {"unknown_end", static_cast<uintptr_t>(-1), static_cast<uintptr_t>(-1)},
+ {"test_level_one", reinterpret_cast<uint64_t>(&test_level_one), 0},
+ {"test_level_two", reinterpret_cast<uint64_t>(&test_level_two), 0},
+ {"test_level_three", reinterpret_cast<uint64_t>(&test_level_three), 0},
+ {"test_level_four", reinterpret_cast<uint64_t>(&test_level_four), 0},
+ {"test_recursive_call", reinterpret_cast<uint64_t>(&test_recursive_call), 0},
+ {"test_get_context_and_wait", reinterpret_cast<uint64_t>(&test_get_context_and_wait), 0},
+ {"unknown_end", static_cast<uint64_t>(-1), static_cast<uint64_t>(-1)},
};
std::sort(
symbols.begin(), symbols.end(),
@@ -141,7 +141,7 @@
const size_t stack_size = 16 * 1024;
void* stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
ASSERT_NE(MAP_FAILED, stack);
- uintptr_t stack_addr = reinterpret_cast<uintptr_t>(stack);
+ uint64_t stack_addr = reinterpret_cast<uint64_t>(stack);
pthread_attr_t attr;
ASSERT_EQ(0, pthread_attr_init(&attr));
ASSERT_EQ(0, pthread_attr_setstack(&attr, reinterpret_cast<void*>(stack), stack_size));
@@ -174,8 +174,8 @@
for (auto it = map->begin(); it != map->end(); ++it) {
const backtrace_map_t* entry = *it;
testdata +=
- android::base::StringPrintf("map: start: %" PRIxPTR " end: %" PRIxPTR " offset: %" PRIxPTR
- " load_bias: %" PRIxPTR " flags: %d name: %s\n",
+ android::base::StringPrintf("map: start: %" PRIx64 " end: %" PRIx64 " offset: %" PRIx64
+ " load_bias: %" PRIx64 " flags: %d name: %s\n",
entry->start, entry->end, entry->offset, entry->load_bias,
entry->flags, entry->name.c_str());
}
@@ -194,9 +194,9 @@
// 5. Dump function symbols
std::vector<FunctionSymbol> function_symbols = GetFunctionSymbols();
for (const auto& symbol : function_symbols) {
- testdata += android::base::StringPrintf(
- "function: start: %" PRIxPTR " end: %" PRIxPTR" name: %s\n",
- symbol.start, symbol.end, symbol.name.c_str());
+ testdata +=
+ android::base::StringPrintf("function: start: %" PRIx64 " end: %" PRIx64 " name: %s\n",
+ symbol.start, symbol.end, symbol.name.c_str());
}
ASSERT_TRUE(android::base::WriteStringToFile(testdata, "offline_testdata"));
@@ -204,7 +204,7 @@
// Return the name of the function which matches the address. Although we don't know the
// exact end of each function, it is accurate enough for the tests.
-static std::string FunctionNameForAddress(uintptr_t addr,
+static std::string FunctionNameForAddress(uint64_t addr,
const std::vector<FunctionSymbol>& symbols) {
for (auto& symbol : symbols) {
if (addr >= symbol.start && addr < symbol.end) {
@@ -240,7 +240,7 @@
backtrace_map_t& map = testdata->maps.back();
int pos;
sscanf(line.c_str(),
- "map: start: %" SCNxPTR " end: %" SCNxPTR " offset: %" SCNxPTR " load_bias: %" SCNxPTR
+ "map: start: %" SCNx64 " end: %" SCNx64 " offset: %" SCNx64 " load_bias: %" SCNx64
" flags: %d name: %n",
&map.start, &map.end, &map.offset, &map.load_bias, &map.flags, &pos);
map.name = android::base::Trim(line.substr(pos));
@@ -302,9 +302,8 @@
testdata->symbols.resize(testdata->symbols.size() + 1);
FunctionSymbol& symbol = testdata->symbols.back();
int pos;
- sscanf(line.c_str(),
- "function: start: %" SCNxPTR " end: %" SCNxPTR " name: %n",
- &symbol.start, &symbol.end, &pos);
+ sscanf(line.c_str(), "function: start: %" SCNx64 " end: %" SCNx64 " name: %n", &symbol.start,
+ &symbol.end, &pos);
symbol.name = line.substr(pos);
}
}
@@ -342,7 +341,7 @@
ASSERT_TRUE(backtrace->Unwind(0, &ucontext));
// Collect pc values of the call stack frames.
- std::vector<uintptr_t> pc_values;
+ std::vector<uint64_t> pc_values;
for (size_t i = 0; i < backtrace->NumFrames(); ++i) {
pc_values.push_back(backtrace->GetFrame(i)->pc);
}
@@ -420,7 +419,7 @@
ASSERT_EQ(testdata.symbols.size(), backtrace->NumFrames());
for (size_t i = 0; i < backtrace->NumFrames(); ++i) {
- uintptr_t vaddr_in_file =
+ uint64_t vaddr_in_file =
backtrace->GetFrame(i)->pc - testdata.maps[0].start + testdata.maps[0].load_bias;
std::string name = FunctionNameForAddress(vaddr_in_file, testdata.symbols);
ASSERT_EQ(name, testdata.symbols[i].name);
diff --git a/libbacktrace/backtrace_test.cpp b/libbacktrace/backtrace_test.cpp
index 57b7553..10152f7 100644
--- a/libbacktrace/backtrace_test.cpp
+++ b/libbacktrace/backtrace_test.cpp
@@ -745,8 +745,8 @@
delete back_map;
ASSERT_FALSE(BacktraceMap::IsValid(map));
- ASSERT_EQ(static_cast<uintptr_t>(0), map.start);
- ASSERT_EQ(static_cast<uintptr_t>(0), map.end);
+ ASSERT_EQ(static_cast<uint64_t>(0), map.start);
+ ASSERT_EQ(static_cast<uint64_t>(0), map.end);
ASSERT_EQ(0, map.flags);
ASSERT_EQ("", map.name);
}
@@ -851,8 +851,8 @@
}
struct map_test_t {
- uintptr_t start;
- uintptr_t end;
+ uint64_t start;
+ uint64_t end;
};
static bool map_sort(map_test_t i, map_test_t j) { return i.start < j.start; }
@@ -863,7 +863,7 @@
}
std::string map_txt;
for (auto map : maps) {
- map_txt += android::base::StringPrintf("%" PRIxPTR "-%" PRIxPTR "\n", map.start, map.end);
+ map_txt += android::base::StringPrintf("%" PRIx64 "-%" PRIx64 "\n", map.start, map.end);
}
return map_txt;
}
@@ -875,7 +875,7 @@
std::string map_txt;
for (const backtrace_map_t* map : *maps) {
map_txt += android::base::StringPrintf(
- "%" PRIxPTR "-%" PRIxPTR " flags: 0x%x offset: 0x%" PRIxPTR " load_bias: 0x%" PRIxPTR,
+ "%" PRIx64 "-%" PRIx64 " flags: 0x%x offset: 0x%" PRIx64 " load_bias: 0x%" PRIx64,
map->start, map->end, map->flags, map->offset, map->load_bias);
if (!map->name.empty()) {
map_txt += ' ' + map->name;
@@ -894,7 +894,7 @@
std::vector<map_test_t> test_maps;
while (fgets(buffer, sizeof(buffer), map_file)) {
map_test_t map;
- ASSERT_EQ(2, sscanf(buffer, "%" SCNxPTR "-%" SCNxPTR " ", &map.start, &map.end));
+ ASSERT_EQ(2, sscanf(buffer, "%" SCNx64 "-%" SCNx64 " ", &map.start, &map.end));
test_maps.push_back(map);
}
fclose(map_file);
@@ -984,7 +984,7 @@
return nullptr;
}
-static void RunReadTest(Backtrace* backtrace, uintptr_t read_addr) {
+static void RunReadTest(Backtrace* backtrace, uint64_t read_addr) {
size_t pagesize = static_cast<size_t>(sysconf(_SC_PAGE_SIZE));
// Create a page of data to use to do quick compares.
@@ -1035,15 +1035,15 @@
std::unique_ptr<Backtrace> backtrace(Backtrace::Create(getpid(), thread_data.tid));
ASSERT_TRUE(backtrace.get() != nullptr);
- RunReadTest(backtrace.get(), reinterpret_cast<uintptr_t>(thread_data.data));
+ RunReadTest(backtrace.get(), reinterpret_cast<uint64_t>(thread_data.data));
android_atomic_acquire_store(0, &thread_data.state);
ASSERT_TRUE(WaitForNonZero(&thread_data.state, 10));
}
-volatile uintptr_t g_ready = 0;
-volatile uintptr_t g_addr = 0;
+volatile uint64_t g_ready = 0;
+volatile uint64_t g_addr = 0;
static void ForkedReadTest() {
// Create two map pages.
@@ -1063,7 +1063,7 @@
// Set up a simple pattern in memory.
InitMemory(memory, pagesize);
- g_addr = reinterpret_cast<uintptr_t>(memory);
+ g_addr = reinterpret_cast<uint64_t>(memory);
g_ready = 1;
while (1) {
@@ -1089,17 +1089,15 @@
std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
ASSERT_TRUE(backtrace.get() != nullptr);
- uintptr_t read_addr;
- size_t bytes_read = backtrace->Read(reinterpret_cast<uintptr_t>(&g_ready),
- reinterpret_cast<uint8_t*>(&read_addr),
- sizeof(uintptr_t));
- ASSERT_EQ(sizeof(uintptr_t), bytes_read);
+ uint64_t read_addr;
+ size_t bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(&g_ready),
+ reinterpret_cast<uint8_t*>(&read_addr), sizeof(uint64_t));
+ ASSERT_EQ(sizeof(uint64_t), bytes_read);
if (read_addr) {
// The forked process is ready to be read.
- bytes_read = backtrace->Read(reinterpret_cast<uintptr_t>(&g_addr),
- reinterpret_cast<uint8_t*>(&read_addr),
- sizeof(uintptr_t));
- ASSERT_EQ(sizeof(uintptr_t), bytes_read);
+ bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(&g_addr),
+ reinterpret_cast<uint8_t*>(&read_addr), sizeof(uint64_t));
+ ASSERT_EQ(sizeof(uint64_t), bytes_read);
RunReadTest(backtrace.get(), read_addr);
@@ -1173,7 +1171,7 @@
struct stat buf;
ASSERT_TRUE(stat(tmp_so_name, &buf) != -1);
- uintptr_t map_size = buf.st_size;
+ uint64_t map_size = buf.st_size;
int fd = open(tmp_so_name, O_RDONLY);
ASSERT_TRUE(fd != -1);
@@ -1192,11 +1190,10 @@
backtrace->Unwind(0);
// Loop through the entire map, and get every function we can find.
- map_size += reinterpret_cast<uintptr_t>(map);
+ map_size += reinterpret_cast<uint64_t>(map);
std::string last_func;
- for (uintptr_t read_addr = reinterpret_cast<uintptr_t>(map);
- read_addr < map_size; read_addr += 4) {
- uintptr_t offset;
+ for (uint64_t read_addr = reinterpret_cast<uint64_t>(map); read_addr < map_size; read_addr += 4) {
+ uint64_t offset;
std::string func_name = backtrace->GetFunctionName(read_addr, &offset);
if (!func_name.empty() && last_func != func_name) {
found_functions.push_back(func_name);
@@ -1204,7 +1201,7 @@
last_func = func_name;
}
- ASSERT_TRUE(munmap(map, map_size - reinterpret_cast<uintptr_t>(map)) == 0);
+ ASSERT_TRUE(munmap(map, map_size - reinterpret_cast<uint64_t>(map)) == 0);
VerifyFunctionsFound(found_functions);
}
@@ -1217,7 +1214,7 @@
struct stat buf;
ASSERT_TRUE(stat(tmp_so_name, &buf) != -1);
- uintptr_t map_size = buf.st_size;
+ uint64_t map_size = buf.st_size;
pid_t pid;
if ((pid = fork()) == 0) {
@@ -1240,7 +1237,7 @@
exit(0);
}
- g_addr = reinterpret_cast<uintptr_t>(map);
+ g_addr = reinterpret_cast<uint64_t>(map);
g_ready = 1;
while (true) {
usleep(US_PER_MSEC);
@@ -1260,10 +1257,14 @@
std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, BACKTRACE_CURRENT_THREAD));
ASSERT_TRUE(backtrace.get() != nullptr);
- uintptr_t read_addr;
- ASSERT_EQ(sizeof(uintptr_t), backtrace->Read(reinterpret_cast<uintptr_t>(&g_ready), reinterpret_cast<uint8_t*>(&read_addr), sizeof(uintptr_t)));
+ uint64_t read_addr;
+ ASSERT_EQ(sizeof(uint64_t),
+ backtrace->Read(reinterpret_cast<uint64_t>(&g_ready),
+ reinterpret_cast<uint8_t*>(&read_addr), sizeof(uint64_t)));
if (read_addr) {
- ASSERT_EQ(sizeof(uintptr_t), backtrace->Read(reinterpret_cast<uintptr_t>(&g_addr), reinterpret_cast<uint8_t*>(&read_addr), sizeof(uintptr_t)));
+ ASSERT_EQ(sizeof(uint64_t),
+ backtrace->Read(reinterpret_cast<uint64_t>(&g_addr),
+ reinterpret_cast<uint8_t*>(&read_addr), sizeof(uint64_t)));
// Needed before GetFunctionName will work.
backtrace->Unwind(0);
@@ -1272,7 +1273,7 @@
map_size += read_addr;
std::string last_func;
for (; read_addr < map_size; read_addr += 4) {
- uintptr_t offset;
+ uint64_t offset;
std::string func_name = backtrace->GetFunctionName(read_addr, &offset);
if (!func_name.empty() && last_func != func_name) {
found_functions.push_back(func_name);
@@ -1295,7 +1296,7 @@
VerifyFunctionsFound(found_functions);
}
-static bool FindFuncFrameInBacktrace(Backtrace* backtrace, uintptr_t test_func, size_t* frame_num) {
+static bool FindFuncFrameInBacktrace(Backtrace* backtrace, uint64_t test_func, size_t* frame_num) {
backtrace_map_t map;
backtrace->FillInMap(test_func, &map);
if (!BacktraceMap::IsValid(map)) {
@@ -1314,7 +1315,7 @@
return false;
}
-static void VerifyUnreadableElfFrame(Backtrace* backtrace, uintptr_t test_func, size_t frame_num) {
+static void VerifyUnreadableElfFrame(Backtrace* backtrace, uint64_t test_func, size_t frame_num) {
ASSERT_LT(backtrace->NumFrames(), static_cast<size_t>(MAX_BACKTRACE_FRAMES))
<< DumpFrames(backtrace);
@@ -1322,11 +1323,12 @@
// Make sure that there is at least one more frame above the test func call.
ASSERT_LT(frame_num, backtrace->NumFrames()) << DumpFrames(backtrace);
- uintptr_t diff = backtrace->GetFrame(frame_num)->pc - test_func;
+ uint64_t diff = backtrace->GetFrame(frame_num)->pc - test_func;
ASSERT_LT(diff, 200U) << DumpFrames(backtrace);
}
-static void VerifyUnreadableElfBacktrace(uintptr_t test_func) {
+static void VerifyUnreadableElfBacktrace(void* func) {
+ uint64_t test_func = reinterpret_cast<uint64_t>(func);
std::unique_ptr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS,
BACKTRACE_CURRENT_THREAD));
ASSERT_TRUE(backtrace.get() != nullptr);
@@ -1339,7 +1341,7 @@
VerifyUnreadableElfFrame(backtrace.get(), test_func, frame_num);
}
-typedef int (*test_func_t)(int, int, int, int, void (*)(uintptr_t), uintptr_t);
+typedef int (*test_func_t)(int, int, int, int, void (*)(void*), void*);
TEST(libbacktrace, unwind_through_unreadable_elf_local) {
const char* tmp_so_name = CopySharedLibrary();
@@ -1352,8 +1354,8 @@
test_func = reinterpret_cast<test_func_t>(dlsym(lib_handle, "test_level_one"));
ASSERT_TRUE(test_func != nullptr);
- ASSERT_NE(test_func(1, 2, 3, 4, VerifyUnreadableElfBacktrace,
- reinterpret_cast<uintptr_t>(test_func)), 0);
+ ASSERT_NE(test_func(1, 2, 3, 4, VerifyUnreadableElfBacktrace, reinterpret_cast<void*>(test_func)),
+ 0);
ASSERT_TRUE(dlclose(lib_handle) == 0);
}
@@ -1391,10 +1393,9 @@
ASSERT_EQ(BACKTRACE_UNWIND_NO_ERROR, backtrace->GetError().error_code);
size_t frame_num;
- if (FindFuncFrameInBacktrace(backtrace.get(),
- reinterpret_cast<uintptr_t>(test_func), &frame_num)) {
-
- VerifyUnreadableElfFrame(backtrace.get(), reinterpret_cast<uintptr_t>(test_func), frame_num);
+ if (FindFuncFrameInBacktrace(backtrace.get(), reinterpret_cast<uint64_t>(test_func),
+ &frame_num)) {
+ VerifyUnreadableElfFrame(backtrace.get(), reinterpret_cast<uint64_t>(test_func), frame_num);
done = true;
}
@@ -1426,8 +1427,8 @@
ASSERT_TRUE(backtrace.get() != nullptr);
// Verify that trying to get a function name before doing an unwind works.
- uintptr_t cur_func_offset = reinterpret_cast<uintptr_t>(&test_level_one) + 1;
- size_t offset;
+ uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
+ uint64_t offset;
ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset));
}
@@ -1439,14 +1440,14 @@
std::unique_ptr<Backtrace> backtrace(Backtrace::Create(pid, pid));
// Verify that trying to get a function name before doing an unwind works.
- uintptr_t cur_func_offset = reinterpret_cast<uintptr_t>(&test_level_one) + 1;
- size_t offset;
+ uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
+ uint64_t offset;
ASSERT_NE(std::string(""), backtrace->GetFunctionName(cur_func_offset, &offset));
FinishRemoteProcess(pid);
}
-static void SetUcontextSp(uintptr_t sp, ucontext_t* ucontext) {
+static void SetUcontextSp(uint64_t sp, ucontext_t* ucontext) {
#if defined(__arm__)
ucontext->uc_mcontext.arm_sp = sp;
#elif defined(__aarch64__)
@@ -1462,7 +1463,7 @@
#endif
}
-static void SetUcontextPc(uintptr_t pc, ucontext_t* ucontext) {
+static void SetUcontextPc(uint64_t pc, ucontext_t* ucontext) {
#if defined(__arm__)
ucontext->uc_mcontext.arm_pc = pc;
#elif defined(__aarch64__)
@@ -1478,7 +1479,7 @@
#endif
}
-static void SetUcontextLr(uintptr_t lr, ucontext_t* ucontext) {
+static void SetUcontextLr(uint64_t lr, ucontext_t* ucontext) {
#if defined(__arm__)
ucontext->uc_mcontext.arm_lr = lr;
#elif defined(__aarch64__)
@@ -1513,7 +1514,7 @@
}
static void UnwindFromDevice(Backtrace* backtrace, void* device_map) {
- uintptr_t device_map_uint = reinterpret_cast<uintptr_t>(device_map);
+ uint64_t device_map_uint = reinterpret_cast<uint64_t>(device_map);
backtrace_map_t map;
backtrace->FillInMap(device_map_uint, &map);
@@ -1521,12 +1522,12 @@
ASSERT_EQ(PROT_DEVICE_MAP, map.flags & PROT_DEVICE_MAP);
// Quick sanity checks.
- size_t offset;
+ uint64_t offset;
ASSERT_EQ(std::string(""), backtrace->GetFunctionName(device_map_uint, &offset));
ASSERT_EQ(std::string(""), backtrace->GetFunctionName(device_map_uint, &offset, &map));
ASSERT_EQ(std::string(""), backtrace->GetFunctionName(0, &offset));
- uintptr_t cur_func_offset = reinterpret_cast<uintptr_t>(&test_level_one) + 1;
+ uint64_t cur_func_offset = reinterpret_cast<uint64_t>(&test_level_one) + 1;
// Now verify the device map flag actually causes the function name to be empty.
backtrace->FillInMap(cur_func_offset, &map);
ASSERT_TRUE((map.flags & PROT_DEVICE_MAP) == 0);
@@ -1539,7 +1540,7 @@
// Create a context that has the pc in the device map, but the sp
// in a non-device map.
memset(&ucontext, 0, sizeof(ucontext));
- SetUcontextSp(reinterpret_cast<uintptr_t>(&ucontext), &ucontext);
+ SetUcontextSp(reinterpret_cast<uint64_t>(&ucontext), &ucontext);
SetUcontextPc(device_map_uint, &ucontext);
SetUcontextLr(cur_func_offset, &ucontext);
@@ -1549,7 +1550,7 @@
ASSERT_EQ(1U, backtrace->NumFrames());
const backtrace_frame_data_t* frame = backtrace->GetFrame(0);
ASSERT_EQ(device_map_uint, frame->pc);
- ASSERT_EQ(reinterpret_cast<uintptr_t>(&ucontext), frame->sp);
+ ASSERT_EQ(reinterpret_cast<uint64_t>(&ucontext), frame->sp);
// Check what happens when skipping the first frame.
ASSERT_TRUE(backtrace->Unwind(1, &ucontext));
@@ -1669,7 +1670,7 @@
std::unique_ptr<BacktraceMap> map(map_create_func(pid, false));
std::unique_ptr<Backtrace> backtrace(create_func(pid, pid, map.get()));
- size_t bytes_read = backtrace->Read(reinterpret_cast<uintptr_t>(const_cast<int*>(&value)),
+ size_t bytes_read = backtrace->Read(reinterpret_cast<uint64_t>(const_cast<int*>(&value)),
reinterpret_cast<uint8_t*>(&read_value), sizeof(read_value));
ASSERT_EQ(sizeof(read_value), bytes_read);
diff --git a/libbacktrace/include/backtrace/Backtrace.h b/libbacktrace/include/backtrace/Backtrace.h
index 5922664..1b8ad19 100644
--- a/libbacktrace/include/backtrace/Backtrace.h
+++ b/libbacktrace/include/backtrace/Backtrace.h
@@ -26,11 +26,11 @@
#include <backtrace/backtrace_constants.h>
#include <backtrace/BacktraceMap.h>
-#if __LP64__
-#define PRIPTR "016" PRIxPTR
+#if defined(__LP64__)
+#define PRIPTR "016" PRIx64
typedef uint64_t word_t;
#else
-#define PRIPTR "08" PRIxPTR
+#define PRIPTR "08" PRIx64
typedef uint32_t word_t;
#endif
@@ -77,13 +77,15 @@
struct backtrace_frame_data_t {
size_t num; // The current fame number.
- uintptr_t pc; // The absolute pc.
- uintptr_t rel_pc; // The relative pc.
- uintptr_t sp; // The top of the stack.
+ uint64_t pc; // The absolute pc.
+ uint64_t rel_pc; // The relative pc.
+ uint64_t sp; // The top of the stack.
size_t stack_size; // The size of the stack, zero indicate an unknown stack size.
+ uint64_t dex_pc; // If non-zero, the Dex PC for the ART interpreter.
backtrace_map_t map; // The map associated with the given pc.
std::string func_name; // The function name associated with this pc, NULL if not found.
- uintptr_t func_offset; // pc relative to the start of the function, only valid if func_name is not NULL.
+ uint64_t func_offset; // pc relative to the start of the function, only valid if func_name is not
+ // NULL.
};
#if defined(__APPLE__)
@@ -138,20 +140,20 @@
// Get the function name and offset into the function given the pc.
// If the string is empty, then no valid function name was found,
// or the pc is not in any valid map.
- virtual std::string GetFunctionName(uintptr_t pc, uintptr_t* offset,
+ virtual std::string GetFunctionName(uint64_t pc, uint64_t* offset,
const backtrace_map_t* map = NULL);
// Fill in the map data associated with the given pc.
- virtual void FillInMap(uintptr_t pc, backtrace_map_t* map);
+ virtual void FillInMap(uint64_t pc, backtrace_map_t* map);
// Read the data at a specific address.
- virtual bool ReadWord(uintptr_t ptr, word_t* out_value) = 0;
+ virtual bool ReadWord(uint64_t ptr, word_t* out_value) = 0;
// Read arbitrary data from a specific address. If a read request would
// span from one map to another, this call only reads up until the end
// of the current map.
// Returns the total number of bytes actually read.
- virtual size_t Read(uintptr_t addr, uint8_t* buffer, size_t bytes) = 0;
+ virtual size_t Read(uint64_t addr, uint8_t* buffer, size_t bytes) = 0;
// Create a string representing the formatted line of backtrace information
// for a single frame.
@@ -188,9 +190,9 @@
// The name returned is not demangled, GetFunctionName() takes care of
// demangling the name.
- virtual std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) = 0;
+ virtual std::string GetFunctionNameRaw(uint64_t pc, uint64_t* offset) = 0;
- virtual bool VerifyReadWordArgs(uintptr_t ptr, word_t* out_value);
+ virtual bool VerifyReadWordArgs(uint64_t ptr, word_t* out_value);
bool BuildMap();
diff --git a/libbacktrace/include/backtrace/BacktraceMap.h b/libbacktrace/include/backtrace/BacktraceMap.h
index 4ae68dd..4d020e6 100644
--- a/libbacktrace/include/backtrace/BacktraceMap.h
+++ b/libbacktrace/include/backtrace/BacktraceMap.h
@@ -39,10 +39,10 @@
static constexpr int PROT_DEVICE_MAP = 0x8000;
struct backtrace_map_t {
- uintptr_t start = 0;
- uintptr_t end = 0;
- uintptr_t offset = 0;
- uintptr_t load_bias = 0;
+ uint64_t start = 0;
+ uint64_t end = 0;
+ uint64_t offset = 0;
+ uint64_t load_bias = 0;
int flags = 0;
std::string name;
};
@@ -91,7 +91,7 @@
return nullptr;
}
backtrace_map_t* map = &map_->maps_[index_];
- if (map->load_bias == static_cast<uintptr_t>(-1)) {
+ if (map->load_bias == static_cast<uint64_t>(-1)) {
map->load_bias = map_->GetLoadBias(index_);
}
return map;
@@ -106,15 +106,15 @@
iterator end() { return iterator(this, maps_.size()); }
// Fill in the map data structure for the given address.
- virtual void FillIn(uintptr_t addr, backtrace_map_t* map);
+ virtual void FillIn(uint64_t addr, backtrace_map_t* map);
// Only supported with the new unwinder.
- virtual std::string GetFunctionName(uintptr_t /*pc*/, uintptr_t* /*offset*/) { return ""; }
+ virtual std::string GetFunctionName(uint64_t /*pc*/, uint64_t* /*offset*/) { return ""; }
virtual std::shared_ptr<unwindstack::Memory> GetProcessMemory() { return nullptr; }
// The flags returned are the same flags as used by the mmap call.
// The values are PROT_*.
- int GetFlags(uintptr_t pc) {
+ int GetFlags(uint64_t pc) {
backtrace_map_t map;
FillIn(pc, &map);
if (IsValid(map)) {
@@ -123,9 +123,9 @@
return PROT_NONE;
}
- bool IsReadable(uintptr_t pc) { return GetFlags(pc) & PROT_READ; }
- bool IsWritable(uintptr_t pc) { return GetFlags(pc) & PROT_WRITE; }
- bool IsExecutable(uintptr_t pc) { return GetFlags(pc) & PROT_EXEC; }
+ bool IsReadable(uint64_t pc) { return GetFlags(pc) & PROT_READ; }
+ bool IsWritable(uint64_t pc) { return GetFlags(pc) & PROT_WRITE; }
+ bool IsExecutable(uint64_t pc) { return GetFlags(pc) & PROT_EXEC; }
// In order to use the iterators on this object, a caller must
// call the LockIterator and UnlockIterator function to guarantee
diff --git a/liblog/Android.bp b/liblog/Android.bp
index eae0b10..7d9e306 100644
--- a/liblog/Android.bp
+++ b/liblog/Android.bp
@@ -80,6 +80,10 @@
address: false,
},
},
+ android_arm: {
+ // TODO: This is to work around b/24465209. Remove after root cause is fixed
+ ldflags: ["-Wl,--hash-style=both"],
+ },
windows: {
srcs: ["uio.c"],
enabled: true,
diff --git a/liblog/tests/Android.mk b/liblog/tests/Android.mk
index 39b52ac..cfa849b 100644
--- a/liblog/tests/Android.mk
+++ b/liblog/tests/Android.mk
@@ -24,13 +24,12 @@
test_tags := tests
benchmark_c_flags := \
- -Ibionic/tests \
- -Wall -Wextra \
+ -Wall \
+ -Wextra \
-Werror \
-fno-builtin \
benchmark_src_files := \
- benchmark_main.cpp \
liblog_benchmark.cpp
# Build benchmarks for the device. Run with:
@@ -41,7 +40,7 @@
LOCAL_CFLAGS += $(benchmark_c_flags)
LOCAL_SHARED_LIBRARIES += liblog libm libbase
LOCAL_SRC_FILES := $(benchmark_src_files)
-include $(BUILD_NATIVE_TEST)
+include $(BUILD_NATIVE_BENCHMARK)
# -----------------------------------------------------------------------------
# Unit tests.
diff --git a/liblog/tests/benchmark.h b/liblog/tests/benchmark.h
deleted file mode 100644
index e9280f6..0000000
--- a/liblog/tests/benchmark.h
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (C) 2012-2014 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 <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <vector>
-
-#ifndef BIONIC_BENCHMARK_H_
-#define BIONIC_BENCHMARK_H_
-
-namespace testing {
-
-class Benchmark;
-template <typename T> class BenchmarkWantsArg;
-template <typename T> class BenchmarkWithArg;
-
-void BenchmarkRegister(Benchmark* bm);
-int PrettyPrintInt(char* str, int len, unsigned int arg);
-
-class Benchmark {
- public:
- Benchmark(const char* name, void (*fn)(int)) : name_(strdup(name)), fn_(fn) {
- BenchmarkRegister(this);
- }
- explicit Benchmark(const char* name) : name_(strdup(name)), fn_(NULL) {}
-
- virtual ~Benchmark() {
- free(name_);
- }
-
- const char* Name() { return name_; }
- virtual const char* ArgName() { return NULL; }
- virtual void RunFn(int iterations) { fn_(iterations); }
-
- protected:
- char* name_;
-
- private:
- void (*fn_)(int);
-};
-
-template <typename T>
-class BenchmarkWantsArgBase : public Benchmark {
- public:
- BenchmarkWantsArgBase(const char* name, void (*fn)(int, T)) : Benchmark(name) {
- fn_arg_ = fn;
- }
-
- BenchmarkWantsArgBase<T>* Arg(const char* arg_name, T arg) {
- BenchmarkRegister(new BenchmarkWithArg<T>(name_, fn_arg_, arg_name, arg));
- return this;
- }
-
- protected:
- virtual void RunFn(int) { printf("can't run arg benchmark %s without arg\n", Name()); }
- void (*fn_arg_)(int, T);
-};
-
-template <typename T>
-class BenchmarkWithArg : public BenchmarkWantsArg<T> {
- public:
- BenchmarkWithArg(const char* name, void (*fn)(int, T), const char* arg_name, T arg) :
- BenchmarkWantsArg<T>(name, fn), arg_(arg) {
- arg_name_ = strdup(arg_name);
- }
-
- virtual ~BenchmarkWithArg() {
- free(arg_name_);
- }
-
- virtual const char* ArgName() { return arg_name_; }
-
- protected:
- virtual void RunFn(int iterations) { BenchmarkWantsArg<T>::fn_arg_(iterations, arg_); }
-
- private:
- T arg_;
- char* arg_name_;
-};
-
-template <typename T>
-class BenchmarkWantsArg : public BenchmarkWantsArgBase<T> {
- public:
- BenchmarkWantsArg<T>(const char* name, void (*fn)(int, T)) :
- BenchmarkWantsArgBase<T>(name, fn) { }
-};
-
-template <>
-class BenchmarkWantsArg<int> : public BenchmarkWantsArgBase<int> {
- public:
- BenchmarkWantsArg<int>(const char* name, void (*fn)(int, int)) :
- BenchmarkWantsArgBase<int>(name, fn) { }
-
- BenchmarkWantsArg<int>* Arg(int arg) {
- char arg_name[100];
- PrettyPrintInt(arg_name, sizeof(arg_name), arg);
- BenchmarkRegister(new BenchmarkWithArg<int>(name_, fn_arg_, arg_name, arg));
- return this;
- }
-};
-
-static inline Benchmark* BenchmarkFactory(const char* name, void (*fn)(int)) {
- return new Benchmark(name, fn);
-}
-
-template <typename T>
-static inline BenchmarkWantsArg<T>* BenchmarkFactory(const char* name, void (*fn)(int, T)) {
- return new BenchmarkWantsArg<T>(name, fn);
-}
-
-} // namespace testing
-
-template <typename T>
-static inline void BenchmarkAddArg(::testing::Benchmark* b, const char* name, T arg) {
- ::testing::BenchmarkWantsArg<T>* ba;
- ba = static_cast< ::testing::BenchmarkWantsArg<T>* >(b);
- ba->Arg(name, arg);
-}
-
-void SetBenchmarkBytesProcessed(uint64_t);
-void ResetBenchmarkTiming(void);
-void StopBenchmarkTiming(void);
-void StartBenchmarkTiming(void);
-void StartBenchmarkTiming(uint64_t);
-void StopBenchmarkTiming(uint64_t);
-
-#define BENCHMARK(f) \
- static ::testing::Benchmark* _benchmark_##f __attribute__((unused)) = /* NOLINT */ \
- (::testing::Benchmark*)::testing::BenchmarkFactory(#f, f) /* NOLINT */
-
-#endif // BIONIC_BENCHMARK_H_
diff --git a/liblog/tests/benchmark_main.cpp b/liblog/tests/benchmark_main.cpp
deleted file mode 100644
index 7367f1b..0000000
--- a/liblog/tests/benchmark_main.cpp
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (C) 2012-2014 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 <benchmark.h>
-
-#include <inttypes.h>
-#include <math.h>
-#include <regex.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include <map>
-#include <string>
-#include <vector>
-
-static uint64_t gBytesProcessed;
-static uint64_t gBenchmarkTotalTimeNs;
-static uint64_t gBenchmarkTotalTimeNsSquared;
-static uint64_t gBenchmarkNum;
-static uint64_t gBenchmarkStartTimeNs;
-
-typedef std::vector< ::testing::Benchmark*> BenchmarkList;
-static BenchmarkList* gBenchmarks;
-
-static int Round(int n) {
- int base = 1;
- while (base * 10 < n) {
- base *= 10;
- }
- if (n < 2 * base) {
- return 2 * base;
- }
- if (n < 5 * base) {
- return 5 * base;
- }
- return 10 * base;
-}
-
-static uint64_t NanoTime() {
- struct timespec t;
- t.tv_sec = t.tv_nsec = 0;
- clock_gettime(CLOCK_MONOTONIC, &t);
- return static_cast<uint64_t>(t.tv_sec) * 1000000000ULL + t.tv_nsec;
-}
-
-namespace testing {
-
-int PrettyPrintInt(char* str, int len, unsigned int arg) {
- if (arg >= (1 << 30) && arg % (1 << 30) == 0) {
- return snprintf(str, len, "%uGi", arg / (1 << 30));
- } else if (arg >= (1 << 20) && arg % (1 << 20) == 0) {
- return snprintf(str, len, "%uMi", arg / (1 << 20));
- } else if (arg >= (1 << 10) && arg % (1 << 10) == 0) {
- return snprintf(str, len, "%uKi", arg / (1 << 10));
- } else if (arg >= 1000000000 && arg % 1000000000 == 0) {
- return snprintf(str, len, "%uG", arg / 1000000000);
- } else if (arg >= 1000000 && arg % 1000000 == 0) {
- return snprintf(str, len, "%uM", arg / 1000000);
- } else if (arg >= 1000 && arg % 1000 == 0) {
- return snprintf(str, len, "%uK", arg / 1000);
- } else {
- return snprintf(str, len, "%u", arg);
- }
-}
-
-bool ShouldRun(Benchmark* b, int argc, char* argv[]) {
- if (argc == 1) {
- return true; // With no arguments, we run all benchmarks.
- }
- // Otherwise, we interpret each argument as a regular expression and
- // see if any of our benchmarks match.
- for (int i = 1; i < argc; i++) {
- regex_t re;
- if (regcomp(&re, argv[i], 0) != 0) {
- fprintf(stderr, "couldn't compile \"%s\" as a regular expression!\n",
- argv[i]);
- exit(EXIT_FAILURE);
- }
- int match = regexec(&re, b->Name(), 0, NULL, 0);
- regfree(&re);
- if (match != REG_NOMATCH) {
- return true;
- }
- }
- return false;
-}
-
-void BenchmarkRegister(Benchmark* b) {
- if (gBenchmarks == NULL) {
- gBenchmarks = new BenchmarkList;
- }
- gBenchmarks->push_back(b);
-}
-
-void RunRepeatedly(Benchmark* b, int iterations) {
- gBytesProcessed = 0;
- ResetBenchmarkTiming();
- uint64_t StartTimeNs = NanoTime();
- b->RunFn(iterations);
- // Catch us if we fail to log anything.
- if ((gBenchmarkTotalTimeNs == 0) && (StartTimeNs != 0) &&
- (gBenchmarkStartTimeNs == 0)) {
- gBenchmarkTotalTimeNs = NanoTime() - StartTimeNs;
- }
-}
-
-void Run(Benchmark* b) {
- // run once in case it's expensive
- unsigned iterations = 1;
- uint64_t s = NanoTime();
- RunRepeatedly(b, iterations);
- s = NanoTime() - s;
- while (s < 2e9 && gBenchmarkTotalTimeNs < 1e9 && iterations < 1e9) {
- unsigned last = iterations;
- if (gBenchmarkTotalTimeNs / iterations == 0) {
- iterations = 1e9;
- } else {
- iterations = 1e9 / (gBenchmarkTotalTimeNs / iterations);
- }
- iterations =
- std::max(last + 1, std::min(iterations + iterations / 2, 100 * last));
- iterations = Round(iterations);
- s = NanoTime();
- RunRepeatedly(b, iterations);
- s = NanoTime() - s;
- }
-
- char throughput[100];
- throughput[0] = '\0';
- if (gBenchmarkTotalTimeNs > 0 && gBytesProcessed > 0) {
- double mib_processed = static_cast<double>(gBytesProcessed) / 1e6;
- double seconds = static_cast<double>(gBenchmarkTotalTimeNs) / 1e9;
- snprintf(throughput, sizeof(throughput), " %8.2f MiB/s",
- mib_processed / seconds);
- }
-
- char full_name[100];
- snprintf(full_name, sizeof(full_name), "%s%s%s", b->Name(),
- b->ArgName() ? "/" : "", b->ArgName() ? b->ArgName() : "");
-
- uint64_t mean = gBenchmarkTotalTimeNs / iterations;
- uint64_t sdev = 0;
- if (gBenchmarkNum == iterations) {
- mean = gBenchmarkTotalTimeNs / gBenchmarkNum;
- uint64_t nXvariance = gBenchmarkTotalTimeNsSquared * gBenchmarkNum -
- (gBenchmarkTotalTimeNs * gBenchmarkTotalTimeNs);
- sdev = (sqrt((double)nXvariance) / gBenchmarkNum / gBenchmarkNum) + 0.5;
- }
- if (mean > (10000 * sdev)) {
- printf("%-25s %10" PRIu64 " %10" PRIu64 "%s\n", full_name,
- static_cast<uint64_t>(iterations), mean, throughput);
- } else {
- printf("%-25s %10" PRIu64 " %10" PRIu64 "(\317\203%" PRIu64 ")%s\n",
- full_name, static_cast<uint64_t>(iterations), mean, sdev, throughput);
- }
- fflush(stdout);
-}
-
-} // namespace testing
-
-void SetBenchmarkBytesProcessed(uint64_t x) {
- gBytesProcessed = x;
-}
-
-void ResetBenchmarkTiming() {
- gBenchmarkStartTimeNs = 0;
- gBenchmarkTotalTimeNs = 0;
- gBenchmarkTotalTimeNsSquared = 0;
- gBenchmarkNum = 0;
-}
-
-void StopBenchmarkTiming(void) {
- if (gBenchmarkStartTimeNs != 0) {
- int64_t diff = NanoTime() - gBenchmarkStartTimeNs;
- gBenchmarkTotalTimeNs += diff;
- gBenchmarkTotalTimeNsSquared += diff * diff;
- ++gBenchmarkNum;
- }
- gBenchmarkStartTimeNs = 0;
-}
-
-void StartBenchmarkTiming(void) {
- if (gBenchmarkStartTimeNs == 0) {
- gBenchmarkStartTimeNs = NanoTime();
- }
-}
-
-void StopBenchmarkTiming(uint64_t NanoTime) {
- if (gBenchmarkStartTimeNs != 0) {
- int64_t diff = NanoTime - gBenchmarkStartTimeNs;
- gBenchmarkTotalTimeNs += diff;
- gBenchmarkTotalTimeNsSquared += diff * diff;
- if (NanoTime != 0) {
- ++gBenchmarkNum;
- }
- }
- gBenchmarkStartTimeNs = 0;
-}
-
-void StartBenchmarkTiming(uint64_t NanoTime) {
- if (gBenchmarkStartTimeNs == 0) {
- gBenchmarkStartTimeNs = NanoTime;
- }
-}
-
-int main(int argc, char* argv[]) {
- if (gBenchmarks->empty()) {
- fprintf(stderr, "No benchmarks registered!\n");
- exit(EXIT_FAILURE);
- }
-
- bool need_header = true;
- for (auto b : *gBenchmarks) {
- if (ShouldRun(b, argc, argv)) {
- if (need_header) {
- printf("%-25s %10s %10s\n", "", "iterations", "ns/op");
- fflush(stdout);
- need_header = false;
- }
- Run(b);
- }
- }
-
- if (need_header) {
- fprintf(stderr, "No matching benchmarks!\n");
- fprintf(stderr, "Available benchmarks:\n");
- for (auto b : *gBenchmarks) {
- fprintf(stderr, " %s\n", b->Name());
- }
- exit(EXIT_FAILURE);
- }
-
- return 0;
-}
diff --git a/liblog/tests/liblog_benchmark.cpp b/liblog/tests/liblog_benchmark.cpp
index c4bf959..c2f3f83 100644
--- a/liblog/tests/liblog_benchmark.cpp
+++ b/liblog/tests/liblog_benchmark.cpp
@@ -19,18 +19,20 @@
#include <poll.h>
#include <sys/endian.h>
#include <sys/socket.h>
+#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <unordered_set>
#include <android-base/file.h>
+#include <benchmark/benchmark.h>
#include <cutils/sockets.h>
#include <log/event_tag_map.h>
#include <log/log_transport.h>
#include <private/android_logger.h>
-#include "benchmark.h"
+BENCHMARK_MAIN();
// enhanced version of LOG_FAILURE_RETRY to add support for EAGAIN and
// non-syscall libs. Since we are benchmarking, or using this in the emergency
@@ -51,15 +53,11 @@
* the log at high pressure. Expect this to be less than double the process
* wakeup time (2ms?)
*/
-static void BM_log_maximum_retry(int iters) {
- StartBenchmarkTiming();
-
- for (int i = 0; i < iters; ++i) {
- LOG_FAILURE_RETRY(
- __android_log_print(ANDROID_LOG_INFO, "BM_log_maximum_retry", "%d", i));
+static void BM_log_maximum_retry(benchmark::State& state) {
+ while (state.KeepRunning()) {
+ LOG_FAILURE_RETRY(__android_log_print(
+ ANDROID_LOG_INFO, "BM_log_maximum_retry", "%zu", state.iterations()));
}
-
- StopBenchmarkTiming();
}
BENCHMARK(BM_log_maximum_retry);
@@ -68,14 +66,11 @@
* at high pressure. Expect this to be less than double the process wakeup
* time (2ms?)
*/
-static void BM_log_maximum(int iters) {
- StartBenchmarkTiming();
-
- for (int i = 0; i < iters; ++i) {
- __android_log_print(ANDROID_LOG_INFO, "BM_log_maximum", "%d", i);
+static void BM_log_maximum(benchmark::State& state) {
+ while (state.KeepRunning()) {
+ __android_log_print(ANDROID_LOG_INFO, "BM_log_maximum", "%zu",
+ state.iterations());
}
-
- StopBenchmarkTiming();
}
BENCHMARK(BM_log_maximum);
@@ -87,36 +82,98 @@
android_set_log_transport(LOGGER_DEFAULT);
}
-static void BM_log_maximum_null(int iters) {
+static void BM_log_maximum_null(benchmark::State& state) {
set_log_null();
- BM_log_maximum(iters);
+ BM_log_maximum(state);
set_log_default();
}
BENCHMARK(BM_log_maximum_null);
/*
* Measure the time it takes to collect the time using
- * discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
+ * discrete acquisition (state.PauseTiming() to state.ResumeTiming())
* under light load. Expect this to be a syscall period (2us) or
* data read time if zero-syscall.
*
* vdso support in the kernel and the library can allow
- * clock_gettime to be zero-syscall.
+ * clock_gettime to be zero-syscall, but there there does remain some
+ * benchmarking overhead to pause and resume; assumptions are both are
+ * covered.
*/
-static void BM_clock_overhead(int iters) {
- for (int i = 0; i < iters; ++i) {
- StartBenchmarkTiming();
- StopBenchmarkTiming();
+static void BM_clock_overhead(benchmark::State& state) {
+ while (state.KeepRunning()) {
+ state.PauseTiming();
+ state.ResumeTiming();
}
}
BENCHMARK(BM_clock_overhead);
+static void do_clock_overhead(benchmark::State& state, clockid_t clk_id) {
+ timespec t;
+ while (state.KeepRunning()) {
+ clock_gettime(clk_id, &t);
+ }
+}
+
+static void BM_time_clock_gettime_REALTIME(benchmark::State& state) {
+ do_clock_overhead(state, CLOCK_REALTIME);
+}
+BENCHMARK(BM_time_clock_gettime_REALTIME);
+
+static void BM_time_clock_gettime_MONOTONIC(benchmark::State& state) {
+ do_clock_overhead(state, CLOCK_MONOTONIC);
+}
+BENCHMARK(BM_time_clock_gettime_MONOTONIC);
+
+static void BM_time_clock_gettime_MONOTONIC_syscall(benchmark::State& state) {
+ timespec t;
+ while (state.KeepRunning()) {
+ syscall(__NR_clock_gettime, CLOCK_MONOTONIC, &t);
+ }
+}
+BENCHMARK(BM_time_clock_gettime_MONOTONIC_syscall);
+
+static void BM_time_clock_gettime_MONOTONIC_RAW(benchmark::State& state) {
+ do_clock_overhead(state, CLOCK_MONOTONIC_RAW);
+}
+BENCHMARK(BM_time_clock_gettime_MONOTONIC_RAW);
+
+static void BM_time_clock_gettime_BOOTTIME(benchmark::State& state) {
+ do_clock_overhead(state, CLOCK_BOOTTIME);
+}
+BENCHMARK(BM_time_clock_gettime_BOOTTIME);
+
+static void BM_time_clock_getres_MONOTONIC(benchmark::State& state) {
+ timespec t;
+ while (state.KeepRunning()) {
+ clock_getres(CLOCK_MONOTONIC, &t);
+ }
+}
+BENCHMARK(BM_time_clock_getres_MONOTONIC);
+
+static void BM_time_clock_getres_MONOTONIC_syscall(benchmark::State& state) {
+ timespec t;
+ while (state.KeepRunning()) {
+ syscall(__NR_clock_getres, CLOCK_MONOTONIC, &t);
+ }
+}
+BENCHMARK(BM_time_clock_getres_MONOTONIC_syscall);
+
+static void BM_time_time(benchmark::State& state) {
+ while (state.KeepRunning()) {
+ time_t now;
+ now = time(&now);
+ }
+}
+BENCHMARK(BM_time_time);
+
/*
* Measure the time it takes to submit the android logging data to pstore
*/
-static void BM_pmsg_short(int iters) {
+static void BM_pmsg_short(benchmark::State& state) {
int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
if (pstore_fd < 0) {
+ state.SkipWithError("/dev/pmsg0");
return;
}
@@ -175,13 +232,12 @@
newVec[2].iov_base = &buffer;
newVec[2].iov_len = sizeof(buffer);
- StartBenchmarkTiming();
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
++snapshot;
buffer.payload.data = htole32(snapshot);
writev(pstore_fd, newVec, nr);
}
- StopBenchmarkTiming();
+ state.PauseTiming();
close(pstore_fd);
}
BENCHMARK(BM_pmsg_short);
@@ -190,9 +246,10 @@
* Measure the time it takes to submit the android logging data to pstore
* best case aligned single block.
*/
-static void BM_pmsg_short_aligned(int iters) {
+static void BM_pmsg_short_aligned(benchmark::State& state) {
int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
if (pstore_fd < 0) {
+ state.SkipWithError("/dev/pmsg0");
return;
}
@@ -228,7 +285,8 @@
memset(buf, 0, sizeof(buf));
struct packet* buffer = (struct packet*)(((uintptr_t)buf + 7) & ~7);
if (((uintptr_t)&buffer->pmsg_header) & 7) {
- fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+ fprintf(stderr, "&buffer=0x%p iterations=%zu\n", &buffer->pmsg_header,
+ state.iterations());
}
buffer->pmsg_header.magic = LOGGER_MAGIC;
@@ -247,15 +305,14 @@
uint32_t snapshot = 0;
buffer->payload.payload.data = htole32(snapshot);
- StartBenchmarkTiming();
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
++snapshot;
buffer->payload.payload.data = htole32(snapshot);
write(pstore_fd, &buffer->pmsg_header,
sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t) +
sizeof(android_log_event_int_t));
}
- StopBenchmarkTiming();
+ state.PauseTiming();
close(pstore_fd);
}
BENCHMARK(BM_pmsg_short_aligned);
@@ -264,9 +321,10 @@
* Measure the time it takes to submit the android logging data to pstore
* best case aligned single block.
*/
-static void BM_pmsg_short_unaligned1(int iters) {
+static void BM_pmsg_short_unaligned1(benchmark::State& state) {
int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
if (pstore_fd < 0) {
+ state.SkipWithError("/dev/pmsg0");
return;
}
@@ -302,7 +360,8 @@
memset(buf, 0, sizeof(buf));
struct packet* buffer = (struct packet*)((((uintptr_t)buf + 7) & ~7) + 1);
if ((((uintptr_t)&buffer->pmsg_header) & 7) != 1) {
- fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+ fprintf(stderr, "&buffer=0x%p iterations=%zu\n", &buffer->pmsg_header,
+ state.iterations());
}
buffer->pmsg_header.magic = LOGGER_MAGIC;
@@ -321,15 +380,14 @@
uint32_t snapshot = 0;
buffer->payload.payload.data = htole32(snapshot);
- StartBenchmarkTiming();
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
++snapshot;
buffer->payload.payload.data = htole32(snapshot);
write(pstore_fd, &buffer->pmsg_header,
sizeof(android_pmsg_log_header_t) + sizeof(android_log_header_t) +
sizeof(android_log_event_int_t));
}
- StopBenchmarkTiming();
+ state.PauseTiming();
close(pstore_fd);
}
BENCHMARK(BM_pmsg_short_unaligned1);
@@ -338,9 +396,10 @@
* Measure the time it takes to submit the android logging data to pstore
* best case aligned single block.
*/
-static void BM_pmsg_long_aligned(int iters) {
+static void BM_pmsg_long_aligned(benchmark::State& state) {
int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
if (pstore_fd < 0) {
+ state.SkipWithError("/dev/pmsg0");
return;
}
@@ -376,7 +435,8 @@
memset(buf, 0, sizeof(buf));
struct packet* buffer = (struct packet*)(((uintptr_t)buf + 7) & ~7);
if (((uintptr_t)&buffer->pmsg_header) & 7) {
- fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+ fprintf(stderr, "&buffer=0x%p iterations=%zu\n", &buffer->pmsg_header,
+ state.iterations());
}
buffer->pmsg_header.magic = LOGGER_MAGIC;
@@ -395,13 +455,12 @@
uint32_t snapshot = 0;
buffer->payload.payload.data = htole32(snapshot);
- StartBenchmarkTiming();
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
++snapshot;
buffer->payload.payload.data = htole32(snapshot);
write(pstore_fd, &buffer->pmsg_header, LOGGER_ENTRY_MAX_PAYLOAD);
}
- StopBenchmarkTiming();
+ state.PauseTiming();
close(pstore_fd);
}
BENCHMARK(BM_pmsg_long_aligned);
@@ -410,9 +469,10 @@
* Measure the time it takes to submit the android logging data to pstore
* best case aligned single block.
*/
-static void BM_pmsg_long_unaligned1(int iters) {
+static void BM_pmsg_long_unaligned1(benchmark::State& state) {
int pstore_fd = TEMP_FAILURE_RETRY(open("/dev/pmsg0", O_WRONLY));
if (pstore_fd < 0) {
+ state.SkipWithError("/dev/pmsg0");
return;
}
@@ -448,7 +508,8 @@
memset(buf, 0, sizeof(buf));
struct packet* buffer = (struct packet*)((((uintptr_t)buf + 7) & ~7) + 1);
if ((((uintptr_t)&buffer->pmsg_header) & 7) != 1) {
- fprintf(stderr, "&buffer=0x%p iters=%d\n", &buffer->pmsg_header, iters);
+ fprintf(stderr, "&buffer=0x%p iterations=%zu\n", &buffer->pmsg_header,
+ state.iterations());
}
buffer->pmsg_header.magic = LOGGER_MAGIC;
@@ -467,22 +528,20 @@
uint32_t snapshot = 0;
buffer->payload.payload.data = htole32(snapshot);
- StartBenchmarkTiming();
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
++snapshot;
buffer->payload.payload.data = htole32(snapshot);
write(pstore_fd, &buffer->pmsg_header, LOGGER_ENTRY_MAX_PAYLOAD);
}
- StopBenchmarkTiming();
+ state.PauseTiming();
close(pstore_fd);
}
BENCHMARK(BM_pmsg_long_unaligned1);
/*
* Measure the time it takes to form sprintf plus time using
- * discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
- * under light load. Expect this to be a syscall period (2us) or sprintf
- * time if zero-syscall time.
+ * discrete acquisition under light load. Expect this to be a syscall period
+ * (2us) or sprintf time if zero-syscall time.
*/
/* helper function */
static void test_print(const char* fmt, ...) {
@@ -498,58 +557,55 @@
#define logd_sleep() usleep(50) // really allow logd to catch up
/* performance test */
-static void BM_sprintf_overhead(int iters) {
- for (int i = 0; i < iters; ++i) {
- StartBenchmarkTiming();
- test_print("BM_sprintf_overhead:%d", i);
- StopBenchmarkTiming();
+static void BM_sprintf_overhead(benchmark::State& state) {
+ while (state.KeepRunning()) {
+ test_print("BM_sprintf_overhead:%zu", state.iterations());
+ state.PauseTiming();
logd_yield();
+ state.ResumeTiming();
}
}
BENCHMARK(BM_sprintf_overhead);
/*
* Measure the time it takes to submit the android printing logging call
- * using discrete acquisition discrete acquisition (StartBenchmarkTiming() ->
- * StopBenchmarkTiming()) under light load. Expect this to be a dozen or so
- * syscall periods (40us) plus time to run *printf
+ * using discrete acquisition discrete acquisition under light load. Expect
+ * this to be a dozen or so syscall periods (40us) plus time to run *printf
*/
-static void BM_log_print_overhead(int iters) {
- for (int i = 0; i < iters; ++i) {
- StartBenchmarkTiming();
- __android_log_print(ANDROID_LOG_INFO, "BM_log_overhead", "%d", i);
- StopBenchmarkTiming();
+static void BM_log_print_overhead(benchmark::State& state) {
+ while (state.KeepRunning()) {
+ __android_log_print(ANDROID_LOG_INFO, "BM_log_overhead", "%zu",
+ state.iterations());
+ state.PauseTiming();
logd_yield();
+ state.ResumeTiming();
}
}
BENCHMARK(BM_log_print_overhead);
/*
* Measure the time it takes to submit the android event logging call
- * using discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
- * under light load. Expect this to be a long path to logger to convert the
- * unknown tag (0) into a tagname (less than 200us).
+ * using discrete acquisition under light load. Expect this to be a long path
+ * to logger to convert the unknown tag (0) into a tagname (less than 200us).
*/
-static void BM_log_event_overhead(int iters) {
- for (unsigned long long i = 0; i < (unsigned)iters; ++i) {
- StartBenchmarkTiming();
+static void BM_log_event_overhead(benchmark::State& state) {
+ for (int64_t i = 0; state.KeepRunning(); ++i) {
// log tag number 0 is not known, nor shall it ever be known
__android_log_btwrite(0, EVENT_TYPE_LONG, &i, sizeof(i));
- StopBenchmarkTiming();
+ state.PauseTiming();
logd_yield();
+ state.ResumeTiming();
}
}
BENCHMARK(BM_log_event_overhead);
/*
* Measure the time it takes to submit the android event logging call
- * using discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
- * under light load with a known logtag. Expect this to be a dozen or so
- * syscall periods (less than 40us)
+ * using discrete acquisition under light load with a known logtag. Expect
+ * this to be a dozen or so syscall periods (less than 40us)
*/
-static void BM_log_event_overhead_42(int iters) {
- for (unsigned long long i = 0; i < (unsigned)iters; ++i) {
- StartBenchmarkTiming();
+static void BM_log_event_overhead_42(benchmark::State& state) {
+ for (int64_t i = 0; state.KeepRunning(); ++i) {
// In system/core/logcat/event.logtags:
// # These are used for testing, do not modify without updating
// # tests/framework-tests/src/android/util/EventLogFunctionalTest.java.
@@ -557,40 +613,42 @@
// # system/core/liblog/tests/liblog_test.cpp
// 42 answer (to life the universe etc|3)
__android_log_btwrite(42, EVENT_TYPE_LONG, &i, sizeof(i));
- StopBenchmarkTiming();
+ state.PauseTiming();
logd_yield();
+ state.ResumeTiming();
}
}
BENCHMARK(BM_log_event_overhead_42);
-static void BM_log_event_overhead_null(int iters) {
+static void BM_log_event_overhead_null(benchmark::State& state) {
set_log_null();
- BM_log_event_overhead(iters);
+ BM_log_event_overhead(state);
set_log_default();
}
BENCHMARK(BM_log_event_overhead_null);
/*
* Measure the time it takes to submit the android event logging call
- * using discrete acquisition (StartBenchmarkTiming() -> StopBenchmarkTiming())
- * under very-light load (<1% CPU utilization).
+ * using discrete acquisition under very-light load (<1% CPU utilization).
*/
-static void BM_log_light_overhead(int iters) {
- for (unsigned long long i = 0; i < (unsigned)iters; ++i) {
- StartBenchmarkTiming();
+static void BM_log_light_overhead(benchmark::State& state) {
+ for (int64_t i = 0; state.KeepRunning(); ++i) {
__android_log_btwrite(0, EVENT_TYPE_LONG, &i, sizeof(i));
- StopBenchmarkTiming();
+ state.PauseTiming();
usleep(10000);
+ state.ResumeTiming();
}
}
BENCHMARK(BM_log_light_overhead);
-static void BM_log_light_overhead_null(int iters) {
+static void BM_log_light_overhead_null(benchmark::State& state) {
set_log_null();
- BM_log_light_overhead(iters);
+ BM_log_light_overhead(state);
set_log_default();
}
-BENCHMARK(BM_log_light_overhead_null);
+// Default gets out of hand for this test, so we set a reasonable number of
+// iterations for a timely result.
+BENCHMARK(BM_log_light_overhead_null)->Iterations(500);
static void caught_latency(int /*signum*/) {
unsigned long long v = 0xDEADBEEFA55A5AA5ULL;
@@ -614,10 +672,12 @@
/*
* Measure the time it takes for the logd posting call to acquire the
- * timestamp to place into the internal record. Expect this to be less than
- * 4 syscalls (3us).
+ * timestamp to place into the internal record. Expect this to be less than
+ * 4 syscalls (3us). This test uses manual injection of timing because it is
+ * comparing the timestamp at send, and then picking up the corresponding log
+ * end-to-end long path from logd to see what actual timestamp was submitted.
*/
-static void BM_log_latency(int iters) {
+static void BM_log_latency(benchmark::State& state) {
pid_t pid = getpid();
struct logger_list* logger_list =
@@ -631,7 +691,8 @@
signal(SIGALRM, caught_latency);
alarm(alarm_time);
- for (int j = 0, i = 0; i < iters && j < 10 * iters; ++i, ++j) {
+ for (size_t j = 0; state.KeepRunning() && j < 10 * state.iterations(); ++j) {
+ retry: // We allow transitory errors (logd overloaded) to be retried.
log_time ts;
LOG_FAILURE_RETRY((ts = log_time(CLOCK_REALTIME),
android_btWriteLog(0, EVENT_TYPE_LONG, &ts, sizeof(ts))));
@@ -642,7 +703,7 @@
alarm(alarm_time);
if (ret <= 0) {
- iters = i;
+ state.SkipWithError("android_logger_list_read");
break;
}
if ((log_msg.entry.len != (4 + 1 + 8)) ||
@@ -658,7 +719,7 @@
log_time tx(eventData + 4 + 1);
if (ts != tx) {
if (0xDEADBEEFA55A5AA5ULL == caught_convert(eventData + 4 + 1)) {
- iters = i;
+ state.SkipWithError("signal");
break;
}
continue;
@@ -666,12 +727,8 @@
uint64_t start = ts.nsec();
uint64_t end = log_msg.nsec();
- if (end >= start) {
- StartBenchmarkTiming(start);
- StopBenchmarkTiming(end);
- } else {
- --i;
- }
+ if (end < start) goto retry;
+ state.SetIterationTime((end - start) / (double)NS_PER_SEC);
break;
}
}
@@ -681,7 +738,9 @@
android_logger_list_free(logger_list);
}
-BENCHMARK(BM_log_latency);
+// Default gets out of hand for this test, so we set a reasonable number of
+// iterations for a timely result.
+BENCHMARK(BM_log_latency)->UseManualTime()->Iterations(200);
static void caught_delay(int /*signum*/) {
unsigned long long v = 0xDEADBEEFA55A5AA6ULL;
@@ -693,7 +752,7 @@
* Measure the time it takes for the logd posting call to make it into
* the logs. Expect this to be less than double the process wakeup time (2ms).
*/
-static void BM_log_delay(int iters) {
+static void BM_log_delay(benchmark::State& state) {
pid_t pid = getpid();
struct logger_list* logger_list =
@@ -707,9 +766,7 @@
signal(SIGALRM, caught_delay);
alarm(alarm_time);
- StartBenchmarkTiming();
-
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
log_time ts(CLOCK_REALTIME);
LOG_FAILURE_RETRY(android_btWriteLog(0, EVENT_TYPE_LONG, &ts, sizeof(ts)));
@@ -720,7 +777,7 @@
alarm(alarm_time);
if (ret <= 0) {
- iters = i;
+ state.SkipWithError("android_logger_list_read");
break;
}
if ((log_msg.entry.len != (4 + 1 + 8)) ||
@@ -736,7 +793,7 @@
log_time tx(eventData + 4 + 1);
if (ts != tx) {
if (0xDEADBEEFA55A5AA6ULL == caught_convert(eventData + 4 + 1)) {
- iters = i;
+ state.SkipWithError("signal");
break;
}
continue;
@@ -745,12 +802,11 @@
break;
}
}
+ state.PauseTiming();
signal(SIGALRM, SIG_DFL);
alarm(0);
- StopBenchmarkTiming();
-
android_logger_list_free(logger_list);
}
BENCHMARK(BM_log_delay);
@@ -758,45 +814,33 @@
/*
* Measure the time it takes for __android_log_is_loggable.
*/
-static void BM_is_loggable(int iters) {
+static void BM_is_loggable(benchmark::State& state) {
static const char logd[] = "logd";
- StartBenchmarkTiming();
-
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
__android_log_is_loggable_len(ANDROID_LOG_WARN, logd, strlen(logd),
ANDROID_LOG_VERBOSE);
}
-
- StopBenchmarkTiming();
}
BENCHMARK(BM_is_loggable);
/*
* Measure the time it takes for android_log_clockid.
*/
-static void BM_clockid(int iters) {
- StartBenchmarkTiming();
-
- for (int i = 0; i < iters; ++i) {
+static void BM_clockid(benchmark::State& state) {
+ while (state.KeepRunning()) {
android_log_clockid();
}
-
- StopBenchmarkTiming();
}
BENCHMARK(BM_clockid);
/*
* Measure the time it takes for __android_log_security.
*/
-static void BM_security(int iters) {
- StartBenchmarkTiming();
-
- for (int i = 0; i < iters; ++i) {
+static void BM_security(benchmark::State& state) {
+ while (state.KeepRunning()) {
__android_log_security();
}
-
- StopBenchmarkTiming();
}
BENCHMARK(BM_security);
@@ -824,21 +868,17 @@
/*
* Measure the time it takes for android_lookupEventTag_len
*/
-static void BM_lookupEventTag(int iters) {
+static void BM_lookupEventTag(benchmark::State& state) {
prechargeEventMap();
std::unordered_set<uint32_t>::const_iterator it = set.begin();
- StartBenchmarkTiming();
-
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
size_t len;
android_lookupEventTag_len(map, &len, (*it));
++it;
if (it == set.end()) it = set.begin();
}
-
- StopBenchmarkTiming();
}
BENCHMARK(BM_lookupEventTag);
@@ -847,7 +887,7 @@
*/
static uint32_t notTag = 1;
-static void BM_lookupEventTag_NOT(int iters) {
+static void BM_lookupEventTag_NOT(benchmark::State& state) {
prechargeEventMap();
while (set.find(notTag) != set.end()) {
@@ -855,15 +895,11 @@
if (notTag >= USHRT_MAX) notTag = 1;
}
- StartBenchmarkTiming();
-
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
size_t len;
android_lookupEventTag_len(map, &len, notTag);
}
- StopBenchmarkTiming();
-
++notTag;
if (notTag >= USHRT_MAX) notTag = 1;
}
@@ -872,42 +908,38 @@
/*
* Measure the time it takes for android_lookupEventFormat_len
*/
-static void BM_lookupEventFormat(int iters) {
+static void BM_lookupEventFormat(benchmark::State& state) {
prechargeEventMap();
std::unordered_set<uint32_t>::const_iterator it = set.begin();
- StartBenchmarkTiming();
-
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
size_t len;
android_lookupEventFormat_len(map, &len, (*it));
++it;
if (it == set.end()) it = set.begin();
}
-
- StopBenchmarkTiming();
}
BENCHMARK(BM_lookupEventFormat);
/*
* Measure the time it takes for android_lookupEventTagNum plus above
*/
-static void BM_lookupEventTagNum(int iters) {
+static void BM_lookupEventTagNum(benchmark::State& state) {
prechargeEventMap();
std::unordered_set<uint32_t>::const_iterator it = set.begin();
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
size_t len;
const char* name = android_lookupEventTag_len(map, &len, (*it));
std::string Name(name, len);
const char* format = android_lookupEventFormat_len(map, &len, (*it));
std::string Format(format, len);
- StartBenchmarkTiming();
+ state.ResumeTiming();
android_lookupEventTagNum(map, Name.c_str(), Format.c_str(),
ANDROID_LOG_UNKNOWN);
- StopBenchmarkTiming();
+ state.PauseTiming();
++it;
if (it == set.end()) it = set.begin();
}
@@ -943,7 +975,7 @@
close(sock);
}
-static void BM_lookupEventTagNum_logd_new(int iters) {
+static void BM_lookupEventTagNum_logd_new(benchmark::State& state) {
fprintf(stderr,
"WARNING: "
"This test can cause logd to grow in size and hit DOS limiter\n");
@@ -965,7 +997,7 @@
data_event_log_tags = empty_event_log_tags;
}
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
char buffer[256];
memset(buffer, 0, sizeof(buffer));
log_time now(CLOCK_MONOTONIC);
@@ -973,9 +1005,9 @@
snprintf(name, sizeof(name), "a%" PRIu64, now.nsec());
snprintf(buffer, sizeof(buffer), "getEventTag name=%s format=\"(new|1)\"",
name);
- StartBenchmarkTiming();
+ state.ResumeTiming();
send_to_control(buffer, sizeof(buffer));
- StopBenchmarkTiming();
+ state.PauseTiming();
}
// Restore copies (logd still know about them, until crash or reboot)
@@ -1002,12 +1034,12 @@
}
BENCHMARK(BM_lookupEventTagNum_logd_new);
-static void BM_lookupEventTagNum_logd_existing(int iters) {
+static void BM_lookupEventTagNum_logd_existing(benchmark::State& state) {
prechargeEventMap();
std::unordered_set<uint32_t>::const_iterator it = set.begin();
- for (int i = 0; i < iters; ++i) {
+ while (state.KeepRunning()) {
size_t len;
const char* name = android_lookupEventTag_len(map, &len, (*it));
std::string Name(name, len);
@@ -1018,9 +1050,9 @@
snprintf(buffer, sizeof(buffer), "getEventTag name=%s format=\"%s\"",
Name.c_str(), Format.c_str());
- StartBenchmarkTiming();
+ state.ResumeTiming();
send_to_control(buffer, sizeof(buffer));
- StopBenchmarkTiming();
+ state.PauseTiming();
++it;
if (it == set.end()) it = set.begin();
}
diff --git a/libunwindstack/Android.bp b/libunwindstack/Android.bp
index 484bc7d..9389b40 100644
--- a/libunwindstack/Android.bp
+++ b/libunwindstack/Android.bp
@@ -170,6 +170,7 @@
data: [
"tests/files/elf32.xz",
"tests/files/elf64.xz",
+ "tests/files/offline/jit_debug_arm32/*",
"tests/files/offline/jit_debug_x86_32/*",
"tests/files/offline/gnu_debugdata_arm32/*",
"tests/files/offline/straddle_arm32/*",
diff --git a/libunwindstack/DwarfSection.cpp b/libunwindstack/DwarfSection.cpp
index 0954187..91d855b 100644
--- a/libunwindstack/DwarfSection.cpp
+++ b/libunwindstack/DwarfSection.cpp
@@ -34,6 +34,8 @@
namespace unwindstack {
+constexpr uint64_t DEX_PC_REG = 0x20444558;
+
DwarfSection::DwarfSection(Memory* memory) : memory_(memory), last_error_(DWARF_ERROR_NONE) {}
const DwarfFde* DwarfSection::GetFdeFromPc(uint64_t pc) {
@@ -98,6 +100,84 @@
}
template <typename AddressType>
+struct EvalInfo {
+ const dwarf_loc_regs_t* loc_regs;
+ const DwarfCie* cie;
+ RegsImpl<AddressType>* cur_regs;
+ Memory* regular_memory;
+ AddressType cfa;
+ bool return_address_undefined = false;
+ uint64_t reg_map = 0;
+ AddressType reg_values[64];
+};
+
+template <typename AddressType>
+bool DwarfSectionImpl<AddressType>::EvalRegister(const DwarfLocation* loc, uint32_t reg,
+ AddressType* reg_ptr, void* info) {
+ EvalInfo<AddressType>* eval_info = reinterpret_cast<EvalInfo<AddressType>*>(info);
+ Memory* regular_memory = eval_info->regular_memory;
+ switch (loc->type) {
+ case DWARF_LOCATION_OFFSET:
+ if (!regular_memory->ReadFully(eval_info->cfa + loc->values[0], reg_ptr, sizeof(AddressType))) {
+ last_error_ = DWARF_ERROR_MEMORY_INVALID;
+ return false;
+ }
+ break;
+ case DWARF_LOCATION_VAL_OFFSET:
+ *reg_ptr = eval_info->cfa + loc->values[0];
+ break;
+ case DWARF_LOCATION_REGISTER: {
+ uint32_t cur_reg = loc->values[0];
+ if (cur_reg >= eval_info->cur_regs->total_regs()) {
+ last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
+ return false;
+ }
+ AddressType* cur_reg_ptr = &(*eval_info->cur_regs)[cur_reg];
+ const auto& entry = eval_info->loc_regs->find(cur_reg);
+ if (entry != eval_info->loc_regs->end()) {
+ if (!(eval_info->reg_map & (1 << cur_reg))) {
+ eval_info->reg_map |= 1 << cur_reg;
+ eval_info->reg_values[cur_reg] = *cur_reg_ptr;
+ if (!EvalRegister(&entry->second, cur_reg, cur_reg_ptr, eval_info)) {
+ return false;
+ }
+ }
+
+ // Use the register value from before any evaluations.
+ *reg_ptr = eval_info->reg_values[cur_reg] + loc->values[1];
+ } else {
+ *reg_ptr = *cur_reg_ptr + loc->values[1];
+ }
+ break;
+ }
+ case DWARF_LOCATION_EXPRESSION:
+ case DWARF_LOCATION_VAL_EXPRESSION: {
+ AddressType value;
+ if (!EvalExpression(*loc, eval_info->cie->version, regular_memory, &value)) {
+ return false;
+ }
+ if (loc->type == DWARF_LOCATION_EXPRESSION) {
+ if (!regular_memory->ReadFully(value, reg_ptr, sizeof(AddressType))) {
+ last_error_ = DWARF_ERROR_MEMORY_INVALID;
+ return false;
+ }
+ } else {
+ *reg_ptr = value;
+ }
+ break;
+ }
+ case DWARF_LOCATION_UNDEFINED:
+ if (reg == eval_info->cie->return_address_register) {
+ eval_info->return_address_undefined = true;
+ }
+ default:
+ break;
+ }
+
+ return true;
+}
+
+template <typename AddressType>
bool DwarfSectionImpl<AddressType>::Eval(const DwarfCie* cie, Memory* regular_memory,
const dwarf_loc_regs_t& loc_regs, Regs* regs,
bool* finished) {
@@ -114,9 +194,13 @@
return false;
}
+ // Always set the dex pc to zero when evaluating.
+ cur_regs->set_dex_pc(0);
+
AddressType prev_cfa = regs->sp();
- AddressType cfa;
+ EvalInfo<AddressType> eval_info{
+ .loc_regs = &loc_regs, .cie = cie, .regular_memory = regular_memory, .cur_regs = cur_regs};
const DwarfLocation* loc = &cfa_entry->second;
// Only a few location types are valid for the cfa.
switch (loc->type) {
@@ -129,11 +213,11 @@
// pointer register does not have any associated location
// information, use the current cfa value.
if (regs->sp_reg() == loc->values[0] && loc_regs.count(regs->sp_reg()) == 0) {
- cfa = prev_cfa;
+ eval_info.cfa = prev_cfa;
} else {
- cfa = (*cur_regs)[loc->values[0]];
+ eval_info.cfa = (*cur_regs)[loc->values[0]];
}
- cfa += loc->values[1];
+ eval_info.cfa += loc->values[1];
break;
case DWARF_LOCATION_EXPRESSION:
case DWARF_LOCATION_VAL_EXPRESSION: {
@@ -142,12 +226,12 @@
return false;
}
if (loc->type == DWARF_LOCATION_EXPRESSION) {
- if (!regular_memory->ReadFully(value, &cfa, sizeof(AddressType))) {
+ if (!regular_memory->ReadFully(value, &eval_info.cfa, sizeof(AddressType))) {
last_error_ = DWARF_ERROR_MEMORY_INVALID;
return false;
}
} else {
- cfa = value;
+ eval_info.cfa = value;
}
break;
}
@@ -156,81 +240,38 @@
return false;
}
- // This code is not guaranteed to work in cases where a register location
- // is a double indirection to the actual value. For example, if r3 is set
- // to r5 + 4, and r5 is set to CFA + 4, then this won't necessarily work
- // because it does not guarantee that r5 is evaluated before r3.
- // Check that this case does not exist, and error if it does.
- bool return_address_undefined = false;
for (const auto& entry : loc_regs) {
- uint16_t reg = entry.first;
+ uint32_t reg = entry.first;
// Already handled the CFA register.
if (reg == CFA_REG) continue;
- if (reg >= cur_regs->total_regs()) {
- // Skip this unknown register.
+ AddressType* reg_ptr;
+ AddressType dex_pc = 0;
+ if (reg == DEX_PC_REG) {
+ // Special register that indicates this is a dex pc.
+ dex_pc = 0;
+ reg_ptr = &dex_pc;
+ } else if (reg >= cur_regs->total_regs() || eval_info.reg_map & (1 << reg)) {
+ // Skip this unknown register, or a register that has already been
+ // processed.
continue;
+ } else {
+ reg_ptr = &(*cur_regs)[reg];
+ eval_info.reg_map |= 1 << reg;
+ eval_info.reg_values[reg] = *reg_ptr;
}
- const DwarfLocation* loc = &entry.second;
- switch (loc->type) {
- case DWARF_LOCATION_OFFSET:
- if (!regular_memory->ReadFully(cfa + loc->values[0], &(*cur_regs)[reg],
- sizeof(AddressType))) {
- last_error_ = DWARF_ERROR_MEMORY_INVALID;
- return false;
- }
- break;
- case DWARF_LOCATION_VAL_OFFSET:
- (*cur_regs)[reg] = cfa + loc->values[0];
- break;
- case DWARF_LOCATION_REGISTER: {
- uint16_t cur_reg = loc->values[0];
- if (cur_reg >= cur_regs->total_regs()) {
- last_error_ = DWARF_ERROR_ILLEGAL_VALUE;
- return false;
- }
- if (loc_regs.find(cur_reg) != loc_regs.end()) {
- // This is a double indirection, a register definition references
- // another register which is also defined as something other
- // than a register.
- log(0,
- "Invalid indirection: register %d references register %d which is "
- "not a plain register.\n",
- reg, cur_reg);
- last_error_ = DWARF_ERROR_ILLEGAL_STATE;
- return false;
- }
- (*cur_regs)[reg] = (*cur_regs)[cur_reg] + loc->values[1];
- break;
- }
- case DWARF_LOCATION_EXPRESSION:
- case DWARF_LOCATION_VAL_EXPRESSION: {
- AddressType value;
- if (!EvalExpression(*loc, cie->version, regular_memory, &value)) {
- return false;
- }
- if (loc->type == DWARF_LOCATION_EXPRESSION) {
- if (!regular_memory->ReadFully(value, &(*cur_regs)[reg], sizeof(AddressType))) {
- last_error_ = DWARF_ERROR_MEMORY_INVALID;
- return false;
- }
- } else {
- (*cur_regs)[reg] = value;
- }
- break;
- }
- case DWARF_LOCATION_UNDEFINED:
- if (reg == cie->return_address_register) {
- return_address_undefined = true;
- }
- default:
- break;
+ if (!EvalRegister(&entry.second, reg, reg_ptr, &eval_info)) {
+ return false;
+ }
+
+ if (reg == DEX_PC_REG) {
+ cur_regs->set_dex_pc(dex_pc);
}
}
// Find the return address location.
- if (return_address_undefined) {
+ if (eval_info.return_address_undefined) {
cur_regs->set_pc(0);
} else {
cur_regs->set_pc((*cur_regs)[cie->return_address_register]);
@@ -239,7 +280,7 @@
// If the pc was set to zero, consider this the final frame.
*finished = (cur_regs->pc() == 0) ? true : false;
- cur_regs->set_sp(cfa);
+ cur_regs->set_sp(eval_info.cfa);
return true;
}
diff --git a/libunwindstack/JitDebug.cpp b/libunwindstack/JitDebug.cpp
index 1008439..d1dc0e6 100644
--- a/libunwindstack/JitDebug.cpp
+++ b/libunwindstack/JitDebug.cpp
@@ -173,7 +173,6 @@
initialized_ = true;
std::string descriptor_name("__jit_debug_descriptor");
- uint64_t descriptor_addr = 0;
for (MapInfo* info : *maps) {
if (!(info->flags & PROT_EXEC) || !(info->flags & PROT_READ) || info->offset != 0) {
continue;
@@ -194,17 +193,16 @@
}
Elf* elf = info->GetElf(memory_, true);
+ uint64_t descriptor_addr;
if (elf->GetGlobalVariable(descriptor_name, &descriptor_addr)) {
+ // Search for the first non-zero entry.
descriptor_addr += info->start;
- break;
+ entry_addr_ = (this->*read_descriptor_func_)(descriptor_addr);
+ if (entry_addr_ != 0) {
+ break;
+ }
}
}
-
- if (descriptor_addr == 0) {
- return;
- }
-
- entry_addr_ = (this->*read_descriptor_func_)(descriptor_addr);
}
Elf* JitDebug::GetElf(Maps* maps, uint64_t pc) {
diff --git a/libunwindstack/Unwinder.cpp b/libunwindstack/Unwinder.cpp
index b0a1c0c..d711772 100644
--- a/libunwindstack/Unwinder.cpp
+++ b/libunwindstack/Unwinder.cpp
@@ -40,6 +40,7 @@
frame->num = frame_num;
frame->sp = regs_->sp();
frame->rel_pc = adjusted_rel_pc;
+ frame->dex_pc = regs_->dex_pc();
if (map_info == nullptr) {
frame->pc = regs_->pc();
diff --git a/libunwindstack/include/unwindstack/DwarfLocation.h b/libunwindstack/include/unwindstack/DwarfLocation.h
index 3467e6a..0881182 100644
--- a/libunwindstack/include/unwindstack/DwarfLocation.h
+++ b/libunwindstack/include/unwindstack/DwarfLocation.h
@@ -38,7 +38,7 @@
uint64_t values[2];
};
-typedef std::unordered_map<uint16_t, DwarfLocation> dwarf_loc_regs_t;
+typedef std::unordered_map<uint32_t, DwarfLocation> dwarf_loc_regs_t;
} // namespace unwindstack
diff --git a/libunwindstack/include/unwindstack/DwarfSection.h b/libunwindstack/include/unwindstack/DwarfSection.h
index 10be6b4..e0004aa 100644
--- a/libunwindstack/include/unwindstack/DwarfSection.h
+++ b/libunwindstack/include/unwindstack/DwarfSection.h
@@ -132,6 +132,8 @@
const DwarfFde* GetFdeFromIndex(size_t index) override;
+ bool EvalRegister(const DwarfLocation* loc, uint32_t reg, AddressType* reg_ptr, void* info);
+
bool Eval(const DwarfCie* cie, Memory* regular_memory, const dwarf_loc_regs_t& loc_regs,
Regs* regs, bool* finished) override;
diff --git a/libunwindstack/include/unwindstack/Regs.h b/libunwindstack/include/unwindstack/Regs.h
index 1904d4d..a5ba7a0 100644
--- a/libunwindstack/include/unwindstack/Regs.h
+++ b/libunwindstack/include/unwindstack/Regs.h
@@ -57,6 +57,9 @@
virtual uint64_t pc() = 0;
virtual uint64_t sp() = 0;
+ uint64_t dex_pc() { return dex_pc_; }
+ void set_dex_pc(uint64_t dex_pc) { dex_pc_ = dex_pc; }
+
virtual uint64_t GetAdjustedPc(uint64_t rel_pc, Elf* elf) = 0;
virtual bool StepIfSignalHandler(uint64_t rel_pc, Elf* elf, Memory* process_memory) = 0;
@@ -79,6 +82,7 @@
uint16_t total_regs_;
uint16_t sp_reg_;
Location return_loc_;
+ uint64_t dex_pc_ = 0;
};
template <typename AddressType>
diff --git a/libunwindstack/include/unwindstack/Unwinder.h b/libunwindstack/include/unwindstack/Unwinder.h
index 5adec4f..32858ae 100644
--- a/libunwindstack/include/unwindstack/Unwinder.h
+++ b/libunwindstack/include/unwindstack/Unwinder.h
@@ -41,6 +41,7 @@
uint64_t rel_pc;
uint64_t pc;
uint64_t sp;
+ uint64_t dex_pc;
std::string function_name;
uint64_t function_offset;
diff --git a/libunwindstack/tests/DwarfSectionImplTest.cpp b/libunwindstack/tests/DwarfSectionImplTest.cpp
index d54b0bf..dfd2ce0 100644
--- a/libunwindstack/tests/DwarfSectionImplTest.cpp
+++ b/libunwindstack/tests/DwarfSectionImplTest.cpp
@@ -266,13 +266,67 @@
regs.set_pc(0x100);
regs.set_sp(0x2000);
+ regs[1] = 0x100;
+ regs[3] = 0x300;
regs[8] = 0x10;
loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
- loc_regs[1] = DwarfLocation{DWARF_LOCATION_REGISTER, {3, 0}};
- loc_regs[9] = DwarfLocation{DWARF_LOCATION_REGISTER, {1, 0}};
+ loc_regs[1] = DwarfLocation{DWARF_LOCATION_REGISTER, {3, 1}};
+ loc_regs[9] = DwarfLocation{DWARF_LOCATION_REGISTER, {1, 2}};
bool finished;
- ASSERT_FALSE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
- EXPECT_EQ(DWARF_ERROR_ILLEGAL_STATE, this->section_->last_error());
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_EQ(0x301U, regs[1]);
+ EXPECT_EQ(0x300U, regs[3]);
+ EXPECT_EQ(0x10U, regs[8]);
+ EXPECT_EQ(0x102U, regs[9]);
+}
+
+TYPED_TEST_P(DwarfSectionImplTest, Eval_register_reference_chain) {
+ DwarfCie cie{.return_address_register = 5};
+ RegsImplFake<TypeParam> regs(10, 9);
+ dwarf_loc_regs_t loc_regs;
+
+ regs.set_pc(0x100);
+ regs.set_sp(0x2000);
+ regs[0] = 0x10;
+ regs[1] = 0x20;
+ regs[2] = 0x30;
+ regs[3] = 0x40;
+ regs[4] = 0x50;
+ regs[5] = 0x60;
+ regs[8] = 0x20;
+ loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
+ loc_regs[1] = DwarfLocation{DWARF_LOCATION_REGISTER, {0, 1}};
+ loc_regs[2] = DwarfLocation{DWARF_LOCATION_REGISTER, {1, 2}};
+ loc_regs[3] = DwarfLocation{DWARF_LOCATION_REGISTER, {2, 3}};
+ loc_regs[4] = DwarfLocation{DWARF_LOCATION_REGISTER, {3, 4}};
+ loc_regs[5] = DwarfLocation{DWARF_LOCATION_REGISTER, {4, 5}};
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_EQ(0x10U, regs[0]);
+ EXPECT_EQ(0x11U, regs[1]);
+ EXPECT_EQ(0x22U, regs[2]);
+ EXPECT_EQ(0x33U, regs[3]);
+ EXPECT_EQ(0x44U, regs[4]);
+ EXPECT_EQ(0x55U, regs[5]);
+ EXPECT_EQ(0x20U, regs[8]);
+}
+
+TYPED_TEST_P(DwarfSectionImplTest, Eval_dex_pc) {
+ DwarfCie cie{.return_address_register = 5};
+ RegsImplFake<TypeParam> regs(10, 9);
+ dwarf_loc_regs_t loc_regs;
+
+ regs.set_pc(0x100);
+ regs.set_sp(0x2000);
+ regs[0] = 0x10;
+ regs[8] = 0x20;
+ loc_regs[CFA_REG] = DwarfLocation{DWARF_LOCATION_REGISTER, {8, 0}};
+ loc_regs[0x20444558] = DwarfLocation{DWARF_LOCATION_REGISTER, {0, 1}};
+ bool finished;
+ ASSERT_TRUE(this->section_->Eval(&cie, &this->memory_, loc_regs, ®s, &finished));
+ EXPECT_EQ(0x10U, regs[0]);
+ EXPECT_EQ(0x20U, regs[8]);
+ EXPECT_EQ(0x11U, regs.dex_pc());
}
TYPED_TEST_P(DwarfSectionImplTest, Eval_invalid_register) {
@@ -840,11 +894,11 @@
DwarfSectionImplTest, 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_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,
- GetCie_fail_should_not_cache, GetCie_32_version_check, GetCie_negative_data_alignment_factor,
- GetCie_64_no_augment, GetCie_augment, GetCie_version_3, GetCie_version_4,
- GetFdeFromOffset_fail_should_not_cache, GetFdeFromOffset_32_no_augment,
+ 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, GetCie_fail_should_not_cache, GetCie_32_version_check,
+ GetCie_negative_data_alignment_factor, GetCie_64_no_augment, GetCie_augment, GetCie_version_3,
+ GetCie_version_4, GetFdeFromOffset_fail_should_not_cache, GetFdeFromOffset_32_no_augment,
GetFdeFromOffset_32_no_augment_non_zero_segment_size, GetFdeFromOffset_32_augment,
GetFdeFromOffset_64_no_augment, GetFdeFromOffset_cached, GetCfaLocationInfo_cie_not_cached,
GetCfaLocationInfo_cie_cached, Log);
diff --git a/libunwindstack/tests/JitDebugTest.cpp b/libunwindstack/tests/JitDebugTest.cpp
index 83d7a49..1a50989 100644
--- a/libunwindstack/tests/JitDebugTest.cpp
+++ b/libunwindstack/tests/JitDebugTest.cpp
@@ -49,6 +49,7 @@
"a000-c000 --xp 00000000 00:00 0\n"
"c000-f000 rwxp 00000000 00:00 0\n"
"f000-11000 r-xp 00000000 00:00 0\n"
+ "12000-14000 r-xp 00000000 00:00 0\n"
"100000-110000 rw-p 0000000 00:00 0\n"
"200000-210000 rw-p 0000000 00:00 0\n"));
ASSERT_TRUE(maps_->Parse());
@@ -72,6 +73,16 @@
elf->FakeSetInterface(interface);
interface->FakeSetGlobalVariable("__jit_debug_descriptor", 0x800);
map_info->elf = elf;
+
+ map_info = maps_->Get(6);
+ ASSERT_TRUE(map_info != nullptr);
+ elf_memories_.push_back(new MemoryFake);
+ elf = new ElfFake(elf_memories_.back());
+ elf->FakeSetValid(true);
+ interface = new ElfInterfaceFake(elf_memories_.back());
+ elf->FakeSetInterface(interface);
+ interface->FakeSetGlobalVariable("__jit_debug_descriptor", 0x800);
+ map_info->elf = elf;
}
template <typename EhdrType, typename ShdrType>
@@ -293,6 +304,27 @@
EXPECT_EQ(elf, elf2);
}
+TEST_F(JitDebugTest, get_multiple_jit_debug_descriptors_valid) {
+ CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
+ CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x5000, ELFCLASS32, EM_ARM, 0x2000, 0x300);
+
+ WriteDescriptor32(0xf800, 0x200000);
+ WriteEntry32Pad(0x200000, 0, 0, 0x4000, 0x1000);
+ WriteDescriptor32(0x12800, 0x201000);
+ WriteEntry32Pad(0x201000, 0, 0, 0x5000, 0x1000);
+
+ ASSERT_TRUE(jit_debug_->GetElf(maps_.get(), 0x1500) != nullptr);
+ ASSERT_TRUE(jit_debug_->GetElf(maps_.get(), 0x2000) == nullptr);
+
+ // Now clear the descriptor entry for the first one.
+ WriteDescriptor32(0xf800, 0);
+ jit_debug_.reset(new JitDebug(process_memory_));
+ jit_debug_->SetArch(ARCH_ARM);
+
+ ASSERT_TRUE(jit_debug_->GetElf(maps_.get(), 0x1500) == nullptr);
+ ASSERT_TRUE(jit_debug_->GetElf(maps_.get(), 0x2000) != nullptr);
+}
+
TEST_F(JitDebugTest, get_elf_x86) {
CreateElf<Elf32_Ehdr, Elf32_Shdr>(0x4000, ELFCLASS32, EM_ARM, 0x1500, 0x200);
diff --git a/libunwindstack/tests/UnwindOfflineTest.cpp b/libunwindstack/tests/UnwindOfflineTest.cpp
index 9216204..582ac18 100644
--- a/libunwindstack/tests/UnwindOfflineTest.cpp
+++ b/libunwindstack/tests/UnwindOfflineTest.cpp
@@ -406,4 +406,223 @@
frame_info);
}
+TEST(UnwindOfflineTest, jit_debug_arm32) {
+ std::string dir(TestGetFileDirectory() + "offline/jit_debug_arm32/");
+
+ MemoryOfflineParts* memory = new MemoryOfflineParts;
+ AddMemory(dir + "descriptor.data", memory);
+ AddMemory(dir + "descriptor1.data", memory);
+ AddMemory(dir + "stack.data", memory);
+ for (size_t i = 0; i < 7; i++) {
+ AddMemory(dir + "entry" + std::to_string(i) + ".data", memory);
+ AddMemory(dir + "jit" + std::to_string(i) + ".data", memory);
+ }
+
+ FILE* fp = fopen((dir + "regs.txt").c_str(), "r");
+ ASSERT_TRUE(fp != nullptr);
+ RegsArm regs;
+ uint64_t reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r0: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R0] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r1: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R1] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r2: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R2] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r3: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R3] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r4: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R4] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r5: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R5] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r6: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R6] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r7: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R7] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r8: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R8] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r9: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R9] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r10: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R10] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "r11: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R11] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "ip: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_R12] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "sp: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_SP] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "lr: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_LR] = reg_value;
+ ASSERT_EQ(1, fscanf(fp, "pc: %" SCNx64 "\n", ®_value));
+ regs[ARM_REG_PC] = reg_value;
+ regs.SetFromRaw();
+ fclose(fp);
+
+ fp = fopen((dir + "maps.txt").c_str(), "r");
+ ASSERT_TRUE(fp != nullptr);
+ // The file is guaranteed to be less than 4096 bytes.
+ std::vector<char> buffer(4096);
+ ASSERT_NE(0U, fread(buffer.data(), 1, buffer.size(), fp));
+ fclose(fp);
+
+ BufferMaps maps(buffer.data());
+ ASSERT_TRUE(maps.Parse());
+
+ ASSERT_EQ(ARCH_ARM, regs.Arch());
+
+ std::shared_ptr<Memory> process_memory(memory);
+
+ char* cwd = getcwd(nullptr, 0);
+ ASSERT_EQ(0, chdir(dir.c_str()));
+ JitDebug jit_debug(process_memory);
+ Unwinder unwinder(128, &maps, ®s, process_memory);
+ unwinder.SetJitDebug(&jit_debug, regs.Arch());
+ unwinder.Unwind();
+ ASSERT_EQ(0, chdir(cwd));
+ free(cwd);
+
+ std::string frame_info(DumpFrames(unwinder));
+ ASSERT_EQ(76U, unwinder.NumFrames()) << "Unwind:\n" << frame_info;
+ EXPECT_EQ(
+ " #00 pc 00018a5e libarttestd.so (Java_Main_unwindInProcess+865)\n"
+ " #01 pc 0000212d (offset 0x2000) 137-cfi.odex (boolean Main.unwindInProcess(boolean, int, "
+ "boolean)+92)\n"
+ " #02 pc 00011cb1 anonymous:e2796000 (boolean Main.bar(boolean)+72)\n"
+ " #03 pc 00462175 libartd.so (art_quick_invoke_stub_internal+68)\n"
+ " #04 pc 00467129 libartd.so (art_quick_invoke_stub+228)\n"
+ " #05 pc 000bf7a9 libartd.so "
+ "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+864)\n"
+ " #06 pc 00247833 libartd.so "
+ "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+ "11ShadowFrameEtPNS_6JValueE+382)\n"
+ " #07 pc 0022e935 libartd.so "
+ "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+ "6JValueEb+244)\n"
+ " #08 pc 0022f71d libartd.so "
+ "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+ "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+ " #09 pc 00442865 libartd.so (artQuickToInterpreterBridge+796)\n"
+ " #10 pc 004666ff libartd.so (art_quick_to_interpreter_bridge+30)\n"
+ " #11 pc 00011c31 anonymous:e2796000 (int Main.compare(Main, Main)+64)\n"
+ " #12 pc 00462175 libartd.so (art_quick_invoke_stub_internal+68)\n"
+ " #13 pc 00467129 libartd.so (art_quick_invoke_stub+228)\n"
+ " #14 pc 000bf7a9 libartd.so "
+ "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+864)\n"
+ " #15 pc 00247833 libartd.so "
+ "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+ "11ShadowFrameEtPNS_6JValueE+382)\n"
+ " #16 pc 0022e935 libartd.so "
+ "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+ "6JValueEb+244)\n"
+ " #17 pc 0022f71d libartd.so "
+ "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+ "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+ " #18 pc 00442865 libartd.so (artQuickToInterpreterBridge+796)\n"
+ " #19 pc 004666ff libartd.so (art_quick_to_interpreter_bridge+30)\n"
+ " #20 pc 00011b77 anonymous:e2796000 (int Main.compare(java.lang.Object, "
+ "java.lang.Object)+118)\n"
+ " #21 pc 00462175 libartd.so (art_quick_invoke_stub_internal+68)\n"
+ " #22 pc 00467129 libartd.so (art_quick_invoke_stub+228)\n"
+ " #23 pc 000bf7a9 libartd.so "
+ "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+864)\n"
+ " #24 pc 00247833 libartd.so "
+ "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+ "11ShadowFrameEtPNS_6JValueE+382)\n"
+ " #25 pc 0022e935 libartd.so "
+ "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+ "6JValueEb+244)\n"
+ " #26 pc 0022f71d libartd.so "
+ "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+ "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+ " #27 pc 00442865 libartd.so (artQuickToInterpreterBridge+796)\n"
+ " #28 pc 004666ff libartd.so (art_quick_to_interpreter_bridge+30)\n"
+ " #29 pc 00011a29 anonymous:e2796000 (int "
+ "java.util.Arrays.binarySearch0(java.lang.Object[], int, int, java.lang.Object, "
+ "java.util.Comparator)+304)\n"
+ " #30 pc 00462175 libartd.so (art_quick_invoke_stub_internal+68)\n"
+ " #31 pc 0046722f libartd.so (art_quick_invoke_static_stub+226)\n"
+ " #32 pc 000bf7bb libartd.so "
+ "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+882)\n"
+ " #33 pc 00247833 libartd.so "
+ "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+ "11ShadowFrameEtPNS_6JValueE+382)\n"
+ " #34 pc 0022e935 libartd.so "
+ "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+ "6JValueEb+244)\n"
+ " #35 pc 0022f71d libartd.so "
+ "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+ "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+ " #36 pc 00442865 libartd.so (artQuickToInterpreterBridge+796)\n"
+ " #37 pc 004666ff libartd.so (art_quick_to_interpreter_bridge+30)\n"
+ " #38 pc 0001139b anonymous:e2796000 (boolean Main.foo()+178)\n"
+ " #39 pc 00462175 libartd.so (art_quick_invoke_stub_internal+68)\n"
+ " #40 pc 00467129 libartd.so (art_quick_invoke_stub+228)\n"
+ " #41 pc 000bf7a9 libartd.so "
+ "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+864)\n"
+ " #42 pc 00247833 libartd.so "
+ "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+ "11ShadowFrameEtPNS_6JValueE+382)\n"
+ " #43 pc 0022e935 libartd.so "
+ "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+ "6JValueEb+244)\n"
+ " #44 pc 0022f71d libartd.so "
+ "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+ "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+ " #45 pc 00442865 libartd.so (artQuickToInterpreterBridge+796)\n"
+ " #46 pc 004666ff libartd.so (art_quick_to_interpreter_bridge+30)\n"
+ " #47 pc 00010aa7 anonymous:e2796000 (void Main.runPrimary()+70)\n"
+ " #48 pc 00462175 libartd.so (art_quick_invoke_stub_internal+68)\n"
+ " #49 pc 00467129 libartd.so (art_quick_invoke_stub+228)\n"
+ " #50 pc 000bf7a9 libartd.so "
+ "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+864)\n"
+ " #51 pc 00247833 libartd.so "
+ "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+ "11ShadowFrameEtPNS_6JValueE+382)\n"
+ " #52 pc 0022e935 libartd.so "
+ "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+ "6JValueEb+244)\n"
+ " #53 pc 0022f71d libartd.so "
+ "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+ "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+ " #54 pc 00442865 libartd.so (artQuickToInterpreterBridge+796)\n"
+ " #55 pc 004666ff libartd.so (art_quick_to_interpreter_bridge+30)\n"
+ " #56 pc 0000ba99 anonymous:e2796000 (void Main.main(java.lang.String[])+144)\n"
+ " #57 pc 00462175 libartd.so (art_quick_invoke_stub_internal+68)\n"
+ " #58 pc 0046722f libartd.so (art_quick_invoke_static_stub+226)\n"
+ " #59 pc 000bf7bb libartd.so "
+ "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+882)\n"
+ " #60 pc 00247833 libartd.so "
+ "(_ZN3art11interpreter34ArtInterpreterToCompiledCodeBridgeEPNS_6ThreadEPNS_9ArtMethodEPNS_"
+ "11ShadowFrameEtPNS_6JValueE+382)\n"
+ " #61 pc 0022e935 libartd.so "
+ "(_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_"
+ "6JValueEb+244)\n"
+ " #62 pc 0022f71d libartd.so "
+ "(_ZN3art11interpreter30EnterInterpreterFromEntryPointEPNS_6ThreadERKNS_"
+ "20CodeItemDataAccessorEPNS_11ShadowFrameE+128)\n"
+ " #63 pc 00442865 libartd.so (artQuickToInterpreterBridge+796)\n"
+ " #64 pc 004666ff libartd.so (art_quick_to_interpreter_bridge+30)\n"
+ " #65 pc 00462175 libartd.so (art_quick_invoke_stub_internal+68)\n"
+ " #66 pc 0046722f libartd.so (art_quick_invoke_static_stub+226)\n"
+ " #67 pc 000bf7bb libartd.so "
+ "(_ZN3art9ArtMethod6InvokeEPNS_6ThreadEPjjPNS_6JValueEPKc+882)\n"
+ " #68 pc 003b292d libartd.so "
+ "(_ZN3artL18InvokeWithArgArrayERKNS_33ScopedObjectAccessAlreadyRunnableEPNS_9ArtMethodEPNS_"
+ "8ArgArrayEPNS_6JValueEPKc+52)\n"
+ " #69 pc 003b26c3 libartd.so "
+ "(_ZN3art17InvokeWithVarArgsERKNS_33ScopedObjectAccessAlreadyRunnableEP8_jobjectP10_"
+ "jmethodIDSt9__va_list+210)\n"
+ " #70 pc 00308411 libartd.so "
+ "(_ZN3art3JNI21CallStaticVoidMethodVEP7_JNIEnvP7_jclassP10_jmethodIDSt9__va_list+76)\n"
+ " #71 pc 000e6a9f libartd.so "
+ "(_ZN3art8CheckJNI11CallMethodVEPKcP7_JNIEnvP8_jobjectP7_jclassP10_jmethodIDSt9__va_listNS_"
+ "9Primitive4TypeENS_10InvokeTypeE+1486)\n"
+ " #72 pc 000e19b9 libartd.so "
+ "(_ZN3art8CheckJNI21CallStaticVoidMethodVEP7_JNIEnvP7_jclassP10_jmethodIDSt9__va_list+40)\n"
+ " #73 pc 0000159f dalvikvm32 "
+ "(_ZN7_JNIEnv20CallStaticVoidMethodEP7_jclassP10_jmethodIDz+30)\n"
+ " #74 pc 00001349 dalvikvm32 (main+896)\n"
+ " #75 pc 000850c9 libc.so\n",
+ frame_info);
+}
+
} // namespace unwindstack
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/137-cfi.odex b/libunwindstack/tests/files/offline/jit_debug_arm32/137-cfi.odex
new file mode 100644
index 0000000..35a6bc5
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/137-cfi.odex
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/dalvikvm32 b/libunwindstack/tests/files/offline/jit_debug_arm32/dalvikvm32
new file mode 100644
index 0000000..def299e
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/dalvikvm32
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor.data b/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor.data
new file mode 100644
index 0000000..7b876b5
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor1.data b/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor1.data
new file mode 100644
index 0000000..3c468d6
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/descriptor1.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry0.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry0.data
new file mode 100644
index 0000000..2c7689b
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry0.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry1.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry1.data
new file mode 100644
index 0000000..22a35b8
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry1.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry2.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry2.data
new file mode 100644
index 0000000..61f3927
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry2.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry3.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry3.data
new file mode 100644
index 0000000..1a37628
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry3.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry4.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry4.data
new file mode 100644
index 0000000..7ef62ca
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry4.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry5.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry5.data
new file mode 100644
index 0000000..6d27c89
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry5.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/entry6.data b/libunwindstack/tests/files/offline/jit_debug_arm32/entry6.data
new file mode 100644
index 0000000..bfbceea
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/entry6.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit0.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit0.data
new file mode 100644
index 0000000..b78848e
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit0.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit1.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit1.data
new file mode 100644
index 0000000..8f927ac
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit1.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit2.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit2.data
new file mode 100644
index 0000000..1d1dfca
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit2.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit3.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit3.data
new file mode 100644
index 0000000..89aeb43
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit3.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit4.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit4.data
new file mode 100644
index 0000000..e076934
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit4.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit5.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit5.data
new file mode 100644
index 0000000..17d6041
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit5.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/jit6.data b/libunwindstack/tests/files/offline/jit_debug_arm32/jit6.data
new file mode 100644
index 0000000..aaff037
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/jit6.data
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/libart.so b/libunwindstack/tests/files/offline/jit_debug_arm32/libart.so
new file mode 100644
index 0000000..0527893
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/libart.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/libartd.so b/libunwindstack/tests/files/offline/jit_debug_arm32/libartd.so
new file mode 100644
index 0000000..8559056
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/libartd.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/libarttestd.so b/libunwindstack/tests/files/offline/jit_debug_arm32/libarttestd.so
new file mode 100644
index 0000000..06dbf10
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/libarttestd.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/libc.so b/libunwindstack/tests/files/offline/jit_debug_arm32/libc.so
new file mode 100644
index 0000000..9894e66
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/libc.so
Binary files differ
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/maps.txt b/libunwindstack/tests/files/offline/jit_debug_arm32/maps.txt
new file mode 100644
index 0000000..f25c781
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/maps.txt
@@ -0,0 +1,8 @@
+ab0d3000-ab0d8000 r-xp 0 00:00 0 dalvikvm32
+dfe4e000-dfe7b000 r-xp 0 00:00 0 libarttestd.so
+e0447000-e0448000 r-xp 2000 00:00 0 137-cfi.odex
+e2796000-e4796000 r-xp 0 00:00 0 anonymous:e2796000
+e648e000-e690f000 r-xp 00000000 00:00 0 libart.so
+ed306000-ed801000 r-xp 0 00:00 0 libartd.so
+eda88000-edb23000 r-xp 0 00:00 0 libc.so
+ede4e000-ede50000 r-xp 0 00:00 0 anonymous:ede4e000
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/regs.txt b/libunwindstack/tests/files/offline/jit_debug_arm32/regs.txt
new file mode 100644
index 0000000..0e20066
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/regs.txt
@@ -0,0 +1,16 @@
+r0: dfe7c0f8
+r1: 0
+r2: 0
+r3: 40000000
+r4: e051ffb4
+r5: 0
+r6: e051ffc0
+r7: ede514e8
+r8: ff85d1a8
+r9: ed9210c0
+r10: 58
+r11: 0
+ip: edb26d04
+sp: ff85d180
+lr: edaff5af
+pc: dfe66a5e
diff --git a/libunwindstack/tests/files/offline/jit_debug_arm32/stack.data b/libunwindstack/tests/files/offline/jit_debug_arm32/stack.data
new file mode 100644
index 0000000..b2ff14e
--- /dev/null
+++ b/libunwindstack/tests/files/offline/jit_debug_arm32/stack.data
Binary files differ
diff --git a/libunwindstack/tools/unwind.cpp b/libunwindstack/tools/unwind.cpp
index 07e48af..33e5527 100644
--- a/libunwindstack/tools/unwind.cpp
+++ b/libunwindstack/tools/unwind.cpp
@@ -96,8 +96,13 @@
unwinder.Unwind();
// Print the frames.
+ const std::vector<unwindstack::FrameData>& frames = unwinder.frames();
for (size_t i = 0; i < unwinder.NumFrames(); i++) {
printf("%s\n", unwinder.FormatFrame(i).c_str());
+ const unwindstack::FrameData* frame = &frames[i];
+ if (frame->dex_pc != 0) {
+ printf(" dex pc %" PRIx64 "\n", frame->dex_pc);
+ }
}
}
diff --git a/libutils/Android.bp b/libutils/Android.bp
index 6b50f0c..3bca6c8 100644
--- a/libutils/Android.bp
+++ b/libutils/Android.bp
@@ -43,8 +43,8 @@
},
}
-cc_library {
- name: "libutils",
+cc_defaults {
+ name: "libutils_defaults",
vendor_available: true,
vndk: {
enabled: true,
@@ -52,29 +52,6 @@
},
host_supported: true,
- srcs: [
- "CallStack.cpp",
- "FileMap.cpp",
- "JenkinsHash.cpp",
- "NativeHandle.cpp",
- "Printer.cpp",
- "PropertyMap.cpp",
- "RefBase.cpp",
- "SharedBuffer.cpp",
- "Static.cpp",
- "StopWatch.cpp",
- "String8.cpp",
- "String16.cpp",
- "StrongPointer.cpp",
- "SystemClock.cpp",
- "Threads.cpp",
- "Timers.cpp",
- "Tokenizer.cpp",
- "Unicode.cpp",
- "VectorImpl.cpp",
- "misc.cpp",
- ],
-
cflags: ["-Wall", "-Werror"],
include_dirs: ["external/safe-iop/include"],
header_libs: [
@@ -96,14 +73,9 @@
target: {
android: {
- srcs: [
- "Trace.cpp",
- ],
-
cflags: ["-fvisibility=protected"],
shared_libs: [
- "libbacktrace",
"libcutils",
"libdl",
"libvndksupport",
@@ -113,12 +85,6 @@
misc_undefined: ["integer"],
},
},
- linux: {
- srcs: [
- "Looper.cpp",
- "ProcessCallStack.cpp",
- ],
- },
host: {
cflags: ["-DLIBUTILS_NATIVE=1"],
@@ -148,6 +114,75 @@
},
}
+cc_library {
+ name: "libutils",
+ defaults: ["libutils_defaults"],
+
+ srcs: [
+ "FileMap.cpp",
+ "JenkinsHash.cpp",
+ "NativeHandle.cpp",
+ "Printer.cpp",
+ "PropertyMap.cpp",
+ "RefBase.cpp",
+ "SharedBuffer.cpp",
+ "Static.cpp",
+ "StopWatch.cpp",
+ "String8.cpp",
+ "String16.cpp",
+ "StrongPointer.cpp",
+ "SystemClock.cpp",
+ "Threads.cpp",
+ "Timers.cpp",
+ "Tokenizer.cpp",
+ "Unicode.cpp",
+ "VectorImpl.cpp",
+ "misc.cpp",
+ ],
+
+ target: {
+ android: {
+ srcs: [
+ "Trace.cpp",
+ ],
+ },
+ linux: {
+ srcs: [
+ "Looper.cpp",
+ ],
+ },
+ },
+}
+
+cc_library {
+ name: "libutilscallstack",
+ defaults: ["libutils_defaults"],
+
+ srcs: [
+ "CallStack.cpp",
+ ],
+
+ arch: {
+ mips: {
+ cflags: ["-DALIGN_DOUBLE"],
+ },
+ },
+
+ target: {
+ android: {
+ shared_libs: [
+ "libutils",
+ "libbacktrace",
+ ],
+ },
+ linux: {
+ srcs: [
+ "ProcessCallStack.cpp",
+ ],
+ },
+ },
+}
+
// Include subdirectory makefiles
// ============================================================
diff --git a/logd/README.property b/logd/README.property
index de6767a..da5f96f 100644
--- a/logd/README.property
+++ b/logd/README.property
@@ -31,9 +31,9 @@
resist increasing the log buffer.
persist.logd.size.<buffer> number ro Size of the buffer for <buffer> log
ro.logd.size.<buffer> number svelte default for persist.logd.size.<buffer>
-ro.config.low_ram bool false if true, logd.statistics, logd.kernel
- default false, logd.size 64K instead
- of 256K.
+ro.config.low_ram bool false if true, logd.statistics,
+ ro.logd.kernel default false,
+ logd.size 64K instead of 256K.
persist.logd.filter string Pruning filter to optimize content.
At runtime use: logcat -P "<string>"
ro.logd.filter string "~! ~1000/!" default for persist.logd.filter.
diff --git a/logd/main.cpp b/logd/main.cpp
index c8183f0..4af0d21 100644
--- a/logd/main.cpp
+++ b/logd/main.cpp
@@ -438,8 +438,8 @@
int fdPmesg = -1;
bool klogd = __android_logger_property_get_bool(
- "logd.kernel", BOOL_DEFAULT_TRUE | BOOL_DEFAULT_FLAG_PERSIST |
- BOOL_DEFAULT_FLAG_ENG | BOOL_DEFAULT_FLAG_SVELTE);
+ "ro.logd.kernel",
+ BOOL_DEFAULT_TRUE | BOOL_DEFAULT_FLAG_ENG | BOOL_DEFAULT_FLAG_SVELTE);
if (klogd) {
static const char proc_kmsg[] = "/proc/kmsg";
fdPmesg = android_get_control_file(proc_kmsg);
diff --git a/property_service/libpropertyinfoserializer/property_info_file.cpp b/property_service/libpropertyinfoserializer/property_info_file.cpp
index bf96d88..2cdc62d 100644
--- a/property_service/libpropertyinfoserializer/property_info_file.cpp
+++ b/property_service/libpropertyinfoserializer/property_info_file.cpp
@@ -1,9 +1,26 @@
+//
+// Copyright (C) 2017 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 <property_info_serializer/property_info_serializer.h>
#include <android-base/strings.h>
#include "space_tokenizer.h"
+using android::base::Join;
using android::base::Split;
using android::base::StartsWith;
using android::base::Trim;
@@ -11,6 +28,34 @@
namespace android {
namespace properties {
+namespace {
+
+bool IsTypeValid(const std::vector<std::string>& type_strings) {
+ if (type_strings.empty()) {
+ return false;
+ }
+
+ // There must be at least one string following 'enum'
+ if (type_strings[0] == "enum") {
+ return type_strings.size() > 1;
+ }
+
+ // There should not be any string following any other types.
+ if (type_strings.size() != 1) {
+ return false;
+ }
+
+ // Check that the type matches one of remaining valid types.
+ static const char* const no_parameter_types[] = {"string", "bool", "int",
+ "uint", "double", "size"};
+ for (const auto& type : no_parameter_types) {
+ if (type_strings[0] == type) {
+ return true;
+ }
+ }
+ return false;
+}
+
bool ParsePropertyInfoLine(const std::string& line, PropertyInfoEntry* out, std::string* error) {
auto tokenizer = SpaceTokenizer(line);
@@ -26,14 +71,28 @@
return false;
}
- // It is not an error to not find these, as older files will not contain them.
+ // It is not an error to not find exact_match or a type, as older files will not contain them.
auto exact_match = tokenizer.GetNext();
- auto type = tokenizer.GetRemaining();
+ // We reformat type to be space deliminated regardless of the input whitespace for easier storage
+ // and subsequent parsing.
+ auto type_strings = std::vector<std::string>{};
+ auto type = tokenizer.GetNext();
+ while (!type.empty()) {
+ type_strings.emplace_back(type);
+ type = tokenizer.GetNext();
+ }
- *out = {property, context, type, exact_match == "exact"};
+ if (!type_strings.empty() && !IsTypeValid(type_strings)) {
+ *error = "Type '" + Join(type_strings, " ") + "' is not valid";
+ return false;
+ }
+
+ *out = {property, context, Join(type_strings, " "), exact_match == "exact"};
return true;
}
+} // namespace
+
void ParsePropertyInfoFile(const std::string& file_contents,
std::vector<PropertyInfoEntry>* property_infos,
std::vector<std::string>* errors) {
diff --git a/rootdir/Android.mk b/rootdir/Android.mk
index 7804f6d..ca992d6 100644
--- a/rootdir/Android.mk
+++ b/rootdir/Android.mk
@@ -135,12 +135,71 @@
)
endef
+# Update namespace configuration file with library lists and VNDK version
+#
+# $(1): Input source file (ld.config.txt)
+# $(2): Output built module
+# $(3): VNDK version suffix
+define update_and_install_ld_config
+llndk_libraries := $(call normalize-path-list,$(addsuffix .so,\
+ $(filter-out $(VNDK_PRIVATE_LIBRARIES),$(LLNDK_LIBRARIES))))
+private_llndk_libraries := $(call normalize-path-list,$(addsuffix .so,\
+ $(filter $(VNDK_PRIVATE_LIBRARIES),$(LLNDK_LIBRARIES))))
+vndk_sameprocess_libraries := $(call normalize-path-list,$(addsuffix .so,\
+ $(filter-out $(VNDK_PRIVATE_LIBRARIES),$(VNDK_SAMEPROCESS_LIBRARIES))))
+vndk_core_libraries := $(call normalize-path-list,$(addsuffix .so,\
+ $(filter-out $(VNDK_PRIVATE_LIBRARIES),$(VNDK_CORE_LIBRARIES))))
+sanitizer_runtime_libraries := $(call normalize-path-list,$(addsuffix .so,\
+ $(ADDRESS_SANITIZER_RUNTIME_LIBRARY) \
+ $(UBSAN_RUNTIME_LIBRARY) \
+ $(TSAN_RUNTIME_LIBRARY) \
+ $(2ND_ADDRESS_SANITIZER_RUNTIME_LIBRARY) \
+ $(2ND_UBSAN_RUNTIME_LIBRARY) \
+ $(2ND_TSAN_RUNTIME_LIBRARY)))
+# If BOARD_VNDK_VERSION is not defined, VNDK version suffix will not be used.
+vndk_version_suffix := $(if $(strip $(3)),-$(strip $(3)))
+
+$(2): PRIVATE_LLNDK_LIBRARIES := $$(llndk_libraries)
+$(2): PRIVATE_PRIVATE_LLNDK_LIBRARIES := $$(private_llndk_libraries)
+$(2): PRIVATE_VNDK_SAMEPROCESS_LIBRARIES := $$(vndk_sameprocess_libraries)
+$(2): PRIVATE_VNDK_CORE_LIBRARIES := $$(vndk_core_libraries)
+$(2): PRIVATE_SANITIZER_RUNTIME_LIBRARIES := $$(sanitizer_runtime_libraries)
+$(2): PRIVATE_VNDK_VERSION := $$(vndk_version_suffix)
+$(2): $(1)
+ @echo "Generate: $$< -> $$@"
+ @mkdir -p $$(dir $$@)
+ $$(hide) sed -e 's?%LLNDK_LIBRARIES%?$$(PRIVATE_LLNDK_LIBRARIES)?g' $$< >$$@
+ $$(hide) sed -i -e 's?%PRIVATE_LLNDK_LIBRARIES%?$$(PRIVATE_PRIVATE_LLNDK_LIBRARIES)?g' $$@
+ $$(hide) sed -i -e 's?%VNDK_SAMEPROCESS_LIBRARIES%?$$(PRIVATE_VNDK_SAMEPROCESS_LIBRARIES)?g' $$@
+ $$(hide) sed -i -e 's?%VNDK_CORE_LIBRARIES%?$$(PRIVATE_VNDK_CORE_LIBRARIES)?g' $$@
+ $$(hide) sed -i -e 's?%SANITIZER_RUNTIME_LIBRARIES%?$$(PRIVATE_SANITIZER_RUNTIME_LIBRARIES)?g' $$@
+ $$(hide) sed -i -e 's?%VNDK_VER%?$$(PRIVATE_VNDK_VERSION)?g' $$@
+
+llndk_libraries :=
+private_llndk_libraries :=
+vndk_sameprocess_libraries :=
+vndk_core_libraries :=
+sanitizer_runtime_libraries :=
+vndk_version_suffix :=
+endef # update_and_install_ld_config
+
#######################################
# ld.config.txt
+#
+# For VNDK enforced devices that have defined BOARD_VNDK_VERSION, use
+# "ld.config.txt.in" as a source file. This configuration includes strict VNDK
+# run-time restrictions for vendor process.
+# Other treblized devices, that have not defined BOARD_VNDK_VERSION or that
+# have set BOARD_VNDK_RUNTIME_DISABLE to true, use "ld.config.txt" as a source
+# file. This configuration does not have strict VNDK run-time restrictions.
+# If the device is not treblized, use "ld.config.legacy.txt" for legacy
+# namespace configuration.
include $(CLEAR_VARS)
+LOCAL_MODULE := ld.config.txt
+LOCAL_MODULE_CLASS := ETC
+LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
_enforce_vndk_at_runtime := false
-
ifdef BOARD_VNDK_VERSION
ifneq ($(BOARD_VNDK_RUNTIME_DISABLE),true)
_enforce_vndk_at_runtime := true
@@ -148,65 +207,52 @@
endif
ifeq ($(_enforce_vndk_at_runtime),true)
-LOCAL_MODULE := ld.config.txt
-LOCAL_MODULE_CLASS := ETC
-LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
+# for VNDK enforced devices
LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
include $(BUILD_SYSTEM)/base_rules.mk
+$(eval $(call update_and_install_ld_config,\
+ $(LOCAL_PATH)/etc/ld.config.txt.in,\
+ $(LOCAL_BUILT_MODULE),\
+ $(PLATFORM_VNDK_VERSION)))
-llndk_libraries := $(call normalize-path-list,$(addsuffix .so,\
-$(filter-out $(VNDK_PRIVATE_LIBRARIES),$(LLNDK_LIBRARIES))))
+else ifeq ($(PRODUCT_TREBLE_LINKER_NAMESPACES)|$(SANITIZE_TARGET),true|)
+# for treblized but VNDK non-enforced devices
+LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
+include $(BUILD_SYSTEM)/base_rules.mk
+$(eval $(call update_and_install_ld_config,\
+ $(LOCAL_PATH)/etc/ld.config.txt,\
+ $(LOCAL_BUILT_MODULE),\
+ $(if $(BOARD_VNDK_VERSION),$(PLATFORM_VNDK_VERSION))))
-private_llndk_libraries := $(call normalize-path-list,$(addsuffix .so,\
-$(filter $(VNDK_PRIVATE_LIBRARIES),$(LLNDK_LIBRARIES))))
-
-vndk_sameprocess_libraries := $(call normalize-path-list,$(addsuffix .so,\
-$(filter-out $(VNDK_PRIVATE_LIBRARIES),$(VNDK_SAMEPROCESS_LIBRARIES))))
-
-vndk_core_libraries := $(call normalize-path-list,$(addsuffix .so,\
-$(filter-out $(VNDK_PRIVATE_LIBRARIES),$(VNDK_CORE_LIBRARIES))))
-
-sanitizer_runtime_libraries := $(call normalize-path-list,$(addsuffix .so,\
-$(ADDRESS_SANITIZER_RUNTIME_LIBRARY) \
-$(UBSAN_RUNTIME_LIBRARY) \
-$(TSAN_RUNTIME_LIBRARY) \
-$(2ND_ADDRESS_SANITIZER_RUNTIME_LIBRARY) \
-$(2ND_UBSAN_RUNTIME_LIBRARY) \
-$(2ND_TSAN_RUNTIME_LIBRARY)))
-
-$(LOCAL_BUILT_MODULE): PRIVATE_LLNDK_LIBRARIES := $(llndk_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_PRIVATE_LLNDK_LIBRARIES := $(private_llndk_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_VNDK_SAMEPROCESS_LIBRARIES := $(vndk_sameprocess_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_LLNDK_PRIVATE_LIBRARIES := $(llndk_private_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_VNDK_CORE_LIBRARIES := $(vndk_core_libraries)
-$(LOCAL_BUILT_MODULE): PRIVATE_SANITIZER_RUNTIME_LIBRARIES := $(sanitizer_runtime_libraries)
-$(LOCAL_BUILT_MODULE): $(LOCAL_PATH)/etc/ld.config.txt.in
- @echo "Generate: $< -> $@"
- @mkdir -p $(dir $@)
- $(hide) sed -e 's?%LLNDK_LIBRARIES%?$(PRIVATE_LLNDK_LIBRARIES)?g' $< >$@
- $(hide) sed -i -e 's?%PRIVATE_LLNDK_LIBRARIES%?$(PRIVATE_PRIVATE_LLNDK_LIBRARIES)?g' $@
- $(hide) sed -i -e 's?%VNDK_SAMEPROCESS_LIBRARIES%?$(PRIVATE_VNDK_SAMEPROCESS_LIBRARIES)?g' $@
- $(hide) sed -i -e 's?%VNDK_CORE_LIBRARIES%?$(PRIVATE_VNDK_CORE_LIBRARIES)?g' $@
- $(hide) sed -i -e 's?%SANITIZER_RUNTIME_LIBRARIES%?$(PRIVATE_SANITIZER_RUNTIME_LIBRARIES)?g' $@
-
-llndk_libraries :=
-vndk_sameprocess_libraries :=
-vndk_core_libraries :=
-sanitizer_runtime_libraries :=
-else # if _enforce_vndk_at_runtime is not true
-
-LOCAL_MODULE := ld.config.txt
-ifeq ($(PRODUCT_TREBLE_LINKER_NAMESPACES)|$(SANITIZE_TARGET),true|)
- LOCAL_SRC_FILES := etc/ld.config.txt
- LOCAL_MODULE_STEM := $(call append_vndk_version,$(LOCAL_MODULE))
else
- LOCAL_SRC_FILES := etc/ld.config.legacy.txt
- LOCAL_MODULE_STEM := $(LOCAL_MODULE)
-endif
+# for legacy non-treblized devices
+LOCAL_SRC_FILES := etc/ld.config.legacy.txt
+LOCAL_MODULE_STEM := $(LOCAL_MODULE)
+include $(BUILD_PREBUILT)
+
+endif # if _enforce_vndk_at_runtime is true
+
+_enforce_vndk_at_runtime :=
+
+#######################################
+# ld.config.noenforce.txt
+#
+# This file is a temporary configuration file only for GSI. Originally GSI has
+# BOARD_VNDK_VERSION defined and has strict VNDK enforcing rule based on
+# "ld.config.txt.in". However for the devices, that have not defined
+# BOARD_VNDK_VERSION, GSI provides this configuration file which is based on
+# "ld.config.txt".
+# Do not install this file for the devices other than GSI.
+include $(CLEAR_VARS)
+LOCAL_MODULE := ld.config.noenforce.txt
LOCAL_MODULE_CLASS := ETC
LOCAL_MODULE_PATH := $(TARGET_OUT_ETC)
-include $(BUILD_PREBUILT)
-endif
+LOCAL_MODULE_STEM := $(LOCAL_MODULE)
+include $(BUILD_SYSTEM)/base_rules.mk
+$(eval $(call update_and_install_ld_config,\
+ $(LOCAL_PATH)/etc/ld.config.txt,\
+ $(LOCAL_BUILT_MODULE),\
+ $(PLATFORM_VNDK_VERSION)))
#######################################
# llndk.libraries.txt
diff --git a/rootdir/OWNERS b/rootdir/OWNERS
index f335715..6029ae7 100644
--- a/rootdir/OWNERS
+++ b/rootdir/OWNERS
@@ -1,3 +1,4 @@
+jeffv@google.com
jiyong@google.com
smoreland@google.com
tomcherry@google.com
diff --git a/rootdir/etc/ld.config.txt b/rootdir/etc/ld.config.txt
index b86104d..5d97a73 100644
--- a/rootdir/etc/ld.config.txt
+++ b/rootdir/etc/ld.config.txt
@@ -128,7 +128,7 @@
namespace.rs.search.paths = /odm/${LIB}/vndk-sp
namespace.rs.search.paths += /vendor/${LIB}/vndk-sp
-namespace.rs.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.rs.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
namespace.rs.search.paths += /odm/${LIB}
namespace.rs.search.paths += /vendor/${LIB}
@@ -140,8 +140,8 @@
namespace.rs.asan.search.paths += /odm/${LIB}/vndk-sp
namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
namespace.rs.asan.search.paths += /vendor/${LIB}/vndk-sp
-namespace.rs.asan.search.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.rs.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.rs.asan.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
namespace.rs.asan.search.paths += /data/asan/odm/${LIB}
namespace.rs.asan.search.paths += /odm/${LIB}
namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}
@@ -198,7 +198,7 @@
namespace.vndk.search.paths = /odm/${LIB}/vndk-sp
namespace.vndk.search.paths += /vendor/${LIB}/vndk-sp
-namespace.vndk.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
namespace.vndk.permitted.paths = /odm/${LIB}/hw
namespace.vndk.permitted.paths += /odm/${LIB}/egl
@@ -209,8 +209,8 @@
namespace.vndk.asan.search.paths += /odm/${LIB}/vndk-sp
namespace.vndk.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
namespace.vndk.asan.search.paths += /vendor/${LIB}/vndk-sp
-namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.vndk.asan.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
namespace.vndk.asan.permitted.paths = /data/asan/odm/${LIB}/hw
namespace.vndk.asan.permitted.paths += /odm/${LIB}/hw
@@ -254,8 +254,8 @@
namespace.default.search.paths += /vendor/${LIB}/vndk-sp
# Access to system libraries are allowed
-namespace.default.search.paths += /system/${LIB}/vndk${VNDK_VER}
-namespace.default.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.default.search.paths += /system/${LIB}/vndk%VNDK_VER%
+namespace.default.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
namespace.default.search.paths += /system/${LIB}
namespace.default.asan.search.paths = /data/asan/odm/${LIB}
@@ -270,9 +270,9 @@
namespace.default.asan.search.paths += /vendor/${LIB}/vndk
namespace.default.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
namespace.default.asan.search.paths += /vendor/${LIB}/vndk-sp
-namespace.default.asan.search.paths += /data/asan/system/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths += /system/${LIB}/vndk${VNDK_VER}
-namespace.default.asan.search.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.default.asan.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.default.asan.search.paths += /data/asan/system/${LIB}/vndk%VNDK_VER%
+namespace.default.asan.search.paths += /system/${LIB}/vndk%VNDK_VER%
+namespace.default.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.default.asan.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
namespace.default.asan.search.paths += /data/asan/system/${LIB}
namespace.default.asan.search.paths += /system/${LIB}
diff --git a/rootdir/etc/ld.config.txt.in b/rootdir/etc/ld.config.txt.in
index ffc4359..cad09c3 100644
--- a/rootdir/etc/ld.config.txt.in
+++ b/rootdir/etc/ld.config.txt.in
@@ -131,7 +131,7 @@
namespace.rs.search.paths = /odm/${LIB}/vndk-sp
namespace.rs.search.paths += /vendor/${LIB}/vndk-sp
-namespace.rs.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.rs.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
namespace.rs.search.paths += /odm/${LIB}
namespace.rs.search.paths += /vendor/${LIB}
@@ -143,8 +143,8 @@
namespace.rs.asan.search.paths += /odm/${LIB}/vndk-sp
namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
namespace.rs.asan.search.paths += /vendor/${LIB}/vndk-sp
-namespace.rs.asan.search.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.rs.asan.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.rs.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.rs.asan.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
namespace.rs.asan.search.paths += /data/asan/odm/${LIB}
namespace.rs.asan.search.paths += /odm/${LIB}
namespace.rs.asan.search.paths += /data/asan/vendor/${LIB}
@@ -176,21 +176,21 @@
namespace.vndk.search.paths = /odm/${LIB}/vndk-sp
namespace.vndk.search.paths += /vendor/${LIB}/vndk-sp
-namespace.vndk.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
namespace.vndk.permitted.paths = /odm/${LIB}/hw
namespace.vndk.permitted.paths += /odm/${LIB}/egl
namespace.vndk.permitted.paths += /vendor/${LIB}/hw
namespace.vndk.permitted.paths += /vendor/${LIB}/egl
# This is exceptionally required since android.hidl.memory@1.0-impl.so is here
-namespace.vndk.permitted.paths += /system/${LIB}/vndk-sp${VNDK_VER}/hw
+namespace.vndk.permitted.paths += /system/${LIB}/vndk-sp%VNDK_VER%/hw
namespace.vndk.asan.search.paths = /data/asan/odm/${LIB}/vndk-sp
namespace.vndk.asan.search.paths += /odm/${LIB}/vndk-sp
namespace.vndk.asan.search.paths += /data/asan/vendor/${LIB}/vndk-sp
namespace.vndk.asan.search.paths += /vendor/${LIB}/vndk-sp
-namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
+namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.vndk.asan.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
namespace.vndk.asan.permitted.paths = /data/asan/odm/${LIB}/hw
namespace.vndk.asan.permitted.paths += /odm/${LIB}/hw
@@ -201,8 +201,8 @@
namespace.vndk.asan.permitted.paths += /data/asan/vendor/${LIB}/egl
namespace.vndk.asan.permitted.paths += /vendor/${LIB}/egl
-namespace.vndk.asan.permitted.paths += /data/asan/system/${LIB}/vndk-sp${VNDK_VER}/hw
-namespace.vndk.asan.permitted.paths += /system/${LIB}/vndk-sp${VNDK_VER}/hw
+namespace.vndk.asan.permitted.paths += /data/asan/system/${LIB}/vndk-sp%VNDK_VER%/hw
+namespace.vndk.asan.permitted.paths += /system/${LIB}/vndk-sp%VNDK_VER%/hw
# When these NDK libs are required inside this namespace, then it is redirected
# to the default namespace. This is possible since their ABI is stable across
@@ -274,13 +274,13 @@
###############################################################################
namespace.vndk.isolated = false
-namespace.vndk.search.paths = /system/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.search.paths += /system/${LIB}/vndk${VNDK_VER}
+namespace.vndk.search.paths = /system/${LIB}/vndk-sp%VNDK_VER%
+namespace.vndk.search.paths += /system/${LIB}/vndk%VNDK_VER%
-namespace.vndk.asan.search.paths = /data/asan/system/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths += /system/${LIB}/vndk-sp${VNDK_VER}
-namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk${VNDK_VER}
-namespace.vndk.asan.search.paths += /system/${LIB}/vndk${VNDK_VER}
+namespace.vndk.asan.search.paths = /data/asan/system/${LIB}/vndk-sp%VNDK_VER%
+namespace.vndk.asan.search.paths += /system/${LIB}/vndk-sp%VNDK_VER%
+namespace.vndk.asan.search.paths += /data/asan/system/${LIB}/vndk%VNDK_VER%
+namespace.vndk.asan.search.paths += /system/${LIB}/vndk%VNDK_VER%
# When these NDK libs are required inside this namespace, then it is redirected
# to the system namespace. This is possible since their ABI is stable across
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 6fc3fe7..6a1872f 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -218,6 +218,12 @@
# This is needed by any process that uses socket tagging.
chmod 0644 /dev/xt_qtaguid
+ mkdir /dev/cg2_bpf
+ mount cgroup2 cg2_bpf /dev/cg2_bpf
+ chown root root /dev/cg2_bpf
+ chmod 0600 /dev/cg2_bpf
+ mount bpf bpf /sys/fs/bpf
+
# Create location for fs_mgr to store abbreviated output from filesystem
# checker programs.
mkdir /dev/fscklogs 0770 root system
@@ -462,6 +468,8 @@
mkdir /data/app 0771 system system
mkdir /data/property 0700 root root
mkdir /data/tombstones 0771 system system
+ mkdir /data/vendor/tombstones 0771 root root
+ mkdir /data/vendor/tombstones/wifi 0771 wifi wifi
# create dalvik-cache, so as to enforce our permissions
mkdir /data/dalvik-cache 0771 root root
diff --git a/sdcard/Android.bp b/sdcard/Android.bp
new file mode 100644
index 0000000..c096587
--- /dev/null
+++ b/sdcard/Android.bp
@@ -0,0 +1,17 @@
+cc_binary {
+ srcs: ["sdcard.cpp"],
+ name: "sdcard",
+ cflags: [
+ "-Wall",
+ "-Wno-unused-parameter",
+ "-Werror",
+ ],
+ shared_libs: [
+ "libbase",
+ "libcutils",
+ "libminijail",
+ ],
+ sanitize: {
+ misc_undefined: ["integer"],
+ },
+}
diff --git a/sdcard/Android.mk b/sdcard/Android.mk
deleted file mode 100644
index 5b4dc58..0000000
--- a/sdcard/Android.mk
+++ /dev/null
@@ -1,12 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := sdcard.cpp fuse.cpp
-LOCAL_MODULE := sdcard
-LOCAL_CFLAGS := -Wall -Wno-unused-parameter -Werror
-LOCAL_SHARED_LIBRARIES := libbase libcutils libminijail libpackagelistparser
-
-LOCAL_SANITIZE := integer
-
-include $(BUILD_EXECUTABLE)
diff --git a/sdcard/fuse.cpp b/sdcard/fuse.cpp
deleted file mode 100644
index 10d0f04..0000000
--- a/sdcard/fuse.cpp
+++ /dev/null
@@ -1,1476 +0,0 @@
-/*
- * Copyright (C) 2010 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 <errno.h>
-#include <string.h>
-#include <unistd.h>
-
-#define LOG_TAG "sdcard"
-
-#include "fuse.h"
-
-#include <android-base/logging.h>
-
-/* FUSE_CANONICAL_PATH is not currently upstreamed */
-#define FUSE_CANONICAL_PATH 2016
-
-#define FUSE_UNKNOWN_INO 0xffffffff
-
-/* Pseudo-error constant used to indicate that no fuse status is needed
- * or that a reply has already been written. */
-#define NO_STATUS 1
-
-static inline void *id_to_ptr(__u64 nid)
-{
- return (void *) (uintptr_t) nid;
-}
-
-static inline __u64 ptr_to_id(void *ptr)
-{
- return (__u64) (uintptr_t) ptr;
-}
-
-static void acquire_node_locked(struct node* node)
-{
- node->refcount++;
- DLOG(INFO) << "ACQUIRE " << std::hex << node << std::dec
- << " (" << node->name << ") rc=" << node->refcount;
-}
-
-static void remove_node_from_parent_locked(struct node* node);
-
-static void release_node_locked(struct node* node)
-{
- DLOG(INFO) << "RELEASE " << std::hex << node << std::dec
- << " (" << node->name << ") rc=" << node->refcount;
- if (node->refcount > 0) {
- node->refcount--;
- if (!node->refcount) {
- DLOG(INFO) << "DESTROY " << std::hex << node << std::dec << " (" << node->name << ")";
- remove_node_from_parent_locked(node);
-
- /* TODO: remove debugging - poison memory */
- memset(node->name, 0xef, node->namelen);
- free(node->name);
- free(node->actual_name);
- memset(node, 0xfc, sizeof(*node));
- free(node);
- }
- } else {
- LOG(ERROR) << std::hex << node << std::dec << " refcount=0";
- }
-}
-
-static void add_node_to_parent_locked(struct node *node, struct node *parent) {
- node->parent = parent;
- node->next = parent->child;
- parent->child = node;
- acquire_node_locked(parent);
-}
-
-static void remove_node_from_parent_locked(struct node* node)
-{
- if (node->parent) {
- if (node->parent->child == node) {
- node->parent->child = node->parent->child->next;
- } else {
- struct node *node2;
- node2 = node->parent->child;
- while (node2->next != node)
- node2 = node2->next;
- node2->next = node->next;
- }
- release_node_locked(node->parent);
- node->parent = NULL;
- node->next = NULL;
- }
-}
-
-/* Gets the absolute path to a node into the provided buffer.
- *
- * Populates 'buf' with the path and returns the length of the path on success,
- * or returns -1 if the path is too long for the provided buffer.
- */
-static ssize_t get_node_path_locked(struct node* node, char* buf, size_t bufsize) {
- const char* name;
- size_t namelen;
- if (node->graft_path) {
- name = node->graft_path;
- namelen = node->graft_pathlen;
- } else if (node->actual_name) {
- name = node->actual_name;
- namelen = node->namelen;
- } else {
- name = node->name;
- namelen = node->namelen;
- }
-
- if (bufsize < namelen + 1) {
- return -1;
- }
-
- ssize_t pathlen = 0;
- if (node->parent && node->graft_path == NULL) {
- pathlen = get_node_path_locked(node->parent, buf, bufsize - namelen - 1);
- if (pathlen < 0) {
- return -1;
- }
- buf[pathlen++] = '/';
- }
-
- memcpy(buf + pathlen, name, namelen + 1); /* include trailing \0 */
- return pathlen + namelen;
-}
-
-/* Finds the absolute path of a file within a given directory.
- * Performs a case-insensitive search for the file and sets the buffer to the path
- * of the first matching file. If 'search' is zero or if no match is found, sets
- * the buffer to the path that the file would have, assuming the name were case-sensitive.
- *
- * Populates 'buf' with the path and returns the actual name (within 'buf') on success,
- * or returns NULL if the path is too long for the provided buffer.
- */
-static char* find_file_within(const char* path, const char* name,
- char* buf, size_t bufsize, int search)
-{
- size_t pathlen = strlen(path);
- size_t namelen = strlen(name);
- size_t childlen = pathlen + namelen + 1;
- char* actual;
-
- if (bufsize <= childlen) {
- return NULL;
- }
-
- memcpy(buf, path, pathlen);
- buf[pathlen] = '/';
- actual = buf + pathlen + 1;
- memcpy(actual, name, namelen + 1);
-
- if (search && access(buf, F_OK)) {
- struct dirent* entry;
- DIR* dir = opendir(path);
- if (!dir) {
- PLOG(ERROR) << "opendir(" << path << ") failed";
- return actual;
- }
- while ((entry = readdir(dir))) {
- if (!strcasecmp(entry->d_name, name)) {
- /* we have a match - replace the name, don't need to copy the null again */
- memcpy(actual, entry->d_name, namelen);
- break;
- }
- }
- closedir(dir);
- }
- return actual;
-}
-
-static void attr_from_stat(struct fuse* fuse, struct fuse_attr *attr,
- const struct stat *s, const struct node* node) {
- attr->ino = node->ino;
- attr->size = s->st_size;
- attr->blocks = s->st_blocks;
- attr->atime = s->st_atim.tv_sec;
- attr->mtime = s->st_mtim.tv_sec;
- attr->ctime = s->st_ctim.tv_sec;
- attr->atimensec = s->st_atim.tv_nsec;
- attr->mtimensec = s->st_mtim.tv_nsec;
- attr->ctimensec = s->st_ctim.tv_nsec;
- attr->mode = s->st_mode;
- attr->nlink = s->st_nlink;
-
- attr->uid = node->uid;
-
- if (fuse->gid == AID_SDCARD_RW) {
- /* As an optimization, certain trusted system components only run
- * as owner but operate across all users. Since we're now handing
- * out the sdcard_rw GID only to trusted apps, we're okay relaxing
- * the user boundary enforcement for the default view. The UIDs
- * assigned to app directories are still multiuser aware. */
- attr->gid = AID_SDCARD_RW;
- } else {
- attr->gid = multiuser_get_uid(node->userid, fuse->gid);
- }
-
- int visible_mode = 0775 & ~fuse->mask;
- if (node->perm == PERM_PRE_ROOT) {
- /* Top of multi-user view should always be visible to ensure
- * secondary users can traverse inside. */
- visible_mode = 0711;
- } else if (node->under_android) {
- /* Block "other" access to Android directories, since only apps
- * belonging to a specific user should be in there; we still
- * leave +x open for the default view. */
- if (fuse->gid == AID_SDCARD_RW) {
- visible_mode = visible_mode & ~0006;
- } else {
- visible_mode = visible_mode & ~0007;
- }
- }
- int owner_mode = s->st_mode & 0700;
- int filtered_mode = visible_mode & (owner_mode | (owner_mode >> 3) | (owner_mode >> 6));
- attr->mode = (attr->mode & S_IFMT) | filtered_mode;
-}
-
-static int touch(char* path, mode_t mode) {
- int fd = TEMP_FAILURE_RETRY(open(path, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
- mode));
- if (fd == -1) {
- if (errno == EEXIST) {
- return 0;
- } else {
- PLOG(ERROR) << "open(" << path << ") failed";
- return -1;
- }
- }
- close(fd);
- return 0;
-}
-
-static void derive_permissions_locked(struct fuse* fuse, struct node *parent,
- struct node *node) {
- appid_t appid;
-
- /* By default, each node inherits from its parent */
- node->perm = PERM_INHERIT;
- node->userid = parent->userid;
- node->uid = parent->uid;
- node->under_android = parent->under_android;
-
- /* Derive custom permissions based on parent and current node */
- switch (parent->perm) {
- case PERM_INHERIT:
- /* Already inherited above */
- break;
- case PERM_PRE_ROOT:
- /* Legacy internal layout places users at top level */
- node->perm = PERM_ROOT;
- node->userid = strtoul(node->name, NULL, 10);
- break;
- case PERM_ROOT:
- /* Assume masked off by default. */
- if (!strcasecmp(node->name, "Android")) {
- /* App-specific directories inside; let anyone traverse */
- node->perm = PERM_ANDROID;
- node->under_android = true;
- }
- break;
- case PERM_ANDROID:
- if (!strcasecmp(node->name, "data")) {
- /* App-specific directories inside; let anyone traverse */
- node->perm = PERM_ANDROID_DATA;
- } else if (!strcasecmp(node->name, "obb")) {
- /* App-specific directories inside; let anyone traverse */
- node->perm = PERM_ANDROID_OBB;
- /* Single OBB directory is always shared */
- node->graft_path = fuse->global->obb_path;
- node->graft_pathlen = strlen(fuse->global->obb_path);
- } else if (!strcasecmp(node->name, "media")) {
- /* App-specific directories inside; let anyone traverse */
- node->perm = PERM_ANDROID_MEDIA;
- }
- break;
- case PERM_ANDROID_DATA:
- case PERM_ANDROID_OBB:
- case PERM_ANDROID_MEDIA:
- const auto& iter = fuse->global->package_to_appid->find(node->name);
- if (iter != fuse->global->package_to_appid->end()) {
- appid = iter->second;
- node->uid = multiuser_get_uid(parent->userid, appid);
- }
- break;
- }
-}
-
-void derive_permissions_recursive_locked(struct fuse* fuse, struct node *parent) {
- struct node *node;
- for (node = parent->child; node; node = node->next) {
- derive_permissions_locked(fuse, parent, node);
- if (node->child) {
- derive_permissions_recursive_locked(fuse, node);
- }
- }
-}
-
-/* Kernel has already enforced everything we returned through
- * derive_permissions_locked(), so this is used to lock down access
- * even further, such as enforcing that apps hold sdcard_rw. */
-static bool check_caller_access_to_name(struct fuse* fuse,
- const struct fuse_in_header *hdr, const struct node* parent_node,
- const char* name, int mode) {
- /* Always block security-sensitive files at root */
- if (parent_node && parent_node->perm == PERM_ROOT) {
- if (!strcasecmp(name, "autorun.inf")
- || !strcasecmp(name, ".android_secure")
- || !strcasecmp(name, "android_secure")) {
- return false;
- }
- }
-
- /* Root always has access; access for any other UIDs should always
- * be controlled through packages.list. */
- if (hdr->uid == AID_ROOT) {
- return true;
- }
-
- /* No extra permissions to enforce */
- return true;
-}
-
-static bool check_caller_access_to_node(struct fuse* fuse,
- const struct fuse_in_header *hdr, const struct node* node, int mode) {
- return check_caller_access_to_name(fuse, hdr, node->parent, node->name, mode);
-}
-
-struct node *create_node_locked(struct fuse* fuse,
- struct node *parent, const char *name, const char* actual_name)
-{
- struct node *node;
- size_t namelen = strlen(name);
-
- // Detect overflows in the inode counter. "4 billion nodes should be enough
- // for everybody".
- if (fuse->global->inode_ctr == 0) {
- LOG(ERROR) << "No more inode numbers available";
- return NULL;
- }
-
- node = static_cast<struct node*>(calloc(1, sizeof(struct node)));
- if (!node) {
- return NULL;
- }
- node->name = static_cast<char*>(malloc(namelen + 1));
- if (!node->name) {
- free(node);
- return NULL;
- }
- memcpy(node->name, name, namelen + 1);
- if (strcmp(name, actual_name)) {
- node->actual_name = static_cast<char*>(malloc(namelen + 1));
- if (!node->actual_name) {
- free(node->name);
- free(node);
- return NULL;
- }
- memcpy(node->actual_name, actual_name, namelen + 1);
- }
- node->namelen = namelen;
- node->nid = ptr_to_id(node);
- node->ino = fuse->global->inode_ctr++;
- node->gen = fuse->global->next_generation++;
-
- node->deleted = false;
-
- derive_permissions_locked(fuse, parent, node);
- acquire_node_locked(node);
- add_node_to_parent_locked(node, parent);
- return node;
-}
-
-static int rename_node_locked(struct node *node, const char *name,
- const char* actual_name)
-{
- size_t namelen = strlen(name);
- int need_actual_name = strcmp(name, actual_name);
-
- /* make the storage bigger without actually changing the name
- * in case an error occurs part way */
- if (namelen > node->namelen) {
- char* new_name = static_cast<char*>(realloc(node->name, namelen + 1));
- if (!new_name) {
- return -ENOMEM;
- }
- node->name = new_name;
- if (need_actual_name && node->actual_name) {
- char* new_actual_name = static_cast<char*>(realloc(node->actual_name, namelen + 1));
- if (!new_actual_name) {
- return -ENOMEM;
- }
- node->actual_name = new_actual_name;
- }
- }
-
- /* update the name, taking care to allocate storage before overwriting the old name */
- if (need_actual_name) {
- if (!node->actual_name) {
- node->actual_name = static_cast<char*>(malloc(namelen + 1));
- if (!node->actual_name) {
- return -ENOMEM;
- }
- }
- memcpy(node->actual_name, actual_name, namelen + 1);
- } else {
- free(node->actual_name);
- node->actual_name = NULL;
- }
- memcpy(node->name, name, namelen + 1);
- node->namelen = namelen;
- return 0;
-}
-
-static struct node *lookup_node_by_id_locked(struct fuse *fuse, __u64 nid)
-{
- if (nid == FUSE_ROOT_ID) {
- return &fuse->global->root;
- } else {
- return static_cast<struct node*>(id_to_ptr(nid));
- }
-}
-
-static struct node* lookup_node_and_path_by_id_locked(struct fuse* fuse, __u64 nid,
- char* buf, size_t bufsize)
-{
- struct node* node = lookup_node_by_id_locked(fuse, nid);
- if (node && get_node_path_locked(node, buf, bufsize) < 0) {
- node = NULL;
- }
- return node;
-}
-
-static struct node *lookup_child_by_name_locked(struct node *node, const char *name)
-{
- for (node = node->child; node; node = node->next) {
- /* use exact string comparison, nodes that differ by case
- * must be considered distinct even if they refer to the same
- * underlying file as otherwise operations such as "mv x x"
- * will not work because the source and target nodes are the same. */
- if (!strcmp(name, node->name) && !node->deleted) {
- return node;
- }
- }
- return 0;
-}
-
-static struct node* acquire_or_create_child_locked(
- struct fuse* fuse, struct node* parent,
- const char* name, const char* actual_name)
-{
- struct node* child = lookup_child_by_name_locked(parent, name);
- if (child) {
- acquire_node_locked(child);
- } else {
- child = create_node_locked(fuse, parent, name, actual_name);
- }
- return child;
-}
-
-static void fuse_status(struct fuse *fuse, __u64 unique, int err)
-{
- struct fuse_out_header hdr;
- hdr.len = sizeof(hdr);
- hdr.error = err;
- hdr.unique = unique;
- ssize_t ret = TEMP_FAILURE_RETRY(write(fuse->fd, &hdr, sizeof(hdr)));
- if (ret == -1) {
- PLOG(ERROR) << "*** STATUS FAILED ***";
- } else if (static_cast<size_t>(ret) != sizeof(hdr)) {
- LOG(ERROR) << "*** STATUS FAILED: written " << ret << " expected "
- << sizeof(hdr) << " ***";
- }
-}
-
-static void fuse_reply(struct fuse *fuse, __u64 unique, void *data, int len)
-{
- struct fuse_out_header hdr;
- hdr.len = len + sizeof(hdr);
- hdr.error = 0;
- hdr.unique = unique;
-
- struct iovec vec[2];
- vec[0].iov_base = &hdr;
- vec[0].iov_len = sizeof(hdr);
- vec[1].iov_base = data;
- vec[1].iov_len = len;
-
- ssize_t ret = TEMP_FAILURE_RETRY(writev(fuse->fd, vec, 2));
- if (ret == -1) {
- PLOG(ERROR) << "*** REPLY FAILED ***";
- } else if (static_cast<size_t>(ret) != sizeof(hdr) + len) {
- LOG(ERROR) << "*** REPLY FAILED: written " << ret << " expected "
- << sizeof(hdr) + len << " ***";
- }
-}
-
-static int fuse_reply_entry(struct fuse* fuse, __u64 unique,
- struct node* parent, const char* name, const char* actual_name,
- const char* path)
-{
- struct node* node;
- struct fuse_entry_out out;
- struct stat s;
-
- if (lstat(path, &s) == -1) {
- return -errno;
- }
-
- pthread_mutex_lock(&fuse->global->lock);
- node = acquire_or_create_child_locked(fuse, parent, name, actual_name);
- if (!node) {
- pthread_mutex_unlock(&fuse->global->lock);
- return -ENOMEM;
- }
- memset(&out, 0, sizeof(out));
- attr_from_stat(fuse, &out.attr, &s, node);
- out.attr_valid = 10;
- out.entry_valid = 10;
- out.nodeid = node->nid;
- out.generation = node->gen;
- pthread_mutex_unlock(&fuse->global->lock);
- fuse_reply(fuse, unique, &out, sizeof(out));
- return NO_STATUS;
-}
-
-static int fuse_reply_attr(struct fuse* fuse, __u64 unique, const struct node* node,
- const char* path)
-{
- struct fuse_attr_out out;
- struct stat s;
-
- if (lstat(path, &s) == -1) {
- return -errno;
- }
- memset(&out, 0, sizeof(out));
- attr_from_stat(fuse, &out.attr, &s, node);
- out.attr_valid = 10;
- fuse_reply(fuse, unique, &out, sizeof(out));
- return NO_STATUS;
-}
-
-static void fuse_notify_delete(struct fuse* fuse, const __u64 parent,
- const __u64 child, const char* name) {
- struct fuse_out_header hdr;
- struct fuse_notify_delete_out data;
- size_t namelen = strlen(name);
- hdr.len = sizeof(hdr) + sizeof(data) + namelen + 1;
- hdr.error = FUSE_NOTIFY_DELETE;
- hdr.unique = 0;
-
- data.parent = parent;
- data.child = child;
- data.namelen = namelen;
- data.padding = 0;
-
- struct iovec vec[3];
- vec[0].iov_base = &hdr;
- vec[0].iov_len = sizeof(hdr);
- vec[1].iov_base = &data;
- vec[1].iov_len = sizeof(data);
- vec[2].iov_base = (void*) name;
- vec[2].iov_len = namelen + 1;
-
- ssize_t ret = TEMP_FAILURE_RETRY(writev(fuse->fd, vec, 3));
- /* Ignore ENOENT, since other views may not have seen the entry */
- if (ret == -1) {
- if (errno != ENOENT) {
- PLOG(ERROR) << "*** NOTIFY FAILED ***";
- }
- } else if (static_cast<size_t>(ret) != sizeof(hdr) + sizeof(data) + namelen + 1) {
- LOG(ERROR) << "*** NOTIFY FAILED: written " << ret << " expected "
- << sizeof(hdr) + sizeof(data) + namelen + 1 << " ***";
- }
-}
-
-static int handle_lookup(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header *hdr, const char* name)
-{
- struct node* parent_node;
- char parent_path[PATH_MAX];
- char child_path[PATH_MAX];
- const char* actual_name;
-
- pthread_mutex_lock(&fuse->global->lock);
- parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
- parent_path, sizeof(parent_path));
- DLOG(INFO) << "[" << handler->token << "] LOOKUP " << name << " @ " << hdr->nodeid
- << " (" << (parent_node ? parent_node->name : "?") << ")";
- pthread_mutex_unlock(&fuse->global->lock);
-
- if (!parent_node || !(actual_name = find_file_within(parent_path, name,
- child_path, sizeof(child_path), 1))) {
- return -ENOENT;
- }
- if (!check_caller_access_to_name(fuse, hdr, parent_node, name, R_OK)) {
- return -EACCES;
- }
-
- return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
-}
-
-static int handle_forget(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header *hdr, const struct fuse_forget_in *req)
-{
- struct node* node;
-
- pthread_mutex_lock(&fuse->global->lock);
- node = lookup_node_by_id_locked(fuse, hdr->nodeid);
- DLOG(INFO) << "[" << handler->token << "] FORGET #" << req->nlookup
- << " @ " << std::hex << hdr->nodeid
- << " (" << (node ? node->name : "?") << ")";
- if (node) {
- __u64 n = req->nlookup;
- while (n) {
- n--;
- release_node_locked(node);
- }
- }
- pthread_mutex_unlock(&fuse->global->lock);
- return NO_STATUS; /* no reply */
-}
-
-static int handle_getattr(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header *hdr, const struct fuse_getattr_in *req)
-{
- struct node* node;
- char path[PATH_MAX];
-
- pthread_mutex_lock(&fuse->global->lock);
- node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
- DLOG(INFO) << "[" << handler->token << "] GETATTR flags=" << req->getattr_flags
- << " fh=" << std::hex << req->fh << " @ " << hdr->nodeid << std::dec
- << " (" << (node ? node->name : "?") << ")";
- pthread_mutex_unlock(&fuse->global->lock);
-
- if (!node) {
- return -ENOENT;
- }
- if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
- return -EACCES;
- }
-
- return fuse_reply_attr(fuse, hdr->unique, node, path);
-}
-
-static int handle_setattr(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header *hdr, const struct fuse_setattr_in *req)
-{
- struct node* node;
- char path[PATH_MAX];
- struct timespec times[2];
-
- pthread_mutex_lock(&fuse->global->lock);
- node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
- DLOG(INFO) << "[" << handler->token << "] SETATTR fh=" << std::hex << req->fh
- << " valid=" << std::hex << req->valid << " @ " << hdr->nodeid << std::dec
- << " (" << (node ? node->name : "?") << ")";
- pthread_mutex_unlock(&fuse->global->lock);
-
- if (!node) {
- return -ENOENT;
- }
-
- if (!(req->valid & FATTR_FH) &&
- !check_caller_access_to_node(fuse, hdr, node, W_OK)) {
- return -EACCES;
- }
-
- /* XXX: incomplete implementation on purpose.
- * chmod/chown should NEVER be implemented.*/
-
- if ((req->valid & FATTR_SIZE) && TEMP_FAILURE_RETRY(truncate64(path, req->size)) == -1) {
- return -errno;
- }
-
- /* Handle changing atime and mtime. If FATTR_ATIME_and FATTR_ATIME_NOW
- * are both set, then set it to the current time. Else, set it to the
- * time specified in the request. Same goes for mtime. Use utimensat(2)
- * as it allows ATIME and MTIME to be changed independently, and has
- * nanosecond resolution which fuse also has.
- */
- if (req->valid & (FATTR_ATIME | FATTR_MTIME)) {
- times[0].tv_nsec = UTIME_OMIT;
- times[1].tv_nsec = UTIME_OMIT;
- if (req->valid & FATTR_ATIME) {
- if (req->valid & FATTR_ATIME_NOW) {
- times[0].tv_nsec = UTIME_NOW;
- } else {
- times[0].tv_sec = req->atime;
- times[0].tv_nsec = req->atimensec;
- }
- }
- if (req->valid & FATTR_MTIME) {
- if (req->valid & FATTR_MTIME_NOW) {
- times[1].tv_nsec = UTIME_NOW;
- } else {
- times[1].tv_sec = req->mtime;
- times[1].tv_nsec = req->mtimensec;
- }
- }
- DLOG(INFO) << "[" << handler->token << "] Calling utimensat on " << path
- << " with atime " << times[0].tv_sec << ", mtime=" << times[1].tv_sec;
- if (utimensat(-1, path, times, 0) < 0) {
- return -errno;
- }
- }
- return fuse_reply_attr(fuse, hdr->unique, node, path);
-}
-
-static int handle_mknod(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_mknod_in* req, const char* name)
-{
- struct node* parent_node;
- char parent_path[PATH_MAX];
- char child_path[PATH_MAX];
- const char* actual_name;
-
- pthread_mutex_lock(&fuse->global->lock);
- parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
- parent_path, sizeof(parent_path));
- DLOG(INFO) << "[" << handler->token << "] MKNOD " << name << " 0" << std::oct << req->mode
- << " @ " << std::hex << hdr->nodeid
- << " (" << (parent_node ? parent_node->name : "?") << ")";
- pthread_mutex_unlock(&fuse->global->lock);
-
- if (!parent_node || !(actual_name = find_file_within(parent_path, name,
- child_path, sizeof(child_path), 1))) {
- return -ENOENT;
- }
- if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
- return -EACCES;
- }
- __u32 mode = (req->mode & (~0777)) | 0664;
- if (mknod(child_path, mode, req->rdev) == -1) {
- return -errno;
- }
- return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
-}
-
-static int handle_mkdir(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_mkdir_in* req, const char* name)
-{
- struct node* parent_node;
- char parent_path[PATH_MAX];
- char child_path[PATH_MAX];
- const char* actual_name;
-
- pthread_mutex_lock(&fuse->global->lock);
- parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
- parent_path, sizeof(parent_path));
- DLOG(INFO) << "[" << handler->token << "] MKDIR " << name << " 0" << std::oct << req->mode
- << " @ " << std::hex << hdr->nodeid
- << " (" << (parent_node ? parent_node->name : "?") << ")";
- pthread_mutex_unlock(&fuse->global->lock);
-
- if (!parent_node || !(actual_name = find_file_within(parent_path, name,
- child_path, sizeof(child_path), 1))) {
- return -ENOENT;
- }
- if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
- return -EACCES;
- }
- __u32 mode = (req->mode & (~0777)) | 0775;
- if (mkdir(child_path, mode) == -1) {
- return -errno;
- }
-
- /* When creating /Android/data and /Android/obb, mark them as .nomedia */
- if (parent_node->perm == PERM_ANDROID && !strcasecmp(name, "data")) {
- char nomedia[PATH_MAX];
- snprintf(nomedia, PATH_MAX, "%s/.nomedia", child_path);
- if (touch(nomedia, 0664) != 0) {
- PLOG(ERROR) << "touch(" << nomedia << ") failed";
- return -ENOENT;
- }
- }
- if (parent_node->perm == PERM_ANDROID && !strcasecmp(name, "obb")) {
- char nomedia[PATH_MAX];
- snprintf(nomedia, PATH_MAX, "%s/.nomedia", fuse->global->obb_path);
- if (touch(nomedia, 0664) != 0) {
- PLOG(ERROR) << "touch(" << nomedia << ") failed";
- return -ENOENT;
- }
- }
-
- return fuse_reply_entry(fuse, hdr->unique, parent_node, name, actual_name, child_path);
-}
-
-static int handle_unlink(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const char* name)
-{
- struct node* parent_node;
- struct node* child_node;
- char parent_path[PATH_MAX];
- char child_path[PATH_MAX];
-
- pthread_mutex_lock(&fuse->global->lock);
- parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
- parent_path, sizeof(parent_path));
- DLOG(INFO) << "[" << handler->token << "] UNLINK " << name << " @ " << std::hex << hdr->nodeid
- << " (" << (parent_node ? parent_node->name : "?") << ")";
- pthread_mutex_unlock(&fuse->global->lock);
-
- if (!parent_node || !find_file_within(parent_path, name,
- child_path, sizeof(child_path), 1)) {
- return -ENOENT;
- }
- if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
- return -EACCES;
- }
- if (unlink(child_path) == -1) {
- return -errno;
- }
- pthread_mutex_lock(&fuse->global->lock);
- child_node = lookup_child_by_name_locked(parent_node, name);
- if (child_node) {
- child_node->deleted = true;
- }
- pthread_mutex_unlock(&fuse->global->lock);
- if (parent_node && child_node) {
- /* Tell all other views that node is gone */
- DLOG(INFO) << "[" << handler->token << "] fuse_notify_delete"
- << " parent=" << std::hex << parent_node->nid
- << ", child=" << std::hex << child_node->nid << std::dec
- << ", name=" << name;
- if (fuse != fuse->global->fuse_default) {
- fuse_notify_delete(fuse->global->fuse_default, parent_node->nid, child_node->nid, name);
- }
- if (fuse != fuse->global->fuse_read) {
- fuse_notify_delete(fuse->global->fuse_read, parent_node->nid, child_node->nid, name);
- }
- if (fuse != fuse->global->fuse_write) {
- fuse_notify_delete(fuse->global->fuse_write, parent_node->nid, child_node->nid, name);
- }
- }
- return 0;
-}
-
-static int handle_rmdir(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const char* name)
-{
- struct node* child_node;
- struct node* parent_node;
- char parent_path[PATH_MAX];
- char child_path[PATH_MAX];
-
- pthread_mutex_lock(&fuse->global->lock);
- parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
- parent_path, sizeof(parent_path));
- DLOG(INFO) << "[" << handler->token << "] UNLINK " << name << " @ " << std::hex << hdr->nodeid
- << " (" << (parent_node ? parent_node->name : "?") << ")";
- pthread_mutex_unlock(&fuse->global->lock);
-
- if (!parent_node || !find_file_within(parent_path, name,
- child_path, sizeof(child_path), 1)) {
- return -ENOENT;
- }
- if (!check_caller_access_to_name(fuse, hdr, parent_node, name, W_OK)) {
- return -EACCES;
- }
- if (rmdir(child_path) == -1) {
- return -errno;
- }
- pthread_mutex_lock(&fuse->global->lock);
- child_node = lookup_child_by_name_locked(parent_node, name);
- if (child_node) {
- child_node->deleted = true;
- }
- pthread_mutex_unlock(&fuse->global->lock);
- if (parent_node && child_node) {
- /* Tell all other views that node is gone */
- DLOG(INFO) << "[" << handler->token << "] fuse_notify_delete"
- << " parent=" << std::hex << parent_node->nid
- << ", child=" << std::hex << child_node->nid << std::dec
- << ", name=" << name;
- if (fuse != fuse->global->fuse_default) {
- fuse_notify_delete(fuse->global->fuse_default, parent_node->nid, child_node->nid, name);
- }
- if (fuse != fuse->global->fuse_read) {
- fuse_notify_delete(fuse->global->fuse_read, parent_node->nid, child_node->nid, name);
- }
- if (fuse != fuse->global->fuse_write) {
- fuse_notify_delete(fuse->global->fuse_write, parent_node->nid, child_node->nid, name);
- }
- }
- return 0;
-}
-
-static int handle_rename(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_rename_in* req,
- const char* old_name, const char* new_name)
-{
- struct node* old_parent_node;
- struct node* new_parent_node;
- struct node* child_node;
- char old_parent_path[PATH_MAX];
- char new_parent_path[PATH_MAX];
- char old_child_path[PATH_MAX];
- char new_child_path[PATH_MAX];
- const char* new_actual_name;
- int search;
- int res;
-
- pthread_mutex_lock(&fuse->global->lock);
- old_parent_node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
- old_parent_path, sizeof(old_parent_path));
- new_parent_node = lookup_node_and_path_by_id_locked(fuse, req->newdir,
- new_parent_path, sizeof(new_parent_path));
- DLOG(INFO) << "[" << handler->token << "] RENAME " << old_name << "->" << new_name
- << " @ " << std::hex << hdr->nodeid
- << " (" << (old_parent_node ? old_parent_node->name : "?") << ") -> "
- << std::hex << req->newdir
- << " (" << (new_parent_node ? new_parent_node->name : "?") << ")";
- if (!old_parent_node || !new_parent_node) {
- res = -ENOENT;
- goto lookup_error;
- }
- if (!check_caller_access_to_name(fuse, hdr, old_parent_node, old_name, W_OK)) {
- res = -EACCES;
- goto lookup_error;
- }
- if (!check_caller_access_to_name(fuse, hdr, new_parent_node, new_name, W_OK)) {
- res = -EACCES;
- goto lookup_error;
- }
- child_node = lookup_child_by_name_locked(old_parent_node, old_name);
- if (!child_node || get_node_path_locked(child_node,
- old_child_path, sizeof(old_child_path)) < 0) {
- res = -ENOENT;
- goto lookup_error;
- }
- acquire_node_locked(child_node);
- pthread_mutex_unlock(&fuse->global->lock);
-
- /* Special case for renaming a file where destination is same path
- * differing only by case. In this case we don't want to look for a case
- * insensitive match. This allows commands like "mv foo FOO" to work as expected.
- */
- search = old_parent_node != new_parent_node
- || strcasecmp(old_name, new_name);
- if (!(new_actual_name = find_file_within(new_parent_path, new_name,
- new_child_path, sizeof(new_child_path), search))) {
- res = -ENOENT;
- goto io_error;
- }
-
- DLOG(INFO) << "[" << handler->token << "] RENAME " << old_child_path << "->" << new_child_path;
- res = rename(old_child_path, new_child_path);
- if (res == -1) {
- res = -errno;
- goto io_error;
- }
-
- pthread_mutex_lock(&fuse->global->lock);
- res = rename_node_locked(child_node, new_name, new_actual_name);
- if (!res) {
- remove_node_from_parent_locked(child_node);
- derive_permissions_locked(fuse, new_parent_node, child_node);
- derive_permissions_recursive_locked(fuse, child_node);
- add_node_to_parent_locked(child_node, new_parent_node);
- }
- goto done;
-
-io_error:
- pthread_mutex_lock(&fuse->global->lock);
-done:
- release_node_locked(child_node);
-lookup_error:
- pthread_mutex_unlock(&fuse->global->lock);
- return res;
-}
-
-static int open_flags_to_access_mode(int open_flags) {
- if ((open_flags & O_ACCMODE) == O_RDONLY) {
- return R_OK;
- } else if ((open_flags & O_ACCMODE) == O_WRONLY) {
- return W_OK;
- } else {
- /* Probably O_RDRW, but treat as default to be safe */
- return R_OK | W_OK;
- }
-}
-
-static int handle_open(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_open_in* req)
-{
- struct node* node;
- char path[PATH_MAX];
- struct fuse_open_out out = {};
- struct handle *h;
-
- pthread_mutex_lock(&fuse->global->lock);
- node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
- DLOG(INFO) << "[" << handler->token << "] OPEN 0" << std::oct << req->flags
- << " @ " << std::hex << hdr->nodeid << std::dec
- << " (" << (node ? node->name : "?") << ")";
- pthread_mutex_unlock(&fuse->global->lock);
-
- if (!node) {
- return -ENOENT;
- }
- if (!check_caller_access_to_node(fuse, hdr, node,
- open_flags_to_access_mode(req->flags))) {
- return -EACCES;
- }
- h = static_cast<struct handle*>(malloc(sizeof(*h)));
- if (!h) {
- return -ENOMEM;
- }
- DLOG(INFO) << "[" << handler->token << "] OPEN " << path;
- h->fd = TEMP_FAILURE_RETRY(open(path, req->flags));
- if (h->fd == -1) {
- free(h);
- return -errno;
- }
- out.fh = ptr_to_id(h);
- out.open_flags = 0;
- fuse_reply(fuse, hdr->unique, &out, sizeof(out));
- return NO_STATUS;
-}
-
-static int handle_read(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_read_in* req)
-{
- struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
- __u64 unique = hdr->unique;
- __u32 size = req->size;
- __u64 offset = req->offset;
- int res;
- __u8 *read_buffer = (__u8 *) ((uintptr_t)(handler->read_buffer + PAGE_SIZE) & ~((uintptr_t)PAGE_SIZE-1));
-
- /* Don't access any other fields of hdr or req beyond this point, the read buffer
- * overlaps the request buffer and will clobber data in the request. This
- * saves us 128KB per request handler thread at the cost of this scary comment. */
-
- DLOG(INFO) << "[" << handler->token << "] READ " << std::hex << h << std::dec
- << "(" << h->fd << ") " << size << "@" << offset;
- if (size > MAX_READ) {
- return -EINVAL;
- }
- res = TEMP_FAILURE_RETRY(pread64(h->fd, read_buffer, size, offset));
- if (res == -1) {
- return -errno;
- }
- fuse_reply(fuse, unique, read_buffer, res);
- return NO_STATUS;
-}
-
-static int handle_write(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_write_in* req,
- const void* buffer)
-{
- struct fuse_write_out out;
- struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
- int res;
- __u8 aligned_buffer[req->size] __attribute__((__aligned__(PAGE_SIZE)));
-
- if (req->flags & O_DIRECT) {
- memcpy(aligned_buffer, buffer, req->size);
- buffer = (const __u8*) aligned_buffer;
- }
-
- DLOG(INFO) << "[" << handler->token << "] WRITE " << std::hex << h << std::dec
- << "(" << h->fd << ") " << req->size << "@" << req->offset;
- res = TEMP_FAILURE_RETRY(pwrite64(h->fd, buffer, req->size, req->offset));
- if (res == -1) {
- return -errno;
- }
- out.size = res;
- out.padding = 0;
- fuse_reply(fuse, hdr->unique, &out, sizeof(out));
- return NO_STATUS;
-}
-
-static int handle_statfs(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr)
-{
- char path[PATH_MAX];
- struct statfs stat;
- struct fuse_statfs_out out;
- int res;
-
- pthread_mutex_lock(&fuse->global->lock);
- DLOG(INFO) << "[" << handler->token << "] STATFS";
- res = get_node_path_locked(&fuse->global->root, path, sizeof(path));
- pthread_mutex_unlock(&fuse->global->lock);
- if (res < 0) {
- return -ENOENT;
- }
- if (TEMP_FAILURE_RETRY(statfs(fuse->global->root.name, &stat)) == -1) {
- return -errno;
- }
- memset(&out, 0, sizeof(out));
- out.st.blocks = stat.f_blocks;
- out.st.bfree = stat.f_bfree;
- out.st.bavail = stat.f_bavail;
- out.st.files = stat.f_files;
- out.st.ffree = stat.f_ffree;
- out.st.bsize = stat.f_bsize;
- out.st.namelen = stat.f_namelen;
- out.st.frsize = stat.f_frsize;
- fuse_reply(fuse, hdr->unique, &out, sizeof(out));
- return NO_STATUS;
-}
-
-static int handle_release(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_release_in* req)
-{
- struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
-
- DLOG(INFO) << "[" << handler->token << "] RELEASE " << std::hex << h << std::dec
- << "(" << h->fd << ")";
- close(h->fd);
- free(h);
- return 0;
-}
-
-static int handle_fsync(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_fsync_in* req)
-{
- bool is_dir = (hdr->opcode == FUSE_FSYNCDIR);
- bool is_data_sync = req->fsync_flags & 1;
-
- int fd = -1;
- if (is_dir) {
- struct dirhandle *dh = static_cast<struct dirhandle*>(id_to_ptr(req->fh));
- fd = dirfd(dh->d);
- } else {
- struct handle *h = static_cast<struct handle*>(id_to_ptr(req->fh));
- fd = h->fd;
- }
-
- DLOG(INFO) << "[" << handler->token << "] " << (is_dir ? "FSYNCDIR" : "FSYNC") << " "
- << std::hex << req->fh << std::dec << "(" << fd << ") is_data_sync=" << is_data_sync;
- int res = is_data_sync ? fdatasync(fd) : fsync(fd);
- if (res == -1) {
- return -errno;
- }
- return 0;
-}
-
-static int handle_flush(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr)
-{
- DLOG(INFO) << "[" << handler->token << "] FLUSH";
- return 0;
-}
-
-static int handle_opendir(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_open_in* req)
-{
- struct node* node;
- char path[PATH_MAX];
- struct fuse_open_out out = {};
- struct dirhandle *h;
-
- pthread_mutex_lock(&fuse->global->lock);
- node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid, path, sizeof(path));
- DLOG(INFO) << "[" << handler->token << "] OPENDIR @ " << std::hex << hdr->nodeid
- << " (" << (node ? node->name : "?") << ")";
- pthread_mutex_unlock(&fuse->global->lock);
-
- if (!node) {
- return -ENOENT;
- }
- if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
- return -EACCES;
- }
- h = static_cast<struct dirhandle*>(malloc(sizeof(*h)));
- if (!h) {
- return -ENOMEM;
- }
- DLOG(INFO) << "[" << handler->token << "] OPENDIR " << path;
- h->d = opendir(path);
- if (!h->d) {
- free(h);
- return -errno;
- }
- out.fh = ptr_to_id(h);
- out.open_flags = 0;
- fuse_reply(fuse, hdr->unique, &out, sizeof(out));
- return NO_STATUS;
-}
-
-static int handle_readdir(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_read_in* req)
-{
- char buffer[8192];
- struct fuse_dirent *fde = (struct fuse_dirent*) buffer;
- struct dirent *de;
- struct dirhandle *h = static_cast<struct dirhandle*>(id_to_ptr(req->fh));
-
- DLOG(INFO) << "[" << handler->token << "] READDIR " << h;
- if (req->offset == 0) {
- /* rewinddir() might have been called above us, so rewind here too */
- DLOG(INFO) << "[" << handler->token << "] calling rewinddir()";
- rewinddir(h->d);
- }
- de = readdir(h->d);
- if (!de) {
- return 0;
- }
- fde->ino = FUSE_UNKNOWN_INO;
- /* increment the offset so we can detect when rewinddir() seeks back to the beginning */
- fde->off = req->offset + 1;
- fde->type = de->d_type;
- fde->namelen = strlen(de->d_name);
- memcpy(fde->name, de->d_name, fde->namelen + 1);
- fuse_reply(fuse, hdr->unique, fde,
- FUSE_DIRENT_ALIGN(sizeof(struct fuse_dirent) + fde->namelen));
- return NO_STATUS;
-}
-
-static int handle_releasedir(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_release_in* req)
-{
- struct dirhandle *h = static_cast<struct dirhandle*>(id_to_ptr(req->fh));
-
- DLOG(INFO) << "[" << handler->token << "] RELEASEDIR " << h;
- closedir(h->d);
- free(h);
- return 0;
-}
-
-static int handle_init(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header* hdr, const struct fuse_init_in* req)
-{
- struct fuse_init_out out;
- size_t fuse_struct_size;
-
- DLOG(INFO) << "[" << handler->token << "] INIT ver=" << req->major << "." << req->minor
- << " maxread=" << req->max_readahead << " flags=" << std::hex << req->flags;
-
- /* Kernel 2.6.16 is the first stable kernel with struct fuse_init_out
- * defined (fuse version 7.6). The structure is the same from 7.6 through
- * 7.22. Beginning with 7.23, the structure increased in size and added
- * new parameters.
- */
- if (req->major != FUSE_KERNEL_VERSION || req->minor < 6) {
- LOG(ERROR) << "Fuse kernel version mismatch: Kernel version "
- << req->major << "." << req->minor
- << ", Expected at least " << FUSE_KERNEL_VERSION << ".6";
- return -1;
- }
-
- /* We limit ourselves to 15 because we don't handle BATCH_FORGET yet */
- out.minor = MIN(req->minor, 15);
- fuse_struct_size = sizeof(out);
-#if defined(FUSE_COMPAT_22_INIT_OUT_SIZE)
- /* FUSE_KERNEL_VERSION >= 23. */
-
- /* Since we return minor version 15, the kernel does not accept the latest
- * fuse_init_out size. We need to use FUSE_COMPAT_22_INIT_OUT_SIZE always.*/
- fuse_struct_size = FUSE_COMPAT_22_INIT_OUT_SIZE;
-#endif
-
- out.major = FUSE_KERNEL_VERSION;
- out.max_readahead = req->max_readahead;
- out.flags = FUSE_ATOMIC_O_TRUNC | FUSE_BIG_WRITES;
- out.max_background = 32;
- out.congestion_threshold = 32;
- out.max_write = MAX_WRITE;
- fuse_reply(fuse, hdr->unique, &out, fuse_struct_size);
- return NO_STATUS;
-}
-
-static int handle_canonical_path(struct fuse* fuse, struct fuse_handler* handler,
- const struct fuse_in_header *hdr)
-{
- struct node* node;
- char path[PATH_MAX];
- int len;
-
- pthread_mutex_lock(&fuse->global->lock);
- node = lookup_node_and_path_by_id_locked(fuse, hdr->nodeid,
- path, sizeof(path));
- DLOG(INFO) << "[" << handler->token << "] CANONICAL_PATH @ " << std::hex << hdr->nodeid
- << std::dec << " (" << (node ? node->name : "?") << ")";
- pthread_mutex_unlock(&fuse->global->lock);
-
- if (!node) {
- return -ENOENT;
- }
- if (!check_caller_access_to_node(fuse, hdr, node, R_OK)) {
- return -EACCES;
- }
- len = strlen(path);
- if (len + 1 > PATH_MAX)
- len = PATH_MAX - 1;
- path[PATH_MAX - 1] = 0;
- fuse_reply(fuse, hdr->unique, path, len + 1);
- return NO_STATUS;
-}
-
-static int handle_fuse_request(struct fuse *fuse, struct fuse_handler* handler,
- const struct fuse_in_header *hdr, const void *data, size_t data_len)
-{
- switch (hdr->opcode) {
- case FUSE_LOOKUP: { /* bytez[] -> entry_out */
- const char *name = static_cast<const char*>(data);
- return handle_lookup(fuse, handler, hdr, name);
- }
-
- case FUSE_FORGET: {
- const struct fuse_forget_in *req = static_cast<const struct fuse_forget_in*>(data);
- return handle_forget(fuse, handler, hdr, req);
- }
-
- case FUSE_GETATTR: { /* getattr_in -> attr_out */
- const struct fuse_getattr_in *req = static_cast<const struct fuse_getattr_in*>(data);
- return handle_getattr(fuse, handler, hdr, req);
- }
-
- case FUSE_SETATTR: { /* setattr_in -> attr_out */
- const struct fuse_setattr_in *req = static_cast<const struct fuse_setattr_in*>(data);
- return handle_setattr(fuse, handler, hdr, req);
- }
-
-// case FUSE_READLINK:
-// case FUSE_SYMLINK:
- case FUSE_MKNOD: { /* mknod_in, bytez[] -> entry_out */
- const struct fuse_mknod_in *req = static_cast<const struct fuse_mknod_in*>(data);
- const char *name = ((const char*) data) + sizeof(*req);
- return handle_mknod(fuse, handler, hdr, req, name);
- }
-
- case FUSE_MKDIR: { /* mkdir_in, bytez[] -> entry_out */
- const struct fuse_mkdir_in *req = static_cast<const struct fuse_mkdir_in*>(data);
- const char *name = ((const char*) data) + sizeof(*req);
- return handle_mkdir(fuse, handler, hdr, req, name);
- }
-
- case FUSE_UNLINK: { /* bytez[] -> */
- const char *name = static_cast<const char*>(data);
- return handle_unlink(fuse, handler, hdr, name);
- }
-
- case FUSE_RMDIR: { /* bytez[] -> */
- const char *name = static_cast<const char*>(data);
- return handle_rmdir(fuse, handler, hdr, name);
- }
-
- case FUSE_RENAME: { /* rename_in, oldname, newname -> */
- const struct fuse_rename_in *req = static_cast<const struct fuse_rename_in*>(data);
- const char *old_name = ((const char*) data) + sizeof(*req);
- const char *new_name = old_name + strlen(old_name) + 1;
- return handle_rename(fuse, handler, hdr, req, old_name, new_name);
- }
-
-// case FUSE_LINK:
- case FUSE_OPEN: { /* open_in -> open_out */
- const struct fuse_open_in *req = static_cast<const struct fuse_open_in*>(data);
- return handle_open(fuse, handler, hdr, req);
- }
-
- case FUSE_READ: { /* read_in -> byte[] */
- const struct fuse_read_in *req = static_cast<const struct fuse_read_in*>(data);
- return handle_read(fuse, handler, hdr, req);
- }
-
- case FUSE_WRITE: { /* write_in, byte[write_in.size] -> write_out */
- const struct fuse_write_in *req = static_cast<const struct fuse_write_in*>(data);
- const void* buffer = (const __u8*)data + sizeof(*req);
- return handle_write(fuse, handler, hdr, req, buffer);
- }
-
- case FUSE_STATFS: { /* getattr_in -> attr_out */
- return handle_statfs(fuse, handler, hdr);
- }
-
- case FUSE_RELEASE: { /* release_in -> */
- const struct fuse_release_in *req = static_cast<const struct fuse_release_in*>(data);
- return handle_release(fuse, handler, hdr, req);
- }
-
- case FUSE_FSYNC:
- case FUSE_FSYNCDIR: {
- const struct fuse_fsync_in *req = static_cast<const struct fuse_fsync_in*>(data);
- return handle_fsync(fuse, handler, hdr, req);
- }
-
-// case FUSE_SETXATTR:
-// case FUSE_GETXATTR:
-// case FUSE_LISTXATTR:
-// case FUSE_REMOVEXATTR:
- case FUSE_FLUSH: {
- return handle_flush(fuse, handler, hdr);
- }
-
- case FUSE_OPENDIR: { /* open_in -> open_out */
- const struct fuse_open_in *req = static_cast<const struct fuse_open_in*>(data);
- return handle_opendir(fuse, handler, hdr, req);
- }
-
- case FUSE_READDIR: {
- const struct fuse_read_in *req = static_cast<const struct fuse_read_in*>(data);
- return handle_readdir(fuse, handler, hdr, req);
- }
-
- case FUSE_RELEASEDIR: { /* release_in -> */
- const struct fuse_release_in *req = static_cast<const struct fuse_release_in*>(data);
- return handle_releasedir(fuse, handler, hdr, req);
- }
-
- case FUSE_INIT: { /* init_in -> init_out */
- const struct fuse_init_in *req = static_cast<const struct fuse_init_in*>(data);
- return handle_init(fuse, handler, hdr, req);
- }
-
- case FUSE_CANONICAL_PATH: { /* nodeid -> bytez[] */
- return handle_canonical_path(fuse, handler, hdr);
- }
-
- default: {
- DLOG(INFO) << "[" << handler->token << "] NOTIMPL op=" << hdr->opcode
- << "uniq=" << std::hex << hdr->unique << "nid=" << hdr->nodeid << std::dec;
- return -ENOSYS;
- }
- }
-}
-
-void handle_fuse_requests(struct fuse_handler* handler)
-{
- struct fuse* fuse = handler->fuse;
- for (;;) {
- ssize_t len = TEMP_FAILURE_RETRY(read(fuse->fd,
- handler->request_buffer, sizeof(handler->request_buffer)));
- if (len == -1) {
- if (errno == ENODEV) {
- LOG(ERROR) << "[" << handler->token << "] someone stole our marbles!";
- exit(2);
- }
- PLOG(ERROR) << "[" << handler->token << "] handle_fuse_requests";
- continue;
- }
-
- if (static_cast<size_t>(len) < sizeof(struct fuse_in_header)) {
- LOG(ERROR) << "[" << handler->token << "] request too short: len=" << len;
- continue;
- }
-
- const struct fuse_in_header* hdr =
- reinterpret_cast<const struct fuse_in_header*>(handler->request_buffer);
- if (hdr->len != static_cast<size_t>(len)) {
- LOG(ERROR) << "[" << handler->token << "] malformed header: len=" << len
- << ", hdr->len=" << hdr->len;
- continue;
- }
-
- const void *data = handler->request_buffer + sizeof(struct fuse_in_header);
- size_t data_len = len - sizeof(struct fuse_in_header);
- __u64 unique = hdr->unique;
- int res = handle_fuse_request(fuse, handler, hdr, data, data_len);
-
- /* We do not access the request again after this point because the underlying
- * buffer storage may have been reused while processing the request. */
-
- if (res != NO_STATUS) {
- if (res) {
- DLOG(INFO) << "[" << handler->token << "] ERROR " << res;
- }
- fuse_status(fuse, unique, res);
- }
- }
-}
diff --git a/sdcard/fuse.h b/sdcard/fuse.h
deleted file mode 100644
index 9ccd21d..0000000
--- a/sdcard/fuse.h
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Copyright (C) 2016 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef FUSE_H_
-#define FUSE_H_
-
-#include <dirent.h>
-#include <fcntl.h>
-#include <linux/fuse.h>
-#include <pthread.h>
-#include <stdbool.h>
-#include <stdlib.h>
-#include <sys/param.h>
-#include <sys/stat.h>
-#include <sys/statfs.h>
-#include <sys/types.h>
-#include <sys/uio.h>
-#include <unistd.h>
-
-#include <map>
-#include <string>
-
-#include <android-base/logging.h>
-#include <cutils/fs.h>
-#include <cutils/multiuser.h>
-#include <packagelistparser/packagelistparser.h>
-
-#include <private/android_filesystem_config.h>
-
-#define FUSE_TRACE 0
-
-#if FUSE_TRACE
-static constexpr bool kEnableDLog = true;
-#else // FUSE_TRACE == 0
-static constexpr bool kEnableDLog = false;
-#endif
-
-// Use same strategy as DCHECK().
-#define DLOG(x) \
- if (kEnableDLog) LOG(x)
-
-/* Maximum number of bytes to write in one request. */
-#define MAX_WRITE (256 * 1024)
-
-/* Maximum number of bytes to read in one request. */
-#define MAX_READ (128 * 1024)
-
-/* Largest possible request.
- * The request size is bounded by the maximum size of a FUSE_WRITE request because it has
- * the largest possible data payload. */
-#define MAX_REQUEST_SIZE (sizeof(struct fuse_in_header) + sizeof(struct fuse_write_in) + MAX_WRITE)
-
-namespace {
-struct CaseInsensitiveCompare {
- bool operator()(const std::string& lhs, const std::string& rhs) const {
- return strcasecmp(lhs.c_str(), rhs.c_str()) < 0;
- }
-};
-}
-
-using AppIdMap = std::map<std::string, appid_t, CaseInsensitiveCompare>;
-
-/* Permission mode for a specific node. Controls how file permissions
- * are derived for children nodes. */
-typedef enum {
- /* Nothing special; this node should just inherit from its parent. */
- PERM_INHERIT,
- /* This node is one level above a normal root; used for legacy layouts
- * which use the first level to represent user_id. */
- PERM_PRE_ROOT,
- /* This node is "/" */
- PERM_ROOT,
- /* This node is "/Android" */
- PERM_ANDROID,
- /* This node is "/Android/data" */
- PERM_ANDROID_DATA,
- /* This node is "/Android/obb" */
- PERM_ANDROID_OBB,
- /* This node is "/Android/media" */
- PERM_ANDROID_MEDIA,
-} perm_t;
-
-struct handle {
- int fd;
-};
-
-struct dirhandle {
- DIR *d;
-};
-
-struct node {
- __u32 refcount;
- __u64 nid;
- __u64 gen;
- /*
- * The inode number for this FUSE node. Note that this isn't stable across
- * multiple invocations of the FUSE daemon.
- */
- __u32 ino;
-
- /* State derived based on current position in hierarchy. */
- perm_t perm;
- userid_t userid;
- uid_t uid;
- bool under_android;
-
- struct node *next; /* per-dir sibling list */
- struct node *child; /* first contained file by this dir */
- struct node *parent; /* containing directory */
-
- size_t namelen;
- char *name;
- /* If non-null, this is the real name of the file in the underlying storage.
- * This may differ from the field "name" only by case.
- * strlen(actual_name) will always equal strlen(name), so it is safe to use
- * namelen for both fields.
- */
- char *actual_name;
-
- /* If non-null, an exact underlying path that should be grafted into this
- * position. Used to support things like OBB. */
- char* graft_path;
- size_t graft_pathlen;
-
- bool deleted;
-};
-
-/* Global data for all FUSE mounts */
-struct fuse_global {
- pthread_mutex_t lock;
-
- uid_t uid;
- gid_t gid;
- bool multi_user;
-
- char source_path[PATH_MAX];
- char obb_path[PATH_MAX];
-
- AppIdMap* package_to_appid;
-
- __u64 next_generation;
- struct node root;
-
- /* Used to allocate unique inode numbers for fuse nodes. We use
- * a simple counter based scheme where inode numbers from deleted
- * nodes aren't reused. Note that inode allocations are not stable
- * across multiple invocation of the sdcard daemon, but that shouldn't
- * be a huge problem in practice.
- *
- * Note that we restrict inodes to 32 bit unsigned integers to prevent
- * truncation on 32 bit processes when unsigned long long stat.st_ino is
- * assigned to an unsigned long ino_t type in an LP32 process.
- *
- * Also note that fuse_attr and fuse_dirent inode values are 64 bits wide
- * on both LP32 and LP64, but the fuse kernel code doesn't squash 64 bit
- * inode numbers into 32 bit values on 64 bit kernels (see fuse_squash_ino
- * in fs/fuse/inode.c).
- *
- * Accesses must be guarded by |lock|.
- */
- __u32 inode_ctr;
-
- struct fuse* fuse_default;
- struct fuse* fuse_read;
- struct fuse* fuse_write;
-};
-
-/* Single FUSE mount */
-struct fuse {
- struct fuse_global* global;
-
- char dest_path[PATH_MAX];
-
- int fd;
-
- gid_t gid;
- mode_t mask;
-};
-
-/* Private data used by a single FUSE handler */
-struct fuse_handler {
- struct fuse* fuse;
- int token;
-
- /* To save memory, we never use the contents of the request buffer and the read
- * buffer at the same time. This allows us to share the underlying storage. */
- union {
- __u8 request_buffer[MAX_REQUEST_SIZE];
- __u8 read_buffer[MAX_READ + PAGE_SIZE];
- };
-};
-
-void handle_fuse_requests(struct fuse_handler* handler);
-void derive_permissions_recursive_locked(struct fuse* fuse, struct node *parent);
-
-#endif /* FUSE_H_ */
diff --git a/sdcard/sdcard.cpp b/sdcard/sdcard.cpp
index 0d5e5af..574bbfe 100644
--- a/sdcard/sdcard.cpp
+++ b/sdcard/sdcard.cpp
@@ -38,164 +38,18 @@
#include <cutils/multiuser.h>
#include <cutils/properties.h>
-#include <packagelistparser/packagelistparser.h>
-
#include <libminijail.h>
#include <scoped_minijail.h>
#include <private/android_filesystem_config.h>
-// README
-//
-// What is this?
-//
-// sdcard is a program that uses FUSE to emulate FAT-on-sdcard style
-// directory permissions (all files are given fixed owner, group, and
-// permissions at creation, owner, group, and permissions are not
-// changeable, symlinks and hardlinks are not createable, etc.
-//
-// See usage() for command line options.
-//
-// It must be run as root, but will drop to requested UID/GID as soon as it
-// mounts a filesystem. It will refuse to run if requested UID/GID are zero.
-//
-// Things I believe to be true:
-//
-// - ops that return a fuse_entry (LOOKUP, MKNOD, MKDIR, LINK, SYMLINK,
-// CREAT) must bump that node's refcount
-// - don't forget that FORGET can forget multiple references (req->nlookup)
-// - if an op that returns a fuse_entry fails writing the reply to the
-// kernel, you must rollback the refcount to reflect the reference the
-// kernel did not actually acquire
-//
-// This daemon can also derive custom filesystem permissions based on directory
-// structure when requested. These custom permissions support several features:
-//
-// - Apps can access their own files in /Android/data/com.example/ without
-// requiring any additional GIDs.
-// - Separate permissions for protecting directories like Pictures and Music.
-// - Multi-user separation on the same physical device.
-
-#include "fuse.h"
-
-#define PROP_SDCARDFS_DEVICE "ro.sys.sdcardfs"
-#define PROP_SDCARDFS_USER "persist.sys.sdcardfs"
+// NOTE: This is a vestigial program that simply exists to mount the in-kernel
+// sdcardfs filesystem. The older FUSE-based design that used to live here has
+// been completely removed to avoid confusion.
/* Supplementary groups to execute with. */
static const gid_t kGroups[1] = { AID_PACKAGE_INFO };
-static bool package_parse_callback(pkg_info *info, void *userdata) {
- struct fuse_global *global = (struct fuse_global *)userdata;
- bool res = global->package_to_appid->emplace(info->name, info->uid).second;
- packagelist_free(info);
- return res;
-}
-
-static bool read_package_list(struct fuse_global* global) {
- pthread_mutex_lock(&global->lock);
-
- global->package_to_appid->clear();
- bool rc = packagelist_parse(package_parse_callback, global);
- DLOG(INFO) << "read_package_list: found " << global->package_to_appid->size() << " packages";
-
- // Regenerate ownership details using newly loaded mapping.
- derive_permissions_recursive_locked(global->fuse_default, &global->root);
-
- pthread_mutex_unlock(&global->lock);
-
- return rc;
-}
-
-static void watch_package_list(struct fuse_global* global) {
- struct inotify_event *event;
- char event_buf[512];
-
- int nfd = inotify_init();
- if (nfd == -1) {
- PLOG(ERROR) << "inotify_init failed";
- return;
- }
-
- bool active = false;
- while (1) {
- if (!active) {
- int res = inotify_add_watch(nfd, PACKAGES_LIST_FILE, IN_DELETE_SELF);
- if (res == -1) {
- if (errno == ENOENT || errno == EACCES) {
- /* Framework may not have created the file yet, sleep and retry. */
- LOG(ERROR) << "missing \"" << PACKAGES_LIST_FILE << "\"; retrying...";
- sleep(3);
- continue;
- } else {
- PLOG(ERROR) << "inotify_add_watch failed";
- return;
- }
- }
-
- /* Watch above will tell us about any future changes, so
- * read the current state. */
- if (read_package_list(global) == false) {
- LOG(ERROR) << "read_package_list failed";
- return;
- }
- active = true;
- }
-
- int event_pos = 0;
- ssize_t res = TEMP_FAILURE_RETRY(read(nfd, event_buf, sizeof(event_buf)));
- if (res == -1) {
- PLOG(ERROR) << "failed to read inotify event";
- return;
- } else if (static_cast<size_t>(res) < sizeof(*event)) {
- LOG(ERROR) << "failed to read inotify event: read " << res << " expected "
- << sizeof(event_buf);
- return;
- }
-
- while (res >= static_cast<ssize_t>(sizeof(*event))) {
- int event_size;
- event = reinterpret_cast<struct inotify_event*>(event_buf + event_pos);
-
- DLOG(INFO) << "inotify event: " << std::hex << event->mask << std::dec;
- if ((event->mask & IN_IGNORED) == IN_IGNORED) {
- /* Previously watched file was deleted, probably due to move
- * that swapped in new data; re-arm the watch and read. */
- active = false;
- }
-
- event_size = sizeof(*event) + event->len;
- res -= event_size;
- event_pos += event_size;
- }
- }
-}
-
-static int fuse_setup(struct fuse* fuse, gid_t gid, mode_t mask) {
- char opts[256];
-
- fuse->fd = TEMP_FAILURE_RETRY(open("/dev/fuse", O_RDWR | O_CLOEXEC));
- if (fuse->fd == -1) {
- PLOG(ERROR) << "failed to open fuse device";
- return -1;
- }
-
- umount2(fuse->dest_path, MNT_DETACH);
-
- snprintf(opts, sizeof(opts),
- "fd=%i,rootmode=40000,default_permissions,allow_other,user_id=%d,group_id=%d",
- fuse->fd, fuse->global->uid, fuse->global->gid);
- if (mount("/dev/fuse", fuse->dest_path, "fuse", MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_NOATIME,
- opts) == -1) {
- PLOG(ERROR) << "failed to mount fuse filesystem";
- return -1;
- }
-
- fuse->gid = gid;
- fuse->mask = mask;
-
- return 0;
-}
-
static void drop_privs(uid_t uid, gid_t gid) {
ScopedMinijail j(minijail_new());
minijail_set_supplementary_gids(j.get(), arraysize(kGroups), kGroups);
@@ -205,120 +59,6 @@
minijail_enter(j.get());
}
-static void* start_handler(void* data) {
- struct fuse_handler* handler = static_cast<fuse_handler*>(data);
- handle_fuse_requests(handler);
- return NULL;
-}
-
-static void run(const char* source_path, const char* label, uid_t uid,
- gid_t gid, userid_t userid, bool multi_user, bool full_write) {
- struct fuse_global global;
- struct fuse fuse_default;
- struct fuse fuse_read;
- struct fuse fuse_write;
- struct fuse_handler handler_default;
- struct fuse_handler handler_read;
- struct fuse_handler handler_write;
- pthread_t thread_default;
- pthread_t thread_read;
- pthread_t thread_write;
-
- memset(&global, 0, sizeof(global));
- memset(&fuse_default, 0, sizeof(fuse_default));
- memset(&fuse_read, 0, sizeof(fuse_read));
- memset(&fuse_write, 0, sizeof(fuse_write));
- memset(&handler_default, 0, sizeof(handler_default));
- memset(&handler_read, 0, sizeof(handler_read));
- memset(&handler_write, 0, sizeof(handler_write));
-
- pthread_mutex_init(&global.lock, NULL);
- global.package_to_appid = new AppIdMap;
- global.uid = uid;
- global.gid = gid;
- global.multi_user = multi_user;
- global.next_generation = 0;
- global.inode_ctr = 1;
-
- memset(&global.root, 0, sizeof(global.root));
- global.root.nid = FUSE_ROOT_ID; /* 1 */
- global.root.refcount = 2;
- global.root.namelen = strlen(source_path);
- global.root.name = strdup(source_path);
- global.root.userid = userid;
- global.root.uid = AID_ROOT;
- global.root.under_android = false;
-
- // Clang static analyzer think strcpy potentially overwrites other fields
- // in global. Use snprintf() to mute the false warning.
- snprintf(global.source_path, sizeof(global.source_path), "%s", source_path);
-
- if (multi_user) {
- global.root.perm = PERM_PRE_ROOT;
- snprintf(global.obb_path, sizeof(global.obb_path), "%s/obb", source_path);
- } else {
- global.root.perm = PERM_ROOT;
- snprintf(global.obb_path, sizeof(global.obb_path), "%s/Android/obb", source_path);
- }
-
- fuse_default.global = &global;
- fuse_read.global = &global;
- fuse_write.global = &global;
-
- global.fuse_default = &fuse_default;
- global.fuse_read = &fuse_read;
- global.fuse_write = &fuse_write;
-
- snprintf(fuse_default.dest_path, PATH_MAX, "/mnt/runtime/default/%s", label);
- snprintf(fuse_read.dest_path, PATH_MAX, "/mnt/runtime/read/%s", label);
- snprintf(fuse_write.dest_path, PATH_MAX, "/mnt/runtime/write/%s", label);
-
- handler_default.fuse = &fuse_default;
- handler_read.fuse = &fuse_read;
- handler_write.fuse = &fuse_write;
-
- handler_default.token = 0;
- handler_read.token = 1;
- handler_write.token = 2;
-
- umask(0);
-
- if (multi_user) {
- /* Multi-user storage is fully isolated per user, so "other"
- * permissions are completely masked off. */
- if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
- || fuse_setup(&fuse_read, AID_EVERYBODY, 0027)
- || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0027)) {
- PLOG(FATAL) << "failed to fuse_setup";
- }
- } else {
- /* Physical storage is readable by all users on device, but
- * the Android directories are masked off to a single user
- * deep inside attr_from_stat(). */
- if (fuse_setup(&fuse_default, AID_SDCARD_RW, 0006)
- || fuse_setup(&fuse_read, AID_EVERYBODY, full_write ? 0027 : 0022)
- || fuse_setup(&fuse_write, AID_EVERYBODY, full_write ? 0007 : 0022)) {
- PLOG(FATAL) << "failed to fuse_setup";
- }
- }
-
- // Will abort if priv-dropping fails.
- drop_privs(uid, gid);
-
- if (multi_user) {
- fs_prepare_dir(global.obb_path, 0775, uid, gid);
- }
-
- if (pthread_create(&thread_default, NULL, start_handler, &handler_default)
- || pthread_create(&thread_read, NULL, start_handler, &handler_read)
- || pthread_create(&thread_write, NULL, start_handler, &handler_write)) {
- LOG(FATAL) << "failed to pthread_create";
- }
-
- watch_package_list(&global);
- LOG(FATAL) << "terminated prematurely";
-}
-
static bool sdcardfs_setup(const std::string& source_path, const std::string& dest_path,
uid_t fsuid, gid_t fsgid, bool multi_user, userid_t userid, gid_t gid,
mode_t mask, bool derive_gid, bool default_normal) {
@@ -407,41 +147,6 @@
exit(0);
}
-static bool supports_sdcardfs(void) {
- std::string filesystems;
- if (!android::base::ReadFileToString("/proc/filesystems", &filesystems)) {
- PLOG(ERROR) << "Could not read /proc/filesystems";
- return false;
- }
- for (const auto& fs : android::base::Split(filesystems, "\n")) {
- if (fs.find("sdcardfs") != std::string::npos) return true;
- }
- return false;
-}
-
-static bool should_use_sdcardfs(void) {
- char property[PROPERTY_VALUE_MAX];
-
- // Allow user to have a strong opinion about state
- property_get(PROP_SDCARDFS_USER, property, "");
- if (!strcmp(property, "force_on")) {
- LOG(WARNING) << "User explicitly enabled sdcardfs";
- return supports_sdcardfs();
- } else if (!strcmp(property, "force_off")) {
- LOG(WARNING) << "User explicitly disabled sdcardfs";
- return false;
- }
-
- // Fall back to device opinion about state
- if (property_get_bool(PROP_SDCARDFS_DEVICE, true)) {
- LOG(WARNING) << "Device explicitly enabled sdcardfs";
- return supports_sdcardfs();
- } else {
- LOG(WARNING) << "Device explicitly disabled sdcardfs";
- return false;
- }
-}
-
static int usage() {
LOG(ERROR) << "usage: sdcard [OPTIONS] <source_path> <label>"
<< " -u: specify UID to run as"
@@ -536,11 +241,7 @@
sleep(1);
}
- if (should_use_sdcardfs()) {
- run_sdcardfs(source_path, label, uid, gid, userid, multi_user, full_write, derive_gid,
- default_normal);
- } else {
- run(source_path, label, uid, gid, userid, multi_user, full_write);
- }
+ run_sdcardfs(source_path, label, uid, gid, userid, multi_user, full_write, derive_gid,
+ default_normal);
return 1;
}