Merge "adb: turn CHECKs into an error + transport restart."
diff --git a/adb/sysdeps_win32.cpp b/adb/sysdeps_win32.cpp
index 886ded4..f86cd03 100644
--- a/adb/sysdeps_win32.cpp
+++ b/adb/sysdeps_win32.cpp
@@ -2606,7 +2606,9 @@
extern "C" int wmain(int argc, wchar_t **argv) {
// Convert args from UTF-16 to UTF-8 and pass that to main().
NarrowArgs narrow_args(argc, argv);
- return main(argc, narrow_args.data());
+
+ // Avoid destructing NarrowArgs: argv might have been mutated to point to string literals.
+ _exit(main(argc, narrow_args.data()));
}
// Shadow UTF-8 environment variable name/value pairs that are created from
diff --git a/base/Android.bp b/base/Android.bp
index 25a9f68..58b6fb5 100644
--- a/base/Android.bp
+++ b/base/Android.bp
@@ -111,6 +111,9 @@
"libbase_headers",
],
export_header_lib_headers: ["libbase_headers"],
+ static_libs: ["fmtlib"],
+ whole_static_libs: ["fmtlib"],
+ export_static_lib_headers: ["fmtlib"],
}
cc_library_static {
@@ -119,6 +122,9 @@
sdk_version: "current",
stl: "c++_static",
export_include_dirs: ["include"],
+ static_libs: ["fmtlib_ndk"],
+ whole_static_libs: ["fmtlib_ndk"],
+ export_static_lib_headers: ["fmtlib_ndk"],
}
// Tests
@@ -176,3 +182,21 @@
},
test_suites: ["device-tests"],
}
+
+cc_benchmark {
+ name: "libbase_benchmark",
+ defaults: ["libbase_cflags_defaults"],
+
+ srcs: ["format_benchmark.cpp"],
+ shared_libs: ["libbase"],
+
+ compile_multilib: "both",
+ multilib: {
+ lib32: {
+ suffix: "32",
+ },
+ lib64: {
+ suffix: "64",
+ },
+ },
+}
diff --git a/base/format_benchmark.cpp b/base/format_benchmark.cpp
new file mode 100644
index 0000000..9590b23
--- /dev/null
+++ b/base/format_benchmark.cpp
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "android-base/format.h"
+
+#include <limits>
+
+#include <benchmark/benchmark.h>
+
+#include "android-base/stringprintf.h"
+
+using android::base::StringPrintf;
+
+static void BenchmarkFormatInt(benchmark::State& state) {
+ for (auto _ : state) {
+ benchmark::DoNotOptimize(fmt::format("{} {} {}", 42, std::numeric_limits<int>::min(),
+ std::numeric_limits<int>::max()));
+ }
+}
+
+BENCHMARK(BenchmarkFormatInt);
+
+static void BenchmarkStringPrintfInt(benchmark::State& state) {
+ for (auto _ : state) {
+ benchmark::DoNotOptimize(StringPrintf("%d %d %d", 42, std::numeric_limits<int>::min(),
+ std::numeric_limits<int>::max()));
+ }
+}
+
+BENCHMARK(BenchmarkStringPrintfInt);
+
+static void BenchmarkFormatFloat(benchmark::State& state) {
+ for (auto _ : state) {
+ benchmark::DoNotOptimize(fmt::format("{} {} {}", 42.42, std::numeric_limits<float>::min(),
+ std::numeric_limits<float>::max()));
+ }
+}
+
+BENCHMARK(BenchmarkFormatFloat);
+
+static void BenchmarkStringPrintfFloat(benchmark::State& state) {
+ for (auto _ : state) {
+ benchmark::DoNotOptimize(StringPrintf("%f %f %f", 42.42, std::numeric_limits<float>::min(),
+ std::numeric_limits<float>::max()));
+ }
+}
+
+BENCHMARK(BenchmarkStringPrintfFloat);
+
+static void BenchmarkFormatStrings(benchmark::State& state) {
+ for (auto _ : state) {
+ benchmark::DoNotOptimize(fmt::format("{} hello there {}", "hi,", "!!"));
+ }
+}
+
+BENCHMARK(BenchmarkFormatStrings);
+
+static void BenchmarkStringPrintfStrings(benchmark::State& state) {
+ for (auto _ : state) {
+ benchmark::DoNotOptimize(StringPrintf("%s hello there %s", "hi,", "!!"));
+ }
+}
+
+BENCHMARK(BenchmarkStringPrintfStrings);
+
+// Run the benchmark
+BENCHMARK_MAIN();
diff --git a/mkbootimg/mkbootimg_dummy.cpp b/base/include/android-base/format.h
similarity index 62%
rename from mkbootimg/mkbootimg_dummy.cpp
rename to base/include/android-base/format.h
index 410d379..6799c1f 100644
--- a/mkbootimg/mkbootimg_dummy.cpp
+++ b/base/include/android-base/format.h
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2018 The Android Open Source Project
+ * Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -14,11 +14,12 @@
* limitations under the License.
*/
-#include <abi_check/mkbootimg_abi_check.h>
+#pragma once
-void mkbootimg_dummy(boot_img_hdr* hdr) {
- // TODO: Hack to trigger abi checks, remove this.
- if (hdr) {
- hdr--;
- }
-}
+// We include fmtlib here as an alias, since libbase will have fmtlib statically linked already.
+// It is accessed through its normal fmt:: namespace.
+#include <fmt/core.h>
+#include <fmt/format.h>
+#include <fmt/ostream.h>
+#include <fmt/printf.h>
+#include <fmt/time.h>
diff --git a/base/include/android-base/result.h b/base/include/android-base/result.h
index 8f00710..1b763af 100644
--- a/base/include/android-base/result.h
+++ b/base/include/android-base/result.h
@@ -28,9 +28,8 @@
// from when the error occurred. ResultError can be used in an ostream directly to print its
// string value.
//
-// Success is a typedef that aids in creating Result<T> that do not contain a return value.
-// Result<Success> is the correct return type for a function that either returns successfully or
-// returns an error value. Returning Success() from a function that returns Result<Success> is the
+// Result<void> is the correct return type for a function that either returns successfully or
+// returns an error value. Returning {} from a function that returns Result<void> is the
// correct way to indicate that a function without a return type has completed successfully.
//
// A successful Result<T> is constructed implicitly from any type that can be implicitly converted
@@ -43,10 +42,15 @@
// to the end of the failure string to aid in interacting with C APIs. Alternatively, an errno
// value can be directly specified via the Error() constructor.
//
-// ResultError can be used in the ostream when using Error to construct a Result<T>. In this case,
-// the string that the ResultError takes is passed through the stream normally, but the errno is
-// passed to the Result<T>. This can be used to pass errno from a failing C function up multiple
-// callers.
+// Errorf and ErrnoErrorf accept the format string syntax of the fmblib (https://fmt.dev).
+// Errorf("{} errors", num) is equivalent to Error() << num << " errors".
+//
+// ResultError can be used in the ostream and when using Error/Errorf to construct a Result<T>.
+// In this case, the string that the ResultError takes is passed through the stream normally, but
+// the errno is passed to the Result<T>. This can be used to pass errno from a failing C function up
+// multiple callers. Note that when the outer Result<T> is created with ErrnoError/ErrnoErrorf then
+// the errno from the inner ResultError is not passed. Also when multiple ResultError objects are
+// used, the errno of the last one is respected.
//
// ResultError can also directly construct a Result<T>. This is particularly useful if you have a
// function that return Result<T> but you have a Result<U> and want to return its error. In this
@@ -56,10 +60,10 @@
// Result<U> CalculateResult(const T& input) {
// U output;
// if (!SomeOtherCppFunction(input, &output)) {
-// return Error() << "SomeOtherCppFunction(" << input << ") failed";
+// return Errorf("SomeOtherCppFunction {} failed", input);
// }
// if (!c_api_function(output)) {
-// return ErrnoError() << "c_api_function(" << output << ") failed";
+// return ErrnoErrorf("c_api_function {} failed", output);
// }
// return output;
// }
@@ -76,14 +80,14 @@
#include <string>
#include "android-base/expected.h"
+#include "android-base/format.h"
namespace android {
namespace base {
struct ResultError {
template <typename T>
- ResultError(T&& message, int code)
- : message_(std::forward<T>(message)), code_(code) {}
+ ResultError(T&& message, int code) : message_(std::forward<T>(message)), code_(code) {}
template <typename T>
operator android::base::expected<T, ResultError>() {
@@ -123,18 +127,16 @@
template <typename T>
Error& operator<<(T&& t) {
+ if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, ResultError>) {
+ errno_ = t.code();
+ return (*this) << t.message();
+ }
int saved = errno;
ss_ << t;
errno = saved;
return *this;
}
- Error& operator<<(const ResultError& result_error) {
- (*this) << result_error.message();
- errno_ = result_error.code();
- return *this;
- }
-
const std::string str() const {
std::string str = ss_.str();
if (append_errno_) {
@@ -151,22 +153,53 @@
Error& operator=(const Error&) = delete;
Error& operator=(Error&&) = delete;
+ template <typename... Args>
+ friend Error Errorf(const char* fmt, const Args&... args);
+
+ template <typename... Args>
+ friend Error ErrnoErrorf(const char* fmt, const Args&... args);
+
private:
+ Error(bool append_errno, int errno_to_append, const std::string& message)
+ : errno_(errno_to_append), append_errno_(append_errno) {
+ (*this) << message;
+ }
+
std::stringstream ss_;
int errno_;
- bool append_errno_;
+ const bool append_errno_;
};
inline Error ErrnoError() {
return Error(errno);
}
+inline int ErrorCode(int code) {
+ return code;
+}
+
+// Return the error code of the last ResultError object, if any.
+// Otherwise, return `code` as it is.
+template <typename T, typename... Args>
+inline int ErrorCode(int code, T&& t, const Args&... args) {
+ if constexpr (std::is_same_v<std::remove_cv_t<std::remove_reference_t<T>>, ResultError>) {
+ return ErrorCode(t.code(), args...);
+ }
+ return ErrorCode(code, args...);
+}
+
+template <typename... Args>
+inline Error Errorf(const char* fmt, const Args&... args) {
+ return Error(false, ErrorCode(0, args...), fmt::format(fmt, args...));
+}
+
+template <typename... Args>
+inline Error ErrnoErrorf(const char* fmt, const Args&... args) {
+ return Error(true, errno, fmt::format(fmt, args...));
+}
+
template <typename T>
using Result = android::base::expected<T, ResultError>;
-// Usage: `Result<Success>` as a result type that doesn't contain a value.
-// Use `return {}` or `return Success()` to return with success.
-using Success = std::monostate;
-
} // namespace base
} // namespace android
diff --git a/base/result_test.cpp b/base/result_test.cpp
index d31e775..2ee4057 100644
--- a/base/result_test.cpp
+++ b/base/result_test.cpp
@@ -49,27 +49,6 @@
EXPECT_EQ('s', Result<std::string>("success")->data()[0]);
}
-TEST(result, result_success) {
- Result<Success> result = Success();
- ASSERT_TRUE(result);
- ASSERT_TRUE(result.has_value());
-
- EXPECT_EQ(Success(), *result);
- EXPECT_EQ(Success(), result.value());
-}
-
-TEST(result, result_success_rvalue) {
- // Success() doesn't actually create a Result<Success> object, but rather an object that can be
- // implicitly constructed into a Result<Success> object.
-
- auto MakeRvalueSuccessResult = []() -> Result<Success> { return Success(); };
- ASSERT_TRUE(MakeRvalueSuccessResult());
- ASSERT_TRUE(MakeRvalueSuccessResult().has_value());
-
- EXPECT_EQ(Success(), *MakeRvalueSuccessResult());
- EXPECT_EQ(Success(), MakeRvalueSuccessResult().value());
-}
-
TEST(result, result_void) {
Result<void> ok = {};
EXPECT_TRUE(ok);
@@ -96,7 +75,7 @@
}
TEST(result, result_error) {
- Result<Success> result = Error() << "failure" << 1;
+ Result<void> result = Error() << "failure" << 1;
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
@@ -105,7 +84,7 @@
}
TEST(result, result_error_empty) {
- Result<Success> result = Error();
+ Result<void> result = Error();
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
@@ -120,7 +99,7 @@
// definition will not know what the type, T, of the underlying Result<T> object that it would
// create is.
- auto MakeRvalueErrorResult = []() -> Result<Success> { return Error() << "failure" << 1; };
+ auto MakeRvalueErrorResult = []() -> Result<void> { return Error() << "failure" << 1; };
ASSERT_FALSE(MakeRvalueErrorResult());
ASSERT_FALSE(MakeRvalueErrorResult().has_value());
@@ -131,7 +110,7 @@
TEST(result, result_errno_error) {
constexpr int test_errno = 6;
errno = test_errno;
- Result<Success> result = ErrnoError() << "failure" << 1;
+ Result<void> result = ErrnoError() << "failure" << 1;
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
@@ -143,7 +122,7 @@
TEST(result, result_errno_error_no_text) {
constexpr int test_errno = 6;
errno = test_errno;
- Result<Success> result = ErrnoError();
+ Result<void> result = ErrnoError();
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
@@ -154,7 +133,7 @@
TEST(result, result_error_from_other_result) {
auto error_text = "test error"s;
- Result<Success> result = Error() << error_text;
+ Result<void> result = Error() << error_text;
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
@@ -164,13 +143,13 @@
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.has_value());
- EXPECT_EQ(0, result.error().code());
- EXPECT_EQ(error_text, result.error().message());
+ EXPECT_EQ(0, result2.error().code());
+ EXPECT_EQ(error_text, result2.error().message());
}
TEST(result, result_error_through_ostream) {
auto error_text = "test error"s;
- Result<Success> result = Error() << error_text;
+ Result<void> result = Error() << error_text;
ASSERT_FALSE(result);
ASSERT_FALSE(result.has_value());
@@ -180,15 +159,15 @@
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.has_value());
- EXPECT_EQ(0, result.error().code());
- EXPECT_EQ(error_text, result.error().message());
+ EXPECT_EQ(0, result2.error().code());
+ EXPECT_EQ(error_text, result2.error().message());
}
TEST(result, result_errno_error_through_ostream) {
auto error_text = "test error"s;
constexpr int test_errno = 6;
errno = 6;
- Result<Success> result = ErrnoError() << error_text;
+ Result<void> result = ErrnoError() << error_text;
errno = 0;
@@ -200,8 +179,8 @@
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.has_value());
- EXPECT_EQ(test_errno, result.error().code());
- EXPECT_EQ(error_text + ": " + strerror(test_errno), result.error().message());
+ EXPECT_EQ(test_errno, result2.error().code());
+ EXPECT_EQ(error_text + ": " + strerror(test_errno), result2.error().message());
}
TEST(result, constructor_forwarding) {
@@ -306,9 +285,7 @@
// constructor. This is done with by disabling the forwarding reference constructor if its first
// and only type is Result<T>.
TEST(result, result_result_with_success) {
- auto return_result_result_with_success = []() -> Result<Result<Success>> {
- return Result<Success>();
- };
+ auto return_result_result_with_success = []() -> Result<Result<void>> { return Result<void>(); };
auto result = return_result_result_with_success();
ASSERT_TRUE(result);
ASSERT_TRUE(*result);
@@ -318,8 +295,8 @@
}
TEST(result, result_result_with_failure) {
- auto return_result_result_with_error = []() -> Result<Result<Success>> {
- return Result<Success>(ResultError("failure string", 6));
+ auto return_result_result_with_error = []() -> Result<Result<void>> {
+ return Result<void>(ResultError("failure string", 6));
};
auto result = return_result_result_with_error();
ASSERT_TRUE(result);
@@ -378,5 +355,68 @@
EXPECT_EQ(old_errno, result2.error().code());
}
+TEST(result, error_with_fmt) {
+ Result<int> result = Errorf("{} {}!", "hello", "world");
+ EXPECT_EQ("hello world!", result.error().message());
+
+ result = Errorf("{} {}!", std::string("hello"), std::string("world"));
+ EXPECT_EQ("hello world!", result.error().message());
+
+ result = Errorf("{h} {w}!", fmt::arg("w", "world"), fmt::arg("h", "hello"));
+ EXPECT_EQ("hello world!", result.error().message());
+
+ result = Errorf("hello world!");
+ EXPECT_EQ("hello world!", result.error().message());
+
+ Result<int> result2 = Errorf("error occurred with {}", result.error());
+ EXPECT_EQ("error occurred with hello world!", result2.error().message());
+
+ constexpr int test_errno = 6;
+ errno = test_errno;
+ result = ErrnoErrorf("{} {}!", "hello", "world");
+ EXPECT_EQ(test_errno, result.error().code());
+ EXPECT_EQ("hello world!: "s + strerror(test_errno), result.error().message());
+}
+
+TEST(result, error_with_fmt_carries_errno) {
+ constexpr int inner_errno = 6;
+ errno = inner_errno;
+ Result<int> inner_result = ErrnoErrorf("inner failure");
+ errno = 0;
+ EXPECT_EQ(inner_errno, inner_result.error().code());
+
+ // outer_result is created with Errorf, but its error code is got from inner_result.
+ Result<int> outer_result = Errorf("outer failure caused by {}", inner_result.error());
+ EXPECT_EQ(inner_errno, outer_result.error().code());
+ EXPECT_EQ("outer failure caused by inner failure: "s + strerror(inner_errno),
+ outer_result.error().message());
+
+ // now both result objects are created with ErrnoErrorf. errno from the inner_result
+ // is not passed to outer_result.
+ constexpr int outer_errno = 10;
+ errno = outer_errno;
+ outer_result = ErrnoErrorf("outer failure caused by {}", inner_result.error());
+ EXPECT_EQ(outer_errno, outer_result.error().code());
+ EXPECT_EQ("outer failure caused by inner failure: "s + strerror(inner_errno) + ": "s +
+ strerror(outer_errno),
+ outer_result.error().message());
+}
+
+TEST(result, errno_chaining_multiple) {
+ constexpr int errno1 = 6;
+ errno = errno1;
+ Result<int> inner1 = ErrnoErrorf("error1");
+
+ constexpr int errno2 = 10;
+ errno = errno2;
+ Result<int> inner2 = ErrnoErrorf("error2");
+
+ // takes the error code of inner2 since its the last one.
+ Result<int> outer = Errorf("two errors: {}, {}", inner1.error(), inner2.error());
+ EXPECT_EQ(errno2, outer.error().code());
+ EXPECT_EQ("two errors: error1: "s + strerror(errno1) + ", error2: "s + strerror(errno2),
+ outer.error().message());
+}
+
} // namespace base
} // namespace android
diff --git a/fastboot/device/commands.cpp b/fastboot/device/commands.cpp
index 1b09f79..409ef70 100644
--- a/fastboot/device/commands.cpp
+++ b/fastboot/device/commands.cpp
@@ -39,6 +39,7 @@
#include "flashing.h"
#include "utility.h"
+using android::fs_mgr::MetadataBuilder;
using ::android::hardware::hidl_string;
using ::android::hardware::boot::V1_0::BoolResult;
using ::android::hardware::boot::V1_0::CommandResult;
@@ -46,8 +47,6 @@
using ::android::hardware::fastboot::V1_0::Result;
using ::android::hardware::fastboot::V1_0::Status;
-using namespace android::fs_mgr;
-
struct VariableHandlers {
// Callback to retrieve the value of a single variable.
std::function<bool(FastbootDevice*, const std::vector<std::string>&, std::string*)> get;
@@ -340,7 +339,7 @@
PartitionBuilder::PartitionBuilder(FastbootDevice* device, const std::string& partition_name)
: device_(device) {
std::string slot_suffix = GetSuperSlotSuffix(device, partition_name);
- slot_number_ = SlotNumberForSlotSuffix(slot_suffix);
+ slot_number_ = android::fs_mgr::SlotNumberForSlotSuffix(slot_suffix);
auto super_device = FindPhysicalPartition(fs_mgr_get_super_partition_name(slot_number_));
if (!super_device) {
return;
@@ -350,7 +349,7 @@
}
bool PartitionBuilder::Write() {
- std::unique_ptr<LpMetadata> metadata = builder_->Export();
+ auto metadata = builder_->Export();
if (!metadata) {
return false;
}
@@ -381,7 +380,7 @@
return device->WriteFail("Partition already exists");
}
- Partition* partition = builder->AddPartition(partition_name, 0);
+ auto partition = builder->AddPartition(partition_name, 0);
if (!partition) {
return device->WriteFail("Failed to add partition");
}
@@ -437,7 +436,7 @@
return device->WriteFail("Could not open super partition");
}
- Partition* partition = builder->FindPartition(partition_name);
+ auto partition = builder->FindPartition(partition_name);
if (!partition) {
return device->WriteFail("Partition does not exist");
}
@@ -466,7 +465,7 @@
class AutoMountMetadata {
public:
AutoMountMetadata() {
- Fstab proc_mounts;
+ android::fs_mgr::Fstab proc_mounts;
if (!ReadFstabFromFile("/proc/mounts", &proc_mounts)) {
LOG(ERROR) << "Could not read /proc/mounts";
return;
@@ -494,7 +493,7 @@
explicit operator bool() const { return mounted_; }
private:
- Fstab fstab_;
+ android::fs_mgr::Fstab fstab_;
bool mounted_ = false;
bool should_unmount_ = false;
};
diff --git a/fs_mgr/fs_mgr.cpp b/fs_mgr/fs_mgr.cpp
index 56ea92c..410209b 100644
--- a/fs_mgr/fs_mgr.cpp
+++ b/fs_mgr/fs_mgr.cpp
@@ -245,11 +245,11 @@
if (should_force_check(*fs_stat)) {
ret = android_fork_execvp_ext(
ARRAY_SIZE(e2fsck_forced_argv), const_cast<char**>(e2fsck_forced_argv), &status,
- true, LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), NULL, 0);
+ true, LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), nullptr, 0);
} else {
ret = android_fork_execvp_ext(
ARRAY_SIZE(e2fsck_argv), const_cast<char**>(e2fsck_argv), &status, true,
- LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), NULL, 0);
+ LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), nullptr, 0);
}
if (ret < 0) {
@@ -263,13 +263,19 @@
}
} else if (is_f2fs(fs_type)) {
const char* f2fs_fsck_argv[] = {F2FS_FSCK_BIN, "-a", blk_device.c_str()};
- LINFO << "Running " << F2FS_FSCK_BIN << " -a " << realpath(blk_device);
+ const char* f2fs_fsck_forced_argv[] = {F2FS_FSCK_BIN, "-f", blk_device.c_str()};
- ret = android_fork_execvp_ext(ARRAY_SIZE(f2fs_fsck_argv),
- const_cast<char **>(f2fs_fsck_argv),
- &status, true, LOG_KLOG | LOG_FILE,
- true, const_cast<char *>(FSCK_LOG_FILE),
- NULL, 0);
+ if (should_force_check(*fs_stat)) {
+ LINFO << "Running " << F2FS_FSCK_BIN << " -f " << realpath(blk_device);
+ ret = android_fork_execvp_ext(
+ ARRAY_SIZE(f2fs_fsck_forced_argv), const_cast<char**>(f2fs_fsck_forced_argv), &status,
+ true, LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), nullptr, 0);
+ } else {
+ LINFO << "Running " << F2FS_FSCK_BIN << " -a " << realpath(blk_device);
+ ret = android_fork_execvp_ext(
+ ARRAY_SIZE(f2fs_fsck_argv), const_cast<char**>(f2fs_fsck_argv), &status, true,
+ LOG_KLOG | LOG_FILE, true, const_cast<char*>(FSCK_LOG_FILE), nullptr, 0);
+ }
if (ret < 0) {
/* No need to check for error in fork, we can't really handle it now */
LERROR << "Failed trying to run " << F2FS_FSCK_BIN;
diff --git a/fs_mgr/fs_mgr_fstab.cpp b/fs_mgr/fs_mgr_fstab.cpp
index 403f9be..31790b1 100644
--- a/fs_mgr/fs_mgr_fstab.cpp
+++ b/fs_mgr/fs_mgr_fstab.cpp
@@ -171,6 +171,18 @@
fs_options.append(","); // appends a comma if not the first
}
fs_options.append(flag);
+
+ if (entry->fs_type == "f2fs" && StartsWith(flag, "reserve_root=")) {
+ std::string arg;
+ if (auto equal_sign = flag.find('='); equal_sign != std::string::npos) {
+ arg = flag.substr(equal_sign + 1);
+ }
+ if (!ParseInt(arg, &entry->reserved_size)) {
+ LWARNING << "Warning: reserve_root= flag malformed: " << arg;
+ } else {
+ entry->reserved_size <<= 12;
+ }
+ }
}
}
entry->fs_options = std::move(fs_options);
diff --git a/fs_mgr/libfiemap_writer/Android.bp b/fs_mgr/libfiemap_writer/Android.bp
index 32fc3d2..ed209aa 100644
--- a/fs_mgr/libfiemap_writer/Android.bp
+++ b/fs_mgr/libfiemap_writer/Android.bp
@@ -30,6 +30,7 @@
],
static_libs: [
+ "libdm",
"libext4_utils",
],
diff --git a/fs_mgr/libfiemap_writer/fiemap_writer.cpp b/fs_mgr/libfiemap_writer/fiemap_writer.cpp
index e3803d5..f064436 100644
--- a/fs_mgr/libfiemap_writer/fiemap_writer.cpp
+++ b/fs_mgr/libfiemap_writer/fiemap_writer.cpp
@@ -37,10 +37,13 @@
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
+#include <libdm/dm.h>
namespace android {
namespace fiemap_writer {
+using namespace android::dm;
+
// We are expecting no more than 512 extents in a fiemap of the file we create.
// If we find more, then it is treated as error for now.
static constexpr const uint32_t kMaxExtents = 512;
@@ -87,14 +90,57 @@
}
static bool DeviceMapperStackPop(const std::string& bdev, std::string* bdev_raw) {
- // TODO: Stop popping the device mapper stack if dm-linear target is found
+ *bdev_raw = bdev;
+
if (!::android::base::StartsWith(bdev, "dm-")) {
// We are at the bottom of the device mapper stack.
- *bdev_raw = bdev;
return true;
}
- std::string dm_leaf_dir = ::android::base::StringPrintf("/sys/block/%s/slaves", bdev.c_str());
+ // Get the device name.
+ auto dm_name_file = "/sys/block/" + bdev + "/dm/name";
+ std::string dm_name;
+ if (!android::base::ReadFileToString(dm_name_file, &dm_name)) {
+ PLOG(ERROR) << "Could not read file: " << dm_name_file;
+ return false;
+ }
+ dm_name = android::base::Trim(dm_name);
+
+ auto& dm = DeviceMapper::Instance();
+ std::vector<DeviceMapper::TargetInfo> table;
+ if (!dm.GetTableInfo(dm_name, &table)) {
+ LOG(ERROR) << "Could not read device-mapper table for " << dm_name << " at " << bdev;
+ return false;
+ }
+
+ // The purpose of libfiemap_writer is to provide an extent-based view into
+ // a file. This is difficult if devices are not layered in a 1:1 manner;
+ // we would have to translate and break up extents based on the actual
+ // block mapping. Since this is too complex, we simply stop processing
+ // the device-mapper stack if we encounter a complex case.
+ //
+ // It is up to the caller to decide whether stopping at a virtual block
+ // device is allowable. In most cases it is not, because we want either
+ // "userdata" or an external volume. It is useful for tests however.
+ // Callers can check by comparing the device number to that of userdata,
+ // or by checking whether is a device-mapper node.
+ if (table.size() > 1) {
+ LOG(INFO) << "Stopping at complex table for " << dm_name << " at " << bdev;
+ return true;
+ }
+ const auto& entry = table[0].spec;
+ std::string target_type(std::string(entry.target_type, sizeof(entry.target_type)).c_str());
+ if (target_type != "bow" && target_type != "default-key" && target_type != "crypt") {
+ LOG(INFO) << "Stopping at complex target-type " << target_type << " for " << dm_name
+ << " at " << bdev;
+ return true;
+ }
+ if (entry.sector_start != 0) {
+ LOG(INFO) << "Stopping at target-type with non-zero starting sector";
+ return true;
+ }
+
+ auto dm_leaf_dir = "/sys/block/" + bdev + "/slaves";
auto d = std::unique_ptr<DIR, decltype(&closedir)>(opendir(dm_leaf_dir.c_str()), closedir);
if (d == nullptr) {
PLOG(ERROR) << "Failed to open: " << dm_leaf_dir;
diff --git a/fs_mgr/libfiemap_writer/include/libfiemap_writer/fiemap_writer.h b/fs_mgr/libfiemap_writer/include/libfiemap_writer/fiemap_writer.h
index 9486122..ee79262 100644
--- a/fs_mgr/libfiemap_writer/include/libfiemap_writer/fiemap_writer.h
+++ b/fs_mgr/libfiemap_writer/include/libfiemap_writer/fiemap_writer.h
@@ -60,10 +60,17 @@
// FiemapWriter::Open).
static bool HasPinnedExtents(const std::string& file_path);
- // Returns the underlying block device of a file. This will look past device-mapper layers.
- // If an intermediate device-mapper layer would not maintain a 1:1 mapping (i.e. is a non-
- // trivial dm-linear), then this will fail. If device-mapper nodes are encountered, then
- // |uses_dm| will be set to true.
+ // Returns the underlying block device of a file. This will look past device-mapper layers
+ // as long as each layer would not change block mappings (i.e., dm-crypt, dm-bow, and dm-
+ // default-key tables are okay; dm-linear is not). If a mapping such as dm-linear is found,
+ // it will be returned in place of any physical block device.
+ //
+ // It is the caller's responsibility to check whether the returned block device is acceptable.
+ // Gsid, for example, will only accept /dev/block/by-name/userdata as the bottom device.
+ // Callers can check the device name (dm- or loop prefix), inspect sysfs, or compare the major
+ // number against a boot device.
+ //
+ // If device-mapper nodes were encountered, then |uses_dm| will be set to true.
static bool GetBlockDeviceForFile(const std::string& file_path, std::string* bdev_path,
bool* uses_dm = nullptr);
diff --git a/fs_mgr/liblp/Android.bp b/fs_mgr/liblp/Android.bp
index 7039994..b504161 100644
--- a/fs_mgr/liblp/Android.bp
+++ b/fs_mgr/liblp/Android.bp
@@ -14,6 +14,16 @@
// limitations under the License.
//
+liblp_lib_deps = [
+ "libbase",
+ "liblog",
+ "libcrypto",
+ "libcrypto_utils",
+ "libsparse",
+ "libext4_utils",
+ "libz",
+]
+
cc_library {
name: "liblp",
host_supported: true,
@@ -30,15 +40,7 @@
"utility.cpp",
"writer.cpp",
],
- shared_libs: [
- "libbase",
- "liblog",
- "libcrypto",
- "libcrypto_utils",
- "libsparse",
- "libext4_utils",
- "libz",
- ],
+ shared_libs: liblp_lib_deps,
target: {
windows: {
enabled: true,
@@ -53,24 +55,28 @@
}
cc_test {
- name: "liblp_test",
+ name: "liblp_test_static",
defaults: ["fs_mgr_defaults"],
cppflags: [
"-Wno-unused-parameter",
],
static_libs: [
"libgmock",
- ],
- shared_libs: [
- "liblp",
- "libbase",
"libfs_mgr",
- "libsparse",
- ],
+ "liblp",
+ ] + liblp_lib_deps,
+ stl: "libc++_static",
srcs: [
"builder_test.cpp",
"io_test.cpp",
"test_partition_opener.cpp",
"utility_test.cpp",
],
+ target: {
+ android: {
+ static_libs: [
+ "libcutils",
+ ],
+ },
+ },
}
diff --git a/fs_mgr/liblp/AndroidTest.xml b/fs_mgr/liblp/AndroidTest.xml
index 007a302..fe1002c 100644
--- a/fs_mgr/liblp/AndroidTest.xml
+++ b/fs_mgr/liblp/AndroidTest.xml
@@ -21,8 +21,8 @@
</target_preparer>
<test class="com.android.tradefed.testtype.VtsMultiDeviceTest">
<option name="test-module-name" value="VtsKernelLiblpTest"/>
- <option name="binary-test-source" value="_32bit::DATA/nativetest/liblp_test/liblp_test" />
- <option name="binary-test-source" value="_64bit::DATA/nativetest64/liblp_test/liblp_test" />
+ <option name="binary-test-source" value="_32bit::DATA/nativetest/liblp_test_static/liblp_test_static" />
+ <option name="binary-test-source" value="_64bit::DATA/nativetest64/liblp_test_static/liblp_test_static" />
<option name="binary-test-type" value="gtest"/>
<option name="test-timeout" value="1m"/>
<option name="precondition-first-api-level" value="29" />
diff --git a/fs_mgr/liblp/builder.cpp b/fs_mgr/liblp/builder.cpp
index 41c01da..25a042f 100644
--- a/fs_mgr/liblp/builder.cpp
+++ b/fs_mgr/liblp/builder.cpp
@@ -214,7 +214,7 @@
sABOverrideValue = ab_device;
}
-MetadataBuilder::MetadataBuilder() : auto_slot_suffixing_(false), ignore_slot_suffixing_(false) {
+MetadataBuilder::MetadataBuilder() : auto_slot_suffixing_(false) {
memset(&geometry_, 0, sizeof(geometry_));
geometry_.magic = LP_METADATA_GEOMETRY_MAGIC;
geometry_.struct_size = sizeof(geometry_);
@@ -443,11 +443,6 @@
LERROR << "Could not find partition group: " << group_name;
return nullptr;
}
- if (IsABDevice() && !auto_slot_suffixing_ && name != "scratch" && !ignore_slot_suffixing_ &&
- GetPartitionSlotSuffix(name).empty()) {
- LERROR << "Unsuffixed partition not allowed on A/B device: " << name;
- return nullptr;
- }
partitions_.push_back(std::make_unique<Partition>(name, group_name, attributes));
return partitions_.back().get();
}
@@ -1049,10 +1044,6 @@
auto_slot_suffixing_ = true;
}
-void MetadataBuilder::IgnoreSlotSuffixing() {
- ignore_slot_suffixing_ = true;
-}
-
bool MetadataBuilder::IsABDevice() const {
if (sABOverrideSet) {
return sABOverrideValue;
diff --git a/fs_mgr/liblp/builder_test.cpp b/fs_mgr/liblp/builder_test.cpp
index 46bfe92..34c68d4 100644
--- a/fs_mgr/liblp/builder_test.cpp
+++ b/fs_mgr/liblp/builder_test.cpp
@@ -106,6 +106,13 @@
EXPECT_EQ(extent->num_sectors(), 32768 / LP_SECTOR_SIZE);
EXPECT_EQ(extent->physical_sector(), 32);
+ auto exported = builder->Export();
+ ASSERT_NE(exported, nullptr);
+ ASSERT_EQ(FindPartition(*exported.get(), "not found"), nullptr);
+ auto entry = FindPartition(*exported.get(), "system");
+ ASSERT_NE(entry, nullptr);
+ ASSERT_EQ(GetPartitionSize(*exported.get(), *entry), 32768);
+
// Test shrinking to 0.
builder->ResizePartition(system, 0);
EXPECT_EQ(system->size(), 0);
@@ -765,15 +772,6 @@
EXPECT_FALSE(builder->ImportPartitions(*exported.get(), {"system"}));
}
-TEST_F(BuilderTest, UnsuffixedPartitions) {
- MetadataBuilder::OverrideABForTesting(true);
- unique_ptr<MetadataBuilder> builder = MetadataBuilder::New(1024 * 1024, 1024, 2);
- ASSERT_NE(builder, nullptr);
-
- ASSERT_EQ(builder->AddPartition("system", 0), nullptr);
- ASSERT_NE(builder->AddPartition("system_a", 0), nullptr);
-}
-
TEST_F(BuilderTest, ABExtents) {
BlockDeviceInfo device_info("super", 10_GiB, 768 * 1024, 0, 4096);
diff --git a/fs_mgr/liblp/include/liblp/builder.h b/fs_mgr/liblp/include/liblp/builder.h
index c706f2a..e70c552 100644
--- a/fs_mgr/liblp/include/liblp/builder.h
+++ b/fs_mgr/liblp/include/liblp/builder.h
@@ -345,7 +345,6 @@
std::vector<std::unique_ptr<PartitionGroup>> groups_;
std::vector<LpMetadataBlockDevice> block_devices_;
bool auto_slot_suffixing_;
- bool ignore_slot_suffixing_;
};
// Read BlockDeviceInfo for a given block device. This always returns false
diff --git a/fs_mgr/liblp/include/liblp/liblp.h b/fs_mgr/liblp/include/liblp/liblp.h
index d3a7b93..135a1b3 100644
--- a/fs_mgr/liblp/include/liblp/liblp.h
+++ b/fs_mgr/liblp/include/liblp/liblp.h
@@ -107,6 +107,10 @@
std::string SlotSuffixForSlotNumber(uint32_t slot_number);
std::string GetPartitionSlotSuffix(const std::string& partition_name);
+// Helpers for common functions.
+const LpMetadataPartition* FindPartition(const LpMetadata& metadata, const std::string& name);
+uint64_t GetPartitionSize(const LpMetadata& metadata, const LpMetadataPartition& partition);
+
} // namespace fs_mgr
} // namespace android
diff --git a/fs_mgr/liblp/utility.cpp b/fs_mgr/liblp/utility.cpp
index 72a3c57..338b525 100644
--- a/fs_mgr/liblp/utility.cpp
+++ b/fs_mgr/liblp/utility.cpp
@@ -135,6 +135,24 @@
return list;
}
+const LpMetadataPartition* FindPartition(const LpMetadata& metadata, const std::string& name) {
+ for (const auto& partition : metadata.partitions) {
+ if (GetPartitionName(partition) == name) {
+ return &partition;
+ }
+ }
+ return nullptr;
+}
+
+uint64_t GetPartitionSize(const LpMetadata& metadata, const LpMetadataPartition& partition) {
+ uint64_t total_size = 0;
+ for (uint32_t i = 0; i < partition.num_extents; i++) {
+ const auto& extent = metadata.extents[partition.first_extent_index + i];
+ total_size += extent.num_sectors * LP_SECTOR_SIZE;
+ }
+ return total_size;
+}
+
std::string GetPartitionSlotSuffix(const std::string& partition_name) {
if (partition_name.size() <= 2) {
return "";
diff --git a/init/action.cpp b/init/action.cpp
index a40172e..a169591 100644
--- a/init/action.cpp
+++ b/init/action.cpp
@@ -28,9 +28,8 @@
namespace android {
namespace init {
-Result<Success> RunBuiltinFunction(const BuiltinFunction& function,
- const std::vector<std::string>& args,
- const std::string& context) {
+Result<void> RunBuiltinFunction(const BuiltinFunction& function,
+ const std::vector<std::string>& args, const std::string& context) {
auto builtin_arguments = BuiltinArguments(context);
builtin_arguments.args.resize(args.size());
@@ -51,7 +50,7 @@
args_(std::move(args)),
line_(line) {}
-Result<Success> Command::InvokeFunc(Subcontext* subcontext) const {
+Result<void> Command::InvokeFunc(Subcontext* subcontext) const {
if (subcontext) {
if (execute_in_subcontext_) {
return subcontext->Execute(args_);
@@ -83,7 +82,7 @@
const KeywordFunctionMap* Action::function_map_ = nullptr;
-Result<Success> Action::AddCommand(std::vector<std::string>&& args, int line) {
+Result<void> Action::AddCommand(std::vector<std::string>&& args, int line) {
if (!function_map_) {
return Error() << "no function map available";
}
@@ -92,7 +91,7 @@
if (!function) return Error() << function.error();
commands_.emplace_back(function->second, function->first, std::move(args), line);
- return Success();
+ return {};
}
void Action::AddCommand(BuiltinFunction f, std::vector<std::string>&& args, int line) {
diff --git a/init/action.h b/init/action.h
index 967c682..13b250a 100644
--- a/init/action.h
+++ b/init/action.h
@@ -31,15 +31,15 @@
namespace android {
namespace init {
-Result<Success> RunBuiltinFunction(const BuiltinFunction& function,
- const std::vector<std::string>& args, const std::string& context);
+Result<void> RunBuiltinFunction(const BuiltinFunction& function,
+ const std::vector<std::string>& args, const std::string& context);
class Command {
public:
Command(BuiltinFunction f, bool execute_in_subcontext, std::vector<std::string>&& args,
int line);
- Result<Success> InvokeFunc(Subcontext* subcontext) const;
+ Result<void> InvokeFunc(Subcontext* subcontext) const;
std::string BuildCommandString() const;
int line() const { return line_; }
@@ -61,7 +61,7 @@
const std::string& event_trigger,
const std::map<std::string, std::string>& property_triggers);
- Result<Success> AddCommand(std::vector<std::string>&& args, int line);
+ Result<void> AddCommand(std::vector<std::string>&& args, int line);
void AddCommand(BuiltinFunction f, std::vector<std::string>&& args, int line);
std::size_t NumCommands() const;
void ExecuteOneCommand(std::size_t command) const;
diff --git a/init/action_parser.cpp b/init/action_parser.cpp
index 4f8bd16..ff20e43 100644
--- a/init/action_parser.cpp
+++ b/init/action_parser.cpp
@@ -55,8 +55,8 @@
return CanReadProperty(subcontext->context(), prop_name);
}
-Result<Success> ParsePropertyTrigger(const std::string& trigger, Subcontext* subcontext,
- std::map<std::string, std::string>* property_triggers) {
+Result<void> ParsePropertyTrigger(const std::string& trigger, Subcontext* subcontext,
+ std::map<std::string, std::string>* property_triggers) {
const static std::string prop_str("property:");
std::string prop_name(trigger.substr(prop_str.length()));
size_t equal_pos = prop_name.find('=');
@@ -74,12 +74,12 @@
if (auto [it, inserted] = property_triggers->emplace(prop_name, prop_value); !inserted) {
return Error() << "multiple property triggers found for same property";
}
- return Success();
+ return {};
}
-Result<Success> ParseTriggers(const std::vector<std::string>& args, Subcontext* subcontext,
- std::string* event_trigger,
- std::map<std::string, std::string>* property_triggers) {
+Result<void> ParseTriggers(const std::vector<std::string>& args, Subcontext* subcontext,
+ std::string* event_trigger,
+ std::map<std::string, std::string>* property_triggers) {
const static std::string prop_str("property:");
for (std::size_t i = 0; i < args.size(); ++i) {
if (args[i].empty()) {
@@ -108,13 +108,13 @@
}
}
- return Success();
+ return {};
}
} // namespace
-Result<Success> ActionParser::ParseSection(std::vector<std::string>&& args,
- const std::string& filename, int line) {
+Result<void> ActionParser::ParseSection(std::vector<std::string>&& args,
+ const std::string& filename, int line) {
std::vector<std::string> triggers(args.begin() + 1, args.end());
if (triggers.size() < 1) {
return Error() << "Actions must have a trigger";
@@ -142,19 +142,19 @@
property_triggers);
action_ = std::move(action);
- return Success();
+ return {};
}
-Result<Success> ActionParser::ParseLineSection(std::vector<std::string>&& args, int line) {
- return action_ ? action_->AddCommand(std::move(args), line) : Success();
+Result<void> ActionParser::ParseLineSection(std::vector<std::string>&& args, int line) {
+ return action_ ? action_->AddCommand(std::move(args), line) : Result<void>{};
}
-Result<Success> ActionParser::EndSection() {
+Result<void> ActionParser::EndSection() {
if (action_ && action_->NumCommands() > 0) {
action_manager_->AddAction(std::move(action_));
}
- return Success();
+ return {};
}
} // namespace init
diff --git a/init/action_parser.h b/init/action_parser.h
index b7f7074..2fe9983 100644
--- a/init/action_parser.h
+++ b/init/action_parser.h
@@ -32,10 +32,10 @@
public:
ActionParser(ActionManager* action_manager, std::vector<Subcontext>* subcontexts)
: action_manager_(action_manager), subcontexts_(subcontexts), action_(nullptr) {}
- Result<Success> ParseSection(std::vector<std::string>&& args, const std::string& filename,
- int line) override;
- Result<Success> ParseLineSection(std::vector<std::string>&& args, int line) override;
- Result<Success> EndSection() override;
+ Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
+ int line) override;
+ Result<void> ParseLineSection(std::vector<std::string>&& args, int line) override;
+ Result<void> EndSection() override;
private:
ActionManager* action_manager_;
diff --git a/init/bootchart.cpp b/init/bootchart.cpp
index c2cf573..b7db9b6 100644
--- a/init/bootchart.cpp
+++ b/init/bootchart.cpp
@@ -165,20 +165,20 @@
LOG(INFO) << "Bootcharting finished";
}
-static Result<Success> do_bootchart_start() {
+static Result<void> do_bootchart_start() {
// We don't care about the content, but we do care that /data/bootchart/enabled actually exists.
std::string start;
if (!android::base::ReadFileToString("/data/bootchart/enabled", &start)) {
LOG(VERBOSE) << "Not bootcharting";
- return Success();
+ return {};
}
g_bootcharting_thread = new std::thread(bootchart_thread_main);
- return Success();
+ return {};
}
-static Result<Success> do_bootchart_stop() {
- if (!g_bootcharting_thread) return Success();
+static Result<void> do_bootchart_stop() {
+ if (!g_bootcharting_thread) return {};
// Tell the worker thread it's time to quit.
{
@@ -190,10 +190,10 @@
g_bootcharting_thread->join();
delete g_bootcharting_thread;
g_bootcharting_thread = nullptr;
- return Success();
+ return {};
}
-Result<Success> do_bootchart(const BuiltinArguments& args) {
+Result<void> do_bootchart(const BuiltinArguments& args) {
if (args[1] == "start") return do_bootchart_start();
return do_bootchart_stop();
}
diff --git a/init/bootchart.h b/init/bootchart.h
index 05474ca..6f19aad 100644
--- a/init/bootchart.h
+++ b/init/bootchart.h
@@ -26,7 +26,7 @@
namespace android {
namespace init {
-Result<Success> do_bootchart(const BuiltinArguments& args);
+Result<void> do_bootchart(const BuiltinArguments& args);
} // namespace init
} // namespace android
diff --git a/init/boringssl_self_test.cpp b/init/boringssl_self_test.cpp
index 0408d30..759eb43 100644
--- a/init/boringssl_self_test.cpp
+++ b/init/boringssl_self_test.cpp
@@ -25,7 +25,7 @@
namespace android {
namespace init {
-Result<Success> StartBoringSslSelfTest(const BuiltinArguments&) {
+Result<void> StartBoringSslSelfTest(const BuiltinArguments&) {
pid_t id = fork();
if (id == 0) {
@@ -49,7 +49,7 @@
PLOG(FATAL) << "Failed to fork for BoringSSL self test";
}
- return Success();
+ return {};
}
} // namespace init
diff --git a/init/boringssl_self_test.h b/init/boringssl_self_test.h
index b21fc78..9e717d0 100644
--- a/init/boringssl_self_test.h
+++ b/init/boringssl_self_test.h
@@ -22,7 +22,7 @@
namespace android {
namespace init {
-Result<Success> StartBoringSslSelfTest(const BuiltinArguments&);
+Result<void> StartBoringSslSelfTest(const BuiltinArguments&);
} // namespace init
} // namespace android
diff --git a/init/builtins.cpp b/init/builtins.cpp
index e9d58c6..44cac4b 100644
--- a/init/builtins.cpp
+++ b/init/builtins.cpp
@@ -90,14 +90,14 @@
static constexpr std::chrono::nanoseconds kCommandRetryTimeout = 5s;
-static Result<Success> reboot_into_recovery(const std::vector<std::string>& options) {
+static Result<void> reboot_into_recovery(const std::vector<std::string>& options) {
LOG(ERROR) << "Rebooting into recovery";
std::string err;
if (!write_bootloader_message(options, &err)) {
return Error() << "Failed to set bootloader message: " << err;
}
property_set("sys.powerctl", "reboot,recovery");
- return Success();
+ return {};
}
template <typename F>
@@ -107,10 +107,10 @@
}
}
-static Result<Success> do_class_start(const BuiltinArguments& args) {
+static Result<void> do_class_start(const BuiltinArguments& args) {
// Do not start a class if it has a property persist.dont_start_class.CLASS set to 1.
if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
- return Success();
+ return {};
// Starting a class does not start services which are explicitly disabled.
// They must be started individually.
for (const auto& service : ServiceList::GetInstance()) {
@@ -121,10 +121,10 @@
}
}
}
- return Success();
+ return {};
}
-static Result<Success> do_class_start_post_data(const BuiltinArguments& args) {
+static Result<void> do_class_start_post_data(const BuiltinArguments& args) {
if (args.context != kInitContext) {
return Error() << "command 'class_start_post_data' only available in init context";
}
@@ -136,43 +136,43 @@
}
}
}
- return Success();
+ return {};
}
-static Result<Success> do_class_stop(const BuiltinArguments& args) {
+static Result<void> do_class_stop(const BuiltinArguments& args) {
ForEachServiceInClass(args[1], &Service::Stop);
- return Success();
+ return {};
}
-static Result<Success> do_class_reset(const BuiltinArguments& args) {
+static Result<void> do_class_reset(const BuiltinArguments& args) {
ForEachServiceInClass(args[1], &Service::Reset);
- return Success();
+ return {};
}
-static Result<Success> do_class_reset_post_data(const BuiltinArguments& args) {
+static Result<void> do_class_reset_post_data(const BuiltinArguments& args) {
if (args.context != kInitContext) {
return Error() << "command 'class_reset_post_data' only available in init context";
}
ForEachServiceInClass(args[1], &Service::ResetIfPostData);
- return Success();
+ return {};
}
-static Result<Success> do_class_restart(const BuiltinArguments& args) {
+static Result<void> do_class_restart(const BuiltinArguments& args) {
// Do not restart a class if it has a property persist.dont_start_class.CLASS set to 1.
if (android::base::GetBoolProperty("persist.init.dont_start_class." + args[1], false))
- return Success();
+ return {};
ForEachServiceInClass(args[1], &Service::Restart);
- return Success();
+ return {};
}
-static Result<Success> do_domainname(const BuiltinArguments& args) {
+static Result<void> do_domainname(const BuiltinArguments& args) {
if (auto result = WriteFile("/proc/sys/kernel/domainname", args[1]); !result) {
return Error() << "Unable to write to /proc/sys/kernel/domainname: " << result.error();
}
- return Success();
+ return {};
}
-static Result<Success> do_enable(const BuiltinArguments& args) {
+static Result<void> do_enable(const BuiltinArguments& args) {
Service* svc = ServiceList::GetInstance().FindService(args[1]);
if (!svc) return Error() << "Could not find service";
@@ -180,10 +180,10 @@
return Error() << "Could not enable service: " << result.error();
}
- return Success();
+ return {};
}
-static Result<Success> do_exec(const BuiltinArguments& args) {
+static Result<void> do_exec(const BuiltinArguments& args) {
auto service = Service::MakeTemporaryOneshotService(args.args);
if (!service) {
return Error() << "Could not create exec service";
@@ -193,10 +193,10 @@
}
ServiceList::GetInstance().AddService(std::move(service));
- return Success();
+ return {};
}
-static Result<Success> do_exec_background(const BuiltinArguments& args) {
+static Result<void> do_exec_background(const BuiltinArguments& args) {
auto service = Service::MakeTemporaryOneshotService(args.args);
if (!service) {
return Error() << "Could not create exec background service";
@@ -206,10 +206,10 @@
}
ServiceList::GetInstance().AddService(std::move(service));
- return Success();
+ return {};
}
-static Result<Success> do_exec_start(const BuiltinArguments& args) {
+static Result<void> do_exec_start(const BuiltinArguments& args) {
Service* service = ServiceList::GetInstance().FindService(args[1]);
if (!service) {
return Error() << "Service not found";
@@ -219,24 +219,24 @@
return Error() << "Could not start exec service: " << result.error();
}
- return Success();
+ return {};
}
-static Result<Success> do_export(const BuiltinArguments& args) {
+static Result<void> do_export(const BuiltinArguments& args) {
if (setenv(args[1].c_str(), args[2].c_str(), 1) == -1) {
return ErrnoError() << "setenv() failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_hostname(const BuiltinArguments& args) {
+static Result<void> do_hostname(const BuiltinArguments& args) {
if (auto result = WriteFile("/proc/sys/kernel/hostname", args[1]); !result) {
return Error() << "Unable to write to /proc/sys/kernel/hostname: " << result.error();
}
- return Success();
+ return {};
}
-static Result<Success> do_ifup(const BuiltinArguments& args) {
+static Result<void> do_ifup(const BuiltinArguments& args) {
struct ifreq ifr;
strlcpy(ifr.ifr_name, args[1].c_str(), IFNAMSIZ);
@@ -254,10 +254,10 @@
return ErrnoError() << "ioctl(..., SIOCSIFFLAGS, ...) failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_insmod(const BuiltinArguments& args) {
+static Result<void> do_insmod(const BuiltinArguments& args) {
int flags = 0;
auto it = args.begin() + 1;
@@ -275,34 +275,34 @@
int rc = syscall(__NR_finit_module, fd.get(), options.c_str(), flags);
if (rc == -1) return ErrnoError() << "finit_module for \"" << filename << "\" failed";
- return Success();
+ return {};
}
-static Result<Success> do_interface_restart(const BuiltinArguments& args) {
+static Result<void> do_interface_restart(const BuiltinArguments& args) {
Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
if (!svc) return Error() << "interface " << args[1] << " not found";
svc->Restart();
- return Success();
+ return {};
}
-static Result<Success> do_interface_start(const BuiltinArguments& args) {
+static Result<void> do_interface_start(const BuiltinArguments& args) {
Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
if (!svc) return Error() << "interface " << args[1] << " not found";
if (auto result = svc->Start(); !result) {
return Error() << "Could not start interface: " << result.error();
}
- return Success();
+ return {};
}
-static Result<Success> do_interface_stop(const BuiltinArguments& args) {
+static Result<void> do_interface_stop(const BuiltinArguments& args) {
Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
if (!svc) return Error() << "interface " << args[1] << " not found";
svc->Stop();
- return Success();
+ return {};
}
// mkdir <path> [mode] [owner] [group]
-static Result<Success> do_mkdir(const BuiltinArguments& args) {
+static Result<void> do_mkdir(const BuiltinArguments& args) {
mode_t mode = 0755;
if (args.size() >= 3) {
mode = std::strtoul(args[2].c_str(), 0, 8);
@@ -351,15 +351,15 @@
{"--prompt_and_wipe_data", "--reason=set_policy_failed:"s + args[1]});
}
}
- return Success();
+ return {};
}
/* umount <path> */
-static Result<Success> do_umount(const BuiltinArguments& args) {
+static Result<void> do_umount(const BuiltinArguments& args) {
if (umount(args[1].c_str()) < 0) {
return ErrnoError() << "umount() failed";
}
- return Success();
+ return {};
}
static struct {
@@ -387,7 +387,7 @@
#define DATA_MNT_POINT "/data"
/* mount <type> <device> <path> <flags ...> <options> */
-static Result<Success> do_mount(const BuiltinArguments& args) {
+static Result<void> do_mount(const BuiltinArguments& args) {
const char* options = nullptr;
unsigned flags = 0;
bool wait = false;
@@ -434,7 +434,7 @@
ioctl(loop, LOOP_CLR_FD, 0);
return ErrnoError() << "mount() failed";
}
- return Success();
+ return {};
}
}
}
@@ -449,7 +449,7 @@
}
- return Success();
+ return {};
}
/* Imports .rc files from the specified paths. Default ones are applied if none is given.
@@ -486,23 +486,23 @@
*
* return code is processed based on input code
*/
-static Result<Success> queue_fs_event(int code) {
+static Result<void> queue_fs_event(int code) {
if (code == FS_MGR_MNTALL_DEV_NEEDS_ENCRYPTION) {
ActionManager::GetInstance().QueueEventTrigger("encrypt");
- return Success();
+ return {};
} else if (code == FS_MGR_MNTALL_DEV_MIGHT_BE_ENCRYPTED) {
property_set("ro.crypto.state", "encrypted");
property_set("ro.crypto.type", "block");
ActionManager::GetInstance().QueueEventTrigger("defaultcrypto");
- return Success();
+ return {};
} else if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTED) {
property_set("ro.crypto.state", "unencrypted");
ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
- return Success();
+ return {};
} else if (code == FS_MGR_MNTALL_DEV_NOT_ENCRYPTABLE) {
property_set("ro.crypto.state", "unsupported");
ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
- return Success();
+ return {};
} else if (code == FS_MGR_MNTALL_DEV_NEEDS_RECOVERY) {
/* Setup a wipe via recovery, and reboot into recovery */
if (android::gsi::IsGsiRunning()) {
@@ -522,7 +522,7 @@
// Although encrypted, we have device key, so we do not need to
// do anything different from the nonencrypted case.
ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
- return Success();
+ return {};
} else if (code == FS_MGR_MNTALL_DEV_IS_METADATA_ENCRYPTED) {
if (fscrypt_install_keyring()) {
return Error() << "fscrypt_install_keyring() failed";
@@ -533,7 +533,7 @@
// Although encrypted, vold has already set the device up, so we do not need to
// do anything different from the nonencrypted case.
ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
- return Success();
+ return {};
} else if (code == FS_MGR_MNTALL_DEV_NEEDS_METADATA_ENCRYPTION) {
if (fscrypt_install_keyring()) {
return Error() << "fscrypt_install_keyring() failed";
@@ -544,7 +544,7 @@
// Although encrypted, vold has already set the device up, so we do not need to
// do anything different from the nonencrypted case.
ActionManager::GetInstance().QueueEventTrigger("nonencrypted");
- return Success();
+ return {};
} else if (code > 0) {
Error() << "fs_mgr_mount_all() returned unexpected error " << code;
}
@@ -558,7 +558,7 @@
* This function might request a reboot, in which case it will
* not return.
*/
-static Result<Success> do_mount_all(const BuiltinArguments& args) {
+static Result<void> do_mount_all(const BuiltinArguments& args) {
std::size_t na = 0;
bool import_rc = true;
bool queue_event = true;
@@ -605,11 +605,11 @@
}
}
- return Success();
+ return {};
}
/* umount_all <fstab> */
-static Result<Success> do_umount_all(const BuiltinArguments& args) {
+static Result<void> do_umount_all(const BuiltinArguments& args) {
Fstab fstab;
if (!ReadFstabFromFile(args[1], &fstab)) {
return Error() << "Could not read fstab";
@@ -618,10 +618,10 @@
if (auto result = fs_mgr_umount_all(&fstab); result != 0) {
return Error() << "umount_fstab() failed " << result;
}
- return Success();
+ return {};
}
-static Result<Success> do_swapon_all(const BuiltinArguments& args) {
+static Result<void> do_swapon_all(const BuiltinArguments& args) {
Fstab fstab;
if (!ReadFstabFromFile(args[1], &fstab)) {
return Error() << "Could not read fstab '" << args[1] << "'";
@@ -631,50 +631,50 @@
return Error() << "fs_mgr_swapon_all() failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_setprop(const BuiltinArguments& args) {
+static Result<void> do_setprop(const BuiltinArguments& args) {
property_set(args[1], args[2]);
- return Success();
+ return {};
}
-static Result<Success> do_setrlimit(const BuiltinArguments& args) {
+static Result<void> do_setrlimit(const BuiltinArguments& args) {
auto rlimit = ParseRlimit(args.args);
if (!rlimit) return rlimit.error();
if (setrlimit(rlimit->first, &rlimit->second) == -1) {
return ErrnoError() << "setrlimit failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_start(const BuiltinArguments& args) {
+static Result<void> do_start(const BuiltinArguments& args) {
Service* svc = ServiceList::GetInstance().FindService(args[1]);
if (!svc) return Error() << "service " << args[1] << " not found";
if (auto result = svc->Start(); !result) {
return Error() << "Could not start service: " << result.error();
}
- return Success();
+ return {};
}
-static Result<Success> do_stop(const BuiltinArguments& args) {
+static Result<void> do_stop(const BuiltinArguments& args) {
Service* svc = ServiceList::GetInstance().FindService(args[1]);
if (!svc) return Error() << "service " << args[1] << " not found";
svc->Stop();
- return Success();
+ return {};
}
-static Result<Success> do_restart(const BuiltinArguments& args) {
+static Result<void> do_restart(const BuiltinArguments& args) {
Service* svc = ServiceList::GetInstance().FindService(args[1]);
if (!svc) return Error() << "service " << args[1] << " not found";
svc->Restart();
- return Success();
+ return {};
}
-static Result<Success> do_trigger(const BuiltinArguments& args) {
+static Result<void> do_trigger(const BuiltinArguments& args) {
ActionManager::GetInstance().QueueEventTrigger(args[1]);
- return Success();
+ return {};
}
static int MakeSymlink(const std::string& target, const std::string& linkpath) {
@@ -695,33 +695,33 @@
return rc;
}
-static Result<Success> do_symlink(const BuiltinArguments& args) {
+static Result<void> do_symlink(const BuiltinArguments& args) {
if (MakeSymlink(args[1], args[2]) < 0) {
// The symlink builtin is often used to create symlinks for older devices to be backwards
// compatible with new paths, therefore we skip reporting this error.
if (errno == EEXIST && android::base::GetMinimumLogSeverity() > android::base::DEBUG) {
- return Success();
+ return {};
}
return ErrnoError() << "symlink() failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_rm(const BuiltinArguments& args) {
+static Result<void> do_rm(const BuiltinArguments& args) {
if (unlink(args[1].c_str()) < 0) {
return ErrnoError() << "unlink() failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_rmdir(const BuiltinArguments& args) {
+static Result<void> do_rmdir(const BuiltinArguments& args) {
if (rmdir(args[1].c_str()) < 0) {
return ErrnoError() << "rmdir() failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_sysclktz(const BuiltinArguments& args) {
+static Result<void> do_sysclktz(const BuiltinArguments& args) {
struct timezone tz = {};
if (!android::base::ParseInt(args[1], &tz.tz_minuteswest)) {
return Error() << "Unable to parse mins_west_of_gmt";
@@ -730,10 +730,10 @@
if (settimeofday(nullptr, &tz) == -1) {
return ErrnoError() << "settimeofday() failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_verity_update_state(const BuiltinArguments& args) {
+static Result<void> do_verity_update_state(const BuiltinArguments& args) {
int mode;
if (!fs_mgr_load_verity_state(&mode)) {
return Error() << "fs_mgr_load_verity_state() failed";
@@ -755,18 +755,18 @@
property_set("partition." + partition + ".verified", std::to_string(mode));
}
- return Success();
+ return {};
}
-static Result<Success> do_write(const BuiltinArguments& args) {
+static Result<void> do_write(const BuiltinArguments& args) {
if (auto result = WriteFile(args[1], args[2]); !result) {
return Error() << "Unable to write to file '" << args[1] << "': " << result.error();
}
- return Success();
+ return {};
}
-static Result<Success> readahead_file(const std::string& filename, bool fully) {
+static Result<void> readahead_file(const std::string& filename, bool fully) {
android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY)));
if (fd == -1) {
return ErrnoError() << "Error opening file";
@@ -786,10 +786,10 @@
return ErrnoError() << "Error reading file";
}
}
- return Success();
+ return {};
}
-static Result<Success> do_readahead(const BuiltinArguments& args) {
+static Result<void> do_readahead(const BuiltinArguments& args) {
struct stat sb;
if (stat(args[1].c_str(), &sb)) {
@@ -845,10 +845,10 @@
} else if (pid < 0) {
return ErrnoError() << "Fork failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_copy(const BuiltinArguments& args) {
+static Result<void> do_copy(const BuiltinArguments& args) {
auto file_contents = ReadFile(args[1]);
if (!file_contents) {
return Error() << "Could not read input file '" << args[1] << "': " << file_contents.error();
@@ -857,10 +857,10 @@
return Error() << "Could not write to output file '" << args[2] << "': " << result.error();
}
- return Success();
+ return {};
}
-static Result<Success> do_chown(const BuiltinArguments& args) {
+static Result<void> do_chown(const BuiltinArguments& args) {
auto uid = DecodeUid(args[1]);
if (!uid) {
return Error() << "Unable to decode UID for '" << args[1] << "': " << uid.error();
@@ -881,7 +881,7 @@
return ErrnoError() << "lchown() failed";
}
- return Success();
+ return {};
}
static mode_t get_mode(const char *s) {
@@ -897,15 +897,15 @@
return mode;
}
-static Result<Success> do_chmod(const BuiltinArguments& args) {
+static Result<void> do_chmod(const BuiltinArguments& args) {
mode_t mode = get_mode(args[1].c_str());
if (fchmodat(AT_FDCWD, args[2].c_str(), mode, AT_SYMLINK_NOFOLLOW) < 0) {
return ErrnoError() << "fchmodat() failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_restorecon(const BuiltinArguments& args) {
+static Result<void> do_restorecon(const BuiltinArguments& args) {
int ret = 0;
struct flag_type {const char* name; int value;};
@@ -944,16 +944,16 @@
}
if (ret) return ErrnoError() << "selinux_android_restorecon() failed";
- return Success();
+ return {};
}
-static Result<Success> do_restorecon_recursive(const BuiltinArguments& args) {
+static Result<void> do_restorecon_recursive(const BuiltinArguments& args) {
std::vector<std::string> non_const_args(args.args);
non_const_args.insert(std::next(non_const_args.begin()), "--recursive");
return do_restorecon({std::move(non_const_args), args.context});
}
-static Result<Success> do_loglevel(const BuiltinArguments& args) {
+static Result<void> do_loglevel(const BuiltinArguments& args) {
// TODO: support names instead/as well?
int log_level = -1;
android::base::ParseInt(args[1], &log_level);
@@ -971,20 +971,20 @@
return Error() << "invalid log level " << log_level;
}
android::base::SetMinimumLogSeverity(severity);
- return Success();
+ return {};
}
-static Result<Success> do_load_persist_props(const BuiltinArguments& args) {
+static Result<void> do_load_persist_props(const BuiltinArguments& args) {
load_persist_props();
- return Success();
+ return {};
}
-static Result<Success> do_load_system_props(const BuiltinArguments& args) {
+static Result<void> do_load_system_props(const BuiltinArguments& args) {
LOG(INFO) << "deprecated action `load_system_props` called.";
- return Success();
+ return {};
}
-static Result<Success> do_wait(const BuiltinArguments& args) {
+static Result<void> do_wait(const BuiltinArguments& args) {
auto timeout = kCommandRetryTimeout;
if (args.size() == 3) {
int timeout_int;
@@ -998,10 +998,10 @@
return Error() << "wait_for_file() failed";
}
- return Success();
+ return {};
}
-static Result<Success> do_wait_for_prop(const BuiltinArguments& args) {
+static Result<void> do_wait_for_prop(const BuiltinArguments& args) {
const char* name = args[1].c_str();
const char* value = args[2].c_str();
size_t value_len = strlen(value);
@@ -1015,15 +1015,15 @@
if (!start_waiting_for_property(name, value)) {
return Error() << "already waiting for a property";
}
- return Success();
+ return {};
}
static bool is_file_crypto() {
return android::base::GetProperty("ro.crypto.type", "") == "file";
}
-static Result<Success> ExecWithRebootOnFailure(const std::string& reboot_reason,
- const BuiltinArguments& args) {
+static Result<void> ExecWithRebootOnFailure(const std::string& reboot_reason,
+ const BuiltinArguments& args) {
auto service = Service::MakeTemporaryOneshotService(args.args);
if (!service) {
return Error() << "Could not create exec service";
@@ -1047,11 +1047,11 @@
return Error() << "Could not start exec service: " << result.error();
}
ServiceList::GetInstance().AddService(std::move(service));
- return Success();
+ return {};
}
-static Result<Success> do_installkey(const BuiltinArguments& args) {
- if (!is_file_crypto()) return Success();
+static Result<void> do_installkey(const BuiltinArguments& args) {
+ if (!is_file_crypto()) return {};
auto unencrypted_dir = args[1] + fscrypt_unencrypted_folder;
if (!make_dir(unencrypted_dir, 0700) && errno != EEXIST) {
@@ -1062,24 +1062,21 @@
{{"exec", "/system/bin/vdc", "--wait", "cryptfs", "enablefilecrypto"}, args.context});
}
-static Result<Success> do_init_user0(const BuiltinArguments& args) {
+static Result<void> do_init_user0(const BuiltinArguments& args) {
return ExecWithRebootOnFailure(
"init_user0_failed",
{{"exec", "/system/bin/vdc", "--wait", "cryptfs", "init_user0"}, args.context});
}
-static Result<Success> do_mark_post_data(const BuiltinArguments& args) {
+static Result<void> do_mark_post_data(const BuiltinArguments& args) {
ServiceList::GetInstance().MarkPostData();
- return Success();
+ return {};
}
-static Result<Success> do_parse_apex_configs(const BuiltinArguments& args) {
+static Result<void> do_parse_apex_configs(const BuiltinArguments& args) {
glob_t glob_result;
- // @ is added to filter out the later paths, which are bind mounts of the places
- // where the APEXes are really mounted at. Otherwise, we will parse the
- // same file twice.
- static constexpr char glob_pattern[] = "/apex/*@*/etc/*.rc";
+ static constexpr char glob_pattern[] = "/apex/*/etc/*.rc";
const int ret = glob(glob_pattern, GLOB_MARK, nullptr, &glob_result);
if (ret != 0 && ret != GLOB_NOMATCH) {
globfree(&glob_result);
@@ -1088,7 +1085,15 @@
std::vector<std::string> configs;
Parser parser = CreateServiceOnlyParser(ServiceList::GetInstance());
for (size_t i = 0; i < glob_result.gl_pathc; i++) {
- configs.emplace_back(glob_result.gl_pathv[i]);
+ std::string path = glob_result.gl_pathv[i];
+ // Filter-out /apex/<name>@<ver> paths. The paths are bind-mounted to
+ // /apex/<name> paths, so unless we filter them out, we will parse the
+ // same file twice.
+ std::vector<std::string> paths = android::base::Split(path, "/");
+ if (paths.size() >= 2 && paths[1].find('@') != std::string::npos) {
+ continue;
+ }
+ configs.push_back(path);
}
globfree(&glob_result);
@@ -1102,15 +1107,15 @@
}
ServiceList::GetInstance().MarkServicesUpdate();
if (success) {
- return Success();
+ return {};
} else {
return Error() << "Could not parse apex configs";
}
}
-static Result<Success> do_enter_default_mount_ns(const BuiltinArguments& args) {
+static Result<void> do_enter_default_mount_ns(const BuiltinArguments& args) {
if (SwitchToDefaultMountNamespace()) {
- return Success();
+ return {};
} else {
return Error() << "Failed to enter into default mount namespace";
}
diff --git a/init/builtins.h b/init/builtins.h
index 814b2d5..5db0d1c 100644
--- a/init/builtins.h
+++ b/init/builtins.h
@@ -29,7 +29,7 @@
namespace android {
namespace init {
-using BuiltinFunction = std::function<Result<Success>(const BuiltinArguments&)>;
+using BuiltinFunction = std::function<Result<void>(const BuiltinArguments&)>;
using KeywordFunctionMap = KeywordMap<std::pair<bool, BuiltinFunction>>;
class BuiltinFunctionMap : public KeywordFunctionMap {
diff --git a/init/epoll.cpp b/init/epoll.cpp
index 94dd553..01d8867 100644
--- a/init/epoll.cpp
+++ b/init/epoll.cpp
@@ -28,17 +28,17 @@
Epoll::Epoll() {}
-Result<Success> Epoll::Open() {
- if (epoll_fd_ >= 0) return Success();
+Result<void> Epoll::Open() {
+ if (epoll_fd_ >= 0) return {};
epoll_fd_.reset(epoll_create1(EPOLL_CLOEXEC));
if (epoll_fd_ == -1) {
return ErrnoError() << "epoll_create1 failed";
}
- return Success();
+ return {};
}
-Result<Success> Epoll::RegisterHandler(int fd, std::function<void()> handler, uint32_t events) {
+Result<void> Epoll::RegisterHandler(int fd, std::function<void()> handler, uint32_t events) {
if (!events) {
return Error() << "Must specify events";
}
@@ -52,24 +52,24 @@
// pointer to the std::function in the map directly for epoll_ctl.
ev.data.ptr = reinterpret_cast<void*>(&it->second);
if (epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &ev) == -1) {
- Result<Success> result = ErrnoError() << "epoll_ctl failed to add fd";
+ Result<void> result = ErrnoError() << "epoll_ctl failed to add fd";
epoll_handlers_.erase(fd);
return result;
}
- return Success();
+ return {};
}
-Result<Success> Epoll::UnregisterHandler(int fd) {
+Result<void> Epoll::UnregisterHandler(int fd) {
if (epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, nullptr) == -1) {
return ErrnoError() << "epoll_ctl failed to remove fd";
}
if (epoll_handlers_.erase(fd) != 1) {
return Error() << "Attempting to remove epoll handler for FD without an existing handler";
}
- return Success();
+ return {};
}
-Result<Success> Epoll::Wait(std::optional<std::chrono::milliseconds> timeout) {
+Result<void> Epoll::Wait(std::optional<std::chrono::milliseconds> timeout) {
int timeout_ms = -1;
if (timeout && timeout->count() < INT_MAX) {
timeout_ms = timeout->count();
@@ -81,7 +81,7 @@
} else if (nr == 1) {
std::invoke(*reinterpret_cast<std::function<void()>*>(ev.data.ptr));
}
- return Success();
+ return {};
}
} // namespace init
diff --git a/init/epoll.h b/init/epoll.h
index 9789bef..ca84266 100644
--- a/init/epoll.h
+++ b/init/epoll.h
@@ -36,11 +36,10 @@
public:
Epoll();
- Result<Success> Open();
- Result<Success> RegisterHandler(int fd, std::function<void()> handler,
- uint32_t events = EPOLLIN);
- Result<Success> UnregisterHandler(int fd);
- Result<Success> Wait(std::optional<std::chrono::milliseconds> timeout);
+ Result<void> Open();
+ Result<void> RegisterHandler(int fd, std::function<void()> handler, uint32_t events = EPOLLIN);
+ Result<void> UnregisterHandler(int fd);
+ Result<void> Wait(std::optional<std::chrono::milliseconds> timeout);
private:
android::base::unique_fd epoll_fd_;
diff --git a/init/host_import_parser.cpp b/init/host_import_parser.cpp
index 93e363f..aa80199 100644
--- a/init/host_import_parser.cpp
+++ b/init/host_import_parser.cpp
@@ -23,16 +23,16 @@
namespace android {
namespace init {
-Result<Success> HostImportParser::ParseSection(std::vector<std::string>&& args, const std::string&,
- int) {
+Result<void> HostImportParser::ParseSection(std::vector<std::string>&& args, const std::string&,
+ int) {
if (args.size() != 2) {
return Error() << "single argument needed for import\n";
}
- return Success();
+ return {};
}
-Result<Success> HostImportParser::ParseLineSection(std::vector<std::string>&&, int) {
+Result<void> HostImportParser::ParseLineSection(std::vector<std::string>&&, int) {
return Error() << "Unexpected line found after import statement";
}
diff --git a/init/host_import_parser.h b/init/host_import_parser.h
index 52b8891..d6f7286 100644
--- a/init/host_import_parser.h
+++ b/init/host_import_parser.h
@@ -27,8 +27,8 @@
class HostImportParser : public SectionParser {
public:
HostImportParser() {}
- Result<Success> ParseSection(std::vector<std::string>&& args, const std::string&, int) override;
- Result<Success> ParseLineSection(std::vector<std::string>&&, int) override;
+ Result<void> ParseSection(std::vector<std::string>&& args, const std::string&, int) override;
+ Result<void> ParseLineSection(std::vector<std::string>&&, int) override;
};
} // namespace init
diff --git a/init/host_init_verifier.cpp b/init/host_init_verifier.cpp
index 8407729..cb861f3 100644
--- a/init/host_init_verifier.cpp
+++ b/init/host_init_verifier.cpp
@@ -118,8 +118,8 @@
namespace android {
namespace init {
-static Result<Success> do_stub(const BuiltinArguments& args) {
- return Success();
+static Result<void> do_stub(const BuiltinArguments& args) {
+ return {};
}
#include "generated_stub_builtin_function_map.h"
diff --git a/init/import_parser.cpp b/init/import_parser.cpp
index fb3185e..c72b7d6 100644
--- a/init/import_parser.cpp
+++ b/init/import_parser.cpp
@@ -23,8 +23,8 @@
namespace android {
namespace init {
-Result<Success> ImportParser::ParseSection(std::vector<std::string>&& args,
- const std::string& filename, int line) {
+Result<void> ImportParser::ParseSection(std::vector<std::string>&& args,
+ const std::string& filename, int line) {
if (args.size() != 2) {
return Error() << "single argument needed for import\n";
}
@@ -38,10 +38,10 @@
LOG(INFO) << "Added '" << conf_file << "' to import list";
if (filename_.empty()) filename_ = filename;
imports_.emplace_back(std::move(conf_file), line);
- return Success();
+ return {};
}
-Result<Success> ImportParser::ParseLineSection(std::vector<std::string>&&, int) {
+Result<void> ImportParser::ParseLineSection(std::vector<std::string>&&, int) {
return Error() << "Unexpected line found after import statement";
}
diff --git a/init/import_parser.h b/init/import_parser.h
index 7bc72e6..5bf9c6c 100644
--- a/init/import_parser.h
+++ b/init/import_parser.h
@@ -28,9 +28,9 @@
class ImportParser : public SectionParser {
public:
ImportParser(Parser* parser) : parser_(parser) {}
- Result<Success> ParseSection(std::vector<std::string>&& args, const std::string& filename,
- int line) override;
- Result<Success> ParseLineSection(std::vector<std::string>&&, int) override;
+ Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
+ int line) override;
+ Result<void> ParseLineSection(std::vector<std::string>&&, int) override;
void EndFile() override;
private:
diff --git a/init/init.cpp b/init/init.cpp
index 8ce96f6..1412e4a 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -237,18 +237,18 @@
return next_process_action_time;
}
-static Result<Success> DoControlStart(Service* service) {
+static Result<void> DoControlStart(Service* service) {
return service->Start();
}
-static Result<Success> DoControlStop(Service* service) {
+static Result<void> DoControlStop(Service* service) {
service->Stop();
- return Success();
+ return {};
}
-static Result<Success> DoControlRestart(Service* service) {
+static Result<void> DoControlRestart(Service* service) {
service->Restart();
- return Success();
+ return {};
}
enum class ControlTarget {
@@ -258,16 +258,16 @@
struct ControlMessageFunction {
ControlTarget target;
- std::function<Result<Success>(Service*)> action;
+ std::function<Result<void>(Service*)> action;
};
static const std::map<std::string, ControlMessageFunction>& get_control_message_map() {
// clang-format off
static const std::map<std::string, ControlMessageFunction> control_message_functions = {
{"sigstop_on", {ControlTarget::SERVICE,
- [](auto* service) { service->set_sigstop(true); return Success(); }}},
+ [](auto* service) { service->set_sigstop(true); return Result<void>{}; }}},
{"sigstop_off", {ControlTarget::SERVICE,
- [](auto* service) { service->set_sigstop(false); return Success(); }}},
+ [](auto* service) { service->set_sigstop(false); return Result<void>{}; }}},
{"start", {ControlTarget::SERVICE, DoControlStart}},
{"stop", {ControlTarget::SERVICE, DoControlStop}},
{"restart", {ControlTarget::SERVICE, DoControlRestart}},
@@ -330,7 +330,7 @@
return true;
}
-static Result<Success> wait_for_coldboot_done_action(const BuiltinArguments& args) {
+static Result<void> wait_for_coldboot_done_action(const BuiltinArguments& args) {
Timer t;
LOG(VERBOSE) << "Waiting for " COLDBOOT_DONE "...";
@@ -348,18 +348,18 @@
}
property_set("ro.boottime.init.cold_boot_wait", std::to_string(t.duration().count()));
- return Success();
+ return {};
}
-static Result<Success> console_init_action(const BuiltinArguments& args) {
+static Result<void> console_init_action(const BuiltinArguments& args) {
std::string console = GetProperty("ro.boot.console", "");
if (!console.empty()) {
default_console = "/dev/" + console;
}
- return Success();
+ return {};
}
-static Result<Success> SetupCgroupsAction(const BuiltinArguments&) {
+static Result<void> SetupCgroupsAction(const BuiltinArguments&) {
// Have to create <CGROUPS_RC_DIR> using make_dir function
// for appropriate sepolicy to be set for it
make_dir(android::base::Dirname(CGROUPS_RC_PATH), 0711);
@@ -367,7 +367,7 @@
return ErrnoError() << "Failed to setup cgroups";
}
- return Success();
+ return {};
}
static void import_kernel_nv(const std::string& key, const std::string& value, bool for_emulator) {
@@ -451,19 +451,19 @@
if (qemu[0]) import_kernel_cmdline(true, import_kernel_nv);
}
-static Result<Success> property_enable_triggers_action(const BuiltinArguments& args) {
+static Result<void> property_enable_triggers_action(const BuiltinArguments& args) {
/* Enable property triggers. */
property_triggers_enabled = 1;
- return Success();
+ return {};
}
-static Result<Success> queue_property_triggers_action(const BuiltinArguments& args) {
+static Result<void> queue_property_triggers_action(const BuiltinArguments& args) {
ActionManager::GetInstance().QueueBuiltinAction(property_enable_triggers_action, "enable_property_trigger");
ActionManager::GetInstance().QueueAllPropertyActions();
- return Success();
+ return {};
}
-static Result<Success> InitBinder(const BuiltinArguments& args) {
+static Result<void> InitBinder(const BuiltinArguments& args) {
// init's use of binder is very limited. init cannot:
// - have any binder threads
// - receive incoming binder calls
@@ -478,7 +478,7 @@
android::ProcessState::self()->setCallRestriction(
ProcessState::CallRestriction::ERROR_IF_NOT_ONEWAY);
#endif
- return Success();
+ return {};
}
// Set the UDC controller for the ConfigFS USB Gadgets.
@@ -757,14 +757,14 @@
am.QueueBuiltinAction(SetKptrRestrictAction, "SetKptrRestrict");
Keychords keychords;
am.QueueBuiltinAction(
- [&epoll, &keychords](const BuiltinArguments& args) -> Result<Success> {
- for (const auto& svc : ServiceList::GetInstance()) {
- keychords.Register(svc->keycodes());
- }
- keychords.Start(&epoll, HandleKeychord);
- return Success();
- },
- "KeychordInit");
+ [&epoll, &keychords](const BuiltinArguments& args) -> Result<void> {
+ for (const auto& svc : ServiceList::GetInstance()) {
+ keychords.Register(svc->keycodes());
+ }
+ keychords.Start(&epoll, HandleKeychord);
+ return {};
+ },
+ "KeychordInit");
am.QueueBuiltinAction(console_init_action, "console_init");
// Trigger all the boot actions to get us started.
diff --git a/init/init_test.cpp b/init/init_test.cpp
index c2f0c41..18c2b38 100644
--- a/init/init_test.cpp
+++ b/init/init_test.cpp
@@ -180,7 +180,7 @@
auto execute_command = [&num_executed](const BuiltinArguments& args) {
EXPECT_EQ(2U, args.size());
EXPECT_EQ(++num_executed, std::stoi(args[1]));
- return Success();
+ return Result<void>{};
};
TestFunctionMap test_function_map;
diff --git a/init/keychords_test.cpp b/init/keychords_test.cpp
index a3baeb1..33373d4 100644
--- a/init/keychords_test.cpp
+++ b/init/keychords_test.cpp
@@ -29,7 +29,6 @@
#include <vector>
#include <android-base/properties.h>
-#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <gtest/gtest.h>
diff --git a/init/keyword_map.h b/init/keyword_map.h
index c95fc73..7837bb3 100644
--- a/init/keyword_map.h
+++ b/init/keyword_map.h
@@ -14,14 +14,11 @@
* limitations under the License.
*/
-#ifndef _INIT_KEYWORD_MAP_H_
-#define _INIT_KEYWORD_MAP_H_
+#pragma once
#include <map>
#include <string>
-#include <android-base/stringprintf.h>
-
#include "result.h"
namespace android {
@@ -37,8 +34,6 @@
}
const Result<Function> FindFunction(const std::vector<std::string>& args) const {
- using android::base::StringPrintf;
-
if (args.empty()) return Error() << "Keyword needed, but not provided";
auto& keyword = args[0];
@@ -46,7 +41,7 @@
auto function_info_it = map().find(keyword);
if (function_info_it == map().end()) {
- return Error() << StringPrintf("Invalid keyword '%s'", keyword.c_str());
+ return Errorf("Invalid keyword '{}'", keyword);
}
auto function_info = function_info_it->second;
@@ -54,17 +49,17 @@
auto min_args = std::get<0>(function_info);
auto max_args = std::get<1>(function_info);
if (min_args == max_args && num_args != min_args) {
- return Error() << StringPrintf("%s requires %zu argument%s", keyword.c_str(), min_args,
- (min_args > 1 || min_args == 0) ? "s" : "");
+ return Errorf("{} requires {} argument{}", keyword, min_args,
+ (min_args > 1 || min_args == 0) ? "s" : "");
}
if (num_args < min_args || num_args > max_args) {
if (max_args == std::numeric_limits<decltype(max_args)>::max()) {
- return Error() << StringPrintf("%s requires at least %zu argument%s",
- keyword.c_str(), min_args, min_args > 1 ? "s" : "");
+ return Errorf("{} requires at least {} argument{}", keyword, min_args,
+ min_args > 1 ? "s" : "");
} else {
- return Error() << StringPrintf("%s requires between %zu and %zu arguments",
- keyword.c_str(), min_args, max_args);
+ return Errorf("{} requires between {} and {} arguments", keyword, min_args,
+ max_args);
}
}
@@ -79,5 +74,3 @@
} // namespace init
} // namespace android
-
-#endif
diff --git a/init/modalias_handler.cpp b/init/modalias_handler.cpp
index c61c210..a511156 100644
--- a/init/modalias_handler.cpp
+++ b/init/modalias_handler.cpp
@@ -33,7 +33,7 @@
namespace android {
namespace init {
-Result<Success> ModaliasHandler::ParseDepCallback(std::vector<std::string>&& args) {
+Result<void> ModaliasHandler::ParseDepCallback(std::vector<std::string>&& args) {
std::vector<std::string> deps;
// Set first item as our modules path
@@ -58,10 +58,10 @@
std::replace(mod_name.begin(), mod_name.end(), '-', '_');
this->module_deps_[mod_name] = deps;
- return Success();
+ return {};
}
-Result<Success> ModaliasHandler::ParseAliasCallback(std::vector<std::string>&& args) {
+Result<void> ModaliasHandler::ParseAliasCallback(std::vector<std::string>&& args) {
auto it = args.begin();
const std::string& type = *it++;
@@ -77,7 +77,7 @@
std::string& module_name = *it++;
this->module_aliases_.emplace_back(alias, module_name);
- return Success();
+ return {};
}
ModaliasHandler::ModaliasHandler() {
@@ -100,7 +100,7 @@
for (const auto& base_path : base_paths) dep_parser.ParseConfig(base_path + "modules.dep");
}
-Result<Success> ModaliasHandler::Insmod(const std::string& path_name, const std::string& args) {
+Result<void> ModaliasHandler::Insmod(const std::string& path_name, const std::string& args) {
base::unique_fd fd(
TEMP_FAILURE_RETRY(open(path_name.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
if (fd == -1) return ErrnoError() << "Could not open module '" << path_name << "'";
@@ -109,17 +109,17 @@
if (ret != 0) {
if (errno == EEXIST) {
// Module already loaded
- return Success();
+ return {};
}
return ErrnoError() << "Failed to insmod '" << path_name << "' with args '" << args << "'";
}
LOG(INFO) << "Loaded kernel module " << path_name;
- return Success();
+ return {};
}
-Result<Success> ModaliasHandler::InsmodWithDeps(const std::string& module_name,
- const std::string& args) {
+Result<void> ModaliasHandler::InsmodWithDeps(const std::string& module_name,
+ const std::string& args) {
if (module_name.empty()) {
return Error() << "Need valid module name";
}
diff --git a/init/modalias_handler.h b/init/modalias_handler.h
index 3247c86..7d0afde 100644
--- a/init/modalias_handler.h
+++ b/init/modalias_handler.h
@@ -35,11 +35,11 @@
void HandleUevent(const Uevent& uevent) override;
private:
- Result<Success> InsmodWithDeps(const std::string& module_name, const std::string& args);
- Result<Success> Insmod(const std::string& path_name, const std::string& args);
+ Result<void> InsmodWithDeps(const std::string& module_name, const std::string& args);
+ Result<void> Insmod(const std::string& path_name, const std::string& args);
- Result<Success> ParseDepCallback(std::vector<std::string>&& args);
- Result<Success> ParseAliasCallback(std::vector<std::string>&& args);
+ Result<void> ParseDepCallback(std::vector<std::string>&& args);
+ Result<void> ParseAliasCallback(std::vector<std::string>&& args);
std::vector<std::pair<std::string, std::string>> module_aliases_;
std::unordered_map<std::string, std::vector<std::string>> module_deps_;
diff --git a/init/parser.h b/init/parser.h
index f30bda7..95b0cd7 100644
--- a/init/parser.h
+++ b/init/parser.h
@@ -27,7 +27,7 @@
// SectionParser is an interface that can parse a given 'section' in init.
//
// You can implement up to 4 functions below, with ParseSection being mandatory. The first two
-// functions return Result<Success> indicating if they have an error. It will be reported along
+// functions return Result<void> indicating if they have an error. It will be reported along
// with the filename and line number of where the error occurred.
//
// 1) ParseSection
@@ -51,10 +51,10 @@
class SectionParser {
public:
virtual ~SectionParser() {}
- virtual Result<Success> ParseSection(std::vector<std::string>&& args,
- const std::string& filename, int line) = 0;
- virtual Result<Success> ParseLineSection(std::vector<std::string>&&, int) { return Success(); };
- virtual Result<Success> EndSection() { return Success(); };
+ virtual Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
+ int line) = 0;
+ virtual Result<void> ParseLineSection(std::vector<std::string>&&, int) { return {}; };
+ virtual Result<void> EndSection() { return {}; };
virtual void EndFile(){};
};
@@ -67,7 +67,7 @@
// Similar to ParseSection() and ParseLineSection(), this function returns bool with false
// indicating a failure and has an std::string* err parameter into which an error string can
// be written.
- using LineCallback = std::function<Result<Success>(std::vector<std::string>&&)>;
+ using LineCallback = std::function<Result<void>(std::vector<std::string>&&)>;
Parser();
diff --git a/init/persistent_properties.cpp b/init/persistent_properties.cpp
index 21adce9..73787b9 100644
--- a/init/persistent_properties.cpp
+++ b/init/persistent_properties.cpp
@@ -169,7 +169,7 @@
return Error() << "Unable to parse persistent property file: Could not parse protobuf";
}
-Result<Success> WritePersistentPropertyFile(const PersistentProperties& persistent_properties) {
+Result<void> WritePersistentPropertyFile(const PersistentProperties& persistent_properties) {
const std::string temp_filename = persistent_property_filename + ".tmp";
unique_fd fd(TEMP_FAILURE_RETRY(
open(temp_filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
@@ -191,7 +191,7 @@
unlink(temp_filename.c_str());
return Error(saved_errno) << "Unable to rename persistent property file";
}
- return Success();
+ return {};
}
// Persistent properties are not written often, so we rather not keep any data in memory and read
diff --git a/init/persistent_properties.h b/init/persistent_properties.h
index 5f4df85..3845a0d 100644
--- a/init/persistent_properties.h
+++ b/init/persistent_properties.h
@@ -30,7 +30,7 @@
// Exposed only for testing
Result<PersistentProperties> LoadPersistentPropertyFile();
-Result<Success> WritePersistentPropertyFile(const PersistentProperties& persistent_properties);
+Result<void> WritePersistentPropertyFile(const PersistentProperties& persistent_properties);
extern std::string persistent_property_filename;
} // namespace init
diff --git a/init/property_service.cpp b/init/property_service.cpp
index ab5dd61..14bb819 100644
--- a/init/property_service.cpp
+++ b/init/property_service.cpp
@@ -645,8 +645,14 @@
while (isspace(*key)) key++;
}
- load_properties_from_file(fn, key, properties);
+ std::string raw_filename(fn);
+ std::string expanded_filename;
+ if (!expand_props(raw_filename, &expanded_filename)) {
+ LOG(ERROR) << "Could not expand filename '" << raw_filename << "'";
+ continue;
+ }
+ load_properties_from_file(expanded_filename.c_str(), key, properties);
} else {
value = strchr(key, '=');
if (!value) continue;
diff --git a/init/reboot.cpp b/init/reboot.cpp
index 54f68bb..eaba3cc 100644
--- a/init/reboot.cpp
+++ b/init/reboot.cpp
@@ -41,7 +41,6 @@
#include <android-base/logging.h>
#include <android-base/macros.h>
#include <android-base/properties.h>
-#include <android-base/stringprintf.h>
#include <android-base/strings.h>
#include <android-base/unique_fd.h>
#include <bootloader_message/bootloader_message.h>
@@ -62,7 +61,6 @@
using android::base::GetBoolProperty;
using android::base::Split;
-using android::base::StringPrintf;
using android::base::Timer;
using android::base::unique_fd;
using android::base::WriteStringToFile;
@@ -707,7 +705,7 @@
// Queue built-in shutdown_done
auto shutdown_handler = [cmd, command, reboot_target, run_fsck](const BuiltinArguments&) {
DoReboot(cmd, command, reboot_target, run_fsck);
- return Success();
+ return Result<void>{};
};
ActionManager::GetInstance().QueueBuiltinAction(shutdown_handler, "shutdown_done");
diff --git a/init/result.h b/init/result.h
index 984b257..b70dd1b 100644
--- a/init/result.h
+++ b/init/result.h
@@ -14,66 +14,16 @@
* limitations under the License.
*/
-// This file contains classes for returning a successful result along with an optional
-// arbitrarily typed return value or for returning a failure result along with an optional string
-// indicating why the function failed.
-
-// There are 3 classes that implement this functionality and one additional helper type.
-//
-// Result<T> either contains a member of type T that can be accessed using similar semantics as
-// std::optional<T> or it contains a ResultError describing an error, which can be accessed via
-// Result<T>::error().
-//
-// ResultError is a type that contains both a std::string describing the error and a copy of errno
-// from when the error occurred. ResultError can be used in an ostream directly to print its
-// string value.
-//
-// Success is a typedef that aids in creating Result<T> that do not contain a return value.
-// Result<Nothing> is the correct return type for a function that either returns successfully or
-// returns an error value. Returning Nothing() from a function that returns Result<Nothing> is the
-// correct way to indicate that a function without a return type has completed successfully.
-//
-// A successful Result<T> is constructed implicitly from any type that can be implicitly converted
-// to T or from the constructor arguments for T. This allows you to return a type T directly from
-// a function that returns Result<T>.
-//
-// Error and ErrnoError are used to construct a Result<T> that has failed. The Error class takes
-// an ostream as an input and are implicitly cast to a Result<T> containing that failure.
-// ErrnoError() is a helper function to create an Error class that appends ": " + strerror(errno)
-// to the end of the failure string to aid in interacting with C APIs. Alternatively, an errno
-// value can be directly specified via the Error() constructor.
-//
-// ResultError can be used in the ostream when using Error to construct a Result<T>. In this case,
-// the string that the ResultError takes is passed through the stream normally, but the errno is
-// passed to the Result<T>. This can be used to pass errno from a failing C function up multiple
-// callers.
-//
-// ResultError can also directly construct a Result<T>. This is particularly useful if you have a
-// function that return Result<T> but you have a Result<U> and want to return its error. In this
-// case, you can return the .error() from the Result<U> to construct the Result<T>.
-
-// An example of how to use these is below:
-// Result<U> CalculateResult(const T& input) {
-// U output;
-// if (!SomeOtherCppFunction(input, &output)) {
-// return Error() << "SomeOtherCppFunction(" << input << ") failed";
-// }
-// if (!c_api_function(output)) {
-// return ErrnoError() << "c_api_function(" << output << ") failed";
-// }
-// return output;
-// }
-//
-// auto output = CalculateResult(input);
-// if (!output) return Error() << "CalculateResult failed: " << output.error();
-// UseOutput(*output);
-
#pragma once
+// The implementation of this file has moved to android-base. This file remains since historically,
+// these classes were a part of init.
+
#include <android-base/result.h>
using android::base::ErrnoError;
+using android::base::ErrnoErrorf;
using android::base::Error;
+using android::base::Errorf;
using android::base::Result;
using android::base::ResultError;
-using android::base::Success;
diff --git a/init/security.cpp b/init/security.cpp
index a3494a2..5d87f3c 100644
--- a/init/security.cpp
+++ b/init/security.cpp
@@ -43,14 +43,14 @@
// devices/configurations where these I/O operations are blocking for a long
// time. We do not reboot or halt on failures, as this is a best-effort
// attempt.
-Result<Success> MixHwrngIntoLinuxRngAction(const BuiltinArguments&) {
+Result<void> MixHwrngIntoLinuxRngAction(const BuiltinArguments&) {
unique_fd hwrandom_fd(
TEMP_FAILURE_RETRY(open("/dev/hw_random", O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
if (hwrandom_fd == -1) {
if (errno == ENOENT) {
LOG(INFO) << "/dev/hw_random not found";
// It's not an error to not have a Hardware RNG.
- return Success();
+ return {};
}
return ErrnoError() << "Failed to open /dev/hw_random";
}
@@ -80,7 +80,7 @@
}
LOG(INFO) << "Mixed " << total_bytes_written << " bytes from /dev/hw_random into /dev/urandom";
- return Success();
+ return {};
}
static bool SetHighestAvailableOptionValue(std::string path, int min, int max) {
@@ -147,31 +147,31 @@
// 9e08f57d684a x86: mm: support ARCH_MMAP_RND_BITS
// ec9ee4acd97c drivers: char: random: add get_random_long()
// 5ef11c35ce86 mm: ASLR: use get_random_long()
-Result<Success> SetMmapRndBitsAction(const BuiltinArguments&) {
+Result<void> SetMmapRndBitsAction(const BuiltinArguments&) {
// values are arch-dependent
#if defined(USER_MODE_LINUX)
// uml does not support mmap_rnd_bits
- return Success();
+ return {};
#elif defined(__aarch64__)
// arm64 supports 18 - 33 bits depending on pagesize and VA_SIZE
if (SetMmapRndBitsMin(33, 24, false) && SetMmapRndBitsMin(16, 16, true)) {
- return Success();
+ return {};
}
#elif defined(__x86_64__)
// x86_64 supports 28 - 32 bits
if (SetMmapRndBitsMin(32, 32, false) && SetMmapRndBitsMin(16, 16, true)) {
- return Success();
+ return {};
}
#elif defined(__arm__) || defined(__i386__)
// check to see if we're running on 64-bit kernel
bool h64 = !access(MMAP_RND_COMPAT_PATH, F_OK);
// supported 32-bit architecture must have 16 bits set
if (SetMmapRndBitsMin(16, 16, h64)) {
- return Success();
+ return {};
}
#elif defined(__mips__) || defined(__mips64__)
// TODO: add mips support b/27788820
- return Success();
+ return {};
#else
LOG(ERROR) << "Unknown architecture";
#endif
@@ -187,14 +187,14 @@
// Set kptr_restrict to the highest available level.
//
// Aborts if unable to set this to an acceptable value.
-Result<Success> SetKptrRestrictAction(const BuiltinArguments&) {
+Result<void> SetKptrRestrictAction(const BuiltinArguments&) {
std::string path = KPTR_RESTRICT_PATH;
if (!SetHighestAvailableOptionValue(path, KPTR_RESTRICT_MINVALUE, KPTR_RESTRICT_MAXVALUE)) {
LOG(FATAL) << "Unable to set adequate kptr_restrict value!";
return Error();
}
- return Success();
+ return {};
}
} // namespace init
diff --git a/init/security.h b/init/security.h
index 6f6b944..b081a05 100644
--- a/init/security.h
+++ b/init/security.h
@@ -26,9 +26,9 @@
namespace android {
namespace init {
-Result<Success> MixHwrngIntoLinuxRngAction(const BuiltinArguments&);
-Result<Success> SetMmapRndBitsAction(const BuiltinArguments&);
-Result<Success> SetKptrRestrictAction(const BuiltinArguments&);
+Result<void> MixHwrngIntoLinuxRngAction(const BuiltinArguments&);
+Result<void> SetMmapRndBitsAction(const BuiltinArguments&);
+Result<void> SetKptrRestrictAction(const BuiltinArguments&);
} // namespace init
} // namespace android
diff --git a/init/service.cpp b/init/service.cpp
index a54cb6b..4fe374c 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -315,7 +315,7 @@
[] (const auto& info) { LOG(INFO) << *info; });
}
-Result<Success> Service::ParseCapabilities(std::vector<std::string>&& args) {
+Result<void> Service::ParseCapabilities(std::vector<std::string>&& args) {
capabilities_ = 0;
if (!CapAmbientSupported()) {
@@ -332,41 +332,40 @@
const std::string& arg = args[i];
int res = LookupCap(arg);
if (res < 0) {
- return Error() << StringPrintf("invalid capability '%s'", arg.c_str());
+ return Errorf("invalid capability '{}'", arg);
}
unsigned int cap = static_cast<unsigned int>(res); // |res| is >= 0.
if (cap > last_valid_cap) {
- return Error() << StringPrintf("capability '%s' not supported by the kernel",
- arg.c_str());
+ return Errorf("capability '{}' not supported by the kernel", arg);
}
(*capabilities_)[cap] = true;
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseClass(std::vector<std::string>&& args) {
+Result<void> Service::ParseClass(std::vector<std::string>&& args) {
classnames_ = std::set<std::string>(args.begin() + 1, args.end());
- return Success();
+ return {};
}
-Result<Success> Service::ParseConsole(std::vector<std::string>&& args) {
+Result<void> Service::ParseConsole(std::vector<std::string>&& args) {
flags_ |= SVC_CONSOLE;
proc_attr_.console = args.size() > 1 ? "/dev/" + args[1] : "";
- return Success();
+ return {};
}
-Result<Success> Service::ParseCritical(std::vector<std::string>&& args) {
+Result<void> Service::ParseCritical(std::vector<std::string>&& args) {
flags_ |= SVC_CRITICAL;
- return Success();
+ return {};
}
-Result<Success> Service::ParseDisabled(std::vector<std::string>&& args) {
+Result<void> Service::ParseDisabled(std::vector<std::string>&& args) {
flags_ |= SVC_DISABLED;
flags_ |= SVC_RC_DISABLED;
- return Success();
+ return {};
}
-Result<Success> Service::ParseEnterNamespace(std::vector<std::string>&& args) {
+Result<void> Service::ParseEnterNamespace(std::vector<std::string>&& args) {
if (args[1] != "net") {
return Error() << "Init only supports entering network namespaces";
}
@@ -377,10 +376,10 @@
// present. Therefore, they also require mount namespaces.
namespaces_.flags |= CLONE_NEWNS;
namespaces_.namespaces_to_enter.emplace_back(CLONE_NEWNET, std::move(args[2]));
- return Success();
+ return {};
}
-Result<Success> Service::ParseGroup(std::vector<std::string>&& args) {
+Result<void> Service::ParseGroup(std::vector<std::string>&& args) {
auto gid = DecodeUid(args[1]);
if (!gid) {
return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
@@ -394,21 +393,21 @@
}
proc_attr_.supp_gids.emplace_back(*gid);
}
- return Success();
+ return {};
}
-Result<Success> Service::ParsePriority(std::vector<std::string>&& args) {
+Result<void> Service::ParsePriority(std::vector<std::string>&& args) {
proc_attr_.priority = 0;
if (!ParseInt(args[1], &proc_attr_.priority,
static_cast<int>(ANDROID_PRIORITY_HIGHEST), // highest is negative
static_cast<int>(ANDROID_PRIORITY_LOWEST))) {
- return Error() << StringPrintf("process priority value must be range %d - %d",
- ANDROID_PRIORITY_HIGHEST, ANDROID_PRIORITY_LOWEST);
+ return Errorf("process priority value must be range {} - {}", ANDROID_PRIORITY_HIGHEST,
+ ANDROID_PRIORITY_LOWEST);
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseInterface(std::vector<std::string>&& args) {
+Result<void> Service::ParseInterface(std::vector<std::string>&& args) {
const std::string& interface_name = args[1];
const std::string& instance_name = args[2];
@@ -436,10 +435,10 @@
interfaces_.insert(fullname);
- return Success();
+ return {};
}
-Result<Success> Service::ParseIoprio(std::vector<std::string>&& args) {
+Result<void> Service::ParseIoprio(std::vector<std::string>&& args) {
if (!ParseInt(args[2], &proc_attr_.ioprio_pri, 0, 7)) {
return Error() << "priority value must be range 0 - 7";
}
@@ -454,10 +453,10 @@
return Error() << "ioprio option usage: ioprio <rt|be|idle> <0-7>";
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseKeycodes(std::vector<std::string>&& args) {
+Result<void> Service::ParseKeycodes(std::vector<std::string>&& args) {
auto it = args.begin() + 1;
if (args.size() == 2 && StartsWith(args[1], "$")) {
std::string expanded;
@@ -468,7 +467,7 @@
// If the property is not set, it defaults to none, in which case there are no keycodes
// for this service.
if (expanded == "none") {
- return Success();
+ return {};
}
args = Split(expanded, ",");
@@ -486,24 +485,24 @@
return Error() << "invalid keycode: " << *it;
}
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseOneshot(std::vector<std::string>&& args) {
+Result<void> Service::ParseOneshot(std::vector<std::string>&& args) {
flags_ |= SVC_ONESHOT;
- return Success();
+ return {};
}
-Result<Success> Service::ParseOnrestart(std::vector<std::string>&& args) {
+Result<void> Service::ParseOnrestart(std::vector<std::string>&& args) {
args.erase(args.begin());
int line = onrestart_.NumCommands() + 1;
if (auto result = onrestart_.AddCommand(std::move(args), line); !result) {
return Error() << "cannot add Onrestart command: " << result.error();
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseNamespace(std::vector<std::string>&& args) {
+Result<void> Service::ParseNamespace(std::vector<std::string>&& args) {
for (size_t i = 1; i < args.size(); i++) {
if (args[i] == "pid") {
namespaces_.flags |= CLONE_NEWPID;
@@ -515,105 +514,105 @@
return Error() << "namespace must be 'pid' or 'mnt'";
}
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseOomScoreAdjust(std::vector<std::string>&& args) {
+Result<void> Service::ParseOomScoreAdjust(std::vector<std::string>&& args) {
if (!ParseInt(args[1], &oom_score_adjust_, -1000, 1000)) {
return Error() << "oom_score_adjust value must be in range -1000 - +1000";
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseOverride(std::vector<std::string>&& args) {
+Result<void> Service::ParseOverride(std::vector<std::string>&& args) {
override_ = true;
- return Success();
+ return {};
}
-Result<Success> Service::ParseMemcgSwappiness(std::vector<std::string>&& args) {
+Result<void> Service::ParseMemcgSwappiness(std::vector<std::string>&& args) {
if (!ParseInt(args[1], &swappiness_, 0)) {
return Error() << "swappiness value must be equal or greater than 0";
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
+Result<void> Service::ParseMemcgLimitInBytes(std::vector<std::string>&& args) {
if (!ParseInt(args[1], &limit_in_bytes_, 0)) {
return Error() << "limit_in_bytes value must be equal or greater than 0";
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
+Result<void> Service::ParseMemcgLimitPercent(std::vector<std::string>&& args) {
if (!ParseInt(args[1], &limit_percent_, 0)) {
return Error() << "limit_percent value must be equal or greater than 0";
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
+Result<void> Service::ParseMemcgLimitProperty(std::vector<std::string>&& args) {
limit_property_ = std::move(args[1]);
- return Success();
+ return {};
}
-Result<Success> Service::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
+Result<void> Service::ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args) {
if (!ParseInt(args[1], &soft_limit_in_bytes_, 0)) {
return Error() << "soft_limit_in_bytes value must be equal or greater than 0";
}
- return Success();
+ return {};
}
-Result<Success> Service::ParseProcessRlimit(std::vector<std::string>&& args) {
+Result<void> Service::ParseProcessRlimit(std::vector<std::string>&& args) {
auto rlimit = ParseRlimit(args);
if (!rlimit) return rlimit.error();
proc_attr_.rlimits.emplace_back(*rlimit);
- return Success();
+ return {};
}
-Result<Success> Service::ParseRestartPeriod(std::vector<std::string>&& args) {
+Result<void> Service::ParseRestartPeriod(std::vector<std::string>&& args) {
int period;
if (!ParseInt(args[1], &period, 5)) {
return Error() << "restart_period value must be an integer >= 5";
}
restart_period_ = std::chrono::seconds(period);
- return Success();
+ return {};
}
-Result<Success> Service::ParseSeclabel(std::vector<std::string>&& args) {
+Result<void> Service::ParseSeclabel(std::vector<std::string>&& args) {
seclabel_ = std::move(args[1]);
- return Success();
+ return {};
}
-Result<Success> Service::ParseSigstop(std::vector<std::string>&& args) {
+Result<void> Service::ParseSigstop(std::vector<std::string>&& args) {
sigstop_ = true;
- return Success();
+ return {};
}
-Result<Success> Service::ParseSetenv(std::vector<std::string>&& args) {
+Result<void> Service::ParseSetenv(std::vector<std::string>&& args) {
environment_vars_.emplace_back(std::move(args[1]), std::move(args[2]));
- return Success();
+ return {};
}
-Result<Success> Service::ParseShutdown(std::vector<std::string>&& args) {
+Result<void> Service::ParseShutdown(std::vector<std::string>&& args) {
if (args[1] == "critical") {
flags_ |= SVC_SHUTDOWN_CRITICAL;
- return Success();
+ return {};
}
return Error() << "Invalid shutdown option";
}
-Result<Success> Service::ParseTimeoutPeriod(std::vector<std::string>&& args) {
+Result<void> Service::ParseTimeoutPeriod(std::vector<std::string>&& args) {
int period;
if (!ParseInt(args[1], &period, 1)) {
return Error() << "timeout_period value must be an integer >= 1";
}
timeout_period_ = std::chrono::seconds(period);
- return Success();
+ return {};
}
template <typename T>
-Result<Success> Service::AddDescriptor(std::vector<std::string>&& args) {
+Result<void> Service::AddDescriptor(std::vector<std::string>&& args) {
int perm = args.size() > 3 ? std::strtoul(args[3].c_str(), 0, 8) : -1;
Result<uid_t> uid = 0;
Result<gid_t> gid = 0;
@@ -644,11 +643,11 @@
}
descriptors_.emplace_back(std::move(descriptor));
- return Success();
+ return {};
}
// name type perm [ uid gid context ]
-Result<Success> Service::ParseSocket(std::vector<std::string>&& args) {
+Result<void> Service::ParseSocket(std::vector<std::string>&& args) {
if (!StartsWith(args[2], "dgram") && !StartsWith(args[2], "stream") &&
!StartsWith(args[2], "seqpacket")) {
return Error() << "socket type must be 'dgram', 'stream' or 'seqpacket'";
@@ -657,7 +656,7 @@
}
// name type perm [ uid gid context ]
-Result<Success> Service::ParseFile(std::vector<std::string>&& args) {
+Result<void> Service::ParseFile(std::vector<std::string>&& args) {
if (args[2] != "r" && args[2] != "w" && args[2] != "rw") {
return Error() << "file type must be 'r', 'w' or 'rw'";
}
@@ -672,24 +671,24 @@
return AddDescriptor<FileInfo>(std::move(args));
}
-Result<Success> Service::ParseUser(std::vector<std::string>&& args) {
+Result<void> Service::ParseUser(std::vector<std::string>&& args) {
auto uid = DecodeUid(args[1]);
if (!uid) {
return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
}
proc_attr_.uid = *uid;
- return Success();
+ return {};
}
-Result<Success> Service::ParseWritepid(std::vector<std::string>&& args) {
+Result<void> Service::ParseWritepid(std::vector<std::string>&& args) {
args.erase(args.begin());
writepid_files_ = std::move(args);
- return Success();
+ return {};
}
-Result<Success> Service::ParseUpdatable(std::vector<std::string>&& args) {
+Result<void> Service::ParseUpdatable(std::vector<std::string>&& args) {
updatable_ = true;
- return Success();
+ return {};
}
class Service::OptionParserMap : public KeywordMap<OptionParser> {
@@ -752,7 +751,7 @@
return option_parsers;
}
-Result<Success> Service::ParseLine(std::vector<std::string>&& args) {
+Result<void> Service::ParseLine(std::vector<std::string>&& args) {
static const OptionParserMap parser_map;
auto parser = parser_map.FindFunction(args);
@@ -761,7 +760,7 @@
return std::invoke(*parser, this, std::move(args));
}
-Result<Success> Service::ExecStart() {
+Result<void> Service::ExecStart() {
if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
// Don't delay the service for ExecStart() as the semantic is that
// the caller might depend on the side effect of the execution.
@@ -782,10 +781,10 @@
<< " gid " << proc_attr_.gid << "+" << proc_attr_.supp_gids.size() << " context "
<< (!seclabel_.empty() ? seclabel_ : "default") << ") started; waiting...";
- return Success();
+ return {};
}
-Result<Success> Service::Start() {
+Result<void> Service::Start() {
if (is_updatable() && !ServiceList::GetInstance().IsServicesUpdated()) {
ServiceList::GetInstance().DelayService(*this);
return Error() << "Cannot start an updatable service '" << name_
@@ -808,7 +807,7 @@
flags_ |= SVC_RESTART;
}
// It is not an error to try to start a service that is already running.
- return Success();
+ return {};
}
bool needs_console = (flags_ & SVC_CONSOLE);
@@ -960,24 +959,24 @@
}
NotifyStateChange("running");
- return Success();
+ return {};
}
-Result<Success> Service::StartIfNotDisabled() {
+Result<void> Service::StartIfNotDisabled() {
if (!(flags_ & SVC_DISABLED)) {
return Start();
} else {
flags_ |= SVC_DISABLED_START;
}
- return Success();
+ return {};
}
-Result<Success> Service::Enable() {
+Result<void> Service::Enable() {
flags_ &= ~(SVC_DISABLED | SVC_RC_DISABLED);
if (flags_ & SVC_DISABLED_START) {
return Start();
}
- return Success();
+ return {};
}
void Service::Reset() {
@@ -993,14 +992,14 @@
}
}
-Result<Success> Service::StartIfPostData() {
+Result<void> Service::StartIfPostData() {
// Start the service, but only if it was started after /data was mounted,
// and it was still running when we reset the post-data services.
if (running_at_post_data_reset_) {
return Start();
}
- return Success();
+ return {};
}
void Service::Stop() {
@@ -1211,8 +1210,8 @@
delayed_service_names_.emplace_back(service.name());
}
-Result<Success> ServiceParser::ParseSection(std::vector<std::string>&& args,
- const std::string& filename, int line) {
+Result<void> ServiceParser::ParseSection(std::vector<std::string>&& args,
+ const std::string& filename, int line) {
if (args.size() < 3) {
return Error() << "services must have a name and a program";
}
@@ -1243,14 +1242,14 @@
}
service_ = std::make_unique<Service>(name, restart_action_subcontext, str_args);
- return Success();
+ return {};
}
-Result<Success> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
- return service_ ? service_->ParseLine(std::move(args)) : Success();
+Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, int line) {
+ return service_ ? service_->ParseLine(std::move(args)) : Result<void>{};
}
-Result<Success> ServiceParser::EndSection() {
+Result<void> ServiceParser::EndSection() {
if (service_) {
Service* old_service = service_list_->FindService(service_->name());
if (old_service) {
@@ -1271,7 +1270,7 @@
service_list_->AddService(std::move(service_));
}
- return Success();
+ return {};
}
bool ServiceParser::IsValidName(const std::string& name) const {
diff --git a/init/service.h b/init/service.h
index 93b5a5c..b4356c8 100644
--- a/init/service.h
+++ b/init/service.h
@@ -76,12 +76,12 @@
static std::unique_ptr<Service> MakeTemporaryOneshotService(const std::vector<std::string>& args);
bool IsRunning() { return (flags_ & SVC_RUNNING) != 0; }
- Result<Success> ParseLine(std::vector<std::string>&& args);
- Result<Success> ExecStart();
- Result<Success> Start();
- Result<Success> StartIfNotDisabled();
- Result<Success> StartIfPostData();
- Result<Success> Enable();
+ Result<void> ParseLine(std::vector<std::string>&& args);
+ Result<void> ExecStart();
+ Result<void> Start();
+ Result<void> StartIfNotDisabled();
+ Result<void> StartIfPostData();
+ Result<void> Enable();
void Reset();
void ResetIfPostData();
void Stop();
@@ -130,7 +130,7 @@
bool is_post_data() const { return post_data_; }
private:
- using OptionParser = Result<Success> (Service::*)(std::vector<std::string>&& args);
+ using OptionParser = Result<void> (Service::*)(std::vector<std::string>&& args);
class OptionParserMap;
void NotifyStateChange(const std::string& new_state) const;
@@ -138,42 +138,42 @@
void KillProcessGroup(int signal);
void SetProcessAttributesAndCaps();
- Result<Success> ParseCapabilities(std::vector<std::string>&& args);
- Result<Success> ParseClass(std::vector<std::string>&& args);
- Result<Success> ParseConsole(std::vector<std::string>&& args);
- Result<Success> ParseCritical(std::vector<std::string>&& args);
- Result<Success> ParseDisabled(std::vector<std::string>&& args);
- Result<Success> ParseEnterNamespace(std::vector<std::string>&& args);
- Result<Success> ParseGroup(std::vector<std::string>&& args);
- Result<Success> ParsePriority(std::vector<std::string>&& args);
- Result<Success> ParseInterface(std::vector<std::string>&& args);
- Result<Success> ParseIoprio(std::vector<std::string>&& args);
- Result<Success> ParseKeycodes(std::vector<std::string>&& args);
- Result<Success> ParseOneshot(std::vector<std::string>&& args);
- Result<Success> ParseOnrestart(std::vector<std::string>&& args);
- Result<Success> ParseOomScoreAdjust(std::vector<std::string>&& args);
- Result<Success> ParseOverride(std::vector<std::string>&& args);
- Result<Success> ParseMemcgLimitInBytes(std::vector<std::string>&& args);
- Result<Success> ParseMemcgLimitPercent(std::vector<std::string>&& args);
- Result<Success> ParseMemcgLimitProperty(std::vector<std::string>&& args);
- Result<Success> ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args);
- Result<Success> ParseMemcgSwappiness(std::vector<std::string>&& args);
- Result<Success> ParseNamespace(std::vector<std::string>&& args);
- Result<Success> ParseProcessRlimit(std::vector<std::string>&& args);
- Result<Success> ParseRestartPeriod(std::vector<std::string>&& args);
- Result<Success> ParseSeclabel(std::vector<std::string>&& args);
- Result<Success> ParseSetenv(std::vector<std::string>&& args);
- Result<Success> ParseShutdown(std::vector<std::string>&& args);
- Result<Success> ParseSigstop(std::vector<std::string>&& args);
- Result<Success> ParseSocket(std::vector<std::string>&& args);
- Result<Success> ParseTimeoutPeriod(std::vector<std::string>&& args);
- Result<Success> ParseFile(std::vector<std::string>&& args);
- Result<Success> ParseUser(std::vector<std::string>&& args);
- Result<Success> ParseWritepid(std::vector<std::string>&& args);
- Result<Success> ParseUpdatable(std::vector<std::string>&& args);
+ Result<void> ParseCapabilities(std::vector<std::string>&& args);
+ Result<void> ParseClass(std::vector<std::string>&& args);
+ Result<void> ParseConsole(std::vector<std::string>&& args);
+ Result<void> ParseCritical(std::vector<std::string>&& args);
+ Result<void> ParseDisabled(std::vector<std::string>&& args);
+ Result<void> ParseEnterNamespace(std::vector<std::string>&& args);
+ Result<void> ParseGroup(std::vector<std::string>&& args);
+ Result<void> ParsePriority(std::vector<std::string>&& args);
+ Result<void> ParseInterface(std::vector<std::string>&& args);
+ Result<void> ParseIoprio(std::vector<std::string>&& args);
+ Result<void> ParseKeycodes(std::vector<std::string>&& args);
+ Result<void> ParseOneshot(std::vector<std::string>&& args);
+ Result<void> ParseOnrestart(std::vector<std::string>&& args);
+ Result<void> ParseOomScoreAdjust(std::vector<std::string>&& args);
+ Result<void> ParseOverride(std::vector<std::string>&& args);
+ Result<void> ParseMemcgLimitInBytes(std::vector<std::string>&& args);
+ Result<void> ParseMemcgLimitPercent(std::vector<std::string>&& args);
+ Result<void> ParseMemcgLimitProperty(std::vector<std::string>&& args);
+ Result<void> ParseMemcgSoftLimitInBytes(std::vector<std::string>&& args);
+ Result<void> ParseMemcgSwappiness(std::vector<std::string>&& args);
+ Result<void> ParseNamespace(std::vector<std::string>&& args);
+ Result<void> ParseProcessRlimit(std::vector<std::string>&& args);
+ Result<void> ParseRestartPeriod(std::vector<std::string>&& args);
+ Result<void> ParseSeclabel(std::vector<std::string>&& args);
+ Result<void> ParseSetenv(std::vector<std::string>&& args);
+ Result<void> ParseShutdown(std::vector<std::string>&& args);
+ Result<void> ParseSigstop(std::vector<std::string>&& args);
+ Result<void> ParseSocket(std::vector<std::string>&& args);
+ Result<void> ParseTimeoutPeriod(std::vector<std::string>&& args);
+ Result<void> ParseFile(std::vector<std::string>&& args);
+ Result<void> ParseUser(std::vector<std::string>&& args);
+ Result<void> ParseWritepid(std::vector<std::string>&& args);
+ Result<void> ParseUpdatable(std::vector<std::string>&& args);
template <typename T>
- Result<Success> AddDescriptor(std::vector<std::string>&& args);
+ Result<void> AddDescriptor(std::vector<std::string>&& args);
static unsigned long next_start_order_;
static bool is_exec_service_running_;
@@ -295,10 +295,10 @@
public:
ServiceParser(ServiceList* service_list, std::vector<Subcontext>* subcontexts)
: service_list_(service_list), subcontexts_(subcontexts), service_(nullptr) {}
- Result<Success> ParseSection(std::vector<std::string>&& args, const std::string& filename,
- int line) override;
- Result<Success> ParseLineSection(std::vector<std::string>&& args, int line) override;
- Result<Success> EndSection() override;
+ Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
+ int line) override;
+ Result<void> ParseLineSection(std::vector<std::string>&& args, int line) override;
+ Result<void> EndSection() override;
void EndFile() override { filename_ = ""; }
private:
diff --git a/init/service_utils.cpp b/init/service_utils.cpp
index 17fc9c8..f88ea97 100644
--- a/init/service_utils.cpp
+++ b/init/service_utils.cpp
@@ -42,7 +42,7 @@
namespace {
-Result<Success> EnterNamespace(int nstype, const char* path) {
+Result<void> EnterNamespace(int nstype, const char* path) {
auto fd = unique_fd{open(path, O_RDONLY | O_CLOEXEC)};
if (fd == -1) {
return ErrnoError() << "Could not open namespace at " << path;
@@ -50,10 +50,10 @@
if (setns(fd, nstype) == -1) {
return ErrnoError() << "Could not setns() namespace at " << path;
}
- return Success();
+ return {};
}
-Result<Success> SetUpMountNamespace(bool remount_proc, bool remount_sys) {
+Result<void> SetUpMountNamespace(bool remount_proc, bool remount_sys) {
constexpr unsigned int kSafeFlags = MS_NODEV | MS_NOEXEC | MS_NOSUID;
// Recursively remount / as slave like zygote does so unmounting and mounting /proc
@@ -83,10 +83,10 @@
return ErrnoError() << "Could not mount(/sys)";
}
}
- return Success();
+ return {};
}
-Result<Success> SetUpPidNamespace(const char* name) {
+Result<void> SetUpPidNamespace(const char* name) {
if (prctl(PR_SET_NAME, name) == -1) {
return ErrnoError() << "Could not set name";
}
@@ -116,7 +116,7 @@
}
_exit(WEXITSTATUS(init_exitstatus));
}
- return Success();
+ return {};
}
void ZapStdio() {
@@ -140,8 +140,7 @@
} // namespace
-Result<Success> EnterNamespaces(const NamespaceInfo& info, const std::string& name,
- bool pre_apexd) {
+Result<void> EnterNamespaces(const NamespaceInfo& info, const std::string& name, bool pre_apexd) {
for (const auto& [nstype, path] : info.namespaces_to_enter) {
if (auto result = EnterNamespace(nstype, path.c_str()); !result) {
return result;
@@ -173,10 +172,10 @@
}
}
- return Success();
+ return {};
}
-Result<Success> SetProcessAttributes(const ProcessAttributes& attr) {
+Result<void> SetProcessAttributes(const ProcessAttributes& attr) {
if (attr.ioprio_class != IoSchedClass_NONE) {
if (android_set_ioprio(getpid(), attr.ioprio_class, attr.ioprio_pri)) {
PLOG(ERROR) << "failed to set pid " << getpid() << " ioprio=" << attr.ioprio_class
@@ -221,10 +220,10 @@
return ErrnoError() << "setpriority failed";
}
}
- return Success();
+ return {};
}
-Result<Success> WritePidToFiles(std::vector<std::string>* files) {
+Result<void> WritePidToFiles(std::vector<std::string>* files) {
// See if there were "writepid" instructions to write to files under cpuset path.
std::string cpuset_path;
if (CgroupGetControllerPath("cpuset", &cpuset_path)) {
@@ -258,7 +257,7 @@
return ErrnoError() << "couldn't write " << pid_str << " to " << file;
}
}
- return Success();
+ return {};
}
} // namespace init
diff --git a/init/service_utils.h b/init/service_utils.h
index f7502a9..c26b123 100644
--- a/init/service_utils.h
+++ b/init/service_utils.h
@@ -34,7 +34,7 @@
// Pair of namespace type, path to name.
std::vector<std::pair<int, std::string>> namespaces_to_enter;
};
-Result<Success> EnterNamespaces(const NamespaceInfo& info, const std::string& name, bool pre_apexd);
+Result<void> EnterNamespaces(const NamespaceInfo& info, const std::string& name, bool pre_apexd);
struct ProcessAttributes {
std::string console;
@@ -46,9 +46,9 @@
std::vector<gid_t> supp_gids;
int priority;
};
-Result<Success> SetProcessAttributes(const ProcessAttributes& attr);
+Result<void> SetProcessAttributes(const ProcessAttributes& attr);
-Result<Success> WritePidToFiles(std::vector<std::string>* files);
+Result<void> WritePidToFiles(std::vector<std::string>* files);
} // namespace init
} // namespace android
diff --git a/init/subcontext.cpp b/init/subcontext.cpp
index 0ff479a..02ed507 100644
--- a/init/subcontext.cpp
+++ b/init/subcontext.cpp
@@ -72,7 +72,7 @@
}
template <typename T>
-Result<Success> SendMessage(int socket, const T& message) {
+Result<void> SendMessage(int socket, const T& message) {
std::string message_string;
if (!message.SerializeToString(&message_string)) {
return Error() << "Unable to serialize message";
@@ -87,7 +87,7 @@
result != static_cast<long>(message_string.size())) {
return ErrnoError() << "send() failed to send message contents";
}
- return Success();
+ return {};
}
std::vector<std::pair<std::string, std::string>> properties_to_set;
@@ -123,7 +123,7 @@
}
auto map_result = function_map_->FindFunction(args);
- Result<Success> result;
+ Result<void> result;
if (!map_result) {
result = Error() << "Cannot find command: " << map_result.error();
} else {
@@ -299,7 +299,7 @@
return subcontext_reply;
}
-Result<Success> Subcontext::Execute(const std::vector<std::string>& args) {
+Result<void> Subcontext::Execute(const std::vector<std::string>& args) {
auto subcontext_command = SubcontextCommand();
std::copy(
args.begin(), args.end(),
@@ -329,7 +329,7 @@
<< subcontext_reply->reply_case();
}
- return Success();
+ return {};
}
Result<std::vector<std::string>> Subcontext::ExpandArgs(const std::vector<std::string>& args) {
diff --git a/init/subcontext.h b/init/subcontext.h
index 628fd50..16bd870 100644
--- a/init/subcontext.h
+++ b/init/subcontext.h
@@ -42,7 +42,7 @@
Fork();
}
- Result<Success> Execute(const std::vector<std::string>& args);
+ Result<void> Execute(const std::vector<std::string>& args);
Result<std::vector<std::string>> ExpandArgs(const std::vector<std::string>& args);
void Restart();
diff --git a/init/subcontext_benchmark.cpp b/init/subcontext_benchmark.cpp
index 6307993..fdbbc41 100644
--- a/init/subcontext_benchmark.cpp
+++ b/init/subcontext_benchmark.cpp
@@ -53,7 +53,7 @@
TestFunctionMap BuildTestFunctionMap() {
TestFunctionMap test_function_map;
test_function_map.Add("return_success", 0, 0, true,
- [](const BuiltinArguments& args) { return Success(); });
+ [](const BuiltinArguments& args) { return Result<void>{}; });
return test_function_map;
}
diff --git a/init/subcontext_test.cpp b/init/subcontext_test.cpp
index 2635683..55912d6 100644
--- a/init/subcontext_test.cpp
+++ b/init/subcontext_test.cpp
@@ -175,14 +175,14 @@
TestFunctionMap test_function_map;
// For CheckDifferentPid
test_function_map.Add("return_pids_as_error", 0, 0, true,
- [](const BuiltinArguments& args) -> Result<Success> {
+ [](const BuiltinArguments& args) -> Result<void> {
return Error() << getpid() << " " << getppid();
});
// For SetProp
test_function_map.Add("setprop", 2, 2, true, [](const BuiltinArguments& args) {
android::base::SetProperty(args[1], args[2]);
- return Success();
+ return Result<void>{};
});
// For MultipleCommands
@@ -190,26 +190,26 @@
auto words = std::make_shared<std::vector<std::string>>();
test_function_map.Add("add_word", 1, 1, true, [words](const BuiltinArguments& args) {
words->emplace_back(args[1]);
- return Success();
+ return Result<void>{};
});
test_function_map.Add("return_words_as_error", 0, 0, true,
- [words](const BuiltinArguments& args) -> Result<Success> {
+ [words](const BuiltinArguments& args) -> Result<void> {
return Error() << Join(*words, " ");
});
// For RecoverAfterAbort
test_function_map.Add("cause_log_fatal", 0, 0, true,
- [](const BuiltinArguments& args) -> Result<Success> {
+ [](const BuiltinArguments& args) -> Result<void> {
return Error() << std::string(4097, 'f');
});
test_function_map.Add(
- "generate_sane_error", 0, 0, true,
- [](const BuiltinArguments& args) -> Result<Success> { return Error() << "Sane error!"; });
+ "generate_sane_error", 0, 0, true,
+ [](const BuiltinArguments& args) -> Result<void> { return Error() << "Sane error!"; });
// For ContextString
test_function_map.Add(
- "return_context_as_error", 0, 0, true,
- [](const BuiltinArguments& args) -> Result<Success> { return Error() << args.context; });
+ "return_context_as_error", 0, 0, true,
+ [](const BuiltinArguments& args) -> Result<void> { return Error() << args.context; });
return test_function_map;
}
diff --git a/init/test_function_map.h b/init/test_function_map.h
index 583df1a..293f1f9 100644
--- a/init/test_function_map.h
+++ b/init/test_function_map.h
@@ -14,13 +14,13 @@
* limitations under the License.
*/
-#ifndef _INIT_TEST_FUNCTION_MAP_H
-#define _INIT_TEST_FUNCTION_MAP_H
+#pragma once
#include <string>
#include <vector>
#include "builtin_arguments.h"
+#include "builtins.h"
#include "keyword_map.h"
namespace android {
@@ -33,7 +33,7 @@
void Add(const std::string& name, const BuiltinFunctionNoArgs function) {
Add(name, 0, 0, false, [function](const BuiltinArguments&) {
function();
- return Success();
+ return Result<void>{};
});
}
@@ -51,5 +51,3 @@
} // namespace init
} // namespace android
-
-#endif
diff --git a/init/ueventd_parser.cpp b/init/ueventd_parser.cpp
index aac3fe5..25bab93 100644
--- a/init/ueventd_parser.cpp
+++ b/init/ueventd_parser.cpp
@@ -29,9 +29,9 @@
namespace android {
namespace init {
-Result<Success> ParsePermissionsLine(std::vector<std::string>&& args,
- std::vector<SysfsPermissions>* out_sysfs_permissions,
- std::vector<Permissions>* out_dev_permissions) {
+Result<void> ParsePermissionsLine(std::vector<std::string>&& args,
+ std::vector<SysfsPermissions>* out_sysfs_permissions,
+ std::vector<Permissions>* out_dev_permissions) {
bool is_sysfs = out_sysfs_permissions != nullptr;
if (is_sysfs && args.size() != 5) {
return Error() << "/sys/ lines must have 5 entries";
@@ -74,22 +74,22 @@
} else {
out_dev_permissions->emplace_back(name, perm, uid, gid);
}
- return Success();
+ return {};
}
-Result<Success> ParseFirmwareDirectoriesLine(std::vector<std::string>&& args,
- std::vector<std::string>* firmware_directories) {
+Result<void> ParseFirmwareDirectoriesLine(std::vector<std::string>&& args,
+ std::vector<std::string>* firmware_directories) {
if (args.size() < 2) {
return Error() << "firmware_directories must have at least 1 entry";
}
std::move(std::next(args.begin()), args.end(), std::back_inserter(*firmware_directories));
- return Success();
+ return {};
}
-Result<Success> ParseModaliasHandlingLine(std::vector<std::string>&& args,
- bool* enable_modalias_handling) {
+Result<void> ParseModaliasHandlingLine(std::vector<std::string>&& args,
+ bool* enable_modalias_handling) {
if (args.size() != 2) {
return Error() << "modalias_handling lines take exactly one parameter";
}
@@ -102,11 +102,11 @@
return Error() << "modalias_handling takes either 'enabled' or 'disabled' as a parameter";
}
- return Success();
+ return {};
}
-Result<Success> ParseUeventSocketRcvbufSizeLine(std::vector<std::string>&& args,
- size_t* uevent_socket_rcvbuf_size) {
+Result<void> ParseUeventSocketRcvbufSizeLine(std::vector<std::string>&& args,
+ size_t* uevent_socket_rcvbuf_size) {
if (args.size() != 2) {
return Error() << "uevent_socket_rcvbuf_size lines take exactly one parameter";
}
@@ -118,27 +118,27 @@
*uevent_socket_rcvbuf_size = parsed_size;
- return Success();
+ return {};
}
class SubsystemParser : public SectionParser {
public:
SubsystemParser(std::vector<Subsystem>* subsystems) : subsystems_(subsystems) {}
- Result<Success> ParseSection(std::vector<std::string>&& args, const std::string& filename,
- int line) override;
- Result<Success> ParseLineSection(std::vector<std::string>&& args, int line) override;
- Result<Success> EndSection() override;
+ Result<void> ParseSection(std::vector<std::string>&& args, const std::string& filename,
+ int line) override;
+ Result<void> ParseLineSection(std::vector<std::string>&& args, int line) override;
+ Result<void> EndSection() override;
private:
- Result<Success> ParseDevName(std::vector<std::string>&& args);
- Result<Success> ParseDirName(std::vector<std::string>&& args);
+ Result<void> ParseDevName(std::vector<std::string>&& args);
+ Result<void> ParseDirName(std::vector<std::string>&& args);
Subsystem subsystem_;
std::vector<Subsystem>* subsystems_;
};
-Result<Success> SubsystemParser::ParseSection(std::vector<std::string>&& args,
- const std::string& filename, int line) {
+Result<void> SubsystemParser::ParseSection(std::vector<std::string>&& args,
+ const std::string& filename, int line) {
if (args.size() != 2) {
return Error() << "subsystems must have exactly one name";
}
@@ -149,33 +149,33 @@
subsystem_ = Subsystem(std::move(args[1]));
- return Success();
+ return {};
}
-Result<Success> SubsystemParser::ParseDevName(std::vector<std::string>&& args) {
+Result<void> SubsystemParser::ParseDevName(std::vector<std::string>&& args) {
if (args[1] == "uevent_devname") {
subsystem_.devname_source_ = Subsystem::DEVNAME_UEVENT_DEVNAME;
- return Success();
+ return {};
}
if (args[1] == "uevent_devpath") {
subsystem_.devname_source_ = Subsystem::DEVNAME_UEVENT_DEVPATH;
- return Success();
+ return {};
}
return Error() << "invalid devname '" << args[1] << "'";
}
-Result<Success> SubsystemParser::ParseDirName(std::vector<std::string>&& args) {
+Result<void> SubsystemParser::ParseDirName(std::vector<std::string>&& args) {
if (args[1].front() != '/') {
return Error() << "dirname '" << args[1] << " ' does not start with '/'";
}
subsystem_.dir_name_ = args[1];
- return Success();
+ return {};
}
-Result<Success> SubsystemParser::ParseLineSection(std::vector<std::string>&& args, int line) {
- using OptionParser = Result<Success> (SubsystemParser::*)(std::vector<std::string> && args);
+Result<void> SubsystemParser::ParseLineSection(std::vector<std::string>&& args, int line) {
+ using OptionParser = Result<void> (SubsystemParser::*)(std::vector<std::string> && args);
static class OptionParserMap : public KeywordMap<OptionParser> {
private:
@@ -197,10 +197,10 @@
return std::invoke(*parser, this, std::move(args));
}
-Result<Success> SubsystemParser::EndSection() {
+Result<void> SubsystemParser::EndSection() {
subsystems_->emplace_back(std::move(subsystem_));
- return Success();
+ return {};
}
UeventdConfiguration ParseConfig(const std::vector<std::string>& configs) {
diff --git a/init/util.cpp b/init/util.cpp
index 243e5f0..14acaa2 100644
--- a/init/util.cpp
+++ b/init/util.cpp
@@ -197,7 +197,7 @@
return rc;
}
-Result<Success> WriteFile(const std::string& path, const std::string& content) {
+Result<void> WriteFile(const std::string& path, const std::string& content) {
android::base::unique_fd fd(TEMP_FAILURE_RETRY(
OpenFile(path, O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0600)));
if (fd == -1) {
@@ -206,7 +206,7 @@
if (!android::base::WriteStringToFd(content, fd)) {
return ErrnoError() << "Unable to write file contents";
}
- return Success();
+ return {};
}
bool mkdir_recursive(const std::string& path, mode_t mode) {
diff --git a/init/util.h b/init/util.h
index 767620b..770084b 100644
--- a/init/util.h
+++ b/init/util.h
@@ -42,7 +42,7 @@
const char* socketcon);
Result<std::string> ReadFile(const std::string& path);
-Result<Success> WriteFile(const std::string& path, const std::string& content);
+Result<void> WriteFile(const std::string& path, const std::string& content);
Result<uid_t> DecodeUid(const std::string& name);
diff --git a/libbacktrace/Android.bp b/libbacktrace/Android.bp
index e171155..9ece847 100644
--- a/libbacktrace/Android.bp
+++ b/libbacktrace/Android.bp
@@ -135,7 +135,6 @@
defaults: ["libbacktrace_common"],
host_supported: true,
srcs: [
- "backtrace_offline_test.cpp",
"backtrace_test.cpp",
],
diff --git a/libbacktrace/UnwindStack.cpp b/libbacktrace/UnwindStack.cpp
index 36640cd..a128623 100644
--- a/libbacktrace/UnwindStack.cpp
+++ b/libbacktrace/UnwindStack.cpp
@@ -129,22 +129,6 @@
return true;
}
-bool Backtrace::UnwindOffline(unwindstack::Regs* regs, BacktraceMap* back_map,
- const backtrace_stackinfo_t& stack,
- std::vector<backtrace_frame_data_t>* frames,
- BacktraceUnwindError* error) {
- UnwindStackOfflineMap* offline_map = reinterpret_cast<UnwindStackOfflineMap*>(back_map);
- // Create the process memory from the stack data since this will almost
- // always be different each unwind.
- if (!offline_map->CreateProcessMemory(stack)) {
- if (error != nullptr) {
- error->error_code = BACKTRACE_UNWIND_ERROR_SETUP_FAILED;
- }
- return false;
- }
- return Backtrace::Unwind(regs, back_map, frames, 0U, nullptr, error);
-}
-
UnwindStackCurrent::UnwindStackCurrent(pid_t pid, pid_t tid, BacktraceMap* map)
: BacktraceCurrent(pid, tid, map) {}
@@ -171,7 +155,7 @@
}
UnwindStackPtrace::UnwindStackPtrace(pid_t pid, pid_t tid, BacktraceMap* map)
- : BacktracePtrace(pid, tid, map), memory_(pid) {}
+ : BacktracePtrace(pid, tid, map), memory_(unwindstack::Memory::CreateProcessMemory(pid)) {}
std::string UnwindStackPtrace::GetFunctionNameRaw(uint64_t pc, uint64_t* offset) {
return GetMap()->GetFunctionName(pc, offset);
@@ -189,73 +173,5 @@
}
size_t UnwindStackPtrace::Read(uint64_t addr, uint8_t* buffer, size_t bytes) {
- return memory_.Read(addr, buffer, bytes);
-}
-
-UnwindStackOffline::UnwindStackOffline(ArchEnum arch, pid_t pid, pid_t tid, BacktraceMap* map,
- bool map_shared)
- : Backtrace(pid, tid, map), arch_(arch) {
- map_shared_ = map_shared;
-}
-
-bool UnwindStackOffline::Unwind(size_t num_ignore_frames, void* ucontext) {
- if (ucontext == nullptr) {
- return false;
- }
-
- unwindstack::ArchEnum arch;
- switch (arch_) {
- case ARCH_ARM:
- arch = unwindstack::ARCH_ARM;
- break;
- case ARCH_ARM64:
- arch = unwindstack::ARCH_ARM64;
- break;
- case ARCH_X86:
- arch = unwindstack::ARCH_X86;
- break;
- case ARCH_X86_64:
- arch = unwindstack::ARCH_X86_64;
- break;
- default:
- return false;
- }
-
- std::unique_ptr<unwindstack::Regs> regs(unwindstack::Regs::CreateFromUcontext(arch, ucontext));
-
- return Backtrace::Unwind(regs.get(), GetMap(), &frames_, num_ignore_frames, nullptr, &error_);
-}
-
-std::string UnwindStackOffline::GetFunctionNameRaw(uint64_t, uint64_t*) {
- return "";
-}
-
-size_t UnwindStackOffline::Read(uint64_t, uint8_t*, size_t) {
- return 0;
-}
-
-bool UnwindStackOffline::ReadWord(uint64_t, word_t*) {
- return false;
-}
-
-Backtrace* Backtrace::CreateOffline(ArchEnum arch, pid_t pid, pid_t tid,
- const std::vector<backtrace_map_t>& maps,
- const backtrace_stackinfo_t& stack) {
- std::unique_ptr<UnwindStackOfflineMap> map(
- reinterpret_cast<UnwindStackOfflineMap*>(BacktraceMap::CreateOffline(pid, maps)));
- if (map.get() == nullptr || !map->CreateProcessMemory(stack)) {
- return nullptr;
- }
- return new UnwindStackOffline(arch, pid, tid, map.release(), false);
-}
-
-Backtrace* Backtrace::CreateOffline(ArchEnum arch, pid_t pid, pid_t tid, BacktraceMap* map) {
- if (map == nullptr) {
- return nullptr;
- }
- return new UnwindStackOffline(arch, pid, tid, map, true);
-}
-
-void Backtrace::SetGlobalElfCache(bool enable) {
- unwindstack::Elf::SetCachingEnabled(enable);
+ return memory_->Read(addr, buffer, bytes);
}
diff --git a/libbacktrace/UnwindStack.h b/libbacktrace/UnwindStack.h
index 4ec591d..47f6757 100644
--- a/libbacktrace/UnwindStack.h
+++ b/libbacktrace/UnwindStack.h
@@ -19,6 +19,7 @@
#include <stdint.h>
+#include <memory>
#include <string>
#include <backtrace/BacktraceMap.h>
@@ -49,23 +50,7 @@
size_t Read(uint64_t addr, uint8_t* buffer, size_t bytes) override;
private:
- unwindstack::MemoryRemote memory_;
-};
-
-class UnwindStackOffline : public Backtrace {
- public:
- UnwindStackOffline(ArchEnum arch, pid_t pid, pid_t tid, BacktraceMap* map, bool map_shared);
-
- bool Unwind(size_t num_ignore_frames, void* context) override;
-
- std::string GetFunctionNameRaw(uint64_t pc, uint64_t* offset) override;
-
- size_t Read(uint64_t addr, uint8_t* buffer, size_t bytes) override;
-
- bool ReadWord(uint64_t ptr, word_t* out_value) override;
-
- private:
- ArchEnum arch_;
+ std::shared_ptr<unwindstack::Memory> memory_;
};
#endif // _LIBBACKTRACE_UNWIND_STACK_H
diff --git a/libbacktrace/UnwindStackMap.cpp b/libbacktrace/UnwindStackMap.cpp
index 4518891..aa0b17c 100644
--- a/libbacktrace/UnwindStackMap.cpp
+++ b/libbacktrace/UnwindStackMap.cpp
@@ -132,43 +132,6 @@
return process_memory_;
}
-UnwindStackOfflineMap::UnwindStackOfflineMap(pid_t pid) : UnwindStackMap(pid) {}
-
-bool UnwindStackOfflineMap::Build() {
- return false;
-}
-
-bool UnwindStackOfflineMap::Build(const std::vector<backtrace_map_t>& backtrace_maps) {
- for (const backtrace_map_t& map : backtrace_maps) {
- maps_.push_back(map);
- }
-
- std::sort(maps_.begin(), maps_.end(),
- [](const backtrace_map_t& a, const backtrace_map_t& b) { return a.start < b.start; });
-
- unwindstack::Maps* maps = new unwindstack::Maps;
- stack_maps_.reset(maps);
- for (const backtrace_map_t& map : maps_) {
- maps->Add(map.start, map.end, map.offset, map.flags, map.name, map.load_bias);
- }
- return true;
-}
-
-bool UnwindStackOfflineMap::CreateProcessMemory(const backtrace_stackinfo_t& stack) {
- if (stack.start >= stack.end) {
- return false;
- }
-
- // Create the process memory from the stack data.
- if (memory_ == nullptr) {
- memory_ = new unwindstack::MemoryOfflineBuffer(stack.data, stack.start, stack.end);
- process_memory_.reset(memory_);
- } else {
- memory_->Reset(stack.data, stack.start, stack.end);
- }
- return true;
-}
-
//-------------------------------------------------------------------------
// BacktraceMap create function.
//-------------------------------------------------------------------------
@@ -189,15 +152,3 @@
}
return map;
}
-
-//-------------------------------------------------------------------------
-// BacktraceMap create offline function.
-//-------------------------------------------------------------------------
-BacktraceMap* BacktraceMap::CreateOffline(pid_t pid, const std::vector<backtrace_map_t>& maps) {
- UnwindStackOfflineMap* map = new UnwindStackOfflineMap(pid);
- if (!map->Build(maps)) {
- delete map;
- return nullptr;
- }
- return map;
-}
diff --git a/libbacktrace/UnwindStackMap.h b/libbacktrace/UnwindStackMap.h
index e19b605..f0e7d8b 100644
--- a/libbacktrace/UnwindStackMap.h
+++ b/libbacktrace/UnwindStackMap.h
@@ -33,6 +33,7 @@
#include <unwindstack/Elf.h>
#include <unwindstack/JitDebug.h>
#include <unwindstack/Maps.h>
+#include <unwindstack/Memory.h>
// Forward declarations.
class UnwindDexFile;
@@ -74,19 +75,4 @@
unwindstack::ArchEnum arch_ = unwindstack::ARCH_UNKNOWN;
};
-class UnwindStackOfflineMap : public UnwindStackMap {
- public:
- UnwindStackOfflineMap(pid_t pid);
- ~UnwindStackOfflineMap() = default;
-
- bool Build() override;
-
- bool Build(const std::vector<backtrace_map_t>& maps);
-
- bool CreateProcessMemory(const backtrace_stackinfo_t& stack);
-
- private:
- unwindstack::MemoryOfflineBuffer* memory_ = nullptr;
-};
-
#endif // _LIBBACKTRACE_UNWINDSTACK_MAP_H
diff --git a/libbacktrace/backtrace_offline_test.cpp b/libbacktrace/backtrace_offline_test.cpp
deleted file mode 100644
index 662fb99..0000000
--- a/libbacktrace/backtrace_offline_test.cpp
+++ /dev/null
@@ -1,397 +0,0 @@
-/*
- * Copyright (C) 2015 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <inttypes.h>
-#include <pthread.h>
-#include <stdint.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include <functional>
-#include <memory>
-#include <string>
-#include <utility>
-#include <vector>
-
-#include <android-base/file.h>
-#include <android-base/logging.h>
-#include <android-base/macros.h>
-#include <android-base/stringprintf.h>
-#include <android-base/strings.h>
-#include <android-base/threads.h>
-#include <backtrace/Backtrace.h>
-#include <backtrace/BacktraceMap.h>
-
-#include <gtest/gtest.h>
-
-#include "BacktraceTest.h"
-
-struct FunctionSymbol {
- std::string name;
- uint64_t start;
- uint64_t end;
-};
-
-static std::vector<FunctionSymbol> GetFunctionSymbols() {
- std::vector<FunctionSymbol> symbols = {
- {"unknown_start", 0, 0},
- {"test_level_one", reinterpret_cast<uint64_t>(&BacktraceTest::test_level_one_), 0},
- {"test_level_two", reinterpret_cast<uint64_t>(&BacktraceTest::test_level_two_), 0},
- {"test_level_three", reinterpret_cast<uint64_t>(&BacktraceTest::test_level_three_), 0},
- {"test_level_four", reinterpret_cast<uint64_t>(&BacktraceTest::test_level_four_), 0},
- {"test_recursive_call", reinterpret_cast<uint64_t>(&BacktraceTest::test_recursive_call_), 0},
- {"test_get_context_and_wait",
- reinterpret_cast<uint64_t>(&BacktraceTest::test_get_context_and_wait_), 0},
- {"unknown_end", static_cast<uint64_t>(-1), static_cast<uint64_t>(-1)},
- };
- std::sort(
- symbols.begin(), symbols.end(),
- [](const FunctionSymbol& s1, const FunctionSymbol& s2) { return s1.start < s2.start; });
- for (size_t i = 0; i + 1 < symbols.size(); ++i) {
- symbols[i].end = symbols[i + 1].start;
- }
- return symbols;
-}
-
-static std::string RawDataToHexString(const void* data, size_t size) {
- const uint8_t* p = static_cast<const uint8_t*>(data);
- std::string s;
- for (size_t i = 0; i < size; ++i) {
- s += android::base::StringPrintf("%02x", p[i]);
- }
- return s;
-}
-
-static void HexStringToRawData(const char* s, std::vector<uint8_t>* data, size_t size) {
- for (size_t i = 0; i < size; ++i) {
- int value;
- sscanf(s, "%02x", &value);
- data->push_back(value);
- s += 2;
- }
-}
-
-struct OfflineThreadArg {
- std::vector<uint8_t> ucontext;
- pid_t tid;
- volatile int exit_flag;
-};
-
-static void* OfflineThreadFunc(void* arg) {
- OfflineThreadArg* fn_arg = reinterpret_cast<OfflineThreadArg*>(arg);
- fn_arg->tid = android::base::GetThreadId();
- BacktraceTest::test_get_context_and_wait_(&fn_arg->ucontext, &fn_arg->exit_flag);
- return nullptr;
-}
-
-std::string GetTestPath(const std::string& arch, const std::string& path) {
- return android::base::GetExecutableDirectory() + "/testdata/" + arch + '/' + path;
-}
-
-// This test is disable because it is for generating test data.
-TEST_F(BacktraceTest, DISABLED_generate_offline_testdata) {
- // Create a thread to generate the needed stack and registers information.
- 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);
- 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));
- pthread_t thread;
- OfflineThreadArg arg;
- arg.exit_flag = 0;
- ASSERT_EQ(0, pthread_create(&thread, &attr, OfflineThreadFunc, &arg));
- // Wait for the offline thread to generate the stack and context information.
- sleep(1);
- // Copy the stack information.
- std::vector<uint8_t> stack_data(reinterpret_cast<uint8_t*>(stack),
- reinterpret_cast<uint8_t*>(stack) + stack_size);
- arg.exit_flag = 1;
- ASSERT_EQ(0, pthread_join(thread, nullptr));
- ASSERT_EQ(0, munmap(stack, stack_size));
-
- std::unique_ptr<BacktraceMap> map(BacktraceMap::Create(getpid()));
- ASSERT_TRUE(map != nullptr);
-
- backtrace_stackinfo_t stack_info;
- stack_info.start = stack_addr;
- stack_info.end = stack_addr + stack_size;
- stack_info.data = stack_data.data();
-
- // Generate offline testdata.
- std::string testdata;
- // 1. Dump pid, tid
- testdata += android::base::StringPrintf("pid: %d tid: %d\n", getpid(), arg.tid);
- // 2. Dump maps
- for (auto it = map->begin(); it != map->end(); ++it) {
- const backtrace_map_t* entry = *it;
- testdata +=
- 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());
- }
- // 3. Dump ucontext
- testdata += android::base::StringPrintf("ucontext: %zu ", arg.ucontext.size());
- testdata += RawDataToHexString(arg.ucontext.data(), arg.ucontext.size());
- testdata.push_back('\n');
-
- // 4. Dump stack
- testdata += android::base::StringPrintf(
- "stack: start: %" PRIx64 " end: %" PRIx64 " size: %zu ",
- stack_info.start, stack_info.end, stack_data.size());
- testdata += RawDataToHexString(stack_data.data(), stack_data.size());
- testdata.push_back('\n');
-
- // 5. Dump function symbols
- std::vector<FunctionSymbol> function_symbols = GetFunctionSymbols();
- for (const auto& symbol : function_symbols) {
- 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"));
-}
-
-// 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(uint64_t addr,
- const std::vector<FunctionSymbol>& symbols) {
- for (auto& symbol : symbols) {
- if (addr >= symbol.start && addr < symbol.end) {
- return symbol.name;
- }
- }
- return "";
-}
-
-struct OfflineTestData {
- int pid;
- int tid;
- std::vector<backtrace_map_t> maps;
- std::vector<uint8_t> ucontext;
- backtrace_stackinfo_t stack_info;
- std::vector<uint8_t> stack;
- std::vector<FunctionSymbol> symbols;
-};
-
-bool ReadOfflineTestData(const std::string offline_testdata_path, OfflineTestData* testdata) {
- std::string s;
- if (!android::base::ReadFileToString(offline_testdata_path, &s)) {
- return false;
- }
- // Parse offline_testdata.
- std::vector<std::string> lines = android::base::Split(s, "\n");
- for (const auto& line : lines) {
- if (android::base::StartsWith(line, "pid:")) {
- sscanf(line.c_str(), "pid: %d tid: %d", &testdata->pid, &testdata->tid);
- } else if (android::base::StartsWith(line, "map:")) {
- testdata->maps.resize(testdata->maps.size() + 1);
- backtrace_map_t& map = testdata->maps.back();
- int pos;
- sscanf(line.c_str(),
- "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));
- } else if (android::base::StartsWith(line, "ucontext:")) {
- size_t size;
- int pos;
- testdata->ucontext.clear();
- sscanf(line.c_str(), "ucontext: %zu %n", &size, &pos);
- HexStringToRawData(&line[pos], &testdata->ucontext, size);
- } else if (android::base::StartsWith(line, "stack:")) {
- size_t size;
- int pos;
- sscanf(line.c_str(),
- "stack: start: %" SCNx64 " end: %" SCNx64 " size: %zu %n",
- &testdata->stack_info.start, &testdata->stack_info.end, &size, &pos);
- CHECK_EQ(testdata->stack_info.end - testdata->stack_info.start, size);
- testdata->stack.clear();
- HexStringToRawData(&line[pos], &testdata->stack, size);
- testdata->stack_info.data = testdata->stack.data();
- } else if (android::base::StartsWith(line, "function:")) {
- testdata->symbols.resize(testdata->symbols.size() + 1);
- FunctionSymbol& symbol = testdata->symbols.back();
- int pos;
- sscanf(line.c_str(), "function: start: %" SCNx64 " end: %" SCNx64 " name: %n", &symbol.start,
- &symbol.end, &pos);
- symbol.name = line.substr(pos);
- }
- }
- return true;
-}
-
-static void BacktraceOfflineTest(std::string arch_str, const std::string& testlib_name) {
- const std::string testlib_path(GetTestPath(arch_str, testlib_name));
- const std::string offline_testdata_path(GetTestPath(arch_str, "offline_testdata"));
- OfflineTestData testdata;
- ASSERT_TRUE(ReadOfflineTestData(offline_testdata_path, &testdata)) << "Failed " << arch_str;
-
- // Fix path of libbacktrace_testlib.so.
- for (auto& map : testdata.maps) {
- if (map.name.find("libbacktrace_test.so") != std::string::npos) {
- map.name = testlib_path;
- }
- }
-
- Backtrace::ArchEnum arch;
- if (arch_str == "arm") {
- arch = Backtrace::ARCH_ARM;
- } else if (arch_str == "arm64") {
- arch = Backtrace::ARCH_ARM64;
- } else if (arch_str == "x86") {
- arch = Backtrace::ARCH_X86;
- } else if (arch_str == "x86_64") {
- arch = Backtrace::ARCH_X86_64;
- } else {
- abort();
- }
-
- std::unique_ptr<Backtrace> backtrace(Backtrace::CreateOffline(
- arch, testdata.pid, testdata.tid, testdata.maps, testdata.stack_info));
- ASSERT_TRUE(backtrace != nullptr) << "Failed " << arch_str;
-
- ASSERT_TRUE(backtrace->Unwind(0, testdata.ucontext.data())) << "Failed " << arch_str;
-
- // Collect pc values of the call stack frames.
- std::vector<uint64_t> pc_values;
- for (size_t i = 0; i < backtrace->NumFrames(); ++i) {
- pc_values.push_back(backtrace->GetFrame(i)->pc);
- }
-
- size_t test_one_index = 0;
- for (size_t i = 0; i < pc_values.size(); ++i) {
- if (FunctionNameForAddress(pc_values[i], testdata.symbols) == "test_level_one") {
- test_one_index = i;
- break;
- }
- }
-
- ASSERT_GE(test_one_index, 3u) << "Failed " << arch_str;
- ASSERT_EQ("test_level_one", FunctionNameForAddress(pc_values[test_one_index], testdata.symbols))
- << "Failed " << arch_str;
- ASSERT_EQ("test_level_two", FunctionNameForAddress(pc_values[test_one_index - 1], testdata.symbols))
- << "Failed " << arch_str;
- ASSERT_EQ("test_level_three",
- FunctionNameForAddress(pc_values[test_one_index - 2], testdata.symbols))
- << "Failed " << arch_str;
- ASSERT_EQ("test_level_four",
- FunctionNameForAddress(pc_values[test_one_index - 3], testdata.symbols))
- << "Failed " << arch_str;
-}
-
-// For now, these tests can only run on the given architectures.
-TEST_F(BacktraceTest, offline_eh_frame) {
- BacktraceOfflineTest("arm64", "libbacktrace_test_eh_frame.so");
- BacktraceOfflineTest("x86_64", "libbacktrace_test_eh_frame.so");
-}
-
-TEST_F(BacktraceTest, offline_debug_frame) {
- BacktraceOfflineTest("arm", "libbacktrace_test_debug_frame.so");
- BacktraceOfflineTest("x86", "libbacktrace_test_debug_frame.so");
-}
-
-TEST_F(BacktraceTest, offline_gnu_debugdata) {
- BacktraceOfflineTest("arm", "libbacktrace_test_gnu_debugdata.so");
- BacktraceOfflineTest("x86", "libbacktrace_test_gnu_debugdata.so");
-}
-
-TEST_F(BacktraceTest, offline_arm_exidx) {
- BacktraceOfflineTest("arm", "libbacktrace_test_arm_exidx.so");
-}
-
-static void LibUnwindingTest(const std::string& arch_str, const std::string& testdata_name,
- const std::string& testlib_name) {
- const std::string testlib_path(GetTestPath(arch_str, testlib_name));
- struct stat st;
- ASSERT_EQ(0, stat(testlib_path.c_str(), &st)) << "can't find testlib " << testlib_path;
-
- const std::string offline_testdata_path(GetTestPath(arch_str, testdata_name));
- OfflineTestData testdata;
- ASSERT_TRUE(ReadOfflineTestData(offline_testdata_path, &testdata));
-
- // Fix path of the testlib.
- for (auto& map : testdata.maps) {
- if (map.name.find(testlib_name) != std::string::npos) {
- map.name = testlib_path;
- }
- }
-
- Backtrace::ArchEnum arch;
- if (arch_str == "arm") {
- arch = Backtrace::ARCH_ARM;
- } else if (arch_str == "arm64") {
- arch = Backtrace::ARCH_ARM64;
- } else if (arch_str == "x86") {
- arch = Backtrace::ARCH_X86;
- } else if (arch_str == "x86_64") {
- arch = Backtrace::ARCH_X86_64;
- } else {
- ASSERT_TRUE(false) << "Unsupported arch " << arch_str;
- abort();
- }
-
- // Do offline backtrace.
- std::unique_ptr<Backtrace> backtrace(Backtrace::CreateOffline(
- arch, testdata.pid, testdata.tid, testdata.maps, testdata.stack_info));
- ASSERT_TRUE(backtrace != nullptr);
-
- ASSERT_TRUE(backtrace->Unwind(0, testdata.ucontext.data()));
-
- ASSERT_EQ(testdata.symbols.size(), backtrace->NumFrames());
- for (size_t i = 0; i < backtrace->NumFrames(); ++i) {
- std::string name = FunctionNameForAddress(backtrace->GetFrame(i)->rel_pc, testdata.symbols);
- ASSERT_EQ(name, testdata.symbols[i].name);
- }
- ASSERT_TRUE(backtrace->GetError().error_code == BACKTRACE_UNWIND_ERROR_ACCESS_MEM_FAILED ||
- backtrace->GetError().error_code == BACKTRACE_UNWIND_ERROR_MAP_MISSING ||
- backtrace->GetError().error_code == BACKTRACE_UNWIND_ERROR_REPEATED_FRAME);
-}
-
-// This test tests the situation that ranges of functions covered by .eh_frame and .ARM.exidx
-// overlap with each other, which appears in /system/lib/libart.so.
-TEST_F(BacktraceTest, offline_unwind_mix_eh_frame_and_arm_exidx) {
- LibUnwindingTest("arm", "offline_testdata_for_libart", "libart.so");
-}
-
-TEST_F(BacktraceTest, offline_debug_frame_with_load_bias) {
- LibUnwindingTest("arm", "offline_testdata_for_libandroid_runtime", "libandroid_runtime.so");
-}
-
-TEST_F(BacktraceTest, offline_try_armexidx_after_debug_frame) {
- LibUnwindingTest("arm", "offline_testdata_for_libGLESv2_adreno", "libGLESv2_adreno.so");
-}
-
-TEST_F(BacktraceTest, offline_cie_with_P_augmentation) {
- // Make sure we can unwind through functions with CIE entry containing P augmentation, which
- // makes unwinding library reading personality handler from memory. One example is
- // /system/lib64/libskia.so.
- LibUnwindingTest("arm64", "offline_testdata_for_libskia", "libskia.so");
-}
-
-TEST_F(BacktraceTest, offline_empty_eh_frame_hdr) {
- // Make sure we can unwind through libraries with empty .eh_frame_hdr section. One example is
- // /vendor/lib64/egl/eglSubDriverAndroid.so.
- LibUnwindingTest("arm64", "offline_testdata_for_eglSubDriverAndroid", "eglSubDriverAndroid.so");
-}
-
-TEST_F(BacktraceTest, offline_max_frames_limit) {
- // The length of callchain can reach 256 when recording an application.
- ASSERT_GE(MAX_BACKTRACE_FRAMES, 256);
-}
diff --git a/libbacktrace/include/backtrace/Backtrace.h b/libbacktrace/include/backtrace/Backtrace.h
index 404e7e8..664b531 100644
--- a/libbacktrace/include/backtrace/Backtrace.h
+++ b/libbacktrace/include/backtrace/Backtrace.h
@@ -126,24 +126,6 @@
// If map is not NULL, the map is still owned by the caller.
static Backtrace* Create(pid_t pid, pid_t tid, BacktraceMap* map = nullptr);
- // Create an offline Backtrace object that can be used to do an unwind without a process
- // that is still running. By default, information is only cached in the map
- // file. If the calling code creates the map, data can be cached between
- // unwinds. If not, all cached data will be destroyed when the Backtrace
- // object is destroyed.
- static Backtrace* CreateOffline(ArchEnum arch, pid_t pid, pid_t tid,
- const std::vector<backtrace_map_t>& maps,
- const backtrace_stackinfo_t& stack);
- static Backtrace* CreateOffline(ArchEnum arch, pid_t pid, pid_t tid, BacktraceMap* map);
-
- // Create an offline Backtrace object that can be used to do an unwind without a process
- // that is still running. If cache_file is set to true, then elf information will be cached
- // for this call. The cached information survives until the calling process ends. This means
- // that subsequent calls to create offline Backtrace objects will continue to use the same
- // cache. It also assumes that the elf files used for each offline unwind are the same.
- static Backtrace* CreateOffline(pid_t pid, pid_t tid, BacktraceMap* map,
- const backtrace_stackinfo_t& stack, bool cache_file = false);
-
virtual ~Backtrace();
// Get the current stack trace and store in the backtrace_ structure.
@@ -153,11 +135,6 @@
std::vector<backtrace_frame_data_t>* frames, size_t num_ignore_frames,
std::vector<std::string>* skip_names, BacktraceUnwindError* error = nullptr);
- static bool UnwindOffline(unwindstack::Regs* regs, BacktraceMap* back_map,
- const backtrace_stackinfo_t& stack_info,
- std::vector<backtrace_frame_data_t>* frames,
- BacktraceUnwindError* error = nullptr);
-
// 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.
diff --git a/libbacktrace/include/backtrace/BacktraceMap.h b/libbacktrace/include/backtrace/BacktraceMap.h
index c564271..f8d5058 100644
--- a/libbacktrace/include/backtrace/BacktraceMap.h
+++ b/libbacktrace/include/backtrace/BacktraceMap.h
@@ -69,8 +69,6 @@
// is unsupported.
static BacktraceMap* Create(pid_t pid, bool uncached = false);
- static BacktraceMap* CreateOffline(pid_t pid, const std::vector<backtrace_map_t>& maps);
-
virtual ~BacktraceMap();
class iterator : public std::iterator<std::bidirectional_iterator_tag, backtrace_map_t*> {
diff --git a/libprocessgroup/Android.bp b/libprocessgroup/Android.bp
index 52a297c..618a5c5 100644
--- a/libprocessgroup/Android.bp
+++ b/libprocessgroup/Android.bp
@@ -24,9 +24,9 @@
],
name: "libprocessgroup",
host_supported: true,
+ native_bridge_supported: true,
recovery_available: true,
vendor_available: true,
- native_bridge_supported: true,
vndk: {
enabled: true,
support_system_process: true,
diff --git a/libprocessgroup/cgroup_map.cpp b/libprocessgroup/cgroup_map.cpp
index 92fcd1e..9797d76 100644
--- a/libprocessgroup/cgroup_map.cpp
+++ b/libprocessgroup/cgroup_map.cpp
@@ -70,8 +70,8 @@
bool CgroupController::IsUsable() const {
if (!HasValue()) return false;
- uint32_t flags = ACgroupController_getFlags(controller_);
- return (flags & CGROUPRC_CONTROLLER_FLAG_MOUNTED) != 0;
+ static bool enabled = (access(GetProcsFilePath("", 0, 0).c_str(), F_OK) == 0);
+ return enabled;
}
std::string CgroupController::GetTasksFilePath(const std::string& rel_path) const {
@@ -160,7 +160,6 @@
const ACgroupController* controller = ACgroupFile_getController(i);
LOG(INFO) << "\t" << ACgroupController_getName(controller) << " ver "
<< ACgroupController_getVersion(controller) << " path "
- << ACgroupController_getFlags(controller) << " flags "
<< ACgroupController_getPath(controller);
}
}
diff --git a/libprocessgroup/cgrouprc/cgroup_controller.cpp b/libprocessgroup/cgrouprc/cgroup_controller.cpp
index 5a326e5..d064d31 100644
--- a/libprocessgroup/cgrouprc/cgroup_controller.cpp
+++ b/libprocessgroup/cgrouprc/cgroup_controller.cpp
@@ -27,11 +27,6 @@
return controller->version();
}
-uint32_t ACgroupController_getFlags(const ACgroupController* controller) {
- CHECK(controller != nullptr);
- return controller->flags();
-}
-
const char* ACgroupController_getName(const ACgroupController* controller) {
CHECK(controller != nullptr);
return controller->name();
diff --git a/libprocessgroup/cgrouprc/include/android/cgrouprc.h b/libprocessgroup/cgrouprc/include/android/cgrouprc.h
index ffc9f0b..0f6a9cd 100644
--- a/libprocessgroup/cgrouprc/include/android/cgrouprc.h
+++ b/libprocessgroup/cgrouprc/include/android/cgrouprc.h
@@ -66,18 +66,11 @@
__INTRODUCED_IN(29);
/**
- * Flag bitmask used in ACgroupController_getFlags
+ * Flag bitmask to be used when ACgroupController_getFlags can be exported
*/
#define CGROUPRC_CONTROLLER_FLAG_MOUNTED 0x1
/**
- * Returns the flags bitmask of the given controller.
- * If the given controller is null, return 0.
- */
-__attribute__((warn_unused_result)) uint32_t ACgroupController_getFlags(const ACgroupController*)
- __INTRODUCED_IN(29);
-
-/**
* Returns the name of the given controller.
* If the given controller is null, return nullptr.
*/
diff --git a/libprocessgroup/cgrouprc/libcgrouprc.llndk.txt b/libprocessgroup/cgrouprc/libcgrouprc.llndk.txt
index ea3df33..91df392 100644
--- a/libprocessgroup/cgrouprc/libcgrouprc.llndk.txt
+++ b/libprocessgroup/cgrouprc/libcgrouprc.llndk.txt
@@ -4,7 +4,6 @@
ACgroupFile_getControllerCount;
ACgroupFile_getController;
ACgroupController_getVersion;
- ACgroupController_getFlags;
ACgroupController_getName;
ACgroupController_getPath;
local:
diff --git a/libprocessgroup/task_profiles.cpp b/libprocessgroup/task_profiles.cpp
index 40d8d90..edc316a 100644
--- a/libprocessgroup/task_profiles.cpp
+++ b/libprocessgroup/task_profiles.cpp
@@ -150,6 +150,7 @@
}
void SetCgroupAction::EnableResourceCaching() {
+ std::lock_guard<std::mutex> lock(fd_mutex_);
if (fd_ != FDS_NOT_CACHED) {
return;
}
@@ -191,6 +192,7 @@
}
bool SetCgroupAction::ExecuteForProcess(uid_t uid, pid_t pid) const {
+ std::lock_guard<std::mutex> lock(fd_mutex_);
if (IsFdValid()) {
// fd is cached, reuse it
if (!AddTidToCgroup(pid, fd_)) {
@@ -221,6 +223,7 @@
}
bool SetCgroupAction::ExecuteForTask(int tid) const {
+ std::lock_guard<std::mutex> lock(fd_mutex_);
if (IsFdValid()) {
// fd is cached, reuse it
if (!AddTidToCgroup(tid, fd_)) {
diff --git a/libprocessgroup/task_profiles.h b/libprocessgroup/task_profiles.h
index 445647d..77bac2d 100644
--- a/libprocessgroup/task_profiles.h
+++ b/libprocessgroup/task_profiles.h
@@ -19,6 +19,7 @@
#include <sys/cdefs.h>
#include <sys/types.h>
#include <map>
+#include <mutex>
#include <string>
#include <vector>
@@ -127,6 +128,7 @@
CgroupController controller_;
std::string path_;
android::base::unique_fd fd_;
+ mutable std::mutex fd_mutex_;
static bool IsAppDependentPath(const std::string& path);
static bool AddTidToCgroup(int tid, int fd);
diff --git a/libunwindstack/Android.bp b/libunwindstack/Android.bp
index b7650a1..5423de5 100644
--- a/libunwindstack/Android.bp
+++ b/libunwindstack/Android.bp
@@ -241,6 +241,7 @@
"tests/files/offline/debug_frame_first_x86/*",
"tests/files/offline/debug_frame_load_bias_arm/*",
"tests/files/offline/eh_frame_hdr_begin_x86_64/*",
+ "tests/files/offline/invalid_elf_offset_arm/*",
"tests/files/offline/jit_debug_arm/*",
"tests/files/offline/jit_debug_x86/*",
"tests/files/offline/jit_map_arm/*",
diff --git a/libunwindstack/ElfInterface.cpp b/libunwindstack/ElfInterface.cpp
index dee8eb3..f0e4138 100644
--- a/libunwindstack/ElfInterface.cpp
+++ b/libunwindstack/ElfInterface.cpp
@@ -29,12 +29,12 @@
#include <unwindstack/DwarfSection.h>
#include <unwindstack/ElfInterface.h>
#include <unwindstack/Log.h>
-#include <unwindstack/Memory.h>
#include <unwindstack/Regs.h>
#include "DwarfDebugFrame.h"
#include "DwarfEhFrame.h"
#include "DwarfEhFrameWithHdr.h"
+#include "MemoryBuffer.h"
#include "Symbols.h"
namespace unwindstack {
diff --git a/libunwindstack/JitDebug.cpp b/libunwindstack/JitDebug.cpp
index 20bc4b9..8a85607 100644
--- a/libunwindstack/JitDebug.cpp
+++ b/libunwindstack/JitDebug.cpp
@@ -23,7 +23,8 @@
#include <unwindstack/Elf.h>
#include <unwindstack/JitDebug.h>
#include <unwindstack/Maps.h>
-#include <unwindstack/Memory.h>
+
+#include "MemoryRange.h"
// This implements the JIT Compilation Interface.
// See https://sourceware.org/gdb/onlinedocs/gdb/JIT-Interface.html
diff --git a/libunwindstack/MapInfo.cpp b/libunwindstack/MapInfo.cpp
index 03658b4..1c0f1e6 100644
--- a/libunwindstack/MapInfo.cpp
+++ b/libunwindstack/MapInfo.cpp
@@ -27,7 +27,9 @@
#include <unwindstack/Elf.h>
#include <unwindstack/MapInfo.h>
#include <unwindstack/Maps.h>
-#include <unwindstack/Memory.h>
+
+#include "MemoryFileAtOffset.h"
+#include "MemoryRange.h"
namespace unwindstack {
@@ -231,11 +233,13 @@
}
}
- // If there is a read-only map then a read-execute map that represents the
- // same elf object, make sure the previous map is using the same elf
- // object if it hasn't already been set.
- if (prev_map != nullptr && elf_start_offset != offset && prev_map->offset == elf_start_offset &&
- prev_map->name == name) {
+ if (!elf->valid()) {
+ elf_start_offset = offset;
+ } else if (prev_map != nullptr && elf_start_offset != offset &&
+ prev_map->offset == elf_start_offset && prev_map->name == name) {
+ // If there is a read-only map then a read-execute map that represents the
+ // same elf object, make sure the previous map is using the same elf
+ // object if it hasn't already been set.
std::lock_guard<std::mutex> guard(prev_map->mutex_);
if (prev_map->elf.get() == nullptr) {
prev_map->elf = elf;
diff --git a/libunwindstack/Memory.cpp b/libunwindstack/Memory.cpp
index 9904fef..a66cd5b 100644
--- a/libunwindstack/Memory.cpp
+++ b/libunwindstack/Memory.cpp
@@ -32,6 +32,14 @@
#include <unwindstack/Memory.h>
#include "Check.h"
+#include "MemoryBuffer.h"
+#include "MemoryCache.h"
+#include "MemoryFileAtOffset.h"
+#include "MemoryLocal.h"
+#include "MemoryOffline.h"
+#include "MemoryOfflineBuffer.h"
+#include "MemoryRange.h"
+#include "MemoryRemote.h"
namespace unwindstack {
@@ -168,6 +176,16 @@
return false;
}
+std::unique_ptr<Memory> Memory::CreateFileMemory(const std::string& path, uint64_t offset) {
+ auto memory = std::make_unique<MemoryFileAtOffset>();
+
+ if (memory->Init(path, offset)) {
+ return memory;
+ }
+
+ return nullptr;
+}
+
std::shared_ptr<Memory> Memory::CreateProcessMemory(pid_t pid) {
if (pid == getpid()) {
return std::shared_ptr<Memory>(new MemoryLocal());
@@ -182,6 +200,11 @@
return std::shared_ptr<Memory>(new MemoryCache(new MemoryRemote(pid)));
}
+std::shared_ptr<Memory> Memory::CreateOfflineMemory(const uint8_t* data, uint64_t start,
+ uint64_t end) {
+ return std::shared_ptr<Memory>(new MemoryOfflineBuffer(data, start, end));
+}
+
size_t MemoryBuffer::Read(uint64_t addr, void* dst, size_t size) {
if (addr >= raw_.size()) {
return 0;
diff --git a/libunwindstack/MemoryBuffer.h b/libunwindstack/MemoryBuffer.h
new file mode 100644
index 0000000..3fe4bbb
--- /dev/null
+++ b/libunwindstack/MemoryBuffer.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_MEMORY_BUFFER_H
+#define _LIBUNWINDSTACK_MEMORY_BUFFER_H
+
+#include <stdint.h>
+
+#include <string>
+#include <vector>
+
+#include <unwindstack/Memory.h>
+
+namespace unwindstack {
+
+class MemoryBuffer : public Memory {
+ public:
+ MemoryBuffer() = default;
+ virtual ~MemoryBuffer() = default;
+
+ size_t Read(uint64_t addr, void* dst, size_t size) override;
+
+ uint8_t* GetPtr(size_t offset);
+
+ void Resize(size_t size) { raw_.resize(size); }
+
+ uint64_t Size() { return raw_.size(); }
+
+ private:
+ std::vector<uint8_t> raw_;
+};
+
+} // namespace unwindstack
+
+#endif // _LIBUNWINDSTACK_MEMORY_BUFFER_H
diff --git a/libunwindstack/MemoryCache.h b/libunwindstack/MemoryCache.h
new file mode 100644
index 0000000..769d907
--- /dev/null
+++ b/libunwindstack/MemoryCache.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_MEMORY_CACHE_H
+#define _LIBUNWINDSTACK_MEMORY_CACHE_H
+
+#include <stdint.h>
+
+#include <memory>
+#include <string>
+#include <unordered_map>
+
+#include <unwindstack/Memory.h>
+
+namespace unwindstack {
+
+class MemoryCache : public Memory {
+ public:
+ MemoryCache(Memory* memory) : impl_(memory) {}
+ virtual ~MemoryCache() = default;
+
+ size_t Read(uint64_t addr, void* dst, size_t size) override;
+
+ void Clear() override { cache_.clear(); }
+
+ private:
+ constexpr static size_t kCacheBits = 12;
+ constexpr static size_t kCacheMask = (1 << kCacheBits) - 1;
+ constexpr static size_t kCacheSize = 1 << kCacheBits;
+ std::unordered_map<uint64_t, uint8_t[kCacheSize]> cache_;
+
+ std::unique_ptr<Memory> impl_;
+};
+
+} // namespace unwindstack
+
+#endif // _LIBUNWINDSTACK_MEMORY_CACHE_H
diff --git a/libunwindstack/MemoryFileAtOffset.h b/libunwindstack/MemoryFileAtOffset.h
new file mode 100644
index 0000000..d136eb4
--- /dev/null
+++ b/libunwindstack/MemoryFileAtOffset.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_MEMORY_FILE_AT_OFFSET_H
+#define _LIBUNWINDSTACK_MEMORY_FILE_AT_OFFSET_H
+
+#include <stdint.h>
+
+#include <unwindstack/Memory.h>
+
+namespace unwindstack {
+
+class MemoryFileAtOffset : public Memory {
+ public:
+ MemoryFileAtOffset() = default;
+ virtual ~MemoryFileAtOffset();
+
+ bool Init(const std::string& file, uint64_t offset, uint64_t size = UINT64_MAX);
+
+ size_t Read(uint64_t addr, void* dst, size_t size) override;
+
+ size_t Size() { return size_; }
+
+ void Clear() override;
+
+ protected:
+ size_t size_ = 0;
+ size_t offset_ = 0;
+ uint8_t* data_ = nullptr;
+};
+
+} // namespace unwindstack
+
+#endif // _LIBUNWINDSTACK_MEMORY_FILE_AT_OFFSET_H
diff --git a/libunwindstack/MemoryLocal.h b/libunwindstack/MemoryLocal.h
new file mode 100644
index 0000000..29aaf12
--- /dev/null
+++ b/libunwindstack/MemoryLocal.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_MEMORY_LOCAL_H
+#define _LIBUNWINDSTACK_MEMORY_LOCAL_H
+
+#include <stdint.h>
+
+#include <unwindstack/Memory.h>
+
+namespace unwindstack {
+
+class MemoryLocal : public Memory {
+ public:
+ MemoryLocal() = default;
+ virtual ~MemoryLocal() = default;
+
+ size_t Read(uint64_t addr, void* dst, size_t size) override;
+};
+
+} // namespace unwindstack
+
+#endif // _LIBUNWINDSTACK_MEMORY_LOCAL_H
diff --git a/libunwindstack/MemoryOffline.h b/libunwindstack/MemoryOffline.h
new file mode 100644
index 0000000..789f1a2
--- /dev/null
+++ b/libunwindstack/MemoryOffline.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_MEMORY_OFFLINE_H
+#define _LIBUNWINDSTACK_MEMORY_OFFLINE_H
+
+#include <stdint.h>
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <unwindstack/Memory.h>
+
+#include "MemoryRange.h"
+
+namespace unwindstack {
+
+class MemoryOffline : public Memory {
+ public:
+ MemoryOffline() = default;
+ virtual ~MemoryOffline() = default;
+
+ bool Init(const std::string& file, uint64_t offset);
+
+ size_t Read(uint64_t addr, void* dst, size_t size) override;
+
+ private:
+ std::unique_ptr<MemoryRange> memory_;
+};
+
+class MemoryOfflineParts : public Memory {
+ public:
+ MemoryOfflineParts() = default;
+ virtual ~MemoryOfflineParts();
+
+ void Add(MemoryOffline* memory) { memories_.push_back(memory); }
+
+ size_t Read(uint64_t addr, void* dst, size_t size) override;
+
+ private:
+ std::vector<MemoryOffline*> memories_;
+};
+
+} // namespace unwindstack
+
+#endif // _LIBUNWINDSTACK_MEMORY_OFFLINE_H
diff --git a/libunwindstack/MemoryOfflineBuffer.h b/libunwindstack/MemoryOfflineBuffer.h
new file mode 100644
index 0000000..64c49a1
--- /dev/null
+++ b/libunwindstack/MemoryOfflineBuffer.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_MEMORY_OFFLINE_BUFFER_H
+#define _LIBUNWINDSTACK_MEMORY_OFFLINE_BUFFER_H
+
+#include <stdint.h>
+
+#include <unwindstack/Memory.h>
+
+namespace unwindstack {
+
+class MemoryOfflineBuffer : public Memory {
+ public:
+ MemoryOfflineBuffer(const uint8_t* data, uint64_t start, uint64_t end);
+ virtual ~MemoryOfflineBuffer() = default;
+
+ void Reset(const uint8_t* data, uint64_t start, uint64_t end);
+
+ size_t Read(uint64_t addr, void* dst, size_t size) override;
+
+ private:
+ const uint8_t* data_;
+ uint64_t start_;
+ uint64_t end_;
+};
+
+} // namespace unwindstack
+
+#endif // _LIBUNWINDSTACK_MEMORY_OFFLINE_BUFFER_H
diff --git a/libunwindstack/MemoryRange.h b/libunwindstack/MemoryRange.h
new file mode 100644
index 0000000..3b4ab5c
--- /dev/null
+++ b/libunwindstack/MemoryRange.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_MEMORY_RANGE_H
+#define _LIBUNWINDSTACK_MEMORY_RANGE_H
+
+#include <stdint.h>
+
+#include <map>
+#include <memory>
+#include <string>
+
+#include <unwindstack/Memory.h>
+
+namespace unwindstack {
+
+// MemoryRange maps one address range onto another.
+// The range [src_begin, src_begin + length) in the underlying Memory is mapped onto offset,
+// such that range.read(offset) is equivalent to underlying.read(src_begin).
+class MemoryRange : public Memory {
+ public:
+ MemoryRange(const std::shared_ptr<Memory>& memory, uint64_t begin, uint64_t length,
+ uint64_t offset);
+ virtual ~MemoryRange() = default;
+
+ size_t Read(uint64_t addr, void* dst, size_t size) override;
+
+ uint64_t offset() { return offset_; }
+ uint64_t length() { return length_; }
+
+ private:
+ std::shared_ptr<Memory> memory_;
+ uint64_t begin_;
+ uint64_t length_;
+ uint64_t offset_;
+};
+
+class MemoryRanges : public Memory {
+ public:
+ MemoryRanges() = default;
+ virtual ~MemoryRanges() = default;
+
+ void Insert(MemoryRange* memory);
+
+ size_t Read(uint64_t addr, void* dst, size_t size) override;
+
+ private:
+ std::map<uint64_t, std::unique_ptr<MemoryRange>> maps_;
+};
+
+} // namespace unwindstack
+
+#endif // _LIBUNWINDSTACK_MEMORY_RANGE_H
diff --git a/libunwindstack/MemoryRemote.h b/libunwindstack/MemoryRemote.h
new file mode 100644
index 0000000..db367d6
--- /dev/null
+++ b/libunwindstack/MemoryRemote.h
@@ -0,0 +1,45 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _LIBUNWINDSTACK_MEMORY_REMOTE_H
+#define _LIBUNWINDSTACK_MEMORY_REMOTE_H
+
+#include <stdint.h>
+#include <sys/types.h>
+
+#include <atomic>
+
+#include <unwindstack/Memory.h>
+
+namespace unwindstack {
+
+class MemoryRemote : public Memory {
+ public:
+ MemoryRemote(pid_t pid) : pid_(pid), read_redirect_func_(0) {}
+ virtual ~MemoryRemote() = default;
+
+ size_t Read(uint64_t addr, void* dst, size_t size) override;
+
+ pid_t pid() { return pid_; }
+
+ private:
+ pid_t pid_;
+ std::atomic_uintptr_t read_redirect_func_;
+};
+
+} // namespace unwindstack
+
+#endif // _LIBUNWINDSTACK_MEMORY_REMOTE_H
diff --git a/libunwindstack/include/unwindstack/MapInfo.h b/libunwindstack/include/unwindstack/MapInfo.h
index 025fd98..13ce10f 100644
--- a/libunwindstack/include/unwindstack/MapInfo.h
+++ b/libunwindstack/include/unwindstack/MapInfo.h
@@ -25,10 +25,11 @@
#include <string>
#include <unwindstack/Elf.h>
-#include <unwindstack/Memory.h>
namespace unwindstack {
+class MemoryFileAtOffset;
+
struct MapInfo {
MapInfo(MapInfo* map_info, uint64_t start, uint64_t end, uint64_t offset, uint64_t flags,
const char* name)
diff --git a/libunwindstack/include/unwindstack/Memory.h b/libunwindstack/include/unwindstack/Memory.h
index b3beb6e..3106564 100644
--- a/libunwindstack/include/unwindstack/Memory.h
+++ b/libunwindstack/include/unwindstack/Memory.h
@@ -21,12 +21,8 @@
#include <sys/types.h>
#include <unistd.h>
-#include <atomic>
-#include <map>
#include <memory>
#include <string>
-#include <unordered_map>
-#include <vector>
namespace unwindstack {
@@ -37,6 +33,9 @@
static std::shared_ptr<Memory> CreateProcessMemory(pid_t pid);
static std::shared_ptr<Memory> CreateProcessMemoryCached(pid_t pid);
+ static std::shared_ptr<Memory> CreateOfflineMemory(const uint8_t* data, uint64_t start,
+ uint64_t end);
+ static std::unique_ptr<Memory> CreateFileMemory(const std::string& path, uint64_t offset);
virtual bool ReadString(uint64_t addr, std::string* string, uint64_t max_read = UINT64_MAX);
@@ -55,157 +54,6 @@
}
};
-class MemoryCache : public Memory {
- public:
- MemoryCache(Memory* memory) : impl_(memory) {}
- virtual ~MemoryCache() = default;
-
- size_t Read(uint64_t addr, void* dst, size_t size) override;
-
- void Clear() override { cache_.clear(); }
-
- private:
- constexpr static size_t kCacheBits = 12;
- constexpr static size_t kCacheMask = (1 << kCacheBits) - 1;
- constexpr static size_t kCacheSize = 1 << kCacheBits;
- std::unordered_map<uint64_t, uint8_t[kCacheSize]> cache_;
-
- std::unique_ptr<Memory> impl_;
-};
-
-class MemoryBuffer : public Memory {
- public:
- MemoryBuffer() = default;
- virtual ~MemoryBuffer() = default;
-
- size_t Read(uint64_t addr, void* dst, size_t size) override;
-
- uint8_t* GetPtr(size_t offset);
-
- void Resize(size_t size) { raw_.resize(size); }
-
- uint64_t Size() { return raw_.size(); }
-
- private:
- std::vector<uint8_t> raw_;
-};
-
-class MemoryFileAtOffset : public Memory {
- public:
- MemoryFileAtOffset() = default;
- virtual ~MemoryFileAtOffset();
-
- bool Init(const std::string& file, uint64_t offset, uint64_t size = UINT64_MAX);
-
- size_t Read(uint64_t addr, void* dst, size_t size) override;
-
- size_t Size() { return size_; }
-
- void Clear() override;
-
- protected:
- size_t size_ = 0;
- size_t offset_ = 0;
- uint8_t* data_ = nullptr;
-};
-
-class MemoryRemote : public Memory {
- public:
- MemoryRemote(pid_t pid) : pid_(pid), read_redirect_func_(0) {}
- virtual ~MemoryRemote() = default;
-
- size_t Read(uint64_t addr, void* dst, size_t size) override;
-
- pid_t pid() { return pid_; }
-
- private:
- pid_t pid_;
- std::atomic_uintptr_t read_redirect_func_;
-};
-
-class MemoryLocal : public Memory {
- public:
- MemoryLocal() = default;
- virtual ~MemoryLocal() = default;
-
- size_t Read(uint64_t addr, void* dst, size_t size) override;
-};
-
-// MemoryRange maps one address range onto another.
-// The range [src_begin, src_begin + length) in the underlying Memory is mapped onto offset,
-// such that range.read(offset) is equivalent to underlying.read(src_begin).
-class MemoryRange : public Memory {
- public:
- MemoryRange(const std::shared_ptr<Memory>& memory, uint64_t begin, uint64_t length,
- uint64_t offset);
- virtual ~MemoryRange() = default;
-
- size_t Read(uint64_t addr, void* dst, size_t size) override;
-
- uint64_t offset() { return offset_; }
- uint64_t length() { return length_; }
-
- private:
- std::shared_ptr<Memory> memory_;
- uint64_t begin_;
- uint64_t length_;
- uint64_t offset_;
-};
-
-class MemoryRanges : public Memory {
- public:
- MemoryRanges() = default;
- virtual ~MemoryRanges() = default;
-
- void Insert(MemoryRange* memory);
-
- size_t Read(uint64_t addr, void* dst, size_t size) override;
-
- private:
- std::map<uint64_t, std::unique_ptr<MemoryRange>> maps_;
-};
-
-class MemoryOffline : public Memory {
- public:
- MemoryOffline() = default;
- virtual ~MemoryOffline() = default;
-
- bool Init(const std::string& file, uint64_t offset);
-
- size_t Read(uint64_t addr, void* dst, size_t size) override;
-
- private:
- std::unique_ptr<MemoryRange> memory_;
-};
-
-class MemoryOfflineBuffer : public Memory {
- public:
- MemoryOfflineBuffer(const uint8_t* data, uint64_t start, uint64_t end);
- virtual ~MemoryOfflineBuffer() = default;
-
- void Reset(const uint8_t* data, uint64_t start, uint64_t end);
-
- size_t Read(uint64_t addr, void* dst, size_t size) override;
-
- private:
- const uint8_t* data_;
- uint64_t start_;
- uint64_t end_;
-};
-
-class MemoryOfflineParts : public Memory {
- public:
- MemoryOfflineParts() = default;
- virtual ~MemoryOfflineParts();
-
- void Add(MemoryOffline* memory) { memories_.push_back(memory); }
-
- size_t Read(uint64_t addr, void* dst, size_t size) override;
-
- private:
- std::vector<MemoryOffline*> memories_;
-};
-
} // namespace unwindstack
#endif // _LIBUNWINDSTACK_MEMORY_H
diff --git a/libunwindstack/tests/MemoryBufferTest.cpp b/libunwindstack/tests/MemoryBufferTest.cpp
index 28e0e76..a6c12aa 100644
--- a/libunwindstack/tests/MemoryBufferTest.cpp
+++ b/libunwindstack/tests/MemoryBufferTest.cpp
@@ -18,9 +18,8 @@
#include <gtest/gtest.h>
-#include <unwindstack/Memory.h>
-
#include "LogFake.h"
+#include "MemoryBuffer.h"
namespace unwindstack {
diff --git a/libunwindstack/tests/MemoryCacheTest.cpp b/libunwindstack/tests/MemoryCacheTest.cpp
index a3def20..3bd3e4d 100644
--- a/libunwindstack/tests/MemoryCacheTest.cpp
+++ b/libunwindstack/tests/MemoryCacheTest.cpp
@@ -20,8 +20,7 @@
#include <gtest/gtest.h>
-#include <unwindstack/Memory.h>
-
+#include "MemoryCache.h"
#include "MemoryFake.h"
namespace unwindstack {
diff --git a/libunwindstack/tests/MemoryFileTest.cpp b/libunwindstack/tests/MemoryFileTest.cpp
index d7d1ace..4124a49 100644
--- a/libunwindstack/tests/MemoryFileTest.cpp
+++ b/libunwindstack/tests/MemoryFileTest.cpp
@@ -21,7 +21,7 @@
#include <android-base/file.h>
#include <gtest/gtest.h>
-#include <unwindstack/Memory.h>
+#include "MemoryFileAtOffset.h"
namespace unwindstack {
diff --git a/libunwindstack/tests/MemoryLocalTest.cpp b/libunwindstack/tests/MemoryLocalTest.cpp
index 5a389d0..c9e5dc0 100644
--- a/libunwindstack/tests/MemoryLocalTest.cpp
+++ b/libunwindstack/tests/MemoryLocalTest.cpp
@@ -22,7 +22,7 @@
#include <gtest/gtest.h>
-#include <unwindstack/Memory.h>
+#include "MemoryLocal.h"
namespace unwindstack {
diff --git a/libunwindstack/tests/MemoryOfflineBufferTest.cpp b/libunwindstack/tests/MemoryOfflineBufferTest.cpp
index f022884..c62c53d 100644
--- a/libunwindstack/tests/MemoryOfflineBufferTest.cpp
+++ b/libunwindstack/tests/MemoryOfflineBufferTest.cpp
@@ -18,9 +18,8 @@
#include <gtest/gtest.h>
-#include <unwindstack/Memory.h>
-
#include "LogFake.h"
+#include "MemoryOfflineBuffer.h"
namespace unwindstack {
diff --git a/libunwindstack/tests/MemoryOfflineTest.cpp b/libunwindstack/tests/MemoryOfflineTest.cpp
index ab9aa9d..d0c441b 100644
--- a/libunwindstack/tests/MemoryOfflineTest.cpp
+++ b/libunwindstack/tests/MemoryOfflineTest.cpp
@@ -19,7 +19,8 @@
#include <gtest/gtest.h>
#include <android-base/file.h>
-#include <unwindstack/Memory.h>
+
+#include "MemoryOffline.h"
namespace unwindstack {
diff --git a/libunwindstack/tests/MemoryRangeTest.cpp b/libunwindstack/tests/MemoryRangeTest.cpp
index 2bac95b..2d4f141 100644
--- a/libunwindstack/tests/MemoryRangeTest.cpp
+++ b/libunwindstack/tests/MemoryRangeTest.cpp
@@ -21,9 +21,8 @@
#include <gtest/gtest.h>
-#include <unwindstack/Memory.h>
-
#include "MemoryFake.h"
+#include "MemoryRange.h"
namespace unwindstack {
diff --git a/libunwindstack/tests/MemoryRangesTest.cpp b/libunwindstack/tests/MemoryRangesTest.cpp
index d24fcd2..e4e9fc4 100644
--- a/libunwindstack/tests/MemoryRangesTest.cpp
+++ b/libunwindstack/tests/MemoryRangesTest.cpp
@@ -20,9 +20,8 @@
#include <gtest/gtest.h>
-#include <unwindstack/Memory.h>
-
#include "MemoryFake.h"
+#include "MemoryRange.h"
namespace unwindstack {
diff --git a/libunwindstack/tests/MemoryRemoteTest.cpp b/libunwindstack/tests/MemoryRemoteTest.cpp
index fb56e8a..c90dedc 100644
--- a/libunwindstack/tests/MemoryRemoteTest.cpp
+++ b/libunwindstack/tests/MemoryRemoteTest.cpp
@@ -30,7 +30,7 @@
#include <android-base/file.h>
#include <gtest/gtest.h>
-#include <unwindstack/Memory.h>
+#include "MemoryRemote.h"
#include "MemoryFake.h"
#include "TestUtils.h"
diff --git a/libunwindstack/tests/UnwindOfflineTest.cpp b/libunwindstack/tests/UnwindOfflineTest.cpp
index 6c64c40..baada82 100644
--- a/libunwindstack/tests/UnwindOfflineTest.cpp
+++ b/libunwindstack/tests/UnwindOfflineTest.cpp
@@ -35,7 +35,6 @@
#include <unwindstack/MachineX86.h>
#include <unwindstack/MachineX86_64.h>
#include <unwindstack/Maps.h>
-#include <unwindstack/Memory.h>
#include <unwindstack/RegsArm.h>
#include <unwindstack/RegsArm64.h>
#include <unwindstack/RegsX86.h>
@@ -43,6 +42,7 @@
#include <unwindstack/Unwinder.h>
#include "ElfTestUtils.h"
+#include "MemoryOffline.h"
#include "TestUtils.h"
namespace unwindstack {
@@ -62,7 +62,7 @@
free(cwd_);
}
- void Init(const char* file_dir, ArchEnum arch) {
+ void Init(const char* file_dir, ArchEnum arch, bool add_stack = true) {
dir_ = TestGetFileDirectory() + "offline/" + file_dir;
std::string data;
@@ -71,23 +71,25 @@
maps_.reset(new BufferMaps(data.c_str()));
ASSERT_TRUE(maps_->Parse());
- std::string stack_name(dir_ + "stack.data");
- struct stat st;
- if (stat(stack_name.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
- std::unique_ptr<MemoryOffline> stack_memory(new MemoryOffline);
- ASSERT_TRUE(stack_memory->Init((dir_ + "stack.data").c_str(), 0));
- process_memory_.reset(stack_memory.release());
- } else {
- std::unique_ptr<MemoryOfflineParts> stack_memory(new MemoryOfflineParts);
- for (size_t i = 0;; i++) {
- stack_name = dir_ + "stack" + std::to_string(i) + ".data";
- if (stat(stack_name.c_str(), &st) == -1 || !S_ISREG(st.st_mode)) {
- ASSERT_TRUE(i != 0) << "No stack data files found.";
- break;
+ if (add_stack) {
+ std::string stack_name(dir_ + "stack.data");
+ struct stat st;
+ if (stat(stack_name.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
+ std::unique_ptr<MemoryOffline> stack_memory(new MemoryOffline);
+ ASSERT_TRUE(stack_memory->Init((dir_ + "stack.data").c_str(), 0));
+ process_memory_.reset(stack_memory.release());
+ } else {
+ std::unique_ptr<MemoryOfflineParts> stack_memory(new MemoryOfflineParts);
+ for (size_t i = 0;; i++) {
+ stack_name = dir_ + "stack" + std::to_string(i) + ".data";
+ if (stat(stack_name.c_str(), &st) == -1 || !S_ISREG(st.st_mode)) {
+ ASSERT_TRUE(i != 0) << "No stack data files found.";
+ break;
+ }
+ AddMemory(stack_name, stack_memory.get());
}
- AddMemory(stack_name, stack_memory.get());
+ process_memory_.reset(stack_memory.release());
}
- process_memory_.reset(stack_memory.release());
}
switch (arch) {
@@ -1442,4 +1444,17 @@
EXPECT_EQ(0x7be4f07d20ULL, unwinder.frames()[12].sp);
}
+TEST_F(UnwindOfflineTest, invalid_elf_offset_arm) {
+ ASSERT_NO_FATAL_FAILURE(Init("invalid_elf_offset_arm/", ARCH_ARM, false));
+
+ Unwinder unwinder(128, maps_.get(), regs_.get(), process_memory_);
+ unwinder.Unwind();
+
+ std::string frame_info(DumpFrames(unwinder));
+ ASSERT_EQ(1U, unwinder.NumFrames()) << "Unwind:\n" << frame_info;
+ EXPECT_EQ(" #00 pc 00aa7508 invalid.apk (offset 0x12e4000)\n", frame_info);
+ EXPECT_EQ(0xc898f508, unwinder.frames()[0].pc);
+ EXPECT_EQ(0xc2044218, unwinder.frames()[0].sp);
+}
+
} // namespace unwindstack
diff --git a/libunwindstack/tests/UnwindTest.cpp b/libunwindstack/tests/UnwindTest.cpp
index 4e38015..f76a101 100644
--- a/libunwindstack/tests/UnwindTest.cpp
+++ b/libunwindstack/tests/UnwindTest.cpp
@@ -35,11 +35,11 @@
#include <android-base/threads.h>
#include <unwindstack/Maps.h>
-#include <unwindstack/Memory.h>
#include <unwindstack/Regs.h>
#include <unwindstack/RegsGetLocal.h>
#include <unwindstack/Unwinder.h>
+#include "MemoryRemote.h"
#include "TestUtils.h"
namespace unwindstack {
diff --git a/libunwindstack/tests/files/offline/invalid_elf_offset_arm/maps.txt b/libunwindstack/tests/files/offline/invalid_elf_offset_arm/maps.txt
new file mode 100644
index 0000000..022404c
--- /dev/null
+++ b/libunwindstack/tests/files/offline/invalid_elf_offset_arm/maps.txt
@@ -0,0 +1 @@
+c7ee8000-c8c52fff r-xp 12e4000 00:00 0 invalid.apk
diff --git a/libunwindstack/tests/files/offline/invalid_elf_offset_arm/regs.txt b/libunwindstack/tests/files/offline/invalid_elf_offset_arm/regs.txt
new file mode 100644
index 0000000..b7f10ef
--- /dev/null
+++ b/libunwindstack/tests/files/offline/invalid_elf_offset_arm/regs.txt
@@ -0,0 +1,16 @@
+r0: c0434c00
+r1: 2a4c9fbc
+r2: 00000000
+r3: c83ef1f9
+r4: 00000004
+r5: c2044904
+r6: 00000000
+r7: c20443b8
+r8: 000b33ff
+r9: c20444b0
+r10: cac90740
+r11: 00000000
+ip: ed891ca4
+sp: c2044218
+lr: ed807265
+pc: c898f508
diff --git a/libunwindstack/tools/unwind_info.cpp b/libunwindstack/tools/unwind_info.cpp
index 92e5c0a..7a6d8ba 100644
--- a/libunwindstack/tools/unwind_info.cpp
+++ b/libunwindstack/tools/unwind_info.cpp
@@ -31,6 +31,7 @@
#include <unwindstack/Elf.h>
#include <unwindstack/ElfInterface.h>
#include <unwindstack/Log.h>
+#include <unwindstack/Memory.h>
#include "ArmExidx.h"
#include "ElfInterfaceArm.h"
@@ -105,14 +106,7 @@
// Send all log messages to stdout.
log_to_stdout(true);
- MemoryFileAtOffset* memory = new MemoryFileAtOffset;
- if (!memory->Init(file, offset)) {
- // Initializatation failed.
- printf("Failed to init\n");
- return 1;
- }
-
- Elf elf(memory);
+ Elf elf(Memory::CreateFileMemory(file, offset).release());
if (!elf.Init() || !elf.valid()) {
printf("%s is not a valid elf file.\n", file);
return 1;
diff --git a/libunwindstack/tools/unwind_reg_info.cpp b/libunwindstack/tools/unwind_reg_info.cpp
index b77a86b..d0562d9 100644
--- a/libunwindstack/tools/unwind_reg_info.cpp
+++ b/libunwindstack/tools/unwind_reg_info.cpp
@@ -33,6 +33,7 @@
#include <unwindstack/Elf.h>
#include <unwindstack/ElfInterface.h>
#include <unwindstack/Log.h>
+#include <unwindstack/Memory.h>
#include "ArmExidx.h"
#include "DwarfOp.h"
@@ -165,14 +166,7 @@
}
int GetInfo(const char* file, uint64_t pc) {
- MemoryFileAtOffset* memory = new MemoryFileAtOffset;
- if (!memory->Init(file, 0)) {
- // Initializatation failed.
- printf("Failed to init\n");
- return 1;
- }
-
- Elf elf(memory);
+ Elf elf(Memory::CreateFileMemory(file, pc).release());
if (!elf.Init() || !elf.valid()) {
printf("%s is not a valid elf file.\n", file);
return 1;
@@ -205,7 +199,7 @@
DwarfSection* section = interface->eh_frame();
if (section != nullptr) {
printf("\neh_frame:\n");
- PrintRegInformation(section, memory, pc, elf.class_type());
+ PrintRegInformation(section, elf.memory(), pc, elf.class_type());
} else {
printf("\nno eh_frame information\n");
}
@@ -213,7 +207,7 @@
section = interface->debug_frame();
if (section != nullptr) {
printf("\ndebug_frame:\n");
- PrintRegInformation(section, memory, pc, elf.class_type());
+ PrintRegInformation(section, elf.memory(), pc, elf.class_type());
printf("\n");
} else {
printf("\nno debug_frame information\n");
diff --git a/libunwindstack/tools/unwind_symbols.cpp b/libunwindstack/tools/unwind_symbols.cpp
index b0a4dd0..8df2284 100644
--- a/libunwindstack/tools/unwind_symbols.cpp
+++ b/libunwindstack/tools/unwind_symbols.cpp
@@ -59,13 +59,7 @@
// Send all log messages to stdout.
unwindstack::log_to_stdout(true);
- unwindstack::MemoryFileAtOffset* memory = new unwindstack::MemoryFileAtOffset;
- if (!memory->Init(argv[1], 0)) {
- printf("Failed to init\n");
- return 1;
- }
-
- unwindstack::Elf elf(memory);
+ unwindstack::Elf elf(unwindstack::Memory::CreateFileMemory(argv[1], 0).release());
if (!elf.Init() || !elf.valid()) {
printf("%s is not a valid elf file.\n", argv[1]);
return 1;
diff --git a/libziparchive/include/ziparchive/zip_archive.h b/libziparchive/include/ziparchive/zip_archive.h
index a56a4a2..463851c 100644
--- a/libziparchive/include/ziparchive/zip_archive.h
+++ b/libziparchive/include/ziparchive/zip_archive.h
@@ -190,7 +190,8 @@
* archive and lower negative values on failure.
*/
int32_t Next(void* cookie, ZipEntry* data, std::string* name);
-// TODO: remove this when everyone's moved over to std::string.
+int32_t Next(void* cookie, ZipEntry* data, std::string_view* name);
+// TODO: remove this when everyone's moved over to std::string/std::string_view.
int32_t Next(void* cookie, ZipEntry* data, ZipString* name);
/*
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index f4b6c74..e966295 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -748,10 +748,19 @@
}
int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
+ std::string_view sv;
+ int32_t result = Next(cookie, data, &sv);
+ if (result == 0 && name) {
+ *name = std::string(sv);
+ }
+ return result;
+}
+
+int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
ZipString zs;
int32_t result = Next(cookie, data, &zs);
- if (result == 0) {
- *name = std::string(reinterpret_cast<const char*>(zs.name), zs.name_length);
+ if (result == 0 && name) {
+ *name = std::string_view(reinterpret_cast<const char*>(zs.name), zs.name_length);
}
return result;
}
diff --git a/libziparchive/zip_archive_test.cc b/libziparchive/zip_archive_test.cc
index b6ca9ec..8781ab7 100644
--- a/libziparchive/zip_archive_test.cc
+++ b/libziparchive/zip_archive_test.cc
@@ -107,6 +107,26 @@
close(fd);
}
+TEST(ziparchive, Iteration_std_string_view) {
+ ZipArchiveHandle handle;
+ ASSERT_EQ(0, OpenArchiveWrapper(kValidZip, &handle));
+
+ void* iteration_cookie;
+ ASSERT_EQ(0, StartIteration(handle, &iteration_cookie));
+
+ ZipEntry data;
+ std::vector<std::string_view> names;
+ std::string_view name;
+ while (Next(iteration_cookie, &data, &name) == 0) names.push_back(name);
+
+ // Assert that the names are as expected.
+ std::vector<std::string_view> expected_names{"a.txt", "b.txt", "b/", "b/c.txt", "b/d.txt"};
+ std::sort(names.begin(), names.end());
+ ASSERT_EQ(expected_names, names);
+
+ CloseArchive(handle);
+}
+
static void AssertIterationOrder(const std::string_view prefix, const std::string_view suffix,
const std::vector<std::string>& expected_names_sorted) {
ZipArchiveHandle handle;
diff --git a/mkbootimg/Android.bp b/mkbootimg/Android.bp
deleted file mode 100644
index c3cf746..0000000
--- a/mkbootimg/Android.bp
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2012 The Android Open Source Project
-
-cc_library_headers {
- name: "libmkbootimg_abi_headers",
- vendor_available: true,
- export_include_dirs: ["include"],
-}
-
-cc_library_headers {
- name: "bootimg_headers",
- vendor_available: true,
- recovery_available: true,
- export_include_dirs: ["include/bootimg"],
- host_supported: true,
- target: {
- windows: {
- enabled: true,
- },
- },
-}
-
-cc_library {
- name: "libmkbootimg_abi_check",
- vendor_available: true,
- vndk: {
- enabled: true,
- },
- srcs: [
- "mkbootimg_dummy.cpp",
- ],
- header_libs: ["libmkbootimg_abi_headers"],
- export_header_lib_headers: ["libmkbootimg_abi_headers"],
-}
-
-python_defaults {
- name: "mkbootimg_defaults",
-
- version: {
- py2: {
- enabled: true,
- embedded_launcher: true,
- },
- py3: {
- enabled: false,
- embedded_launcher: false,
- },
- },
-}
-
-python_binary_host {
- name: "mkbootimg",
- defaults: ["mkbootimg_defaults"],
- srcs: [
- "mkbootimg.py",
- ],
-}
-
-python_binary_host {
- name: "unpack_bootimg",
- defaults: ["mkbootimg_defaults"],
- srcs: [
- "unpack_bootimg.py",
- ],
-}
diff --git a/mkbootimg/OWNERS b/mkbootimg/OWNERS
deleted file mode 100644
index 3a00860..0000000
--- a/mkbootimg/OWNERS
+++ /dev/null
@@ -1,2 +0,0 @@
-hridya@google.com
-tbao@google.com
diff --git a/mkbootimg/include/abi_check/mkbootimg_abi_check.h b/mkbootimg/include/abi_check/mkbootimg_abi_check.h
deleted file mode 100644
index d478aba..0000000
--- a/mkbootimg/include/abi_check/mkbootimg_abi_check.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#include <bootimg/bootimg.h>
-
-// This header has been created for the following reaons:
-// 1) In order for a change in a user defined type to be classified as API /
-// ABI breaking, it needs to be referenced by an 'exported interface'
-// (in this case the function mkbootimg_dummy).
-// 2) Since 'mkbootimg_dummy' needs to be exported, we need to have it
-// exposed through a public header.
-// 3) It is desirable not to pollute bootimg.h with interfaces which are not
-// 'used' in reality by on device binaries. Furthermore, bootimg.h might
-// be exported by a library in the future, so we must avoid polluting it.
-void mkbootimg_dummy(boot_img_hdr*);
diff --git a/mkbootimg/include/bootimg/bootimg.h b/mkbootimg/include/bootimg/bootimg.h
deleted file mode 100644
index 9ee7869..0000000
--- a/mkbootimg/include/bootimg/bootimg.h
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <stdint.h>
-
-#define BOOT_MAGIC "ANDROID!"
-#define BOOT_MAGIC_SIZE 8
-#define BOOT_NAME_SIZE 16
-#define BOOT_ARGS_SIZE 512
-#define BOOT_EXTRA_ARGS_SIZE 1024
-
-// The bootloader expects the structure of boot_img_hdr with header
-// version 0 to be as follows:
-struct boot_img_hdr_v0 {
- // Must be BOOT_MAGIC.
- uint8_t magic[BOOT_MAGIC_SIZE];
-
- uint32_t kernel_size; /* size in bytes */
- uint32_t kernel_addr; /* physical load addr */
-
- uint32_t ramdisk_size; /* size in bytes */
- uint32_t ramdisk_addr; /* physical load addr */
-
- uint32_t second_size; /* size in bytes */
- uint32_t second_addr; /* physical load addr */
-
- uint32_t tags_addr; /* physical addr for kernel tags */
- uint32_t page_size; /* flash page size we assume */
-
- // Version of the boot image header.
- uint32_t header_version;
-
- // Operating system version and security patch level.
- // For version "A.B.C" and patch level "Y-M-D":
- // (7 bits for each of A, B, C; 7 bits for (Y-2000), 4 bits for M)
- // os_version = A[31:25] B[24:18] C[17:11] (Y-2000)[10:4] M[3:0]
- uint32_t os_version;
-
-#if __cplusplus
- void SetOsVersion(unsigned major, unsigned minor, unsigned patch) {
- os_version &= ((1 << 11) - 1);
- os_version |= (((major & 0x7f) << 25) | ((minor & 0x7f) << 18) | ((patch & 0x7f) << 11));
- }
-
- void SetOsPatchLevel(unsigned year, unsigned month) {
- os_version &= ~((1 << 11) - 1);
- os_version |= (((year - 2000) & 0x7f) << 4) | ((month & 0xf) << 0);
- }
-#endif
-
- uint8_t name[BOOT_NAME_SIZE]; /* asciiz product name */
-
- uint8_t cmdline[BOOT_ARGS_SIZE];
-
- uint32_t id[8]; /* timestamp / checksum / sha1 / etc */
-
- // Supplemental command line data; kept here to maintain
- // binary compatibility with older versions of mkbootimg.
- uint8_t extra_cmdline[BOOT_EXTRA_ARGS_SIZE];
-} __attribute__((packed));
-
-/*
- * It is expected that callers would explicitly specify which version of the
- * boot image header they need to use.
- */
-typedef struct boot_img_hdr_v0 boot_img_hdr;
-
-/* When a boot header is of version 0, the structure of boot image is as
- * follows:
- *
- * +-----------------+
- * | boot header | 1 page
- * +-----------------+
- * | kernel | n pages
- * +-----------------+
- * | ramdisk | m pages
- * +-----------------+
- * | second stage | o pages
- * +-----------------+
- *
- * n = (kernel_size + page_size - 1) / page_size
- * m = (ramdisk_size + page_size - 1) / page_size
- * o = (second_size + page_size - 1) / page_size
- *
- * 0. all entities are page_size aligned in flash
- * 1. kernel and ramdisk are required (size != 0)
- * 2. second is optional (second_size == 0 -> no second)
- * 3. load each element (kernel, ramdisk, second) at
- * the specified physical address (kernel_addr, etc)
- * 4. prepare tags at tag_addr. kernel_args[] is
- * appended to the kernel commandline in the tags.
- * 5. r0 = 0, r1 = MACHINE_TYPE, r2 = tags_addr
- * 6. if second_size != 0: jump to second_addr
- * else: jump to kernel_addr
- */
-
-struct boot_img_hdr_v1 : public boot_img_hdr_v0 {
- uint32_t recovery_dtbo_size; /* size in bytes for recovery DTBO/ACPIO image */
- uint64_t recovery_dtbo_offset; /* offset to recovery dtbo/acpio in boot image */
- uint32_t header_size;
-} __attribute__((packed));
-
-/* When the boot image header has a version of 2, the structure of the boot
- * image is as follows:
- *
- * +---------------------+
- * | boot header | 1 page
- * +---------------------+
- * | kernel | n pages
- * +---------------------+
- * | ramdisk | m pages
- * +---------------------+
- * | second stage | o pages
- * +---------------------+
- * | recovery dtbo/acpio | p pages
- * +---------------------+
- * | dtb | q pages
- * +---------------------+
-
- * n = (kernel_size + page_size - 1) / page_size
- * m = (ramdisk_size + page_size - 1) / page_size
- * o = (second_size + page_size - 1) / page_size
- * p = (recovery_dtbo_size + page_size - 1) / page_size
- * q = (dtb_size + page_size - 1) / page_size
- *
- * 0. all entities are page_size aligned in flash
- * 1. kernel, ramdisk and DTB are required (size != 0)
- * 2. recovery_dtbo/recovery_acpio is required for recovery.img in non-A/B
- * devices(recovery_dtbo_size != 0)
- * 3. second is optional (second_size == 0 -> no second)
- * 4. load each element (kernel, ramdisk, second, dtb) at
- * the specified physical address (kernel_addr, etc)
- * 5. If booting to recovery mode in a non-A/B device, extract recovery
- * dtbo/acpio and apply the correct set of overlays on the base device tree
- * depending on the hardware/product revision.
- * 6. prepare tags at tag_addr. kernel_args[] is
- * appended to the kernel commandline in the tags.
- * 7. r0 = 0, r1 = MACHINE_TYPE, r2 = tags_addr
- * 8. if second_size != 0: jump to second_addr
- * else: jump to kernel_addr
- */
-struct boot_img_hdr_v2 : public boot_img_hdr_v1 {
- uint32_t dtb_size; /* size in bytes for DTB image */
- uint64_t dtb_addr; /* physical load address for DTB image */
-} __attribute__((packed));
diff --git a/mkbootimg/mkbootimg.py b/mkbootimg/mkbootimg.py
deleted file mode 100644
index 934f28e..0000000
--- a/mkbootimg/mkbootimg.py
+++ /dev/null
@@ -1,236 +0,0 @@
-#!/usr/bin/env python
-# Copyright 2015, The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-from __future__ import print_function
-from sys import argv, exit, stderr
-from argparse import ArgumentParser, FileType, Action
-from os import fstat
-from struct import pack
-from hashlib import sha1
-import sys
-import re
-
-def filesize(f):
- if f is None:
- return 0
- try:
- return fstat(f.fileno()).st_size
- except OSError:
- return 0
-
-
-def update_sha(sha, f):
- if f:
- sha.update(f.read())
- f.seek(0)
- sha.update(pack('I', filesize(f)))
- else:
- sha.update(pack('I', 0))
-
-
-def pad_file(f, padding):
- pad = (padding - (f.tell() & (padding - 1))) & (padding - 1)
- f.write(pack(str(pad) + 'x'))
-
-
-def get_number_of_pages(image_size, page_size):
- """calculates the number of pages required for the image"""
- return (image_size + page_size - 1) / page_size
-
-
-def get_recovery_dtbo_offset(args):
- """calculates the offset of recovery_dtbo image in the boot image"""
- num_header_pages = 1 # header occupies a page
- num_kernel_pages = get_number_of_pages(filesize(args.kernel), args.pagesize)
- num_ramdisk_pages = get_number_of_pages(filesize(args.ramdisk), args.pagesize)
- num_second_pages = get_number_of_pages(filesize(args.second), args.pagesize)
- dtbo_offset = args.pagesize * (num_header_pages + num_kernel_pages +
- num_ramdisk_pages + num_second_pages)
- return dtbo_offset
-
-
-def write_header(args):
- BOOT_IMAGE_HEADER_V1_SIZE = 1648
- BOOT_IMAGE_HEADER_V2_SIZE = 1660
- BOOT_MAGIC = 'ANDROID!'.encode()
-
- if (args.header_version > 2):
- raise ValueError('Boot header version %d not supported' % args.header_version)
-
- args.output.write(pack('8s', BOOT_MAGIC))
- args.output.write(pack('10I',
- filesize(args.kernel), # size in bytes
- args.base + args.kernel_offset, # physical load addr
- filesize(args.ramdisk), # size in bytes
- args.base + args.ramdisk_offset, # physical load addr
- filesize(args.second), # size in bytes
- args.base + args.second_offset, # physical load addr
- args.base + args.tags_offset, # physical addr for kernel tags
- args.pagesize, # flash page size we assume
- args.header_version, # version of bootimage header
- (args.os_version << 11) | args.os_patch_level)) # os version and patch level
- args.output.write(pack('16s', args.board.encode())) # asciiz product name
- args.output.write(pack('512s', args.cmdline[:512].encode()))
-
- sha = sha1()
- update_sha(sha, args.kernel)
- update_sha(sha, args.ramdisk)
- update_sha(sha, args.second)
-
- if args.header_version > 0:
- update_sha(sha, args.recovery_dtbo)
- if args.header_version > 1:
- update_sha(sha, args.dtb)
-
- img_id = pack('32s', sha.digest())
-
- args.output.write(img_id)
- args.output.write(pack('1024s', args.cmdline[512:].encode()))
-
- if args.header_version > 0:
- args.output.write(pack('I', filesize(args.recovery_dtbo))) # size in bytes
- if args.recovery_dtbo:
- args.output.write(pack('Q', get_recovery_dtbo_offset(args))) # recovery dtbo offset
- else:
- args.output.write(pack('Q', 0)) # Will be set to 0 for devices without a recovery dtbo
-
- # Populate boot image header size for header versions 1 and 2.
- if args.header_version == 1:
- args.output.write(pack('I', BOOT_IMAGE_HEADER_V1_SIZE))
- elif args.header_version == 2:
- args.output.write(pack('I', BOOT_IMAGE_HEADER_V2_SIZE))
-
- if args.header_version > 1:
-
- if filesize(args.dtb) == 0:
- raise ValueError("DTB image must not be empty.")
-
- args.output.write(pack('I', filesize(args.dtb))) # size in bytes
- args.output.write(pack('Q', args.base + args.dtb_offset)) # dtb physical load address
- pad_file(args.output, args.pagesize)
- return img_id
-
-
-class ValidateStrLenAction(Action):
- def __init__(self, option_strings, dest, nargs=None, **kwargs):
- if 'maxlen' not in kwargs:
- raise ValueError('maxlen must be set')
- self.maxlen = int(kwargs['maxlen'])
- del kwargs['maxlen']
- super(ValidateStrLenAction, self).__init__(option_strings, dest, **kwargs)
-
- def __call__(self, parser, namespace, values, option_string=None):
- if len(values) > self.maxlen:
- raise ValueError('String argument too long: max {0:d}, got {1:d}'.
- format(self.maxlen, len(values)))
- setattr(namespace, self.dest, values)
-
-
-def write_padded_file(f_out, f_in, padding):
- if f_in is None:
- return
- f_out.write(f_in.read())
- pad_file(f_out, padding)
-
-
-def parse_int(x):
- return int(x, 0)
-
-def parse_os_version(x):
- match = re.search(r'^(\d{1,3})(?:\.(\d{1,3})(?:\.(\d{1,3}))?)?', x)
- if match:
- a = int(match.group(1))
- b = c = 0
- if match.lastindex >= 2:
- b = int(match.group(2))
- if match.lastindex == 3:
- c = int(match.group(3))
- # 7 bits allocated for each field
- assert a < 128
- assert b < 128
- assert c < 128
- return (a << 14) | (b << 7) | c
- return 0
-
-def parse_os_patch_level(x):
- match = re.search(r'^(\d{4})-(\d{2})-(\d{2})', x)
- if match:
- y = int(match.group(1)) - 2000
- m = int(match.group(2))
- # 7 bits allocated for the year, 4 bits for the month
- assert y >= 0 and y < 128
- assert m > 0 and m <= 12
- return (y << 4) | m
- return 0
-
-def parse_cmdline():
- parser = ArgumentParser()
- parser.add_argument('--kernel', help='path to the kernel', type=FileType('rb'),
- required=True)
- parser.add_argument('--ramdisk', help='path to the ramdisk', type=FileType('rb'))
- parser.add_argument('--second', help='path to the 2nd bootloader', type=FileType('rb'))
- parser.add_argument('--dtb', help='path to dtb', type=FileType('rb'))
- recovery_dtbo_group = parser.add_mutually_exclusive_group()
- recovery_dtbo_group.add_argument('--recovery_dtbo', help='path to the recovery DTBO', type=FileType('rb'))
- recovery_dtbo_group.add_argument('--recovery_acpio', help='path to the recovery ACPIO',
- type=FileType('rb'), metavar='RECOVERY_ACPIO', dest='recovery_dtbo')
- parser.add_argument('--cmdline', help='extra arguments to be passed on the '
- 'kernel command line', default='', action=ValidateStrLenAction, maxlen=1536)
- parser.add_argument('--base', help='base address', type=parse_int, default=0x10000000)
- parser.add_argument('--kernel_offset', help='kernel offset', type=parse_int, default=0x00008000)
- parser.add_argument('--ramdisk_offset', help='ramdisk offset', type=parse_int, default=0x01000000)
- parser.add_argument('--second_offset', help='2nd bootloader offset', type=parse_int,
- default=0x00f00000)
- parser.add_argument('--dtb_offset', help='dtb offset', type=parse_int, default=0x01f00000)
-
- parser.add_argument('--os_version', help='operating system version', type=parse_os_version,
- default=0)
- parser.add_argument('--os_patch_level', help='operating system patch level',
- type=parse_os_patch_level, default=0)
- parser.add_argument('--tags_offset', help='tags offset', type=parse_int, default=0x00000100)
- parser.add_argument('--board', help='board name', default='', action=ValidateStrLenAction,
- maxlen=16)
- parser.add_argument('--pagesize', help='page size', type=parse_int,
- choices=[2**i for i in range(11,15)], default=2048)
- parser.add_argument('--id', help='print the image ID on standard output',
- action='store_true')
- parser.add_argument('--header_version', help='boot image header version', type=parse_int, default=0)
- parser.add_argument('-o', '--output', help='output file name', type=FileType('wb'),
- required=True)
- return parser.parse_args()
-
-
-def write_data(args):
- write_padded_file(args.output, args.kernel, args.pagesize)
- write_padded_file(args.output, args.ramdisk, args.pagesize)
- write_padded_file(args.output, args.second, args.pagesize)
-
- if args.header_version > 0:
- write_padded_file(args.output, args.recovery_dtbo, args.pagesize)
- if args.header_version > 1:
- write_padded_file(args.output, args.dtb, args.pagesize)
-
-def main():
- args = parse_cmdline()
- img_id = write_header(args)
- write_data(args)
- if args.id:
- if isinstance(img_id, str):
- # Python 2's struct.pack returns a string, but py3 returns bytes.
- img_id = [ord(x) for x in img_id]
- print('0x' + ''.join('{:02x}'.format(c) for c in img_id))
-
-if __name__ == '__main__':
- main()
diff --git a/mkbootimg/unpack_bootimg.py b/mkbootimg/unpack_bootimg.py
deleted file mode 100755
index 789bf5e..0000000
--- a/mkbootimg/unpack_bootimg.py
+++ /dev/null
@@ -1,152 +0,0 @@
-#!/usr/bin/env python
-# Copyright 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.
-
-"""unpacks the bootimage.
-
-Extracts the kernel, ramdisk, second bootloader, dtb and recovery dtbo images.
-"""
-
-from __future__ import print_function
-from argparse import ArgumentParser, FileType
-from struct import unpack
-import os
-
-
-def create_out_dir(dir_path):
- """creates a directory 'dir_path' if it does not exist"""
- if not os.path.exists(dir_path):
- os.makedirs(dir_path)
-
-
-def extract_image(offset, size, bootimage, extracted_image_name):
- """extracts an image from the bootimage"""
- bootimage.seek(offset)
- with open(extracted_image_name, 'wb') as file_out:
- file_out.write(bootimage.read(size))
-
-
-def get_number_of_pages(image_size, page_size):
- """calculates the number of pages required for the image"""
- return (image_size + page_size - 1) / page_size
-
-
-def unpack_bootimage(args):
- """extracts kernel, ramdisk, second bootloader and recovery dtbo"""
- boot_magic = unpack('8s', args.boot_img.read(8))
- print('boot_magic: %s' % boot_magic)
- kernel_ramdisk_second_info = unpack('10I', args.boot_img.read(10 * 4))
- print('kernel_size: %s' % kernel_ramdisk_second_info[0])
- print('kernel load address: %#x' % kernel_ramdisk_second_info[1])
- print('ramdisk size: %s' % kernel_ramdisk_second_info[2])
- print('ramdisk load address: %#x' % kernel_ramdisk_second_info[3])
- print('second bootloader size: %s' % kernel_ramdisk_second_info[4])
- print('second bootloader load address: %#x' % kernel_ramdisk_second_info[5])
- print('kernel tags load address: %#x' % kernel_ramdisk_second_info[6])
- print('page size: %s' % kernel_ramdisk_second_info[7])
- print('boot image header version: %s' % kernel_ramdisk_second_info[8])
- print('os version and patch level: %s' % kernel_ramdisk_second_info[9])
-
- product_name = unpack('16s', args.boot_img.read(16))
- print('product name: %s' % product_name)
- cmdline = unpack('512s', args.boot_img.read(512))
- print('command line args: %s' % cmdline)
-
- args.boot_img.read(32) # ignore SHA
-
- extra_cmdline = unpack('1024s', args.boot_img.read(1024))
- print('additional command line args: %s' % extra_cmdline)
-
- kernel_size = kernel_ramdisk_second_info[0]
- ramdisk_size = kernel_ramdisk_second_info[2]
- second_size = kernel_ramdisk_second_info[4]
- page_size = kernel_ramdisk_second_info[7]
- version = kernel_ramdisk_second_info[8]
- if version > 0:
- recovery_dtbo_size = unpack('I', args.boot_img.read(1 * 4))[0]
- print('recovery dtbo size: %s' % recovery_dtbo_size)
- recovery_dtbo_offset = unpack('Q', args.boot_img.read(8))[0]
- print('recovery dtbo offset: %#x' % recovery_dtbo_offset)
- boot_header_size = unpack('I', args.boot_img.read(4))[0]
- print('boot header size: %s' % boot_header_size)
- else:
- recovery_dtbo_size = 0
- if version > 1:
- dtb_size = unpack('I', args.boot_img.read(4))[0]
- print('dtb size: %s' % dtb_size)
- dtb_load_address = unpack('Q', args.boot_img.read(8))[0]
- print('dtb address: %#x' % dtb_load_address)
- else:
- dtb_size = 0
-
-
- # The first page contains the boot header
- num_header_pages = 1
-
- num_kernel_pages = get_number_of_pages(kernel_size, page_size)
- kernel_offset = page_size * num_header_pages # header occupies a page
- image_info_list = [(kernel_offset, kernel_size, 'kernel')]
-
- num_ramdisk_pages = get_number_of_pages(ramdisk_size, page_size)
- ramdisk_offset = page_size * (num_header_pages + num_kernel_pages
- ) # header + kernel
- image_info_list.append((ramdisk_offset, ramdisk_size, 'ramdisk'))
-
- if second_size > 0:
- second_offset = page_size * (
- num_header_pages + num_kernel_pages + num_ramdisk_pages
- ) # header + kernel + ramdisk
- image_info_list.append((second_offset, second_size, 'second'))
-
- if recovery_dtbo_size > 0:
- image_info_list.append((recovery_dtbo_offset, recovery_dtbo_size,
- 'recovery_dtbo'))
- if dtb_size > 0:
- num_second_pages = get_number_of_pages(second_size, page_size)
- num_recovery_dtbo_pages = get_number_of_pages(recovery_dtbo_size, page_size)
- dtb_offset = page_size * (
- num_header_pages + num_kernel_pages + num_ramdisk_pages + num_second_pages +
- num_recovery_dtbo_pages
- )
-
- image_info_list.append((dtb_offset, dtb_size, 'dtb'))
-
- for image_info in image_info_list:
- extract_image(image_info[0], image_info[1], args.boot_img,
- os.path.join(args.out, image_info[2]))
-
-
-def parse_cmdline():
- """parse command line arguments"""
- parser = ArgumentParser(
- description='Unpacks boot.img/recovery.img, extracts the kernel,'
- 'ramdisk, second bootloader, recovery dtbo and dtb')
- parser.add_argument(
- '--boot_img',
- help='path to boot image',
- type=FileType('rb'),
- required=True)
- parser.add_argument('--out', help='path to out binaries', default='out')
- return parser.parse_args()
-
-
-def main():
- """parse arguments and unpack boot image"""
- args = parse_cmdline()
- create_out_dir(args.out)
- unpack_bootimage(args)
-
-
-if __name__ == '__main__':
- main()
diff --git a/rootdir/etc/ld.config.txt b/rootdir/etc/ld.config.txt
index 3b3f61e..b1616d3 100644
--- a/rootdir/etc/ld.config.txt
+++ b/rootdir/etc/ld.config.txt
@@ -187,6 +187,7 @@
namespace.media.links = default
namespace.media.link.default.shared_libs = %LLNDK_LIBRARIES%
namespace.media.link.default.shared_libs += libbinder_ndk.so
+namespace.media.link.default.shared_libs += libcgrouprc.so
namespace.media.link.default.shared_libs += libmediametrics.so
namespace.media.link.default.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
@@ -616,6 +617,7 @@
# TODO(b/122876336): Remove libpac.so once it's migrated to Webview
namespace.default.link.runtime.shared_libs += libpac.so
+namespace.default.link.runtime.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
namespace.default.link.resolv.shared_libs = libnetd_resolv.so
diff --git a/rootdir/etc/ld.config.vndk_lite.txt b/rootdir/etc/ld.config.vndk_lite.txt
index 0880be0..9212408 100644
--- a/rootdir/etc/ld.config.vndk_lite.txt
+++ b/rootdir/etc/ld.config.vndk_lite.txt
@@ -428,6 +428,7 @@
# TODO(b/122876336): Remove libpac.so once it's migrated to Webview
namespace.default.link.runtime.shared_libs += libpac.so
+namespace.default.link.runtime.shared_libs += %SANITIZER_RUNTIME_LIBRARIES%
namespace.default.link.resolv.shared_libs = libnetd_resolv.so