Revert "Fail on flush if no sensors are found" am: fb64fca3da am: 3c1b3d923b am: c218507eab am: ed3c5313be
Change-Id: I5a5474e08b5c2ba0abcbeae897bee6168b5f51d9
diff --git a/cmds/dumpsys/dumpsys.cpp b/cmds/dumpsys/dumpsys.cpp
index a427c8d..1327cfd 100644
--- a/cmds/dumpsys/dumpsys.cpp
+++ b/cmds/dumpsys/dumpsys.cpp
@@ -230,7 +230,7 @@
}
const size_t N = services.size();
- if (N > 1) {
+ if (N > 1 || showListOnly) {
// first print a list of the current services
std::cout << "Currently running services:" << std::endl;
diff --git a/cmds/dumpsys/tests/dumpsys_test.cpp b/cmds/dumpsys/tests/dumpsys_test.cpp
index b9395ba..3467898 100644
--- a/cmds/dumpsys/tests/dumpsys_test.cpp
+++ b/cmds/dumpsys/tests/dumpsys_test.cpp
@@ -206,10 +206,7 @@
}
void AssertRunningServices(const std::vector<std::string>& services) {
- std::string expected;
- if (services.size() > 1) {
- expected.append("Currently running services:\n");
- }
+ std::string expected = "Currently running services:\n";
for (const std::string& service : services) {
expected.append(" ").append(service).append("\n");
}
@@ -263,6 +260,21 @@
AssertRunningServices({"Locksmith", "Valet"});
}
+TEST_F(DumpsysTest, ListServicesOneRegistered) {
+ ExpectListServices({"Locksmith"});
+ ExpectCheckService("Locksmith");
+
+ CallMain({"-l"});
+
+ AssertRunningServices({"Locksmith"});
+}
+
+TEST_F(DumpsysTest, ListServicesEmpty) {
+ CallMain({"-l"});
+
+ AssertRunningServices({});
+}
+
// Tests 'dumpsys -l' when a service is not running
TEST_F(DumpsysTest, ListRunningServices) {
ExpectListServices({"Locksmith", "Valet"});
diff --git a/cmds/installd/CrateManager.cpp b/cmds/installd/CrateManager.cpp
index 6e079eb..b17cba1 100644
--- a/cmds/installd/CrateManager.cpp
+++ b/cmds/installd/CrateManager.cpp
@@ -86,7 +86,7 @@
}
void CrateManager::traverseAllPackagesForUser(
- const std::unique_ptr<std::string>& uuid, userid_t userId,
+ const std::optional<std::string>& uuid, userid_t userId,
std::function<void(FTSENT*)>& onHandlingPackage) {
const char* uuid_ = uuid ? uuid->c_str() : nullptr;
@@ -96,21 +96,21 @@
void CrateManager::createCrate(
CratedFolder cratedFolder,
- std::function<void(CratedFolder, std::unique_ptr<CrateMetadata>&)>& onCreateCrate) {
+ std::function<void(CratedFolder, CrateMetadata&&)>& onCreateCrate) {
const char* path = cratedFolder->fts_path;
if (path == nullptr || *path == '\0') {
return;
}
- std::unique_ptr<CrateMetadata> crateMetadata = std::make_unique<CrateMetadata>();
- crateMetadata->uid = cratedFolder->fts_statp->st_uid;
- crateMetadata->packageName = mPackageName;
- crateMetadata->id = getValidatedCratedPath(path);
+ CrateMetadata crateMetadata;
+ crateMetadata.uid = cratedFolder->fts_statp->st_uid;
+ crateMetadata.packageName = mPackageName;
+ crateMetadata.id = getValidatedCratedPath(path);
- onCreateCrate(cratedFolder, crateMetadata);
+ onCreateCrate(cratedFolder, std::move(crateMetadata));
}
-void CrateManager::traverseAllCrates(std::function<void(CratedFolder, std::unique_ptr<CrateMetadata>&)>& onCreateCrate) {
+void CrateManager::traverseAllCrates(std::function<void(CratedFolder, CrateMetadata&&)>& onCreateCrate) {
std::function<void(FTSENT*)> onVisitCrateDir = [&](FTSENT* cratedFolder) -> void {
createCrate(cratedFolder, onCreateCrate);
};
@@ -118,11 +118,11 @@
}
#if CRATE_DEBUG
-void CrateManager::dump(std::unique_ptr<CrateMetadata>& CrateMetadata) {
+void CrateManager::dump(const CrateMetadata& CrateMetadata) {
LOG(DEBUG) << "CrateMetadata = {"
- << "uid : \"" << CrateMetadata->uid
- << "\", packageName : \"" << CrateMetadata->packageName
- << "\", id : \"" << CrateMetadata->id
+ << "uid : \"" << CrateMetadata.uid
+ << "\", packageName : \"" << CrateMetadata.packageName
+ << "\", id : \"" << CrateMetadata.id
<< "\"}";
}
#endif
diff --git a/cmds/installd/CrateManager.h b/cmds/installd/CrateManager.h
index 4332d4c..1f30b5d 100644
--- a/cmds/installd/CrateManager.h
+++ b/cmds/installd/CrateManager.h
@@ -25,7 +25,7 @@
#include <sys/stat.h>
#include <sys/types.h>
-#include <memory>
+#include <optional>
#include <string>
#include <vector>
@@ -55,18 +55,18 @@
CrateManager(const char* uuid, userid_t userId, const std::string& packageName);
~CrateManager();
- void traverseAllCrates(std::function<void(CratedFolder, std::unique_ptr<CrateMetadata>&)>& onCreateCrate);
+ void traverseAllCrates(std::function<void(CratedFolder, CrateMetadata&&)>& onCreateCrate);
static void traverseChildDir(const std::string& targetDir,
std::function<void(FTSENT*)>& onVisitChildDir);
static void traverseAllPackagesForUser(
- const std::unique_ptr<std::string>& uuid,
+ const std::optional<std::string>& uuid,
userid_t userId,
std::function<void(FTSENT*)>& onHandlingPackage);
#if CRATE_DEBUG
- static void dump(std::unique_ptr<CrateMetadata>& CrateMetadata);
+ static void dump(const CrateMetadata& CrateMetadata);
#endif
private:
std::string mRoot;
@@ -75,7 +75,7 @@
void createCrate(
CratedFolder cratedFolder,
- std::function<void(CratedFolder, std::unique_ptr<CrateMetadata>&)>& onCreateCrate);
+ std::function<void(CratedFolder, CrateMetadata&&)>& onCreateCrate);
};
} // namespace installd
diff --git a/cmds/installd/InstalldNativeService.cpp b/cmds/installd/InstalldNativeService.cpp
index ae44d38..657409b 100644
--- a/cmds/installd/InstalldNativeService.cpp
+++ b/cmds/installd/InstalldNativeService.cpp
@@ -166,7 +166,7 @@
}
}
-binder::Status checkArgumentUuid(const std::unique_ptr<std::string>& uuid) {
+binder::Status checkArgumentUuid(const std::optional<std::string>& uuid) {
if (!uuid || is_valid_filename(*uuid)) {
return ok();
} else {
@@ -175,7 +175,7 @@
}
}
-binder::Status checkArgumentUuidTestOrNull(const std::unique_ptr<std::string>& uuid) {
+binder::Status checkArgumentUuidTestOrNull(const std::optional<std::string>& uuid) {
if (!uuid || strcmp(uuid->c_str(), kTestUuid) == 0) {
return ok();
} else {
@@ -214,7 +214,7 @@
return ok();
}
-binder::Status checkArgumentPath(const std::unique_ptr<std::string>& path) {
+binder::Status checkArgumentPath(const std::optional<std::string>& path) {
if (path) {
return checkArgumentPath(*path);
} else {
@@ -420,7 +420,7 @@
return true;
}
-binder::Status InstalldNativeService::createAppData(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::createAppData(const std::optional<std::string>& uuid,
const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
@@ -501,7 +501,7 @@
return ok();
}
-binder::Status InstalldNativeService::migrateAppData(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::migrateAppData(const std::optional<std::string>& uuid,
const std::string& packageName, int32_t userId, int32_t flags) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
@@ -562,7 +562,7 @@
return res;
}
-binder::Status InstalldNativeService::clearAppData(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::clearAppData(const std::optional<std::string>& uuid,
const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
@@ -682,7 +682,7 @@
return res;
}
-binder::Status InstalldNativeService::destroyAppData(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::destroyAppData(const std::optional<std::string>& uuid,
const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
@@ -754,7 +754,7 @@
return (gid != -1) ? gid : uid;
}
-binder::Status InstalldNativeService::fixupAppData(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::fixupAppData(const std::optional<std::string>& uuid,
int32_t flags) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
@@ -874,7 +874,7 @@
}
binder::Status InstalldNativeService::snapshotAppData(
- const std::unique_ptr<std::string>& volumeUuid,
+ const std::optional<std::string>& volumeUuid,
const std::string& packageName, int32_t user, int32_t snapshotId,
int32_t storageFlags, int64_t* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
@@ -1001,7 +1001,7 @@
}
binder::Status InstalldNativeService::restoreAppDataSnapshot(
- const std::unique_ptr<std::string>& volumeUuid, const std::string& packageName,
+ const std::optional<std::string>& volumeUuid, const std::string& packageName,
const int32_t appId, const std::string& seInfo, const int32_t user,
const int32_t snapshotId, int32_t storageFlags) {
ENFORCE_UID(AID_SYSTEM);
@@ -1071,7 +1071,7 @@
}
binder::Status InstalldNativeService::destroyAppDataSnapshot(
- const std::unique_ptr<std::string> &volumeUuid, const std::string& packageName,
+ const std::optional<std::string> &volumeUuid, const std::string& packageName,
const int32_t user, const int64_t ceSnapshotInode, const int32_t snapshotId,
int32_t storageFlags) {
ENFORCE_UID(AID_SYSTEM);
@@ -1104,7 +1104,7 @@
}
binder::Status InstalldNativeService::destroyCeSnapshotsNotSpecified(
- const std::unique_ptr<std::string> &volumeUuid, const int32_t userId,
+ const std::optional<std::string> &volumeUuid, const int32_t user,
const std::vector<int32_t>& retainSnapshotIds) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID_IS_TEST_OR_NULL(volumeUuid);
@@ -1112,7 +1112,7 @@
const char* volume_uuid = volumeUuid ? volumeUuid->c_str() : nullptr;
- auto base_path = create_data_misc_ce_rollback_base_path(volume_uuid, userId);
+ auto base_path = create_data_misc_ce_rollback_base_path(volume_uuid, user);
std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(base_path.c_str()), closedir);
if (!dir) {
@@ -1131,7 +1131,7 @@
std::find(retainSnapshotIds.begin(), retainSnapshotIds.end(),
snapshot_id) == retainSnapshotIds.end()) {
auto rollback_path = create_data_misc_ce_rollback_path(
- volume_uuid, userId, snapshot_id);
+ volume_uuid, user, snapshot_id);
int res = delete_dir_contents_and_dir(rollback_path, true /* ignore_if_missing */);
if (res != 0) {
return error(res, "Failed clearing snapshot " + rollback_path);
@@ -1141,8 +1141,8 @@
return ok();
}
-binder::Status InstalldNativeService::moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
- const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
+binder::Status InstalldNativeService::moveCompleteApp(const std::optional<std::string>& fromUuid,
+ const std::optional<std::string>& toUuid, const std::string& packageName,
int32_t appId, const std::string& seInfo,
int32_t targetSdkVersion, const std::string& fromCodePath) {
ENFORCE_UID(AID_SYSTEM);
@@ -1249,7 +1249,7 @@
return res;
}
-binder::Status InstalldNativeService::createUserData(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::createUserData(const std::optional<std::string>& uuid,
int32_t userId, int32_t userSerial ATTRIBUTE_UNUSED, int32_t flags) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
@@ -1267,7 +1267,7 @@
return ok();
}
-binder::Status InstalldNativeService::destroyUserData(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::destroyUserData(const std::optional<std::string>& uuid,
int32_t userId, int32_t flags) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
@@ -1304,13 +1304,13 @@
return res;
}
-binder::Status InstalldNativeService::freeCache(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::freeCache(const std::optional<std::string>& uuid,
int64_t targetFreeBytes, int64_t cacheReservedBytes, int32_t flags) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
std::lock_guard<std::recursive_mutex> lock(mLock);
- auto uuidString = uuid ? *uuid : "";
+ auto uuidString = uuid.value_or("");
const char* uuid_ = uuid ? uuid->c_str() : nullptr;
auto data_path = create_data_path(uuid_);
auto noop = (flags & FLAG_FREE_CACHE_NOOP);
@@ -1708,7 +1708,7 @@
fts_close(fts);
}
-binder::Status InstalldNativeService::getAppSize(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::getAppSize(const std::optional<std::string>& uuid,
const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
int32_t appId, const std::vector<int64_t>& ceDataInodes,
const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return) {
@@ -1748,7 +1748,7 @@
memset(&stats, 0, sizeof(stats));
memset(&extStats, 0, sizeof(extStats));
- auto uuidString = uuid ? *uuid : "";
+ auto uuidString = uuid.value_or("");
const char* uuid_ = uuid ? uuid->c_str() : nullptr;
if (!IsQuotaSupported(uuidString)) {
@@ -1935,7 +1935,7 @@
return sizes;
}
-binder::Status InstalldNativeService::getUserSize(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::getUserSize(const std::optional<std::string>& uuid,
int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
std::vector<int64_t>* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
@@ -1955,7 +1955,7 @@
memset(&stats, 0, sizeof(stats));
memset(&extStats, 0, sizeof(extStats));
- auto uuidString = uuid ? *uuid : "";
+ auto uuidString = uuid.value_or("");
const char* uuid_ = uuid ? uuid->c_str() : nullptr;
if (!IsQuotaSupported(uuidString)) {
@@ -2067,7 +2067,7 @@
return ok();
}
-binder::Status InstalldNativeService::getExternalSize(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::getExternalSize(const std::optional<std::string>& uuid,
int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
std::vector<int64_t>* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
@@ -2082,7 +2082,7 @@
LOG(INFO) << "Measuring external " << userId;
#endif
- auto uuidString = uuid ? *uuid : "";
+ auto uuidString = uuid.value_or("");
const char* uuid_ = uuid ? uuid->c_str() : nullptr;
int64_t totalSize = 0;
@@ -2184,9 +2184,9 @@
}
binder::Status InstalldNativeService::getAppCrates(
- const std::unique_ptr<std::string>& uuid,
+ const std::optional<std::string>& uuid,
const std::vector<std::string>& packageNames, int32_t userId,
- std::unique_ptr<std::vector<std::unique_ptr<CrateMetadata>>>* _aidl_return) {
+ std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
for (const auto& packageName : packageNames) {
@@ -2195,15 +2195,15 @@
#ifdef ENABLE_STORAGE_CRATES
std::lock_guard<std::recursive_mutex> lock(mLock);
- auto retVector = std::make_unique<std::vector<std::unique_ptr<CrateMetadata>>>();
+ auto retVector = std::vector<std::optional<CrateMetadata>>();
const char* uuid_ = uuid ? uuid->c_str() : nullptr;
- std::function<void(CratedFolder, std::unique_ptr<CrateMetadata> &)> onCreateCrate =
- [&](CratedFolder cratedFolder, std::unique_ptr<CrateMetadata> &crateMetadata) -> void {
+ std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
+ [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
if (cratedFolder == nullptr) {
return;
}
- retVector->push_back(std::move(crateMetadata));
+ retVector.push_back(std::move(crateMetadata));
};
for (const auto& packageName : packageNames) {
@@ -2215,15 +2215,15 @@
}
#if CRATE_DEBUG
- LOG(WARNING) << "retVector->size() =" << retVector->size();
- for (auto iter = retVector->begin(); iter != retVector->end(); ++iter) {
- CrateManager::dump(*iter);
+ LOG(WARNING) << "retVector.size() =" << retVector.size();
+ for (auto& item : retVector) {
+ CrateManager::dump(item);
}
#endif
*_aidl_return = std::move(retVector);
#else // ENABLE_STORAGE_CRATES
- *_aidl_return = nullptr;
+ _aidl_return->reset();
/* prevent compile warning fail */
if (userId < 0) {
@@ -2234,18 +2234,18 @@
}
binder::Status InstalldNativeService::getUserCrates(
- const std::unique_ptr<std::string>& uuid, int32_t userId,
- std::unique_ptr<std::vector<std::unique_ptr<CrateMetadata>>>* _aidl_return) {
+ const std::optional<std::string>& uuid, int32_t userId,
+ std::optional<std::vector<std::optional<CrateMetadata>>>* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
#ifdef ENABLE_STORAGE_CRATES
std::lock_guard<std::recursive_mutex> lock(mLock);
const char* uuid_ = uuid ? uuid->c_str() : nullptr;
- auto retVector = std::make_unique<std::vector<std::unique_ptr<CrateMetadata>>>();
+ auto retVector = std::vector<std::optional<CrateMetadata>>();
- std::function<void(CratedFolder, std::unique_ptr<CrateMetadata> &)> onCreateCrate =
- [&](CratedFolder cratedFolder, std::unique_ptr<CrateMetadata> &crateMetadata) -> void {
+ std::function<void(CratedFolder, CrateMetadata&&)> onCreateCrate =
+ [&](CratedFolder cratedFolder, CrateMetadata&& crateMetadata) -> void {
if (cratedFolder == nullptr) {
return;
}
@@ -2259,15 +2259,15 @@
CrateManager::traverseAllPackagesForUser(uuid, userId, onHandingPackage);
#if CRATE_DEBUG
- LOG(DEBUG) << "retVector->size() =" << retVector->size();
- for (auto iter = retVector->begin(); iter != retVector->end(); ++iter) {
- CrateManager::dump(*iter);
+ LOG(DEBUG) << "retVector.size() =" << retVector.size();
+ for (auto& item : retVector) {
+ CrateManager::dump(item);
}
#endif
*_aidl_return = std::move(retVector);
#else // ENABLE_STORAGE_CRATES
- *_aidl_return = nullptr;
+ _aidl_return->reset();
/* prevent compile warning fail */
if (userId < 0) {
@@ -2277,7 +2277,7 @@
return ok();
}
-binder::Status InstalldNativeService::setAppQuota(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::setAppQuota(const std::optional<std::string>& uuid,
int32_t userId, int32_t appId, int64_t cacheQuota) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
@@ -2348,19 +2348,19 @@
return ok();
}
-static const char* getCStr(const std::unique_ptr<std::string>& data,
+static const char* getCStr(const std::optional<std::string>& data,
const char* default_value = nullptr) {
- return data == nullptr ? default_value : data->c_str();
+ return data ? data->c_str() : default_value;
}
binder::Status InstalldNativeService::dexopt(const std::string& apkPath, int32_t uid,
- const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
- int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
- const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
- const std::unique_ptr<std::string>& classLoaderContext,
- const std::unique_ptr<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
- const std::unique_ptr<std::string>& profileName,
- const std::unique_ptr<std::string>& dexMetadataPath,
- const std::unique_ptr<std::string>& compilationReason) {
+ const std::optional<std::string>& packageName, const std::string& instructionSet,
+ int32_t dexoptNeeded, const std::optional<std::string>& outputPath, int32_t dexFlags,
+ const std::string& compilerFilter, const std::optional<std::string>& uuid,
+ const std::optional<std::string>& classLoaderContext,
+ const std::optional<std::string>& seInfo, bool downgrade, int32_t targetSdkVersion,
+ const std::optional<std::string>& profileName,
+ const std::optional<std::string>& dexMetadataPath,
+ const std::optional<std::string>& compilationReason) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
CHECK_ARGUMENT_PATH(apkPath);
@@ -2406,7 +2406,7 @@
}
binder::Status InstalldNativeService::linkNativeLibraryDirectory(
- const std::unique_ptr<std::string>& uuid, const std::string& packageName,
+ const std::optional<std::string>& uuid, const std::string& packageName,
const std::string& nativeLibPath32, int32_t userId) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
@@ -2497,7 +2497,7 @@
return res;
}
-binder::Status InstalldNativeService::restoreconAppData(const std::unique_ptr<std::string>& uuid,
+binder::Status InstalldNativeService::restoreconAppData(const std::optional<std::string>& uuid,
const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
const std::string& seInfo) {
ENFORCE_UID(AID_SYSTEM);
@@ -2615,7 +2615,7 @@
}
binder::Status InstalldNativeService::deleteOdex(const std::string& apkPath,
- const std::string& instructionSet, const std::unique_ptr<std::string>& outputPath) {
+ const std::string& instructionSet, const std::optional<std::string>& outputPath) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_PATH(apkPath);
CHECK_ARGUMENT_PATH(outputPath);
@@ -2767,7 +2767,7 @@
binder::Status InstalldNativeService::reconcileSecondaryDexFile(
const std::string& dexPath, const std::string& packageName, int32_t uid,
- const std::vector<std::string>& isas, const std::unique_ptr<std::string>& volumeUuid,
+ const std::vector<std::string>& isas, const std::optional<std::string>& volumeUuid,
int32_t storage_flag, bool* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(volumeUuid);
@@ -2782,7 +2782,7 @@
binder::Status InstalldNativeService::hashSecondaryDexFile(
const std::string& dexPath, const std::string& packageName, int32_t uid,
- const std::unique_ptr<std::string>& volumeUuid, int32_t storageFlag,
+ const std::optional<std::string>& volumeUuid, int32_t storageFlag,
std::vector<uint8_t>* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(volumeUuid);
@@ -2841,7 +2841,7 @@
// Mount volume's CE and DE storage to mirror
binder::Status InstalldNativeService::tryMountDataMirror(
- const std::unique_ptr<std::string>& uuid) {
+ const std::optional<std::string>& uuid) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
if (!sAppDataIsolationEnabled) {
@@ -2905,7 +2905,7 @@
// Unmount volume's CE and DE storage from mirror
binder::Status InstalldNativeService::onPrivateVolumeRemoved(
- const std::unique_ptr<std::string>& uuid) {
+ const std::optional<std::string>& uuid) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_UUID(uuid);
if (!sAppDataIsolationEnabled) {
@@ -2949,7 +2949,7 @@
}
std::string InstalldNativeService::findDataMediaPath(
- const std::unique_ptr<std::string>& uuid, userid_t userid) {
+ const std::optional<std::string>& uuid, userid_t userid) {
std::lock_guard<std::recursive_mutex> lock(mMountsLock);
const char* uuid_ = uuid ? uuid->c_str() : nullptr;
auto path = StringPrintf("%s/media", create_data_path(uuid_).c_str());
@@ -2962,15 +2962,14 @@
}
binder::Status InstalldNativeService::isQuotaSupported(
- const std::unique_ptr<std::string>& uuid, bool* _aidl_return) {
- auto uuidString = uuid ? *uuid : "";
- *_aidl_return = IsQuotaSupported(uuidString);
+ const std::optional<std::string>& uuid, bool* _aidl_return) {
+ *_aidl_return = IsQuotaSupported(uuid.value_or(""));
return ok();
}
binder::Status InstalldNativeService::prepareAppProfile(const std::string& packageName,
int32_t userId, int32_t appId, const std::string& profileName, const std::string& codePath,
- const std::unique_ptr<std::string>& dexMetadata, bool* _aidl_return) {
+ const std::optional<std::string>& dexMetadata, bool* _aidl_return) {
ENFORCE_UID(AID_SYSTEM);
CHECK_ARGUMENT_PACKAGE_NAME(packageName);
CHECK_ARGUMENT_PATH(codePath);
diff --git a/cmds/installd/InstalldNativeService.h b/cmds/installd/InstalldNativeService.h
index eb151ca..08be4d9 100644
--- a/cmds/installd/InstalldNativeService.h
+++ b/cmds/installd/InstalldNativeService.h
@@ -40,76 +40,76 @@
static char const* getServiceName() { return "installd"; }
virtual status_t dump(int fd, const Vector<String16> &args) override;
- binder::Status createUserData(const std::unique_ptr<std::string>& uuid, int32_t userId,
+ binder::Status createUserData(const std::optional<std::string>& uuid, int32_t userId,
int32_t userSerial, int32_t flags);
- binder::Status destroyUserData(const std::unique_ptr<std::string>& uuid, int32_t userId,
+ binder::Status destroyUserData(const std::optional<std::string>& uuid, int32_t userId,
int32_t flags);
- binder::Status createAppData(const std::unique_ptr<std::string>& uuid,
+ binder::Status createAppData(const std::optional<std::string>& uuid,
const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
const std::string& seInfo, int32_t targetSdkVersion, int64_t* _aidl_return);
- binder::Status restoreconAppData(const std::unique_ptr<std::string>& uuid,
+ binder::Status restoreconAppData(const std::optional<std::string>& uuid,
const std::string& packageName, int32_t userId, int32_t flags, int32_t appId,
const std::string& seInfo);
- binder::Status migrateAppData(const std::unique_ptr<std::string>& uuid,
+ binder::Status migrateAppData(const std::optional<std::string>& uuid,
const std::string& packageName, int32_t userId, int32_t flags);
- binder::Status clearAppData(const std::unique_ptr<std::string>& uuid,
+ binder::Status clearAppData(const std::optional<std::string>& uuid,
const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode);
- binder::Status destroyAppData(const std::unique_ptr<std::string>& uuid,
+ binder::Status destroyAppData(const std::optional<std::string>& uuid,
const std::string& packageName, int32_t userId, int32_t flags, int64_t ceDataInode);
- binder::Status fixupAppData(const std::unique_ptr<std::string>& uuid, int32_t flags);
+ binder::Status fixupAppData(const std::optional<std::string>& uuid, int32_t flags);
- binder::Status snapshotAppData(const std::unique_ptr<std::string>& volumeUuid,
+ binder::Status snapshotAppData(const std::optional<std::string>& volumeUuid,
const std::string& packageName, const int32_t user, const int32_t snapshotId,
int32_t storageFlags, int64_t* _aidl_return);
- binder::Status restoreAppDataSnapshot(const std::unique_ptr<std::string>& volumeUuid,
+ binder::Status restoreAppDataSnapshot(const std::optional<std::string>& volumeUuid,
const std::string& packageName, const int32_t appId, const std::string& seInfo,
const int32_t user, const int32_t snapshotId, int32_t storageFlags);
- binder::Status destroyAppDataSnapshot(const std::unique_ptr<std::string> &volumeUuid,
+ binder::Status destroyAppDataSnapshot(const std::optional<std::string> &volumeUuid,
const std::string& packageName, const int32_t user, const int64_t ceSnapshotInode,
const int32_t snapshotId, int32_t storageFlags);
- binder::Status destroyCeSnapshotsNotSpecified(const std::unique_ptr<std::string> &volumeUuid,
- const int32_t userId, const std::vector<int32_t>& retainSnapshotIds);
+ binder::Status destroyCeSnapshotsNotSpecified(const std::optional<std::string> &volumeUuid,
+ const int32_t user, const std::vector<int32_t>& retainSnapshotIds);
- binder::Status getAppSize(const std::unique_ptr<std::string>& uuid,
+ binder::Status getAppSize(const std::optional<std::string>& uuid,
const std::vector<std::string>& packageNames, int32_t userId, int32_t flags,
int32_t appId, const std::vector<int64_t>& ceDataInodes,
const std::vector<std::string>& codePaths, std::vector<int64_t>* _aidl_return);
- binder::Status getUserSize(const std::unique_ptr<std::string>& uuid,
+ binder::Status getUserSize(const std::optional<std::string>& uuid,
int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
std::vector<int64_t>* _aidl_return);
- binder::Status getExternalSize(const std::unique_ptr<std::string>& uuid,
+ binder::Status getExternalSize(const std::optional<std::string>& uuid,
int32_t userId, int32_t flags, const std::vector<int32_t>& appIds,
std::vector<int64_t>* _aidl_return);
- binder::Status getAppCrates(const std::unique_ptr<std::string>& uuid,
+ binder::Status getAppCrates(const std::optional<std::string>& uuid,
const std::vector<std::string>& packageNames,
int32_t userId,
- std::unique_ptr<std::vector<std::unique_ptr<android::os::storage::CrateMetadata>>>*
+ std::optional<std::vector<std::optional<android::os::storage::CrateMetadata>>>*
_aidl_return);
binder::Status getUserCrates(
- const std::unique_ptr<std::string>& uuid, int32_t userId,
- std::unique_ptr<std::vector<std::unique_ptr<android::os::storage::CrateMetadata>>>*
+ const std::optional<std::string>& uuid, int32_t userId,
+ std::optional<std::vector<std::optional<android::os::storage::CrateMetadata>>>*
_aidl_return);
- binder::Status setAppQuota(const std::unique_ptr<std::string>& uuid,
+ binder::Status setAppQuota(const std::optional<std::string>& uuid,
int32_t userId, int32_t appId, int64_t cacheQuota);
- binder::Status moveCompleteApp(const std::unique_ptr<std::string>& fromUuid,
- const std::unique_ptr<std::string>& toUuid, const std::string& packageName,
+ binder::Status moveCompleteApp(const std::optional<std::string>& fromUuid,
+ const std::optional<std::string>& toUuid, const std::string& packageName,
int32_t appId, const std::string& seInfo,
int32_t targetSdkVersion, const std::string& fromCodePath);
binder::Status dexopt(const std::string& apkPath, int32_t uid,
- const std::unique_ptr<std::string>& packageName, const std::string& instructionSet,
- int32_t dexoptNeeded, const std::unique_ptr<std::string>& outputPath, int32_t dexFlags,
- const std::string& compilerFilter, const std::unique_ptr<std::string>& uuid,
- const std::unique_ptr<std::string>& classLoaderContext,
- const std::unique_ptr<std::string>& seInfo, bool downgrade,
- int32_t targetSdkVersion, const std::unique_ptr<std::string>& profileName,
- const std::unique_ptr<std::string>& dexMetadataPath,
- const std::unique_ptr<std::string>& compilationReason);
+ const std::optional<std::string>& packageName, const std::string& instructionSet,
+ int32_t dexoptNeeded, const std::optional<std::string>& outputPath, int32_t dexFlags,
+ const std::string& compilerFilter, const std::optional<std::string>& uuid,
+ const std::optional<std::string>& classLoaderContext,
+ const std::optional<std::string>& seInfo, bool downgrade,
+ int32_t targetSdkVersion, const std::optional<std::string>& profileName,
+ const std::optional<std::string>& dexMetadataPath,
+ const std::optional<std::string>& compilationReason);
binder::Status compileLayouts(const std::string& apkPath, const std::string& packageName,
const std::string& outDexFile, int uid, bool* _aidl_return);
@@ -132,9 +132,9 @@
const std::string& profileName);
binder::Status rmPackageDir(const std::string& packageDir);
- binder::Status freeCache(const std::unique_ptr<std::string>& uuid, int64_t targetFreeBytes,
+ binder::Status freeCache(const std::optional<std::string>& uuid, int64_t targetFreeBytes,
int64_t cacheReservedBytes, int32_t flags);
- binder::Status linkNativeLibraryDirectory(const std::unique_ptr<std::string>& uuid,
+ binder::Status linkNativeLibraryDirectory(const std::optional<std::string>& uuid,
const std::string& packageName, const std::string& nativeLibPath32, int32_t userId);
binder::Status createOatDir(const std::string& oatDir, const std::string& instructionSet);
binder::Status linkFile(const std::string& relativePath, const std::string& fromBase,
@@ -142,27 +142,27 @@
binder::Status moveAb(const std::string& apkPath, const std::string& instructionSet,
const std::string& outputPath);
binder::Status deleteOdex(const std::string& apkPath, const std::string& instructionSet,
- const std::unique_ptr<std::string>& outputPath);
+ const std::optional<std::string>& outputPath);
binder::Status installApkVerity(const std::string& filePath,
android::base::unique_fd verityInput, int32_t contentSize);
binder::Status assertFsverityRootHashMatches(const std::string& filePath,
const std::vector<uint8_t>& expectedHash);
binder::Status reconcileSecondaryDexFile(const std::string& dexPath,
const std::string& packageName, int32_t uid, const std::vector<std::string>& isa,
- const std::unique_ptr<std::string>& volumeUuid, int32_t storage_flag, bool* _aidl_return);
+ const std::optional<std::string>& volumeUuid, int32_t storage_flag, bool* _aidl_return);
binder::Status hashSecondaryDexFile(const std::string& dexPath,
- const std::string& packageName, int32_t uid, const std::unique_ptr<std::string>& volumeUuid,
+ const std::string& packageName, int32_t uid, const std::optional<std::string>& volumeUuid,
int32_t storageFlag, std::vector<uint8_t>* _aidl_return);
binder::Status invalidateMounts();
- binder::Status isQuotaSupported(const std::unique_ptr<std::string>& volumeUuid,
+ binder::Status isQuotaSupported(const std::optional<std::string>& volumeUuid,
bool* _aidl_return);
- binder::Status tryMountDataMirror(const std::unique_ptr<std::string>& volumeUuid);
- binder::Status onPrivateVolumeRemoved(const std::unique_ptr<std::string>& volumeUuid);
+ binder::Status tryMountDataMirror(const std::optional<std::string>& volumeUuid);
+ binder::Status onPrivateVolumeRemoved(const std::optional<std::string>& volumeUuid);
binder::Status prepareAppProfile(const std::string& packageName,
int32_t userId, int32_t appId, const std::string& profileName,
- const std::string& codePath, const std::unique_ptr<std::string>& dexMetadata,
+ const std::string& codePath, const std::optional<std::string>& dexMetadata,
bool* _aidl_return);
binder::Status migrateLegacyObbData();
@@ -179,7 +179,7 @@
/* Map from UID to cache quota size */
std::unordered_map<uid_t, int64_t> mCacheQuotas;
- std::string findDataMediaPath(const std::unique_ptr<std::string>& uuid, userid_t userid);
+ std::string findDataMediaPath(const std::optional<std::string>& uuid, userid_t userid);
};
} // namespace installd
diff --git a/cmds/installd/binder/android/os/IInstalld.aidl b/cmds/installd/binder/android/os/IInstalld.aidl
index 5e5af73..e188807 100644
--- a/cmds/installd/binder/android/os/IInstalld.aidl
+++ b/cmds/installd/binder/android/os/IInstalld.aidl
@@ -114,11 +114,10 @@
int userId, int snapshotId, int storageFlags);
void restoreAppDataSnapshot(@nullable @utf8InCpp String uuid, in @utf8InCpp String packageName,
int appId, @utf8InCpp String seInfo, int user, int snapshotId, int storageflags);
- void destroyAppDataSnapshot(@nullable @utf8InCpp String uuid, @utf8InCpp String packageName,
- int userId, long ceSnapshotInode, int snapshotId, int storageFlags);
void destroyCeSnapshotsNotSpecified(@nullable @utf8InCpp String uuid, int userId,
in int[] retainSnapshotIds);
-
+ void destroyAppDataSnapshot(@nullable @utf8InCpp String uuid, @utf8InCpp String packageName,
+ int userId, long ceSnapshotInode, int snapshotId, int storageFlags);
void tryMountDataMirror(@nullable @utf8InCpp String volumeUuid);
void onPrivateVolumeRemoved(@nullable @utf8InCpp String volumeUuid);
diff --git a/cmds/installd/dexopt.cpp b/cmds/installd/dexopt.cpp
index 5ee6a9f..1c4c980 100644
--- a/cmds/installd/dexopt.cpp
+++ b/cmds/installd/dexopt.cpp
@@ -2281,7 +2281,7 @@
// out_secondary_dex_exists will be set to false.
bool reconcile_secondary_dex_file(const std::string& dex_path,
const std::string& pkgname, int uid, const std::vector<std::string>& isas,
- const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
+ const std::optional<std::string>& volume_uuid, int storage_flag,
/*out*/bool* out_secondary_dex_exists) {
*out_secondary_dex_exists = false; // start by assuming the file does not exist.
if (isas.size() == 0) {
@@ -2302,7 +2302,7 @@
/* child -- drop privileges before continuing */
drop_capabilities(uid);
- const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
+ const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
if (!validate_secondary_dex_path(pkgname, dex_path, volume_uuid_cstr,
uid, storage_flag)) {
LOG(ERROR) << "Could not validate secondary dex path " << dex_path;
@@ -2403,11 +2403,11 @@
// the app.
// For any other errors (e.g. if any of the parameters are invalid) returns false.
bool hash_secondary_dex_file(const std::string& dex_path, const std::string& pkgname, int uid,
- const std::unique_ptr<std::string>& volume_uuid, int storage_flag,
+ const std::optional<std::string>& volume_uuid, int storage_flag,
std::vector<uint8_t>* out_secondary_dex_hash) {
out_secondary_dex_hash->clear();
- const char* volume_uuid_cstr = volume_uuid == nullptr ? nullptr : volume_uuid->c_str();
+ const char* volume_uuid_cstr = volume_uuid ? volume_uuid->c_str() : nullptr;
if (storage_flag != FLAG_STORAGE_CE && storage_flag != FLAG_STORAGE_DE) {
LOG(ERROR) << "hash_secondary_dex_file called with invalid storage_flag: "
@@ -2928,7 +2928,7 @@
appid_t app_id,
const std::string& profile_name,
const std::string& code_path,
- const std::unique_ptr<std::string>& dex_metadata) {
+ const std::optional<std::string>& dex_metadata) {
// Prepare the current profile.
std::string cur_profile = create_current_profile_path(user_id, package_name, profile_name,
/*is_secondary_dex*/ false);
@@ -2939,7 +2939,7 @@
}
// Check if we need to install the profile from the dex metadata.
- if (dex_metadata == nullptr) {
+ if (!dex_metadata) {
return true;
}
diff --git a/cmds/installd/dexopt.h b/cmds/installd/dexopt.h
index ef739ba..92b13c7 100644
--- a/cmds/installd/dexopt.h
+++ b/cmds/installd/dexopt.h
@@ -21,6 +21,8 @@
#include <sys/types.h>
+#include <optional>
+
#include <cutils/multiuser.h>
namespace android {
@@ -98,17 +100,17 @@
appid_t app_id,
const std::string& profile_name,
const std::string& code_path,
- const std::unique_ptr<std::string>& dex_metadata);
+ const std::optional<std::string>& dex_metadata);
bool delete_odex(const char* apk_path, const char* instruction_set, const char* output_path);
bool reconcile_secondary_dex_file(const std::string& dex_path,
const std::string& pkgname, int uid, const std::vector<std::string>& isas,
- const std::unique_ptr<std::string>& volumeUuid, int storage_flag,
+ const std::optional<std::string>& volumeUuid, int storage_flag,
/*out*/bool* out_secondary_dex_exists);
bool hash_secondary_dex_file(const std::string& dex_path,
- const std::string& pkgname, int uid, const std::unique_ptr<std::string>& volume_uuid,
+ const std::string& pkgname, int uid, const std::optional<std::string>& volume_uuid,
int storage_flag, std::vector<uint8_t>* out_secondary_dex_hash);
int dexopt(const char *apk_path, uid_t uid, const char *pkgName, const char *instruction_set,
diff --git a/cmds/installd/tests/installd_cache_test.cpp b/cmds/installd/tests/installd_cache_test.cpp
index 5a5cb53..863cdfe 100644
--- a/cmds/installd/tests/installd_cache_test.cpp
+++ b/cmds/installd/tests/installd_cache_test.cpp
@@ -114,15 +114,14 @@
class CacheTest : public testing::Test {
protected:
InstalldNativeService* service;
- std::unique_ptr<std::string> testUuid;
+ std::optional<std::string> testUuid;
virtual void SetUp() {
setenv("ANDROID_LOG_TAGS", "*:v", 1);
android::base::InitLogging(nullptr);
service = new InstalldNativeService();
- testUuid = std::make_unique<std::string>();
- *testUuid = std::string(kTestUuid);
+ testUuid = kTestUuid;
system("mkdir -p /data/local/tmp/user/0");
}
diff --git a/cmds/installd/tests/installd_dexopt_test.cpp b/cmds/installd/tests/installd_dexopt_test.cpp
index 69fefa1..7d8cf1f 100644
--- a/cmds/installd/tests/installd_dexopt_test.cpp
+++ b/cmds/installd/tests/installd_dexopt_test.cpp
@@ -193,7 +193,7 @@
const uid_t kTestAppGid = multiuser_get_shared_gid(kTestUserId, kTestAppId);
InstalldNativeService* service_;
- std::unique_ptr<std::string> volume_uuid_;
+ std::optional<std::string> volume_uuid_;
std::string package_name_;
std::string apk_path_;
std::string empty_dm_file_;
@@ -221,7 +221,7 @@
ASSERT_TRUE(init_selinux());
service_ = new InstalldNativeService();
- volume_uuid_ = nullptr;
+ volume_uuid_ = std::nullopt;
package_name_ = "com.installd.test.dexopt";
se_info_ = "default";
app_apk_dir_ = android_app_dir + package_name_;
@@ -294,7 +294,7 @@
}
// Create a secondary dex file on CE storage
- const char* volume_uuid_cstr = volume_uuid_ == nullptr ? nullptr : volume_uuid_->c_str();
+ const char* volume_uuid_cstr = volume_uuid_ ? volume_uuid_->c_str() : nullptr;
app_private_dir_ce_ = create_data_user_ce_package_path(
volume_uuid_cstr, kTestUserId, package_name_.c_str());
secondary_dex_ce_ = app_private_dir_ce_ + "/secondary_ce.jar";
@@ -353,36 +353,32 @@
if (class_loader_context == nullptr) {
class_loader_context = "&";
}
- std::unique_ptr<std::string> package_name_ptr(new std::string(package_name_));
int32_t dexopt_needed = 0; // does not matter;
- std::unique_ptr<std::string> out_path = nullptr; // does not matter
+ std::optional<std::string> out_path; // does not matter
int32_t dex_flags = DEXOPT_SECONDARY_DEX | dex_storage_flag;
std::string compiler_filter = "speed-profile";
- std::unique_ptr<std::string> class_loader_context_ptr(
- new std::string(class_loader_context));
- std::unique_ptr<std::string> se_info_ptr(new std::string(se_info_));
bool downgrade = false;
int32_t target_sdk_version = 0; // default
- std::unique_ptr<std::string> profile_name_ptr = nullptr;
- std::unique_ptr<std::string> dm_path_ptr = nullptr;
- std::unique_ptr<std::string> compilation_reason_ptr = nullptr;
+ std::optional<std::string> profile_name;
+ std::optional<std::string> dm_path;
+ std::optional<std::string> compilation_reason;
binder::Status result = service_->dexopt(path,
uid,
- package_name_ptr,
+ package_name_,
kRuntimeIsa,
dexopt_needed,
out_path,
dex_flags,
compiler_filter,
volume_uuid_,
- class_loader_context_ptr,
- se_info_ptr,
+ class_loader_context,
+ se_info_,
downgrade,
target_sdk_version,
- profile_name_ptr,
- dm_path_ptr,
- compilation_reason_ptr);
+ profile_name,
+ dm_path,
+ compilation_reason);
ASSERT_EQ(should_binder_call_succeed, result.isOk()) << result.toString8().c_str();
int expected_access = should_dex_be_compiled ? 0 : -1;
std::string odex = GetSecondaryDexArtifact(path, "odex");
@@ -481,41 +477,35 @@
bool downgrade,
bool should_binder_call_succeed,
/*out */ binder::Status* binder_result) {
- std::unique_ptr<std::string> package_name_ptr(new std::string(package_name_));
- std::unique_ptr<std::string> out_path(
- oat_dir == nullptr ? nullptr : new std::string(oat_dir));
- std::unique_ptr<std::string> class_loader_context_ptr(new std::string("&"));
- std::unique_ptr<std::string> se_info_ptr(new std::string(se_info_));
+ std::optional<std::string> out_path = oat_dir ? std::make_optional<std::string>(oat_dir) : std::nullopt;
+ std::string class_loader_context = "&";
int32_t target_sdk_version = 0; // default
- std::unique_ptr<std::string> profile_name_ptr(new std::string("primary.prof"));
- std::unique_ptr<std::string> dm_path_ptr = nullptr;
- if (dm_path != nullptr) {
- dm_path_ptr.reset(new std::string(dm_path));
- }
- std::unique_ptr<std::string> compilation_reason_ptr(new std::string("test-reason"));
+ std::string profile_name = "primary.prof";
+ std::optional<std::string> dm_path_opt = dm_path ? std::make_optional<std::string>(dm_path) : std::nullopt;
+ std::string compilation_reason = "test-reason";
bool prof_result;
ASSERT_BINDER_SUCCESS(service_->prepareAppProfile(
- package_name_, kTestUserId, kTestAppId, *profile_name_ptr, apk_path_,
- dm_path_ptr, &prof_result));
+ package_name_, kTestUserId, kTestAppId, profile_name, apk_path_,
+ dm_path_opt, &prof_result));
ASSERT_TRUE(prof_result);
binder::Status result = service_->dexopt(apk_path_,
uid,
- package_name_ptr,
+ package_name_,
kRuntimeIsa,
dexopt_needed,
out_path,
dex_flags,
compiler_filter,
volume_uuid_,
- class_loader_context_ptr,
- se_info_ptr,
+ class_loader_context,
+ se_info_,
downgrade,
target_sdk_version,
- profile_name_ptr,
- dm_path_ptr,
- compilation_reason_ptr);
+ profile_name,
+ dm_path_opt,
+ compilation_reason);
ASSERT_EQ(should_binder_call_succeed, result.isOk()) << result.toString8().c_str();
if (!should_binder_call_succeed) {
@@ -953,7 +943,7 @@
bool result;
ASSERT_BINDER_SUCCESS(service_->prepareAppProfile(
package_name, kTestUserId, kTestAppId, profile_name, apk_path_,
- /*dex_metadata*/ nullptr, &result));
+ /*dex_metadata*/ {}, &result));
ASSERT_EQ(expected_result, result);
if (!expected_result) {
diff --git a/cmds/installd/tests/installd_service_test.cpp b/cmds/installd/tests/installd_service_test.cpp
index 0fb62ae..1e7559d 100644
--- a/cmds/installd/tests/installd_service_test.cpp
+++ b/cmds/installd/tests/installd_service_test.cpp
@@ -99,15 +99,14 @@
class ServiceTest : public testing::Test {
protected:
InstalldNativeService* service;
- std::unique_ptr<std::string> testUuid;
+ std::optional<std::string> testUuid;
virtual void SetUp() {
setenv("ANDROID_LOG_TAGS", "*:v", 1);
android::base::InitLogging(nullptr);
service = new InstalldNativeService();
- testUuid = std::make_unique<std::string>();
- *testUuid = std::string(kTestUuid);
+ testUuid = kTestUuid;
system("mkdir -p /data/local/tmp/user/0");
init_globals_from_data_and_root();
@@ -322,7 +321,7 @@
// Request a snapshot of the CE content but not the DE content.
int64_t ce_snapshot_inode;
- ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_unique<std::string>("TEST"),
+ ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_optional<std::string>("TEST"),
"com.foo", 0, 37, FLAG_STORAGE_CE, &ce_snapshot_inode));
struct stat buf;
memset(&buf, 0, sizeof(buf));
@@ -344,7 +343,7 @@
0700, 10000, 20000, false /* follow_symlinks */));
// Request a snapshot of the DE content but not the CE content.
- ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_unique<std::string>("TEST"),
+ ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_optional<std::string>("TEST"),
"com.foo", 0, 37, FLAG_STORAGE_DE, &ce_snapshot_inode));
// Only DE content snapshot was requested.
ASSERT_EQ(ce_snapshot_inode, 0);
@@ -365,7 +364,7 @@
0700, 10000, 20000, false /* follow_symlinks */));
// Request a snapshot of both the CE as well as the DE content.
- ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_unique<std::string>("TEST"),
+ ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_optional<std::string>("TEST"),
"com.foo", 0, 37, FLAG_STORAGE_DE | FLAG_STORAGE_CE, nullptr));
ASSERT_TRUE(android::base::ReadFileToString(
@@ -407,10 +406,10 @@
0700, 10000, 20000, false /* follow_symlinks */));
// Request snapshot for the package com.foo.
- ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_unique<std::string>("TEST"),
+ ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_optional<std::string>("TEST"),
"com.foo", 0, 67, FLAG_STORAGE_DE | FLAG_STORAGE_CE, nullptr));
// Now request snapshot with the same id for the package com.bar
- ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_unique<std::string>("TEST"),
+ ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_optional<std::string>("TEST"),
"com.bar", 0, 67, FLAG_STORAGE_DE | FLAG_STORAGE_CE, nullptr));
// Check that both snapshots have correct data in them.
@@ -439,9 +438,9 @@
ASSERT_EQ(0, delete_dir_contents_and_dir(fake_package_de_path, true));
int64_t ce_snapshot_inode;
- ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_unique<std::string>("TEST"),
+ ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_optional<std::string>("TEST"),
"com.foo", 0, 73, FLAG_STORAGE_CE, &ce_snapshot_inode));
- ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_unique<std::string>("TEST"),
+ ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_optional<std::string>("TEST"),
"com.foo", 0, 73, FLAG_STORAGE_DE, nullptr));
// No CE content snapshot was performed.
ASSERT_EQ(ce_snapshot_inode, 0);
@@ -476,7 +475,7 @@
"TEST_CONTENT_2_DE", fake_package_de_path + "/file2",
0700, 10000, 20000, false /* follow_symlinks */));
- ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_unique<std::string>("TEST"),
+ ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_optional<std::string>("TEST"),
"com.foo", 0, 13, FLAG_STORAGE_DE | FLAG_STORAGE_CE, nullptr));
// Previous snapshot (with data for file1) must be cleared.
@@ -497,7 +496,7 @@
ASSERT_TRUE(mkdirs(rollback_ce_dir, 0700));
ASSERT_TRUE(mkdirs(rollback_de_dir, 0700));
- EXPECT_BINDER_FAIL(service->snapshotAppData(std::make_unique<std::string>("FOO"),
+ EXPECT_BINDER_FAIL(service->snapshotAppData(std::make_optional<std::string>("FOO"),
"com.foo", 0, 17, FLAG_STORAGE_DE, nullptr));
}
@@ -524,7 +523,7 @@
ASSERT_TRUE(android::base::WriteStringToFile(
"TEST_CONTENT_DE", fake_package_de_code_cache_path + "/file1",
0700, 10000, 20000, false /* follow_symlinks */));
- ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_unique<std::string>("TEST"),
+ ASSERT_BINDER_SUCCESS(service->snapshotAppData(std::make_optional<std::string>("TEST"),
"com.foo", 0, 23, FLAG_STORAGE_CE | FLAG_STORAGE_DE, nullptr));
// The snapshot call must clear cache.
struct stat sb;
@@ -558,7 +557,7 @@
"TEST_CONTENT_DE", fake_package_de_path + "/file1",
0700, 10000, 20000, false /* follow_symlinks */));
- ASSERT_BINDER_SUCCESS(service->restoreAppDataSnapshot(std::make_unique<std::string>("TEST"),
+ ASSERT_BINDER_SUCCESS(service->restoreAppDataSnapshot(std::make_optional<std::string>("TEST"),
"com.foo", 10000, "", 0, 239, FLAG_STORAGE_DE | FLAG_STORAGE_CE));
std::string ce_content, de_content;
@@ -584,7 +583,7 @@
int64_t ce_snapshot_inode;
// Request a snapshot of both the CE as well as the DE content.
- ASSERT_TRUE(service->snapshotAppData(std::make_unique<std::string>("TEST"),
+ ASSERT_TRUE(service->snapshotAppData(std::make_optional<std::string>("TEST"),
"com.foo", 0, 57, FLAG_STORAGE_DE | FLAG_STORAGE_CE, &ce_snapshot_inode).isOk());
// Because CE data snapshot was requested, ce_snapshot_inode can't be null.
ASSERT_NE(0, ce_snapshot_inode);
@@ -594,7 +593,7 @@
ASSERT_EQ(0, stat((rollback_de_dir + "/com.foo").c_str(), &sb));
- ASSERT_TRUE(service->destroyAppDataSnapshot(std::make_unique<std::string>("TEST"),
+ ASSERT_TRUE(service->destroyAppDataSnapshot(std::make_optional<std::string>("TEST"),
"com.foo", 0, ce_snapshot_inode, 57, FLAG_STORAGE_DE | FLAG_STORAGE_CE).isOk());
// Check snapshot is deleted.
ASSERT_EQ(-1, stat((rollback_ce_dir + "/com.foo").c_str(), &sb));
@@ -615,7 +614,7 @@
"DE_RESTORE_CONTENT", rollback_de_dir + "/com.foo/file1",
0700, 10000, 20000, false /* follow_symlinks */));
- ASSERT_TRUE(service->destroyAppDataSnapshot(std::make_unique<std::string>("TEST"),
+ ASSERT_TRUE(service->destroyAppDataSnapshot(std::make_optional<std::string>("TEST"),
"com.foo", 0, 0, 1543, FLAG_STORAGE_DE | FLAG_STORAGE_CE).isOk());
// Check snapshot is deleted.
@@ -624,7 +623,7 @@
ASSERT_EQ(-1, stat((rollback_de_dir + "/com.foo").c_str(), &sb));
// Check that deleting already deleted snapshot is no-op.
- ASSERT_TRUE(service->destroyAppDataSnapshot(std::make_unique<std::string>("TEST"),
+ ASSERT_TRUE(service->destroyAppDataSnapshot(std::make_optional<std::string>("TEST"),
"com.foo", 0, 0, 1543, FLAG_STORAGE_DE | FLAG_STORAGE_CE).isOk());
}
@@ -637,7 +636,7 @@
ASSERT_TRUE(mkdirs(rollback_ce_dir, 0700));
ASSERT_TRUE(mkdirs(rollback_de_dir, 0700));
- ASSERT_FALSE(service->destroyAppDataSnapshot(std::make_unique<std::string>("BAR"),
+ ASSERT_FALSE(service->destroyAppDataSnapshot(std::make_optional<std::string>("BAR"),
"com.foo", 0, 0, 43, FLAG_STORAGE_DE).isOk());
}
@@ -669,7 +668,7 @@
0700, 10000, 20000, false /* follow_symlinks */));
ASSERT_TRUE(service->destroyCeSnapshotsNotSpecified(
- std::make_unique<std::string>("TEST"), 0, { 1543, 77 }).isOk());
+ std::make_optional<std::string>("TEST"), 0, { 1543, 77 }).isOk());
// Check only snapshots not specified are deleted.
struct stat sb;
@@ -690,7 +689,7 @@
ASSERT_TRUE(mkdirs(rollback_ce_dir, 0700));
ASSERT_TRUE(mkdirs(rollback_de_dir, 0700));
- EXPECT_BINDER_FAIL(service->restoreAppDataSnapshot(std::make_unique<std::string>("BAR"),
+ EXPECT_BINDER_FAIL(service->restoreAppDataSnapshot(std::make_optional<std::string>("BAR"),
"com.foo", 10000, "", 0, 41, FLAG_STORAGE_DE));
}
diff --git a/include/powermanager/IPowerManager.h b/include/powermanager/IPowerManager.h
index 853f0c9..964e318 100644
--- a/include/powermanager/IPowerManager.h
+++ b/include/powermanager/IPowerManager.h
@@ -46,10 +46,10 @@
IS_POWER_SAVE_MODE = IBinder::FIRST_CALL_TRANSACTION + 12,
GET_POWER_SAVE_STATE = IBinder::FIRST_CALL_TRANSACTION + 13,
SET_POWER_SAVE_MODE_ENABLED = IBinder::FIRST_CALL_TRANSACTION + 14,
- REBOOT = IBinder::FIRST_CALL_TRANSACTION + 17,
- REBOOT_SAFE_MODE = IBinder::FIRST_CALL_TRANSACTION + 18,
- SHUTDOWN = IBinder::FIRST_CALL_TRANSACTION + 19,
- CRASH = IBinder::FIRST_CALL_TRANSACTION + 20,
+ REBOOT = IBinder::FIRST_CALL_TRANSACTION + 21,
+ REBOOT_SAFE_MODE = IBinder::FIRST_CALL_TRANSACTION + 22,
+ SHUTDOWN = IBinder::FIRST_CALL_TRANSACTION + 23,
+ CRASH = IBinder::FIRST_CALL_TRANSACTION + 24,
};
DECLARE_META_INTERFACE(PowerManager)
diff --git a/libs/binder/AppOpsManager.cpp b/libs/binder/AppOpsManager.cpp
index 2174ce2..1c6b491 100644
--- a/libs/binder/AppOpsManager.cpp
+++ b/libs/binder/AppOpsManager.cpp
@@ -91,12 +91,12 @@
}
int32_t AppOpsManager::noteOp(int32_t op, int32_t uid, const String16& callingPackage) {
- return noteOp(op, uid, callingPackage, std::unique_ptr<String16>(),
+ return noteOp(op, uid, callingPackage, {},
String16("Legacy AppOpsManager.noteOp call"));
}
int32_t AppOpsManager::noteOp(int32_t op, int32_t uid, const String16& callingPackage,
- const std::unique_ptr<String16>& attributionTag, const String16& message) {
+ const std::optional<String16>& attributionTag, const String16& message) {
sp<IAppOpsService> service = getService();
int32_t mode = service != nullptr
? service->noteOperation(op, uid, callingPackage, attributionTag,
@@ -108,12 +108,12 @@
int32_t AppOpsManager::startOpNoThrow(int32_t op, int32_t uid, const String16& callingPackage,
bool startIfModeDefault) {
- return startOpNoThrow(op, uid, callingPackage, startIfModeDefault, std::unique_ptr<String16>(),
+ return startOpNoThrow(op, uid, callingPackage, startIfModeDefault, {},
String16("Legacy AppOpsManager.startOpNoThrow call"));
}
int32_t AppOpsManager::startOpNoThrow(int32_t op, int32_t uid, const String16& callingPackage,
- bool startIfModeDefault, const std::unique_ptr<String16>& attributionTag,
+ bool startIfModeDefault, const std::optional<String16>& attributionTag,
const String16& message) {
sp<IAppOpsService> service = getService();
int32_t mode = service != nullptr
@@ -125,11 +125,11 @@
}
void AppOpsManager::finishOp(int32_t op, int32_t uid, const String16& callingPackage) {
- finishOp(op, uid, callingPackage, std::unique_ptr<String16>());
+ finishOp(op, uid, callingPackage, {});
}
void AppOpsManager::finishOp(int32_t op, int32_t uid, const String16& callingPackage,
- const std::unique_ptr<String16>& attributionTag) {
+ const std::optional<String16>& attributionTag) {
sp<IAppOpsService> service = getService();
if (service != nullptr) {
service->finishOperation(getClientId(), op, uid, callingPackage, attributionTag);
diff --git a/libs/binder/IAppOpsService.cpp b/libs/binder/IAppOpsService.cpp
index 0714723..cd78866 100644
--- a/libs/binder/IAppOpsService.cpp
+++ b/libs/binder/IAppOpsService.cpp
@@ -22,6 +22,8 @@
#include <binder/Parcel.h>
#include <utils/String8.h>
+#include <optional>
+
namespace android {
// ----------------------------------------------------------------------
@@ -47,7 +49,7 @@
}
virtual int32_t noteOperation(int32_t code, int32_t uid, const String16& packageName,
- const std::unique_ptr<String16>& attributionTag, bool shouldCollectAsyncNotedOp,
+ const std::optional<String16>& attributionTag, bool shouldCollectAsyncNotedOp,
const String16& message) {
Parcel data, reply;
data.writeInterfaceToken(IAppOpsService::getInterfaceDescriptor());
@@ -64,7 +66,7 @@
}
virtual int32_t startOperation(const sp<IBinder>& token, int32_t code, int32_t uid,
- const String16& packageName, const std::unique_ptr<String16>& attributionTag,
+ const String16& packageName, const std::optional<String16>& attributionTag,
bool startIfModeDefault, bool shouldCollectAsyncNotedOp, const String16& message) {
Parcel data, reply;
data.writeInterfaceToken(IAppOpsService::getInterfaceDescriptor());
@@ -83,7 +85,7 @@
}
virtual void finishOperation(const sp<IBinder>& token, int32_t code, int32_t uid,
- const String16& packageName, const std::unique_ptr<String16>& attributionTag) {
+ const String16& packageName, const std::optional<String16>& attributionTag) {
Parcel data, reply;
data.writeInterfaceToken(IAppOpsService::getInterfaceDescriptor());
data.writeStrongBinder(token);
@@ -182,7 +184,7 @@
int32_t code = data.readInt32();
int32_t uid = data.readInt32();
String16 packageName = data.readString16();
- std::unique_ptr<String16> attributionTag;
+ std::optional<String16> attributionTag;
data.readString16(&attributionTag);
bool shouldCollectAsyncNotedOp = data.readInt32() == 1;
String16 message = data.readString16();
@@ -198,7 +200,7 @@
int32_t code = data.readInt32();
int32_t uid = data.readInt32();
String16 packageName = data.readString16();
- std::unique_ptr<String16> attributionTag;
+ std::optional<String16> attributionTag;
data.readString16(&attributionTag);
bool startIfModeDefault = data.readInt32() == 1;
bool shouldCollectAsyncNotedOp = data.readInt32() == 1;
@@ -215,7 +217,7 @@
int32_t code = data.readInt32();
int32_t uid = data.readInt32();
String16 packageName = data.readString16();
- std::unique_ptr<String16> attributionTag;
+ std::optional<String16> attributionTag;
data.readString16(&attributionTag);
finishOperation(token, code, uid, packageName, attributionTag);
reply->writeNoException();
diff --git a/libs/binder/IMemory.cpp b/libs/binder/IMemory.cpp
index c2bb811..d8b44f9 100644
--- a/libs/binder/IMemory.cpp
+++ b/libs/binder/IMemory.cpp
@@ -82,10 +82,10 @@
explicit BpMemoryHeap(const sp<IBinder>& impl);
virtual ~BpMemoryHeap();
- virtual int getHeapID() const;
- virtual void* getBase() const;
- virtual size_t getSize() const;
- virtual uint32_t getFlags() const;
+ int getHeapID() const override;
+ void* getBase() const override;
+ size_t getSize() const override;
+ uint32_t getFlags() const override;
off_t getOffset() const override;
private:
diff --git a/libs/binder/LazyServiceRegistrar.cpp b/libs/binder/LazyServiceRegistrar.cpp
index 6f49aa1..325e204 100644
--- a/libs/binder/LazyServiceRegistrar.cpp
+++ b/libs/binder/LazyServiceRegistrar.cpp
@@ -45,25 +45,31 @@
Status onClients(const sp<IBinder>& service, bool clients) override;
private:
+ struct Service {
+ sp<IBinder> service;
+ bool allowIsolated;
+ int dumpFlags;
+
+ // whether, based on onClients calls, we know we have a client for this
+ // service or not
+ bool clients = false;
+ };
+
+ /**
+ * Looks up a service guaranteed to be registered (service from onClients).
+ */
+ std::map<std::string, Service>::iterator assertRegisteredService(const sp<IBinder>& service);
+
/**
* Unregisters all services that we can. If we can't unregister all, re-register other
* services.
*/
void tryShutdown();
- /**
- * Counter of the number of services that currently have at least one client.
- */
+ // count of services with clients
size_t mNumConnectedServices;
- struct Service {
- sp<IBinder> service;
- bool allowIsolated;
- int dumpFlags;
- };
- /**
- * Map of registered names and services
- */
+ // map of registered names and services
std::map<std::string, Service> mRegisteredServices;
bool mForcePersist;
@@ -89,12 +95,28 @@
}
// Only add this when a service is added for the first time, as it is not removed
- mRegisteredServices[name] = {service, allowIsolated, dumpFlags};
+ mRegisteredServices[name] = {
+ .service = service,
+ .allowIsolated = allowIsolated,
+ .dumpFlags = dumpFlags
+ };
}
return true;
}
+std::map<std::string, ClientCounterCallback::Service>::iterator ClientCounterCallback::assertRegisteredService(const sp<IBinder>& service) {
+ LOG_ALWAYS_FATAL_IF(service == nullptr, "Got onClients callback for null service");
+ for (auto it = mRegisteredServices.begin(); it != mRegisteredServices.end(); ++it) {
+ auto const& [name, registered] = *it;
+ (void) name;
+ if (registered.service != service) continue;
+ return it;
+ }
+ LOG_ALWAYS_FATAL("Got callback on service which we did not register: %s", String8(service->getInterfaceDescriptor()).c_str());
+ __builtin_unreachable();
+}
+
void ClientCounterCallback::forcePersist(bool persist) {
mForcePersist = persist;
if(!mForcePersist) {
@@ -108,15 +130,25 @@
* invocations could occur on different threads however.
*/
Status ClientCounterCallback::onClients(const sp<IBinder>& service, bool clients) {
- if (clients) {
- mNumConnectedServices++;
- } else {
- mNumConnectedServices--;
+ auto & [name, registered] = *assertRegisteredService(service);
+ if (registered.clients == clients) {
+ LOG_ALWAYS_FATAL("Process already thought %s had clients: %d but servicemanager has "
+ "notified has clients: %d", name.c_str(), registered.clients, clients);
+ }
+ registered.clients = clients;
+
+ // update cache count of clients
+ {
+ size_t numWithClients = 0;
+ for (const auto& [name, registered] : mRegisteredServices) {
+ (void) name;
+ if (registered.clients) numWithClients++;
+ }
+ mNumConnectedServices = numWithClients;
}
ALOGI("Process has %zu (of %zu available) client(s) in use after notification %s has clients: %d",
- mNumConnectedServices, mRegisteredServices.size(),
- String8(service->getInterfaceDescriptor()).string(), clients);
+ mNumConnectedServices, mRegisteredServices.size(), name.c_str(), clients);
tryShutdown();
return Status::ok();
@@ -192,4 +224,4 @@
}
} // namespace hardware
-} // namespace android
\ No newline at end of file
+} // namespace android
diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp
index beab270..5f1f682 100644
--- a/libs/binder/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -751,6 +751,13 @@
return NO_ERROR;
}
+status_t Parcel::writeUtf8AsUtf16(const std::optional<std::string>& str) {
+ if (!str) {
+ return writeInt32(-1);
+ }
+ return writeUtf8AsUtf16(*str);
+}
+
status_t Parcel::writeUtf8AsUtf16(const std::unique_ptr<std::string>& str) {
if (!str) {
return writeInt32(-1);
@@ -775,6 +782,12 @@
return writeByteVectorInternal(val.data(), val.size());
}
+status_t Parcel::writeByteVector(const std::optional<std::vector<int8_t>>& val)
+{
+ if (!val) return writeInt32(-1);
+ return writeByteVectorInternal(val->data(), val->size());
+}
+
status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val)
{
if (!val) return writeInt32(-1);
@@ -785,6 +798,12 @@
return writeByteVectorInternal(reinterpret_cast<const int8_t*>(val.data()), val.size());
}
+status_t Parcel::writeByteVector(const std::optional<std::vector<uint8_t>>& val)
+{
+ if (!val) return writeInt32(-1);
+ return writeByteVectorInternal(reinterpret_cast<const int8_t*>(val->data()), val->size());
+}
+
status_t Parcel::writeByteVector(const std::unique_ptr<std::vector<uint8_t>>& val)
{
if (!val) return writeInt32(-1);
@@ -796,6 +815,11 @@
return writeTypedVector(val, &Parcel::writeInt32);
}
+status_t Parcel::writeInt32Vector(const std::optional<std::vector<int32_t>>& val)
+{
+ return writeNullableTypedVector(val, &Parcel::writeInt32);
+}
+
status_t Parcel::writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val)
{
return writeNullableTypedVector(val, &Parcel::writeInt32);
@@ -806,6 +830,11 @@
return writeTypedVector(val, &Parcel::writeInt64);
}
+status_t Parcel::writeInt64Vector(const std::optional<std::vector<int64_t>>& val)
+{
+ return writeNullableTypedVector(val, &Parcel::writeInt64);
+}
+
status_t Parcel::writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val)
{
return writeNullableTypedVector(val, &Parcel::writeInt64);
@@ -816,6 +845,11 @@
return writeTypedVector(val, &Parcel::writeUint64);
}
+status_t Parcel::writeUint64Vector(const std::optional<std::vector<uint64_t>>& val)
+{
+ return writeNullableTypedVector(val, &Parcel::writeUint64);
+}
+
status_t Parcel::writeUint64Vector(const std::unique_ptr<std::vector<uint64_t>>& val)
{
return writeNullableTypedVector(val, &Parcel::writeUint64);
@@ -826,6 +860,11 @@
return writeTypedVector(val, &Parcel::writeFloat);
}
+status_t Parcel::writeFloatVector(const std::optional<std::vector<float>>& val)
+{
+ return writeNullableTypedVector(val, &Parcel::writeFloat);
+}
+
status_t Parcel::writeFloatVector(const std::unique_ptr<std::vector<float>>& val)
{
return writeNullableTypedVector(val, &Parcel::writeFloat);
@@ -836,6 +875,11 @@
return writeTypedVector(val, &Parcel::writeDouble);
}
+status_t Parcel::writeDoubleVector(const std::optional<std::vector<double>>& val)
+{
+ return writeNullableTypedVector(val, &Parcel::writeDouble);
+}
+
status_t Parcel::writeDoubleVector(const std::unique_ptr<std::vector<double>>& val)
{
return writeNullableTypedVector(val, &Parcel::writeDouble);
@@ -846,6 +890,11 @@
return writeTypedVector(val, &Parcel::writeBool);
}
+status_t Parcel::writeBoolVector(const std::optional<std::vector<bool>>& val)
+{
+ return writeNullableTypedVector(val, &Parcel::writeBool);
+}
+
status_t Parcel::writeBoolVector(const std::unique_ptr<std::vector<bool>>& val)
{
return writeNullableTypedVector(val, &Parcel::writeBool);
@@ -856,6 +905,11 @@
return writeTypedVector(val, &Parcel::writeChar);
}
+status_t Parcel::writeCharVector(const std::optional<std::vector<char16_t>>& val)
+{
+ return writeNullableTypedVector(val, &Parcel::writeChar);
+}
+
status_t Parcel::writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val)
{
return writeNullableTypedVector(val, &Parcel::writeChar);
@@ -867,12 +921,23 @@
}
status_t Parcel::writeString16Vector(
+ const std::optional<std::vector<std::optional<String16>>>& val)
+{
+ return writeNullableTypedVector(val, &Parcel::writeString16);
+}
+
+status_t Parcel::writeString16Vector(
const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val)
{
return writeNullableTypedVector(val, &Parcel::writeString16);
}
status_t Parcel::writeUtf8VectorAsUtf16Vector(
+ const std::optional<std::vector<std::optional<std::string>>>& val) {
+ return writeNullableTypedVector(val, &Parcel::writeUtf8AsUtf16);
+}
+
+status_t Parcel::writeUtf8VectorAsUtf16Vector(
const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) {
return writeNullableTypedVector(val, &Parcel::writeUtf8AsUtf16);
}
@@ -997,6 +1062,15 @@
return err;
}
+status_t Parcel::writeString16(const std::optional<String16>& str)
+{
+ if (!str) {
+ return writeInt32(-1);
+ }
+
+ return writeString16(*str);
+}
+
status_t Parcel::writeString16(const std::unique_ptr<String16>& str)
{
if (!str) {
@@ -1039,11 +1113,20 @@
return writeTypedVector(val, &Parcel::writeStrongBinder);
}
+status_t Parcel::writeStrongBinderVector(const std::optional<std::vector<sp<IBinder>>>& val)
+{
+ return writeNullableTypedVector(val, &Parcel::writeStrongBinder);
+}
+
status_t Parcel::writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val)
{
return writeNullableTypedVector(val, &Parcel::writeStrongBinder);
}
+status_t Parcel::readStrongBinderVector(std::optional<std::vector<sp<IBinder>>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readNullableStrongBinder);
+}
+
status_t Parcel::readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const {
return readNullableTypedVector(val, &Parcel::readNullableStrongBinder);
}
@@ -1142,6 +1225,10 @@
return writeTypedVector(val, &Parcel::writeUniqueFileDescriptor);
}
+status_t Parcel::writeUniqueFileDescriptorVector(const std::optional<std::vector<base::unique_fd>>& val) {
+ return writeNullableTypedVector(val, &Parcel::writeUniqueFileDescriptor);
+}
+
status_t Parcel::writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<base::unique_fd>>& val) {
return writeNullableTypedVector(val, &Parcel::writeUniqueFileDescriptor);
}
@@ -1475,6 +1562,17 @@
return readByteVectorInternal(val, size);
}
+status_t Parcel::readByteVector(std::optional<std::vector<int8_t>>* val) const {
+ size_t size;
+ if (status_t status = reserveOutVector(val, &size); status != OK) return status;
+ if (!*val) {
+ // reserveOutVector does not create the out vector if size is < 0.
+ // This occurs when writing a null byte vector.
+ return OK;
+ }
+ return readByteVectorInternal(&**val, size);
+}
+
status_t Parcel::readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const {
size_t size;
if (status_t status = reserveOutVector(val, &size); status != OK) return status;
@@ -1486,6 +1584,17 @@
return readByteVectorInternal(val->get(), size);
}
+status_t Parcel::readByteVector(std::optional<std::vector<uint8_t>>* val) const {
+ size_t size;
+ if (status_t status = reserveOutVector(val, &size); status != OK) return status;
+ if (!*val) {
+ // reserveOutVector does not create the out vector if size is < 0.
+ // This occurs when writing a null byte vector.
+ return OK;
+ }
+ return readByteVectorInternal(&**val, size);
+}
+
status_t Parcel::readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const {
size_t size;
if (status_t status = reserveOutVector(val, &size); status != OK) return status;
@@ -1497,6 +1606,10 @@
return readByteVectorInternal(val->get(), size);
}
+status_t Parcel::readInt32Vector(std::optional<std::vector<int32_t>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readInt32);
+}
+
status_t Parcel::readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const {
return readNullableTypedVector(val, &Parcel::readInt32);
}
@@ -1505,6 +1618,10 @@
return readTypedVector(val, &Parcel::readInt32);
}
+status_t Parcel::readInt64Vector(std::optional<std::vector<int64_t>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readInt64);
+}
+
status_t Parcel::readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const {
return readNullableTypedVector(val, &Parcel::readInt64);
}
@@ -1513,6 +1630,10 @@
return readTypedVector(val, &Parcel::readInt64);
}
+status_t Parcel::readUint64Vector(std::optional<std::vector<uint64_t>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readUint64);
+}
+
status_t Parcel::readUint64Vector(std::unique_ptr<std::vector<uint64_t>>* val) const {
return readNullableTypedVector(val, &Parcel::readUint64);
}
@@ -1521,6 +1642,10 @@
return readTypedVector(val, &Parcel::readUint64);
}
+status_t Parcel::readFloatVector(std::optional<std::vector<float>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readFloat);
+}
+
status_t Parcel::readFloatVector(std::unique_ptr<std::vector<float>>* val) const {
return readNullableTypedVector(val, &Parcel::readFloat);
}
@@ -1529,6 +1654,10 @@
return readTypedVector(val, &Parcel::readFloat);
}
+status_t Parcel::readDoubleVector(std::optional<std::vector<double>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readDouble);
+}
+
status_t Parcel::readDoubleVector(std::unique_ptr<std::vector<double>>* val) const {
return readNullableTypedVector(val, &Parcel::readDouble);
}
@@ -1537,6 +1666,28 @@
return readTypedVector(val, &Parcel::readDouble);
}
+status_t Parcel::readBoolVector(std::optional<std::vector<bool>>* val) const {
+ const int32_t start = dataPosition();
+ int32_t size;
+ status_t status = readInt32(&size);
+ val->reset();
+
+ if (status != OK || size < 0) {
+ return status;
+ }
+
+ setDataPosition(start);
+ val->emplace();
+
+ status = readBoolVector(&**val);
+
+ if (status != OK) {
+ val->reset();
+ }
+
+ return status;
+}
+
status_t Parcel::readBoolVector(std::unique_ptr<std::vector<bool>>* val) const {
const int32_t start = dataPosition();
int32_t size;
@@ -1589,6 +1740,10 @@
return OK;
}
+status_t Parcel::readCharVector(std::optional<std::vector<char16_t>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readChar);
+}
+
status_t Parcel::readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const {
return readNullableTypedVector(val, &Parcel::readChar);
}
@@ -1598,6 +1753,11 @@
}
status_t Parcel::readString16Vector(
+ std::optional<std::vector<std::optional<String16>>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readString16);
+}
+
+status_t Parcel::readString16Vector(
std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const {
return readNullableTypedVector(val, &Parcel::readString16);
}
@@ -1607,6 +1767,11 @@
}
status_t Parcel::readUtf8VectorFromUtf16Vector(
+ std::optional<std::vector<std::optional<std::string>>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readUtf8FromUtf16);
+}
+
+status_t Parcel::readUtf8VectorFromUtf16Vector(
std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const {
return readNullableTypedVector(val, &Parcel::readUtf8FromUtf16);
}
@@ -1798,6 +1963,21 @@
return NO_ERROR;
}
+status_t Parcel::readUtf8FromUtf16(std::optional<std::string>* str) const {
+ const int32_t start = dataPosition();
+ int32_t size;
+ status_t status = readInt32(&size);
+ str->reset();
+
+ if (status != OK || size < 0) {
+ return status;
+ }
+
+ setDataPosition(start);
+ str->emplace();
+ return readUtf8FromUtf16(&**str);
+}
+
status_t Parcel::readUtf8FromUtf16(std::unique_ptr<std::string>* str) const {
const int32_t start = dataPosition();
int32_t size;
@@ -1874,6 +2054,29 @@
return String16();
}
+status_t Parcel::readString16(std::optional<String16>* pArg) const
+{
+ const int32_t start = dataPosition();
+ int32_t size;
+ status_t status = readInt32(&size);
+ pArg->reset();
+
+ if (status != OK || size < 0) {
+ return status;
+ }
+
+ setDataPosition(start);
+ pArg->emplace();
+
+ status = readString16(&**pArg);
+
+ if (status != OK) {
+ pArg->reset();
+ }
+
+ return status;
+}
+
status_t Parcel::readString16(std::unique_ptr<String16>* pArg) const
{
const int32_t start = dataPosition();
@@ -2079,6 +2282,10 @@
return OK;
}
+status_t Parcel::readUniqueFileDescriptorVector(std::optional<std::vector<base::unique_fd>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readUniqueFileDescriptor);
+}
+
status_t Parcel::readUniqueFileDescriptorVector(std::unique_ptr<std::vector<base::unique_fd>>* val) const {
return readNullableTypedVector(val, &Parcel::readUniqueFileDescriptor);
}
diff --git a/libs/binder/ProcessState.cpp b/libs/binder/ProcessState.cpp
index 4b773e8..f3861bb 100644
--- a/libs/binder/ProcessState.cpp
+++ b/libs/binder/ProcessState.cpp
@@ -328,6 +328,8 @@
}
status_t ProcessState::setThreadPoolMaxThreadCount(size_t maxThreads) {
+ LOG_ALWAYS_FATAL_IF(mThreadPoolStarted && maxThreads < mMaxThreads,
+ "Binder threadpool cannot be shrunk after starting");
status_t result = NO_ERROR;
if (ioctl(mDriverFD, BINDER_SET_MAX_THREADS, &maxThreads) != -1) {
mMaxThreads = maxThreads;
diff --git a/libs/binder/Status.cpp b/libs/binder/Status.cpp
index 674f065..64ab7a9 100644
--- a/libs/binder/Status.cpp
+++ b/libs/binder/Status.cpp
@@ -193,13 +193,15 @@
}
status_t status = parcel->writeInt32(mException);
- if (status != OK) { return status; }
+ if (status != OK) return status;
if (mException == EX_NONE) {
// We have no more information to write.
return status;
}
status = parcel->writeString16(String16(mMessage));
+ if (status != OK) return status;
status = parcel->writeInt32(0); // Empty remote stack trace header
+ if (status != OK) return status;
if (mException == EX_SERVICE_SPECIFIC) {
status = parcel->writeInt32(mErrorCode);
} else if (mException == EX_PARCELABLE) {
diff --git a/libs/binder/include/binder/AppOpsManager.h b/libs/binder/include/binder/AppOpsManager.h
index 6afcd77..6d04f13 100644
--- a/libs/binder/include/binder/AppOpsManager.h
+++ b/libs/binder/include/binder/AppOpsManager.h
@@ -21,6 +21,8 @@
#include <utils/threads.h>
+#include <optional>
+
#ifdef __ANDROID_VNDK__
#error "This header is not visible to vendors"
#endif
@@ -143,18 +145,18 @@
// const String16&) instead
int32_t noteOp(int32_t op, int32_t uid, const String16& callingPackage);
int32_t noteOp(int32_t op, int32_t uid, const String16& callingPackage,
- const std::unique_ptr<String16>& attributionTag, const String16& message);
+ const std::optional<String16>& attributionTag, const String16& message);
// @Deprecated, use startOpNoThrow(int32_t, int32_t, const String16&, bool, const String16&,
// const String16&) instead
int32_t startOpNoThrow(int32_t op, int32_t uid, const String16& callingPackage,
bool startIfModeDefault);
int32_t startOpNoThrow(int32_t op, int32_t uid, const String16& callingPackage,
- bool startIfModeDefault, const std::unique_ptr<String16>& attributionTag,
+ bool startIfModeDefault, const std::optional<String16>& attributionTag,
const String16& message);
// @Deprecated, use finishOp(int32_t, int32_t, const String16&, bool, const String16&) instead
void finishOp(int32_t op, int32_t uid, const String16& callingPackage);
void finishOp(int32_t op, int32_t uid, const String16& callingPackage,
- const std::unique_ptr<String16>& attributionTag);
+ const std::optional<String16>& attributionTag);
void startWatchingMode(int32_t op, const String16& packageName,
const sp<IAppOpsCallback>& callback);
void stopWatchingMode(const sp<IAppOpsCallback>& callback);
diff --git a/libs/binder/include/binder/BpBinder.h b/libs/binder/include/binder/BpBinder.h
index 8e871b8..378a911 100644
--- a/libs/binder/include/binder/BpBinder.h
+++ b/libs/binder/include/binder/BpBinder.h
@@ -137,7 +137,6 @@
volatile int32_t mObitsSent;
Vector<Obituary>* mObituaries;
ObjectManager mObjects;
- Parcel* mConstantData;
mutable String16 mDescriptorCache;
int32_t mTrackedUid;
diff --git a/libs/binder/include/binder/IAppOpsService.h b/libs/binder/include/binder/IAppOpsService.h
index 1ffb8de..a4a20c8 100644
--- a/libs/binder/include/binder/IAppOpsService.h
+++ b/libs/binder/include/binder/IAppOpsService.h
@@ -21,6 +21,8 @@
#include <binder/IAppOpsCallback.h>
#include <binder/IInterface.h>
+#include <optional>
+
#ifdef __ANDROID_VNDK__
#error "This header is not visible to vendors"
#endif
@@ -36,13 +38,13 @@
virtual int32_t checkOperation(int32_t code, int32_t uid, const String16& packageName) = 0;
virtual int32_t noteOperation(int32_t code, int32_t uid, const String16& packageName,
- const std::unique_ptr<String16>& attributionTag, bool shouldCollectAsyncNotedOp,
+ const std::optional<String16>& attributionTag, bool shouldCollectAsyncNotedOp,
const String16& message) = 0;
virtual int32_t startOperation(const sp<IBinder>& token, int32_t code, int32_t uid,
- const String16& packageName, const std::unique_ptr<String16>& attributionTag,
+ const String16& packageName, const std::optional<String16>& attributionTag,
bool startIfModeDefault, bool shouldCollectAsyncNotedOp, const String16& message) = 0;
virtual void finishOperation(const sp<IBinder>& token, int32_t code, int32_t uid,
- const String16& packageName, const std::unique_ptr<String16>& attributionTag) = 0;
+ const String16& packageName, const std::optional<String16>& attributionTag) = 0;
virtual void startWatchingMode(int32_t op, const String16& packageName,
const sp<IAppOpsCallback>& callback) = 0;
virtual void stopWatchingMode(const sp<IAppOpsCallback>& callback) = 0;
diff --git a/libs/binder/include/binder/IBinder.h b/libs/binder/include/binder/IBinder.h
index 64604b7..eea0e89 100644
--- a/libs/binder/include/binder/IBinder.h
+++ b/libs/binder/include/binder/IBinder.h
@@ -173,6 +173,10 @@
* The @a cookie is optional -- if non-NULL, it should be a
* memory address that you own (that is, you know it is unique).
*
+ * @note When all references to the binder being linked to are dropped, the
+ * recipient is automatically unlinked. So, you must hold onto a binder in
+ * order to receive death notifications about it.
+ *
* @note You will only receive death notifications for remote binders,
* as local binders by definition can't die without you dying as well.
* Trying to use this function on a local binder will result in an
diff --git a/libs/binder/include/binder/IPCThreadState.h b/libs/binder/include/binder/IPCThreadState.h
index 4818889..b4e4a42 100644
--- a/libs/binder/include/binder/IPCThreadState.h
+++ b/libs/binder/include/binder/IPCThreadState.h
@@ -39,12 +39,28 @@
status_t clearLastError();
+ /**
+ * Returns the PID of the process which has made the current binder
+ * call. If not in a binder call, this will return getpid. If the
+ * call is oneway, this will return 0.
+ */
pid_t getCallingPid() const;
- // nullptr if unavailable
- //
- // this can't be restored once it's cleared, and it does not return the
- // context of the current process when not in a binder call.
+
+ /**
+ * Returns the SELinux security identifier of the process which has
+ * made the current binder call. If not in a binder call this will
+ * return nullptr. If this isn't requested with
+ * IBinder::setRequestingSid, it will also return nullptr.
+ *
+ * This can't be restored once it's cleared, and it does not return the
+ * context of the current process when not in a binder call.
+ */
const char* getCallingSid() const;
+
+ /**
+ * Returns the UID of the process which has made the current binder
+ * call. If not in a binder call, this will return 0.
+ */
uid_t getCallingUid() const;
void setStrictModePolicy(int32_t policy);
diff --git a/libs/binder/include/binder/MemoryHeapBase.h b/libs/binder/include/binder/MemoryHeapBase.h
index 3fccddc..edada3d 100644
--- a/libs/binder/include/binder/MemoryHeapBase.h
+++ b/libs/binder/include/binder/MemoryHeapBase.h
@@ -57,14 +57,14 @@
virtual ~MemoryHeapBase();
/* implement IMemoryHeap interface */
- virtual int getHeapID() const;
+ int getHeapID() const override;
/* virtual address of the heap. returns MAP_FAILED in case of error */
- virtual void* getBase() const;
+ void* getBase() const override;
- virtual size_t getSize() const;
- virtual uint32_t getFlags() const;
- off_t getOffset() const override;
+ size_t getSize() const override;
+ uint32_t getFlags() const override;
+ off_t getOffset() const override;
const char* getDevice() const;
diff --git a/libs/binder/include/binder/Nullable.h b/libs/binder/include/binder/Nullable.h
index b605bd3..a98583d 100644
--- a/libs/binder/include/binder/Nullable.h
+++ b/libs/binder/include/binder/Nullable.h
@@ -15,7 +15,7 @@
*/
#pragma once
-#include <memory>
+#include <optional>
#include <utility>
namespace android {
@@ -32,11 +32,11 @@
// c = std::move(a);
template <typename T>
-using nullable = std::unique_ptr<T>;
+using nullable = std::optional<T>;
template <typename T, typename... Args>
inline nullable<T> make_nullable(Args&&... args) {
- return std::make_unique<T>(std::forward<Args>(args)...);
+ return std::make_optional<T>(std::forward<Args>(args)...);
}
} // namespace aidl
diff --git a/libs/binder/include/binder/Parcel.h b/libs/binder/include/binder/Parcel.h
index 4b1a758..97f1aee 100644
--- a/libs/binder/include/binder/Parcel.h
+++ b/libs/binder/include/binder/Parcel.h
@@ -120,6 +120,7 @@
status_t writeCString(const char* str);
status_t writeString8(const String8& str);
status_t writeString16(const String16& str);
+ status_t writeString16(const std::optional<String16>& str);
status_t writeString16(const std::unique_ptr<String16>& str);
status_t writeString16(const char16_t* str, size_t len);
status_t writeStrongBinder(const sp<IBinder>& val);
@@ -131,33 +132,48 @@
// Take a UTF8 encoded string, convert to UTF16, write it to the parcel.
status_t writeUtf8AsUtf16(const std::string& str);
+ status_t writeUtf8AsUtf16(const std::optional<std::string>& str);
status_t writeUtf8AsUtf16(const std::unique_ptr<std::string>& str);
+ status_t writeByteVector(const std::optional<std::vector<int8_t>>& val);
status_t writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val);
status_t writeByteVector(const std::vector<int8_t>& val);
+ status_t writeByteVector(const std::optional<std::vector<uint8_t>>& val);
status_t writeByteVector(const std::unique_ptr<std::vector<uint8_t>>& val);
status_t writeByteVector(const std::vector<uint8_t>& val);
+ status_t writeInt32Vector(const std::optional<std::vector<int32_t>>& val);
status_t writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val);
status_t writeInt32Vector(const std::vector<int32_t>& val);
+ status_t writeInt64Vector(const std::optional<std::vector<int64_t>>& val);
status_t writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val);
status_t writeInt64Vector(const std::vector<int64_t>& val);
+ status_t writeUint64Vector(const std::optional<std::vector<uint64_t>>& val);
status_t writeUint64Vector(const std::unique_ptr<std::vector<uint64_t>>& val);
status_t writeUint64Vector(const std::vector<uint64_t>& val);
+ status_t writeFloatVector(const std::optional<std::vector<float>>& val);
status_t writeFloatVector(const std::unique_ptr<std::vector<float>>& val);
status_t writeFloatVector(const std::vector<float>& val);
+ status_t writeDoubleVector(const std::optional<std::vector<double>>& val);
status_t writeDoubleVector(const std::unique_ptr<std::vector<double>>& val);
status_t writeDoubleVector(const std::vector<double>& val);
+ status_t writeBoolVector(const std::optional<std::vector<bool>>& val);
status_t writeBoolVector(const std::unique_ptr<std::vector<bool>>& val);
status_t writeBoolVector(const std::vector<bool>& val);
+ status_t writeCharVector(const std::optional<std::vector<char16_t>>& val);
status_t writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val);
status_t writeCharVector(const std::vector<char16_t>& val);
status_t writeString16Vector(
+ const std::optional<std::vector<std::optional<String16>>>& val);
+ status_t writeString16Vector(
const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val);
status_t writeString16Vector(const std::vector<String16>& val);
status_t writeUtf8VectorAsUtf16Vector(
+ const std::optional<std::vector<std::optional<std::string>>>& val);
+ status_t writeUtf8VectorAsUtf16Vector(
const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val);
status_t writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val);
+ status_t writeStrongBinderVector(const std::optional<std::vector<sp<IBinder>>>& val);
status_t writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val);
status_t writeStrongBinderVector(const std::vector<sp<IBinder>>& val);
@@ -166,14 +182,20 @@
template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
status_t writeEnumVector(const std::vector<T>& val);
template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
+ status_t writeEnumVector(const std::optional<std::vector<T>>& val);
+ template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
status_t writeEnumVector(const std::unique_ptr<std::vector<T>>& val);
// Write an Enum vector with underlying type != int8_t.
template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
status_t writeEnumVector(const std::vector<T>& val);
template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
+ status_t writeEnumVector(const std::optional<std::vector<T>>& val);
+ template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
status_t writeEnumVector(const std::unique_ptr<std::vector<T>>& val);
template<typename T>
+ status_t writeParcelableVector(const std::optional<std::vector<std::optional<T>>>& val);
+ template<typename T>
status_t writeParcelableVector(const std::unique_ptr<std::vector<std::unique_ptr<T>>>& val);
template<typename T>
status_t writeParcelableVector(const std::shared_ptr<std::vector<std::unique_ptr<T>>>& val);
@@ -181,6 +203,8 @@
status_t writeParcelableVector(const std::vector<T>& val);
template<typename T>
+ status_t writeNullableParcelable(const std::optional<T>& parcelable);
+ template<typename T>
status_t writeNullableParcelable(const std::unique_ptr<T>& parcelable);
status_t writeParcelable(const Parcelable& parcelable);
@@ -194,6 +218,8 @@
template<typename T>
status_t writeVectorSize(const std::vector<T>& val);
template<typename T>
+ status_t writeVectorSize(const std::optional<std::vector<T>>& val);
+ template<typename T>
status_t writeVectorSize(const std::unique_ptr<std::vector<T>>& val);
// Place a native_handle into the parcel (the native_handle's file-
@@ -229,6 +255,8 @@
// Place a vector of file desciptors into the parcel. Each descriptor is
// dup'd as in writeDupFileDescriptor
status_t writeUniqueFileDescriptorVector(
+ const std::optional<std::vector<base::unique_fd>>& val);
+ status_t writeUniqueFileDescriptorVector(
const std::unique_ptr<std::vector<base::unique_fd>>& val);
status_t writeUniqueFileDescriptorVector(
const std::vector<base::unique_fd>& val);
@@ -278,6 +306,7 @@
// Read a UTF16 encoded string, convert to UTF8
status_t readUtf8FromUtf16(std::string* str) const;
+ status_t readUtf8FromUtf16(std::optional<std::string>* str) const;
status_t readUtf8FromUtf16(std::unique_ptr<std::string>* str) const;
const char* readCString() const;
@@ -285,27 +314,34 @@
status_t readString8(String8* pArg) const;
String16 readString16() const;
status_t readString16(String16* pArg) const;
+ status_t readString16(std::optional<String16>* pArg) const;
status_t readString16(std::unique_ptr<String16>* pArg) const;
const char16_t* readString16Inplace(size_t* outLen) const;
sp<IBinder> readStrongBinder() const;
status_t readStrongBinder(sp<IBinder>* val) const;
status_t readNullableStrongBinder(sp<IBinder>* val) const;
-
// Read an Enum vector with underlying type int8_t.
// Does not use padding; each byte is contiguous.
template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
status_t readEnumVector(std::vector<T>* val) const;
template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
status_t readEnumVector(std::unique_ptr<std::vector<T>>* val) const;
+ template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
+ status_t readEnumVector(std::optional<std::vector<T>>* val) const;
// Read an Enum vector with underlying type != int8_t.
template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
status_t readEnumVector(std::vector<T>* val) const;
template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
status_t readEnumVector(std::unique_ptr<std::vector<T>>* val) const;
+ template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool> = 0>
+ status_t readEnumVector(std::optional<std::vector<T>>* val) const;
template<typename T>
status_t readParcelableVector(
+ std::optional<std::vector<std::optional<T>>>* val) const;
+ template<typename T>
+ status_t readParcelableVector(
std::unique_ptr<std::vector<std::unique_ptr<T>>>* val) const;
template<typename T>
status_t readParcelableVector(std::vector<T>* val) const;
@@ -313,6 +349,8 @@
status_t readParcelable(Parcelable* parcelable) const;
template<typename T>
+ status_t readParcelable(std::optional<T>* parcelable) const;
+ template<typename T>
status_t readParcelable(std::unique_ptr<T>* parcelable) const;
template<typename T>
@@ -321,31 +359,45 @@
template<typename T>
status_t readNullableStrongBinder(sp<T>* val) const;
+ status_t readStrongBinderVector(std::optional<std::vector<sp<IBinder>>>* val) const;
status_t readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const;
status_t readStrongBinderVector(std::vector<sp<IBinder>>* val) const;
+ status_t readByteVector(std::optional<std::vector<int8_t>>* val) const;
status_t readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const;
status_t readByteVector(std::vector<int8_t>* val) const;
+ status_t readByteVector(std::optional<std::vector<uint8_t>>* val) const;
status_t readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const;
status_t readByteVector(std::vector<uint8_t>* val) const;
+ status_t readInt32Vector(std::optional<std::vector<int32_t>>* val) const;
status_t readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const;
status_t readInt32Vector(std::vector<int32_t>* val) const;
+ status_t readInt64Vector(std::optional<std::vector<int64_t>>* val) const;
status_t readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const;
status_t readInt64Vector(std::vector<int64_t>* val) const;
+ status_t readUint64Vector(std::optional<std::vector<uint64_t>>* val) const;
status_t readUint64Vector(std::unique_ptr<std::vector<uint64_t>>* val) const;
status_t readUint64Vector(std::vector<uint64_t>* val) const;
+ status_t readFloatVector(std::optional<std::vector<float>>* val) const;
status_t readFloatVector(std::unique_ptr<std::vector<float>>* val) const;
status_t readFloatVector(std::vector<float>* val) const;
+ status_t readDoubleVector(std::optional<std::vector<double>>* val) const;
status_t readDoubleVector(std::unique_ptr<std::vector<double>>* val) const;
status_t readDoubleVector(std::vector<double>* val) const;
+ status_t readBoolVector(std::optional<std::vector<bool>>* val) const;
status_t readBoolVector(std::unique_ptr<std::vector<bool>>* val) const;
status_t readBoolVector(std::vector<bool>* val) const;
+ status_t readCharVector(std::optional<std::vector<char16_t>>* val) const;
status_t readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const;
status_t readCharVector(std::vector<char16_t>* val) const;
status_t readString16Vector(
+ std::optional<std::vector<std::optional<String16>>>* val) const;
+ status_t readString16Vector(
std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const;
status_t readString16Vector(std::vector<String16>* val) const;
status_t readUtf8VectorFromUtf16Vector(
+ std::optional<std::vector<std::optional<std::string>>>* val) const;
+ status_t readUtf8VectorFromUtf16Vector(
std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const;
status_t readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const;
@@ -358,10 +410,15 @@
template<typename T>
status_t resizeOutVector(std::vector<T>* val) const;
template<typename T>
+ status_t resizeOutVector(std::optional<std::vector<T>>* val) const;
+ template<typename T>
status_t resizeOutVector(std::unique_ptr<std::vector<T>>* val) const;
template<typename T>
status_t reserveOutVector(std::vector<T>* val, size_t* size) const;
template<typename T>
+ status_t reserveOutVector(std::optional<std::vector<T>>* val,
+ size_t* size) const;
+ template<typename T>
status_t reserveOutVector(std::unique_ptr<std::vector<T>>* val,
size_t* size) const;
@@ -397,6 +454,8 @@
// Retrieve a vector of smart file descriptors from the parcel.
status_t readUniqueFileDescriptorVector(
+ std::optional<std::vector<base::unique_fd>>* val) const;
+ status_t readUniqueFileDescriptorVector(
std::unique_ptr<std::vector<base::unique_fd>>* val) const;
status_t readUniqueFileDescriptorVector(
std::vector<base::unique_fd>* val) const;
@@ -490,6 +549,9 @@
status_t unsafeReadTypedVector(std::vector<T>* val,
status_t(Parcel::*read_func)(U*) const) const;
template<typename T>
+ status_t readNullableTypedVector(std::optional<std::vector<T>>* val,
+ status_t(Parcel::*read_func)(T*) const) const;
+ template<typename T>
status_t readNullableTypedVector(std::unique_ptr<std::vector<T>>* val,
status_t(Parcel::*read_func)(T*) const) const;
template<typename T>
@@ -499,9 +561,15 @@
status_t unsafeWriteTypedVector(const std::vector<T>& val,
status_t(Parcel::*write_func)(U));
template<typename T>
+ status_t writeNullableTypedVector(const std::optional<std::vector<T>>& val,
+ status_t(Parcel::*write_func)(const T&));
+ template<typename T>
status_t writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
status_t(Parcel::*write_func)(const T&));
template<typename T>
+ status_t writeNullableTypedVector(const std::optional<std::vector<T>>& val,
+ status_t(Parcel::*write_func)(T));
+ template<typename T>
status_t writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
status_t(Parcel::*write_func)(T));
template<typename T>
@@ -689,6 +757,15 @@
}
template<typename T>
+status_t Parcel::writeVectorSize(const std::optional<std::vector<T>>& val) {
+ if (!val) {
+ return writeInt32(-1);
+ }
+
+ return writeVectorSize(*val);
+}
+
+template<typename T>
status_t Parcel::writeVectorSize(const std::unique_ptr<std::vector<T>>& val) {
if (!val) {
return writeInt32(-1);
@@ -713,6 +790,22 @@
}
template<typename T>
+status_t Parcel::resizeOutVector(std::optional<std::vector<T>>* val) const {
+ int32_t size;
+ status_t err = readInt32(&size);
+ if (err != NO_ERROR) {
+ return err;
+ }
+
+ val->reset();
+ if (size >= 0) {
+ val->emplace(size_t(size));
+ }
+
+ return OK;
+}
+
+template<typename T>
status_t Parcel::resizeOutVector(std::unique_ptr<std::vector<T>>* val) const {
int32_t size;
status_t err = readInt32(&size);
@@ -745,6 +838,25 @@
}
template<typename T>
+status_t Parcel::reserveOutVector(std::optional<std::vector<T>>* val, size_t* size) const {
+ int32_t read_size;
+ status_t err = readInt32(&read_size);
+ if (err != NO_ERROR) {
+ return err;
+ }
+
+ if (read_size >= 0) {
+ *size = static_cast<size_t>(read_size);
+ val->emplace();
+ (*val)->reserve(*size);
+ } else {
+ val->reset();
+ }
+
+ return OK;
+}
+
+template<typename T>
status_t Parcel::reserveOutVector(std::unique_ptr<std::vector<T>>* val,
size_t* size) const {
int32_t read_size;
@@ -839,6 +951,30 @@
}
template<typename T>
+status_t Parcel::readNullableTypedVector(std::optional<std::vector<T>>* val,
+ status_t(Parcel::*read_func)(T*) const) const {
+ const size_t start = dataPosition();
+ int32_t size;
+ status_t status = readInt32(&size);
+ val->reset();
+
+ if (status != OK || size < 0) {
+ return status;
+ }
+
+ setDataPosition(start);
+ val->emplace();
+
+ status = unsafeReadTypedVector(&**val, read_func);
+
+ if (status != OK) {
+ val->reset();
+ }
+
+ return status;
+}
+
+template<typename T>
status_t Parcel::readNullableTypedVector(std::unique_ptr<std::vector<T>>* val,
status_t(Parcel::*read_func)(T*) const) const {
const size_t start = dataPosition();
@@ -899,6 +1035,16 @@
}
template<typename T>
+status_t Parcel::writeNullableTypedVector(const std::optional<std::vector<T>>& val,
+ status_t(Parcel::*write_func)(const T&)) {
+ if (!val) {
+ return this->writeInt32(-1);
+ }
+
+ return unsafeWriteTypedVector(*val, write_func);
+}
+
+template<typename T>
status_t Parcel::writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
status_t(Parcel::*write_func)(const T&)) {
if (val.get() == nullptr) {
@@ -909,6 +1055,16 @@
}
template<typename T>
+status_t Parcel::writeNullableTypedVector(const std::optional<std::vector<T>>& val,
+ status_t(Parcel::*write_func)(T)) {
+ if (!val) {
+ return this->writeInt32(-1);
+ }
+
+ return unsafeWriteTypedVector(*val, write_func);
+}
+
+template<typename T>
status_t Parcel::writeNullableTypedVector(const std::unique_ptr<std::vector<T>>& val,
status_t(Parcel::*write_func)(T)) {
if (val.get() == nullptr) {
@@ -924,6 +1080,30 @@
}
template<typename T>
+status_t Parcel::readParcelableVector(std::optional<std::vector<std::optional<T>>>* val) const {
+ const size_t start = dataPosition();
+ int32_t size;
+ status_t status = readInt32(&size);
+ val->reset();
+
+ if (status != OK || size < 0) {
+ return status;
+ }
+
+ setDataPosition(start);
+ val->emplace();
+
+ using NullableT = std::optional<T>;
+ status = unsafeReadTypedVector<NullableT, NullableT>(&**val, &Parcel::readParcelable);
+
+ if (status != OK) {
+ val->reset();
+ }
+
+ return status;
+}
+
+template<typename T>
status_t Parcel::readParcelableVector(std::unique_ptr<std::vector<std::unique_ptr<T>>>* val) const {
const size_t start = dataPosition();
int32_t size;
@@ -937,7 +1117,8 @@
setDataPosition(start);
val->reset(new std::vector<std::unique_ptr<T>>());
- status = unsafeReadTypedVector(val->get(), &Parcel::readParcelable<T>);
+ using NullableT = std::unique_ptr<T>;
+ status = unsafeReadTypedVector<NullableT, NullableT>(val->get(), &Parcel::readParcelable);
if (status != OK) {
val->reset();
@@ -947,6 +1128,29 @@
}
template<typename T>
+status_t Parcel::readParcelable(std::optional<T>* parcelable) const {
+ const size_t start = dataPosition();
+ int32_t present;
+ status_t status = readInt32(&present);
+ parcelable->reset();
+
+ if (status != OK || !present) {
+ return status;
+ }
+
+ setDataPosition(start);
+ parcelable->emplace();
+
+ status = readParcelable(&**parcelable);
+
+ if (status != OK) {
+ parcelable->reset();
+ }
+
+ return status;
+}
+
+template<typename T>
status_t Parcel::readParcelable(std::unique_ptr<T>* parcelable) const {
const size_t start = dataPosition();
int32_t present;
@@ -970,6 +1174,11 @@
}
template<typename T>
+status_t Parcel::writeNullableParcelable(const std::optional<T>& parcelable) {
+ return writeRawNullableParcelable(parcelable ? &*parcelable : nullptr);
+}
+
+template<typename T>
status_t Parcel::writeNullableParcelable(const std::unique_ptr<T>& parcelable) {
return writeRawNullableParcelable(parcelable.get());
}
@@ -980,6 +1189,16 @@
}
template<typename T>
+status_t Parcel::writeParcelableVector(const std::optional<std::vector<std::optional<T>>>& val) {
+ if (!val) {
+ return this->writeInt32(-1);
+ }
+
+ using NullableT = std::optional<T>;
+ return unsafeWriteTypedVector<NullableT, const NullableT&>(*val, &Parcel::writeNullableParcelable);
+}
+
+template<typename T>
status_t Parcel::writeParcelableVector(const std::unique_ptr<std::vector<std::unique_ptr<T>>>& val) {
if (val.get() == nullptr) {
return this->writeInt32(-1);
@@ -994,7 +1213,8 @@
return this->writeInt32(-1);
}
- return unsafeWriteTypedVector(*val, &Parcel::writeNullableParcelable<T>);
+ using NullableT = std::unique_ptr<T>;
+ return unsafeWriteTypedVector<NullableT, const NullableT&>(*val, &Parcel::writeNullableParcelable);
}
template<typename T, std::enable_if_t<std::is_same_v<typename std::underlying_type_t<T>,int32_t>, bool>>
@@ -1011,6 +1231,11 @@
return writeByteVectorInternal(reinterpret_cast<const int8_t*>(val.data()), val.size());
}
template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool>>
+status_t Parcel::writeEnumVector(const std::optional<std::vector<T>>& val) {
+ if (!val) return writeInt32(-1);
+ return writeByteVectorInternal(reinterpret_cast<const int8_t*>(val->data()), val->size());
+}
+template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool>>
status_t Parcel::writeEnumVector(const std::unique_ptr<std::vector<T>>& val) {
if (!val) return writeInt32(-1);
return writeByteVectorInternal(reinterpret_cast<const int8_t*>(val->data()), val->size());
@@ -1020,6 +1245,10 @@
return writeTypedVector(val, &Parcel::writeEnum);
}
template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool>>
+status_t Parcel::writeEnumVector(const std::optional<std::vector<T>>& val) {
+ return writeNullableTypedVector(val, &Parcel::writeEnum);
+}
+template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool>>
status_t Parcel::writeEnumVector(const std::unique_ptr<std::vector<T>>& val) {
return writeNullableTypedVector(val, &Parcel::writeEnum);
}
@@ -1051,6 +1280,17 @@
return readByteVectorInternal(val, size);
}
template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool>>
+status_t Parcel::readEnumVector(std::optional<std::vector<T>>* val) const {
+ size_t size;
+ if (status_t status = reserveOutVector(val, &size); status != OK) return status;
+ if (!*val) {
+ // reserveOutVector does not create the out vector if size is < 0.
+ // This occurs when writing a null Enum vector.
+ return OK;
+ }
+ return readByteVectorInternal(&**val, size);
+}
+template<typename T, std::enable_if_t<std::is_enum_v<T> && std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool>>
status_t Parcel::readEnumVector(std::unique_ptr<std::vector<T>>* val) const {
size_t size;
if (status_t status = reserveOutVector(val, &size); status != OK) return status;
@@ -1066,6 +1306,10 @@
return readTypedVector(val, &Parcel::readEnum);
}
template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool>>
+status_t Parcel::readEnumVector(std::optional<std::vector<T>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readEnum);
+}
+template<typename T, std::enable_if_t<std::is_enum_v<T> && !std::is_same_v<typename std::underlying_type_t<T>,int8_t>, bool>>
status_t Parcel::readEnumVector(std::unique_ptr<std::vector<T>>* val) const {
return readNullableTypedVector(val, &Parcel::readEnum);
}
diff --git a/libs/binder/include/binder/ParcelFileDescriptor.h b/libs/binder/include/binder/ParcelFileDescriptor.h
index 4635ad8..2ede6c4 100644
--- a/libs/binder/include/binder/ParcelFileDescriptor.h
+++ b/libs/binder/include/binder/ParcelFileDescriptor.h
@@ -32,6 +32,7 @@
ParcelFileDescriptor();
explicit ParcelFileDescriptor(android::base::unique_fd fd);
ParcelFileDescriptor(ParcelFileDescriptor&& other) : mFd(std::move(other.mFd)) { }
+ ParcelFileDescriptor& operator=(ParcelFileDescriptor&& other) = default;
~ParcelFileDescriptor() override;
int get() const { return mFd.get(); }
diff --git a/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h b/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h
index df5df13..09949ea 100644
--- a/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h
+++ b/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h
@@ -831,34 +831,34 @@
}
/**
- * Writes a vector of int8_t to the next location in a non-null parcel.
+ * Writes a vector of uint8_t to the next location in a non-null parcel.
*/
-inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<int8_t>& vec) {
- return AParcel_writeByteArray(parcel, vec.data(), vec.size());
+inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<uint8_t>& vec) {
+ return AParcel_writeByteArray(parcel, reinterpret_cast<const int8_t*>(vec.data()), vec.size());
}
/**
- * Writes an optional vector of int8_t to the next location in a non-null parcel.
+ * Writes an optional vector of uint8_t to the next location in a non-null parcel.
*/
inline binder_status_t AParcel_writeVector(AParcel* parcel,
- const std::optional<std::vector<int8_t>>& vec) {
+ const std::optional<std::vector<uint8_t>>& vec) {
if (!vec) return AParcel_writeByteArray(parcel, nullptr, -1);
return AParcel_writeVector(parcel, *vec);
}
/**
- * Reads a vector of int8_t from the next location in a non-null parcel.
+ * Reads a vector of uint8_t from the next location in a non-null parcel.
*/
-inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<int8_t>* vec) {
+inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<uint8_t>* vec) {
void* vectorData = static_cast<void*>(vec);
return AParcel_readByteArray(parcel, vectorData, AParcel_stdVectorAllocator<int8_t>);
}
/**
- * Reads an optional vector of int8_t from the next location in a non-null parcel.
+ * Reads an optional vector of uint8_t from the next location in a non-null parcel.
*/
inline binder_status_t AParcel_readVector(const AParcel* parcel,
- std::optional<std::vector<int8_t>>* vec) {
+ std::optional<std::vector<uint8_t>>* vec) {
void* vectorData = static_cast<void*>(vec);
return AParcel_readByteArray(parcel, vectorData, AParcel_nullableStdVectorAllocator<int8_t>);
}
diff --git a/libs/dumputils/dump_utils.cpp b/libs/dumputils/dump_utils.cpp
index fd557b7..2e14408 100644
--- a/libs/dumputils/dump_utils.cpp
+++ b/libs/dumputils/dump_utils.cpp
@@ -56,6 +56,10 @@
"android.hardware.audio@4.0::IDevicesFactory",
"android.hardware.audio@5.0::IDevicesFactory",
"android.hardware.audio@6.0::IDevicesFactory",
+ "android.hardware.automotive.audiocontrol@1.0::IAudioControl",
+ "android.hardware.automotive.audiocontrol@2.0::IAudioControl",
+ "android.hardware.automotive.evs@1.0::IEvsCamera",
+ "android.hardware.automotive.vehicle@2.0::IVehicle",
"android.hardware.biometrics.face@1.0::IBiometricsFace",
"android.hardware.biometrics.fingerprint@2.1::IBiometricsFingerprint",
"android.hardware.bluetooth@1.0::IBluetoothHci",
@@ -67,16 +71,12 @@
"android.hardware.media.c2@1.0::IComponentStore",
"android.hardware.media.omx@1.0::IOmx",
"android.hardware.media.omx@1.0::IOmxStore",
+ "android.hardware.neuralnetworks@1.0::IDevice",
"android.hardware.power@1.3::IPower",
"android.hardware.power.stats@1.0::IPowerStats",
"android.hardware.sensors@1.0::ISensors",
"android.hardware.thermal@2.0::IThermal",
"android.hardware.vr@1.0::IVr",
- "android.hardware.automotive.audiocontrol@1.0::IAudioControl",
- "android.hardware.automotive.audiocontrol@2.0::IAudioControl",
- "android.hardware.automotive.vehicle@2.0::IVehicle",
- "android.hardware.automotive.evs@1.0::IEvsCamera",
- "android.hardware.neuralnetworks@1.0::IDevice",
NULL,
};
diff --git a/libs/fakeservicemanager/Android.bp b/libs/fakeservicemanager/Android.bp
index de32ff4..6909637 100644
--- a/libs/fakeservicemanager/Android.bp
+++ b/libs/fakeservicemanager/Android.bp
@@ -1,5 +1,6 @@
cc_defaults {
name: "fakeservicemanager_defaults",
+ host_supported: true,
srcs: [
"ServiceManager.cpp",
],
diff --git a/libs/gralloc/OWNERS b/libs/gralloc/OWNERS
index 67743cd..4a95778 100644
--- a/libs/gralloc/OWNERS
+++ b/libs/gralloc/OWNERS
@@ -1,2 +1,2 @@
-marissaw@google.com
+chrisforbes@google.com
vhau@google.com
diff --git a/libs/gui/BufferHubProducer.cpp b/libs/gui/BufferHubProducer.cpp
index 4be014f..489f3c3 100644
--- a/libs/gui/BufferHubProducer.cpp
+++ b/libs/gui/BufferHubProducer.cpp
@@ -19,7 +19,6 @@
#include <inttypes.h>
#include <log/log.h>
#include <system/window.h>
-#include <ui/BufferHubBuffer.h>
namespace android {
diff --git a/libs/gui/OWNERS b/libs/gui/OWNERS
index c13401d..b77dfda 100644
--- a/libs/gui/OWNERS
+++ b/libs/gui/OWNERS
@@ -1,10 +1,9 @@
adyabr@google.com
akrulec@google.com
alecmouri@google.com
+chrisforbes@google.com
jessehall@google.com
-jwcai@google.com
lpy@google.com
-marissaw@google.com
mathias@google.com
racarr@google.com
steventhomas@google.com
diff --git a/libs/ui/Android.bp b/libs/ui/Android.bp
index ba6255d..458ee67 100644
--- a/libs/ui/Android.bp
+++ b/libs/ui/Android.bp
@@ -36,9 +36,6 @@
srcs: [
"ColorSpace.cpp",
- "BufferHubBuffer.cpp",
- "BufferHubEventFd.cpp",
- "BufferHubMetadata.cpp",
"DebugUtils.cpp",
"Fence.cpp",
"FenceTime.cpp",
@@ -72,7 +69,6 @@
//defaults: ["libui-validate-regions-defaults"],
shared_libs: [
- "android.frameworks.bufferhub@1.0",
"android.hardware.graphics.allocator@2.0",
"android.hardware.graphics.allocator@3.0",
"android.hardware.graphics.allocator@4.0",
@@ -109,30 +105,20 @@
vendor: {
cflags: ["-DLIBUI_IN_VNDK"],
exclude_srcs: [
- "BufferHubBuffer.cpp",
- "BufferHubEventFd.cpp",
- "BufferHubMetadata.cpp",
],
exclude_header_libs: [
- "libbufferhub_headers",
- "libdvr_headers",
],
exclude_shared_libs: [
- "android.frameworks.bufferhub@1.0",
- "libpdx_default_transport",
],
},
},
header_libs: [
"libbase_headers",
- "libbufferhub_headers",
- "libdvr_headers",
"libnativebase_headers",
"libnativewindow_headers",
"libhardware_headers",
"libui_headers",
- "libpdx_headers",
],
export_static_lib_headers: [
diff --git a/libs/ui/BufferHubBuffer.cpp b/libs/ui/BufferHubBuffer.cpp
deleted file mode 100644
index 1dfc1e9..0000000
--- a/libs/ui/BufferHubBuffer.cpp
+++ /dev/null
@@ -1,358 +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.
- */
-
-#define LOG_TAG "BufferHubBuffer"
-#include <poll.h>
-
-#include <android-base/unique_fd.h>
-#include <android/frameworks/bufferhub/1.0/IBufferHub.h>
-#include <log/log.h>
-#include <ui/BufferHubBuffer.h>
-#include <ui/BufferHubDefs.h>
-#include <utils/Trace.h>
-
-using ::android::base::unique_fd;
-using ::android::BufferHubDefs::isAnyClientAcquired;
-using ::android::BufferHubDefs::isAnyClientGained;
-using ::android::BufferHubDefs::isClientAcquired;
-using ::android::BufferHubDefs::isClientGained;
-using ::android::BufferHubDefs::isClientPosted;
-using ::android::BufferHubDefs::isClientReleased;
-using ::android::frameworks::bufferhub::V1_0::BufferHubStatus;
-using ::android::frameworks::bufferhub::V1_0::BufferTraits;
-using ::android::frameworks::bufferhub::V1_0::IBufferClient;
-using ::android::frameworks::bufferhub::V1_0::IBufferHub;
-using ::android::hardware::hidl_handle;
-using ::android::hardware::graphics::common::V1_2::HardwareBufferDescription;
-
-namespace android {
-
-std::unique_ptr<BufferHubBuffer> BufferHubBuffer::create(uint32_t width, uint32_t height,
- uint32_t layerCount, uint32_t format,
- uint64_t usage, size_t userMetadataSize) {
- auto buffer = std::unique_ptr<BufferHubBuffer>(
- new BufferHubBuffer(width, height, layerCount, format, usage, userMetadataSize));
- return buffer->isValid() ? std::move(buffer) : nullptr;
-}
-
-std::unique_ptr<BufferHubBuffer> BufferHubBuffer::import(const sp<NativeHandle>& token) {
- if (token == nullptr || token.get() == nullptr) {
- ALOGE("%s: token cannot be nullptr!", __FUNCTION__);
- return nullptr;
- }
-
- auto buffer = std::unique_ptr<BufferHubBuffer>(new BufferHubBuffer(token));
- return buffer->isValid() ? std::move(buffer) : nullptr;
-}
-
-BufferHubBuffer::BufferHubBuffer(uint32_t width, uint32_t height, uint32_t layerCount,
- uint32_t format, uint64_t usage, size_t userMetadataSize) {
- ATRACE_CALL();
- ALOGD("%s: width=%u height=%u layerCount=%u, format=%u "
- "usage=%" PRIx64 " mUserMetadataSize=%zu",
- __FUNCTION__, width, height, layerCount, format, usage, userMetadataSize);
-
- sp<IBufferHub> bufferhub = IBufferHub::getService();
- if (bufferhub.get() == nullptr) {
- ALOGE("%s: BufferHub service not found!", __FUNCTION__);
- return;
- }
-
- AHardwareBuffer_Desc aDesc = {width, height, layerCount, format,
- usage, /*stride=*/0UL, /*rfu0=*/0UL, /*rfu1=*/0ULL};
- HardwareBufferDescription desc;
- memcpy(&desc, &aDesc, sizeof(HardwareBufferDescription));
-
- BufferHubStatus ret;
- sp<IBufferClient> client;
- BufferTraits bufferTraits;
- IBufferHub::allocateBuffer_cb allocCb = [&](const auto& status, const auto& outClient,
- const auto& outTraits) {
- ret = status;
- client = std::move(outClient);
- bufferTraits = std::move(outTraits);
- };
-
- if (!bufferhub->allocateBuffer(desc, static_cast<uint32_t>(userMetadataSize), allocCb).isOk()) {
- ALOGE("%s: allocateBuffer transaction failed!", __FUNCTION__);
- return;
- } else if (ret != BufferHubStatus::NO_ERROR) {
- ALOGE("%s: allocateBuffer failed with error %u.", __FUNCTION__, ret);
- return;
- } else if (client == nullptr) {
- ALOGE("%s: allocateBuffer got null BufferClient.", __FUNCTION__);
- return;
- }
-
- const int importRet = initWithBufferTraits(bufferTraits);
- if (importRet < 0) {
- ALOGE("%s: Failed to import buffer: %s", __FUNCTION__, strerror(-importRet));
- client->close();
- }
- mBufferClient = std::move(client);
-}
-
-BufferHubBuffer::BufferHubBuffer(const sp<NativeHandle>& token) {
- sp<IBufferHub> bufferhub = IBufferHub::getService();
- if (bufferhub.get() == nullptr) {
- ALOGE("%s: BufferHub service not found!", __FUNCTION__);
- return;
- }
-
- BufferHubStatus ret;
- sp<IBufferClient> client;
- BufferTraits bufferTraits;
- IBufferHub::importBuffer_cb importCb = [&](const auto& status, const auto& outClient,
- const auto& outTraits) {
- ret = status;
- client = std::move(outClient);
- bufferTraits = std::move(outTraits);
- };
-
- // hidl_handle(native_handle_t*) simply creates a raw pointer reference withouth ownership
- // transfer.
- if (!bufferhub->importBuffer(hidl_handle(token.get()->handle()), importCb).isOk()) {
- ALOGE("%s: importBuffer transaction failed!", __FUNCTION__);
- return;
- } else if (ret != BufferHubStatus::NO_ERROR) {
- ALOGE("%s: importBuffer failed with error %u.", __FUNCTION__, ret);
- return;
- } else if (client == nullptr) {
- ALOGE("%s: importBuffer got null BufferClient.", __FUNCTION__);
- return;
- }
-
- const int importRet = initWithBufferTraits(bufferTraits);
- if (importRet < 0) {
- ALOGE("%s: Failed to import buffer: %s", __FUNCTION__, strerror(-importRet));
- client->close();
- }
- mBufferClient = std::move(client);
-}
-
-BufferHubBuffer::~BufferHubBuffer() {
- // Close buffer client to avoid possible race condition: user could first duplicate and hold
- // token with the original buffer gone, and then try to import the token. The close function
- // will explicitly invalidate the token to avoid this.
- if (mBufferClient != nullptr) {
- if (!mBufferClient->close().isOk()) {
- ALOGE("%s: close BufferClient transaction failed!", __FUNCTION__);
- }
- }
-}
-
-int BufferHubBuffer::initWithBufferTraits(const BufferTraits& bufferTraits) {
- ATRACE_CALL();
-
- if (bufferTraits.bufferInfo.getNativeHandle() == nullptr) {
- ALOGE("%s: missing buffer info handle.", __FUNCTION__);
- return -EINVAL;
- }
-
- if (bufferTraits.bufferHandle.getNativeHandle() == nullptr) {
- ALOGE("%s: missing gralloc handle.", __FUNCTION__);
- return -EINVAL;
- }
-
- // Import fds. Dup fds because hidl_handle owns the fds.
- unique_fd ashmemFd(fcntl(bufferTraits.bufferInfo->data[0], F_DUPFD_CLOEXEC, 0));
- mMetadata = BufferHubMetadata::import(std::move(ashmemFd));
- if (!mMetadata.isValid()) {
- ALOGE("%s: Received an invalid metadata.", __FUNCTION__);
- return -EINVAL;
- }
-
- mEventFd = BufferHubEventFd(fcntl(bufferTraits.bufferInfo->data[1], F_DUPFD_CLOEXEC, 0));
- if (!mEventFd.isValid()) {
- ALOGE("%s: Received ad invalid event fd.", __FUNCTION__);
- return -EINVAL;
- }
-
- int bufferId = bufferTraits.bufferInfo->data[2];
- if (bufferId < 0) {
- ALOGE("%s: Received an invalid (negative) id.", __FUNCTION__);
- return -EINVAL;
- }
-
- uint32_t clientBitMask;
- memcpy(&clientBitMask, &bufferTraits.bufferInfo->data[3], sizeof(clientBitMask));
- if (clientBitMask == 0U) {
- ALOGE("%s: Received an invalid client state mask.", __FUNCTION__);
- return -EINVAL;
- }
-
- uint32_t userMetadataSize;
- memcpy(&userMetadataSize, &bufferTraits.bufferInfo->data[4], sizeof(userMetadataSize));
- if (mMetadata.userMetadataSize() != userMetadataSize) {
- ALOGE("%s: user metadata size not match: expected %u, actual %zu.", __FUNCTION__,
- userMetadataSize, mMetadata.userMetadataSize());
- return -EINVAL;
- }
-
- size_t metadataSize = static_cast<size_t>(mMetadata.metadataSize());
- if (metadataSize < BufferHubDefs::kMetadataHeaderSize) {
- ALOGE("%s: metadata too small: %zu", __FUNCTION__, metadataSize);
- return -EINVAL;
- }
-
- // Populate shortcuts to the atomics in metadata.
- auto metadataHeader = mMetadata.metadataHeader();
- mBufferState = &metadataHeader->bufferState;
- mFenceState = &metadataHeader->fenceState;
- mActiveClientsBitMask = &metadataHeader->activeClientsBitMask;
- // The C++ standard recommends (but does not require) that lock-free atomic operations are
- // also address-free, that is, suitable for communication between processes using shared
- // memory.
- LOG_ALWAYS_FATAL_IF(!std::atomic_is_lock_free(mBufferState) ||
- !std::atomic_is_lock_free(mFenceState) ||
- !std::atomic_is_lock_free(mActiveClientsBitMask),
- "Atomic variables in ashmen are not lock free.");
-
- // Import the buffer: We only need to hold on the native_handle_t here so that
- // GraphicBuffer instance can be created in future.
- mBufferHandle = std::move(bufferTraits.bufferHandle);
- memcpy(&mBufferDesc, &bufferTraits.bufferDesc, sizeof(AHardwareBuffer_Desc));
-
- mId = bufferId;
- mClientStateMask = clientBitMask;
-
- // TODO(b/112012161) Set up shared fences.
- ALOGD("%s: id=%d, mBufferState=%" PRIx32 ".", __FUNCTION__, mId,
- mBufferState->load(std::memory_order_acquire));
- return 0;
-}
-
-int BufferHubBuffer::gain() {
- uint32_t currentBufferState = mBufferState->load(std::memory_order_acquire);
- if (isClientGained(currentBufferState, mClientStateMask)) {
- ALOGV("%s: Buffer is already gained by this client %" PRIx32 ".", __FUNCTION__,
- mClientStateMask);
- return 0;
- }
- do {
- if (isAnyClientGained(currentBufferState & (~mClientStateMask)) ||
- isAnyClientAcquired(currentBufferState)) {
- ALOGE("%s: Buffer is in use, id=%d mClientStateMask=%" PRIx32 " state=%" PRIx32 ".",
- __FUNCTION__, mId, mClientStateMask, currentBufferState);
- return -EBUSY;
- }
- // Change the buffer state to gained state, whose value happens to be the same as
- // mClientStateMask.
- } while (!mBufferState->compare_exchange_weak(currentBufferState, mClientStateMask,
- std::memory_order_acq_rel,
- std::memory_order_acquire));
- // TODO(b/119837586): Update fence state and return GPU fence.
- return 0;
-}
-
-int BufferHubBuffer::post() {
- uint32_t currentBufferState = mBufferState->load(std::memory_order_acquire);
- uint32_t updatedBufferState = (~mClientStateMask) & BufferHubDefs::kHighBitsMask;
- do {
- if (!isClientGained(currentBufferState, mClientStateMask)) {
- ALOGE("%s: Cannot post a buffer that is not gained by this client. buffer_id=%d "
- "mClientStateMask=%" PRIx32 " state=%" PRIx32 ".",
- __FUNCTION__, mId, mClientStateMask, currentBufferState);
- return -EBUSY;
- }
- // Set the producer client buffer state to released, other clients' buffer state to posted.
- // Post to all existing and non-existing clients.
- } while (!mBufferState->compare_exchange_weak(currentBufferState, updatedBufferState,
- std::memory_order_acq_rel,
- std::memory_order_acquire));
- // TODO(b/119837586): Update fence state and return GPU fence if needed.
- return 0;
-}
-
-int BufferHubBuffer::acquire() {
- uint32_t currentBufferState = mBufferState->load(std::memory_order_acquire);
- if (isClientAcquired(currentBufferState, mClientStateMask)) {
- ALOGV("%s: Buffer is already acquired by this client %" PRIx32 ".", __FUNCTION__,
- mClientStateMask);
- return 0;
- }
- uint32_t updatedBufferState = 0U;
- do {
- if (!isClientPosted(currentBufferState, mClientStateMask)) {
- ALOGE("%s: Cannot acquire a buffer that is not in posted state. buffer_id=%d "
- "mClientStateMask=%" PRIx32 " state=%" PRIx32 ".",
- __FUNCTION__, mId, mClientStateMask, currentBufferState);
- return -EBUSY;
- }
- // Change the buffer state for this consumer from posted to acquired.
- updatedBufferState = currentBufferState ^ mClientStateMask;
- } while (!mBufferState->compare_exchange_weak(currentBufferState, updatedBufferState,
- std::memory_order_acq_rel,
- std::memory_order_acquire));
- // TODO(b/119837586): Update fence state and return GPU fence.
- return 0;
-}
-
-int BufferHubBuffer::release() {
- uint32_t currentBufferState = mBufferState->load(std::memory_order_acquire);
- if (isClientReleased(currentBufferState, mClientStateMask)) {
- ALOGV("%s: Buffer is already released by this client %" PRIx32 ".", __FUNCTION__,
- mClientStateMask);
- return 0;
- }
- uint32_t updatedBufferState = 0U;
- do {
- updatedBufferState = currentBufferState & (~mClientStateMask);
- } while (!mBufferState->compare_exchange_weak(currentBufferState, updatedBufferState,
- std::memory_order_acq_rel,
- std::memory_order_acquire));
- // TODO(b/119837586): Update fence state and return GPU fence if needed.
- return 0;
-}
-
-bool BufferHubBuffer::isReleased() const {
- return (mBufferState->load(std::memory_order_acquire) &
- mActiveClientsBitMask->load(std::memory_order_acquire)) == 0;
-}
-
-bool BufferHubBuffer::isValid() const {
- return mBufferHandle.getNativeHandle() != nullptr && mId >= 0 && mClientStateMask != 0U &&
- mEventFd.get() >= 0 && mMetadata.isValid() && mBufferClient != nullptr;
-}
-
-sp<NativeHandle> BufferHubBuffer::duplicate() {
- if (mBufferClient == nullptr) {
- ALOGE("%s: missing BufferClient!", __FUNCTION__);
- return nullptr;
- }
-
- hidl_handle token;
- BufferHubStatus ret;
- IBufferClient::duplicate_cb dupCb = [&](const auto& outToken, const auto& status) {
- token = std::move(outToken);
- ret = status;
- };
-
- if (!mBufferClient->duplicate(dupCb).isOk()) {
- ALOGE("%s: duplicate transaction failed!", __FUNCTION__);
- return nullptr;
- } else if (ret != BufferHubStatus::NO_ERROR) {
- ALOGE("%s: duplicate failed with error %u.", __FUNCTION__, ret);
- return nullptr;
- } else if (token.getNativeHandle() == nullptr) {
- ALOGE("%s: duplicate got null token.", __FUNCTION__);
- return nullptr;
- }
-
- return NativeHandle::create(native_handle_clone(token.getNativeHandle()), /*ownsHandle=*/true);
-}
-
-} // namespace android
diff --git a/libs/ui/BufferHubEventFd.cpp b/libs/ui/BufferHubEventFd.cpp
deleted file mode 100644
index bffc2ca..0000000
--- a/libs/ui/BufferHubEventFd.cpp
+++ /dev/null
@@ -1,49 +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 <sys/eventfd.h>
-
-#include <log/log.h>
-#include <ui/BufferHubEventFd.h>
-
-namespace android {
-
-BufferHubEventFd::BufferHubEventFd() : mFd(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK)) {}
-
-BufferHubEventFd::BufferHubEventFd(int fd) : mFd(fd) {}
-
-status_t BufferHubEventFd::signal() const {
- if (!isValid()) {
- ALOGE("%s: cannot signal an invalid eventfd.", __FUNCTION__);
- return DEAD_OBJECT;
- }
-
- eventfd_write(mFd.get(), 1);
- return OK;
-}
-
-status_t BufferHubEventFd::clear() const {
- if (!isValid()) {
- ALOGE("%s: cannot clear an invalid eventfd.", __FUNCTION__);
- return DEAD_OBJECT;
- }
-
- eventfd_t value;
- eventfd_read(mFd.get(), &value);
- return OK;
-}
-
-} // namespace android
diff --git a/libs/ui/BufferHubMetadata.cpp b/libs/ui/BufferHubMetadata.cpp
deleted file mode 100644
index 05bc7dd..0000000
--- a/libs/ui/BufferHubMetadata.cpp
+++ /dev/null
@@ -1,104 +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 <errno.h>
-#include <sys/mman.h>
-#include <limits>
-
-#include <cutils/ashmem.h>
-#include <log/log.h>
-#include <ui/BufferHubMetadata.h>
-
-namespace android {
-
-namespace {
-
-static const int kAshmemProt = PROT_READ | PROT_WRITE;
-
-} // namespace
-
-using BufferHubDefs::kMetadataHeaderSize;
-using BufferHubDefs::MetadataHeader;
-
-/* static */
-BufferHubMetadata BufferHubMetadata::create(size_t userMetadataSize) {
- // The size the of metadata buffer is used as the "width" parameter during allocation. Thus it
- // cannot overflow uint32_t.
- if (userMetadataSize >= (std::numeric_limits<uint32_t>::max() - kMetadataHeaderSize)) {
- ALOGE("BufferHubMetadata::Create: metadata size too big: %zu.", userMetadataSize);
- return {};
- }
-
- const size_t metadataSize = userMetadataSize + kMetadataHeaderSize;
- int fd = ashmem_create_region(/*name=*/"BufferHubMetadata", metadataSize);
- if (fd < 0) {
- ALOGE("BufferHubMetadata::Create: failed to create ashmem region.");
- return {};
- }
-
- // Hand over the ownership of the fd to a unique_fd immediately after the successful
- // return of ashmem_create_region. The ashmemFd is going to own the fd and to prevent fd
- // leaks during error handling.
- unique_fd ashmemFd{fd};
-
- if (ashmem_set_prot_region(ashmemFd.get(), kAshmemProt) != 0) {
- ALOGE("BufferHubMetadata::Create: failed to set protect region.");
- return {};
- }
-
- return BufferHubMetadata::import(std::move(ashmemFd));
-}
-
-/* static */
-BufferHubMetadata BufferHubMetadata::import(unique_fd ashmemFd) {
- if (!ashmem_valid(ashmemFd.get())) {
- ALOGE("BufferHubMetadata::Import: invalid ashmem fd.");
- return {};
- }
-
- size_t metadataSize = static_cast<size_t>(ashmem_get_size_region(ashmemFd.get()));
- size_t userMetadataSize = metadataSize - kMetadataHeaderSize;
-
- // Note that here the buffer state is mapped from shared memory as an atomic object. The
- // std::atomic's constructor will not be called so that the original value stored in the memory
- // region can be preserved.
- auto metadataHeader = static_cast<MetadataHeader*>(mmap(nullptr, metadataSize, kAshmemProt,
- MAP_SHARED, ashmemFd.get(),
- /*offset=*/0));
- if (metadataHeader == nullptr) {
- ALOGE("BufferHubMetadata::Import: failed to map region.");
- return {};
- }
-
- return BufferHubMetadata(userMetadataSize, std::move(ashmemFd), metadataHeader);
-}
-
-BufferHubMetadata::BufferHubMetadata(size_t userMetadataSize, unique_fd ashmemFd,
- MetadataHeader* metadataHeader)
- : mUserMetadataSize(userMetadataSize),
- mAshmemFd(std::move(ashmemFd)),
- mMetadataHeader(metadataHeader) {}
-
-BufferHubMetadata::~BufferHubMetadata() {
- if (mMetadataHeader != nullptr) {
- int ret = munmap(mMetadataHeader, metadataSize());
- ALOGE_IF(ret != 0,
- "BufferHubMetadata::~BufferHubMetadata: failed to unmap ashmem, error=%d.", errno);
- mMetadataHeader = nullptr;
- }
-}
-
-} // namespace android
diff --git a/libs/ui/GraphicBuffer.cpp b/libs/ui/GraphicBuffer.cpp
index 05fc590..3732fee 100644
--- a/libs/ui/GraphicBuffer.cpp
+++ b/libs/ui/GraphicBuffer.cpp
@@ -23,10 +23,6 @@
#include <grallocusage/GrallocUsageConversion.h>
-#ifndef LIBUI_IN_VNDK
-#include <ui/BufferHubBuffer.h>
-#endif // LIBUI_IN_VNDK
-
#include <ui/GraphicBufferAllocator.h>
#include <ui/GraphicBufferMapper.h>
#include <utils/Trace.h>
@@ -110,22 +106,6 @@
inUsage, inStride);
}
-#ifndef LIBUI_IN_VNDK
-GraphicBuffer::GraphicBuffer(std::unique_ptr<BufferHubBuffer> buffer) : GraphicBuffer() {
- if (buffer == nullptr) {
- mInitCheck = BAD_VALUE;
- return;
- }
-
- mInitCheck = initWithHandle(buffer->duplicateHandle(), /*method=*/TAKE_UNREGISTERED_HANDLE,
- buffer->desc().width, buffer->desc().height,
- static_cast<PixelFormat>(buffer->desc().format),
- buffer->desc().layers, buffer->desc().usage, buffer->desc().stride);
- mBufferId = buffer->id();
- mBufferHubBuffer = std::move(buffer);
-}
-#endif // LIBUI_IN_VNDK
-
GraphicBuffer::~GraphicBuffer()
{
ATRACE_CALL();
@@ -374,29 +354,14 @@
}
size_t GraphicBuffer::getFlattenedSize() const {
-#ifndef LIBUI_IN_VNDK
- if (mBufferHubBuffer != nullptr) {
- return 48;
- }
-#endif
return static_cast<size_t>(13 + (handle ? mTransportNumInts : 0)) * sizeof(int);
}
size_t GraphicBuffer::getFdCount() const {
-#ifndef LIBUI_IN_VNDK
- if (mBufferHubBuffer != nullptr) {
- return 0;
- }
-#endif
return static_cast<size_t>(handle ? mTransportNumFds : 0);
}
status_t GraphicBuffer::flatten(void*& buffer, size_t& size, int*& fds, size_t& count) const {
-#ifndef LIBUI_IN_VNDK
- if (mBufferHubBuffer != nullptr) {
- return flattenBufferHubBuffer(buffer, size);
- }
-#endif
size_t sizeNeeded = GraphicBuffer::getFlattenedSize();
if (size < sizeNeeded) return NO_MEMORY;
@@ -453,12 +418,6 @@
} else if (buf[0] == 'GBFR') {
// old version, when usage bits were 32-bits
flattenWordCount = 12;
- } else if (buf[0] == 'BHBB') { // BufferHub backed buffer.
-#ifndef LIBUI_IN_VNDK
- return unflattenBufferHubBuffer(buffer, size);
-#else
- return BAD_TYPE;
-#endif
} else {
return BAD_TYPE;
}
@@ -565,76 +524,6 @@
mDeathCallbacks.emplace_back(deathCallback, context);
}
-#ifndef LIBUI_IN_VNDK
-status_t GraphicBuffer::flattenBufferHubBuffer(void*& buffer, size_t& size) const {
- sp<NativeHandle> tokenHandle = mBufferHubBuffer->duplicate();
- if (tokenHandle == nullptr || tokenHandle->handle() == nullptr ||
- tokenHandle->handle()->numFds != 0) {
- return BAD_VALUE;
- }
-
- // Size needed for one label, one number of ints inside the token, one generation number and
- // the token itself.
- int numIntsInToken = tokenHandle->handle()->numInts;
- const size_t sizeNeeded = static_cast<size_t>(3 + numIntsInToken) * sizeof(int);
- if (size < sizeNeeded) {
- ALOGE("%s: needed size %d, given size %d. Not enough memory.", __FUNCTION__,
- static_cast<int>(sizeNeeded), static_cast<int>(size));
- return NO_MEMORY;
- }
- size -= sizeNeeded;
-
- int* buf = static_cast<int*>(buffer);
- buf[0] = 'BHBB';
- buf[1] = numIntsInToken;
- memcpy(buf + 2, tokenHandle->handle()->data, static_cast<size_t>(numIntsInToken) * sizeof(int));
- buf[2 + numIntsInToken] = static_cast<int32_t>(mGenerationNumber);
-
- return NO_ERROR;
-}
-
-status_t GraphicBuffer::unflattenBufferHubBuffer(void const*& buffer, size_t& size) {
- const int* buf = static_cast<const int*>(buffer);
- int numIntsInToken = buf[1];
- // Size needed for one label, one number of ints inside the token, one generation number and
- // the token itself.
- const size_t sizeNeeded = static_cast<size_t>(3 + numIntsInToken) * sizeof(int);
- if (size < sizeNeeded) {
- ALOGE("%s: needed size %d, given size %d. Not enough memory.", __FUNCTION__,
- static_cast<int>(sizeNeeded), static_cast<int>(size));
- return NO_MEMORY;
- }
- size -= sizeNeeded;
- native_handle_t* importToken = native_handle_create(/*numFds=*/0, /*numInts=*/numIntsInToken);
- memcpy(importToken->data, buf + 2, static_cast<size_t>(buf[1]) * sizeof(int));
- sp<NativeHandle> importTokenHandle = NativeHandle::create(importToken, /*ownHandle=*/true);
- std::unique_ptr<BufferHubBuffer> bufferHubBuffer = BufferHubBuffer::import(importTokenHandle);
- if (bufferHubBuffer == nullptr || bufferHubBuffer.get() == nullptr) {
- return BAD_VALUE;
- }
- // Reconstruct this GraphicBuffer object using the new BufferHubBuffer object.
- if (handle) {
- free_handle();
- }
- mId = 0;
- mGenerationNumber = static_cast<uint32_t>(buf[2 + numIntsInToken]);
- mInitCheck =
- initWithHandle(bufferHubBuffer->duplicateHandle(), /*method=*/TAKE_UNREGISTERED_HANDLE,
- bufferHubBuffer->desc().width, bufferHubBuffer->desc().height,
- static_cast<PixelFormat>(bufferHubBuffer->desc().format),
- bufferHubBuffer->desc().layers, bufferHubBuffer->desc().usage,
- bufferHubBuffer->desc().stride);
- mBufferId = bufferHubBuffer->id();
- mBufferHubBuffer = std::move(bufferHubBuffer);
-
- return NO_ERROR;
-}
-
-bool GraphicBuffer::isBufferHubBuffer() const {
- return mBufferHubBuffer != nullptr;
-}
-#endif // LIBUI_IN_VNDK
-
// ---------------------------------------------------------------------------
}; // namespace android
diff --git a/libs/ui/OWNERS b/libs/ui/OWNERS
index 97ead21..203a739 100644
--- a/libs/ui/OWNERS
+++ b/libs/ui/OWNERS
@@ -1,7 +1,6 @@
+chrisforbes@google.com
lpy@google.com
-marissaw@google.com
mathias@google.com
romainguy@google.com
stoza@google.com
-jwcai@google.com
-tianyuj@google.com
+vhau@google.com
diff --git a/libs/ui/include/ui/BufferHubBuffer.h b/libs/ui/include/ui/BufferHubBuffer.h
deleted file mode 100644
index 5ba189c..0000000
--- a/libs/ui/include/ui/BufferHubBuffer.h
+++ /dev/null
@@ -1,144 +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.
- */
-
-#ifndef ANDROID_BUFFER_HUB_BUFFER_H_
-#define ANDROID_BUFFER_HUB_BUFFER_H_
-
-#include <android/frameworks/bufferhub/1.0/IBufferClient.h>
-#include <android/hardware_buffer.h>
-#include <cutils/native_handle.h>
-#include <ui/BufferHubDefs.h>
-#include <ui/BufferHubEventFd.h>
-#include <ui/BufferHubMetadata.h>
-#include <utils/NativeHandle.h>
-
-namespace android {
-
-class BufferHubBuffer {
-public:
- // Allocates a standalone BufferHubBuffer.
- static std::unique_ptr<BufferHubBuffer> create(uint32_t width, uint32_t height,
- uint32_t layerCount, uint32_t format,
- uint64_t usage, size_t userMetadataSize);
-
- // Imports the given token to a BufferHubBuffer. Not taking ownership of the token.
- static std::unique_ptr<BufferHubBuffer> import(const sp<NativeHandle>& token);
-
- BufferHubBuffer(const BufferHubBuffer&) = delete;
- void operator=(const BufferHubBuffer&) = delete;
-
- virtual ~BufferHubBuffer();
-
- // Gets ID of the buffer client. All BufferHubBuffer clients derived from the same buffer in
- // BufferHub share the same buffer id.
- int id() const { return mId; }
-
- // Returns the buffer description, which is guaranteed to be faithful values from BufferHub.
- const AHardwareBuffer_Desc& desc() const { return mBufferDesc; }
-
- // Duplicate the underlying Gralloc buffer handle. Caller is responsible to free the handle
- // after use.
- native_handle_t* duplicateHandle() {
- return native_handle_clone(mBufferHandle.getNativeHandle());
- }
-
- const BufferHubEventFd& eventFd() const { return mEventFd; }
-
- // Returns the current value of MetadataHeader::bufferState.
- uint32_t bufferState() const { return mBufferState->load(std::memory_order_acquire); }
-
- // A state mask which is unique to a buffer hub client among all its siblings sharing the same
- // concrete graphic buffer.
- uint32_t clientStateMask() const { return mClientStateMask; }
-
- size_t userMetadataSize() const { return mMetadata.userMetadataSize(); }
-
- // Returns true if the BufferClient is still alive.
- bool isConnected() const { return mBufferClient->ping().isOk(); }
-
- // Returns true if the buffer is valid: non-null buffer handle, valid id, valid client bit mask,
- // valid metadata and valid buffer client
- bool isValid() const;
-
- // Gains the buffer for exclusive write permission. Read permission is implied once a buffer is
- // gained.
- // The buffer can be gained as long as there is no other client in acquired or gained state.
- int gain();
-
- // Posts the gained buffer for other buffer clients to use the buffer.
- // The buffer can be posted iff the buffer state for this client is gained.
- // After posting the buffer, this client is put to released state and does not have access to
- // the buffer for this cycle of the usage of the buffer.
- int post();
-
- // Acquires the buffer for shared read permission.
- // The buffer can be acquired iff the buffer state for this client is posted.
- int acquire();
-
- // Releases the buffer.
- // The buffer can be released from any buffer state.
- // After releasing the buffer, this client no longer have any permissions to the buffer for the
- // current cycle of the usage of the buffer.
- int release();
-
- // Returns whether the buffer is released by all active clients or not.
- bool isReleased() const;
-
- // Creates a token that stands for this BufferHubBuffer client and could be used for Import to
- // create another BufferHubBuffer. The new BufferHubBuffer will share the same underlying
- // gralloc buffer and ashmem region for metadata. Not taking ownership of the token.
- // Returns a valid token on success, nullptr on failure.
- sp<NativeHandle> duplicate();
-
-private:
- BufferHubBuffer(uint32_t width, uint32_t height, uint32_t layerCount, uint32_t format,
- uint64_t usage, size_t userMetadataSize);
-
- BufferHubBuffer(const sp<NativeHandle>& token);
-
- int initWithBufferTraits(const frameworks::bufferhub::V1_0::BufferTraits& bufferTraits);
-
- // Global id for the buffer that is consistent across processes.
- int mId = 0;
-
- // Client state mask of this BufferHubBuffer object. It is unique amoung all
- // clients/users of the buffer.
- uint32_t mClientStateMask = 0U;
-
- // Stores ground truth of the buffer.
- AHardwareBuffer_Desc mBufferDesc;
-
- // Wraps the gralloc buffer handle of this buffer.
- hardware::hidl_handle mBufferHandle;
-
- // Event fd used for signalling buffer state changes. Shared by all clients of the same buffer.
- BufferHubEventFd mEventFd;
-
- // An ashmem-based metadata object. The same shared memory are mapped to the
- // bufferhubd daemon and all buffer clients.
- BufferHubMetadata mMetadata;
- // Shortcuts to the atomics inside the header of mMetadata.
- std::atomic<uint32_t>* mBufferState = nullptr;
- std::atomic<uint32_t>* mFenceState = nullptr;
- std::atomic<uint32_t>* mActiveClientsBitMask = nullptr;
-
- // HwBinder backend
- sp<frameworks::bufferhub::V1_0::IBufferClient> mBufferClient;
-};
-
-} // namespace android
-
-#endif // ANDROID_BUFFER_HUB_BUFFER_H_
diff --git a/libs/ui/include/ui/BufferHubEventFd.h b/libs/ui/include/ui/BufferHubEventFd.h
deleted file mode 100644
index 8772304..0000000
--- a/libs/ui/include/ui/BufferHubEventFd.h
+++ /dev/null
@@ -1,65 +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.
- */
-
-#ifndef ANDROID_BUFFER_HUB_EVENT_FD_H_
-#define ANDROID_BUFFER_HUB_EVENT_FD_H_
-
-#include <android-base/unique_fd.h>
-#include <utils/Errors.h>
-
-namespace android {
-
-class BufferHubEventFd {
-public:
- /**
- * Constructs a valid event fd.
- */
- BufferHubEventFd();
-
- /**
- * Constructs from a valid event fd. Caller is responsible for the validity of the fd. Takes
- * ownership.
- */
- BufferHubEventFd(int fd);
-
- /**
- * Returns whether this BufferHubEventFd holds a valid event_fd.
- */
- bool isValid() const { return get() >= 0; }
-
- /**
- * Returns the fd number of the BufferHubEventFd object. Note that there is no ownership
- * transfer.
- */
- int get() const { return mFd.get(); }
-
- /**
- * Signals the eventfd.
- */
- status_t signal() const;
-
- /**
- * Clears the signal from this eventfd if it is signaled.
- */
- status_t clear() const;
-
-private:
- base::unique_fd mFd;
-};
-
-} // namespace android
-
-#endif // ANDROID_BUFFER_HUB_EVENT_FD_H_
diff --git a/libs/ui/include/ui/BufferHubMetadata.h b/libs/ui/include/ui/BufferHubMetadata.h
deleted file mode 100644
index 3482507..0000000
--- a/libs/ui/include/ui/BufferHubMetadata.h
+++ /dev/null
@@ -1,88 +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.
- */
-
-#ifndef ANDROID_BUFFER_HUB_METADATA_H_
-#define ANDROID_BUFFER_HUB_METADATA_H_
-
-#include <android-base/unique_fd.h>
-#include <ui/BufferHubDefs.h>
-
-namespace android {
-
-namespace {
-using base::unique_fd;
-} // namespace
-
-class BufferHubMetadata {
-public:
- // Creates a new BufferHubMetadata backed by an ashmem region.
- //
- // @param userMetadataSize Size in bytes of the user defined metadata. The entire metadata
- // shared memory region to be allocated is the size of canonical
- // BufferHubDefs::MetadataHeader plus userMetadataSize.
- static BufferHubMetadata create(size_t userMetadataSize);
-
- // Imports an existing BufferHubMetadata from an ashmem FD.
- //
- // @param ashmemFd Ashmem file descriptor representing an ashmem region.
- static BufferHubMetadata import(unique_fd ashmemFd);
-
- BufferHubMetadata() = default;
-
- BufferHubMetadata(BufferHubMetadata&& other) { *this = std::move(other); }
-
- ~BufferHubMetadata();
-
- BufferHubMetadata& operator=(BufferHubMetadata&& other) {
- if (this != &other) {
- mUserMetadataSize = other.mUserMetadataSize;
- other.mUserMetadataSize = 0;
-
- mAshmemFd = std::move(other.mAshmemFd);
-
- // The old raw mMetadataHeader pointer must be cleared, otherwise the destructor will
- // automatically mummap() the shared memory.
- mMetadataHeader = other.mMetadataHeader;
- other.mMetadataHeader = nullptr;
- }
- return *this;
- }
-
- // Returns true if the metadata is valid, i.e. the metadata has a valid ashmem fd and the ashmem
- // has been mapped into virtual address space.
- bool isValid() const { return mAshmemFd.get() != -1 && mMetadataHeader != nullptr; }
-
- size_t userMetadataSize() const { return mUserMetadataSize; }
- size_t metadataSize() const { return mUserMetadataSize + BufferHubDefs::kMetadataHeaderSize; }
-
- const unique_fd& ashmemFd() const { return mAshmemFd; }
- BufferHubDefs::MetadataHeader* metadataHeader() { return mMetadataHeader; }
-
-private:
- BufferHubMetadata(size_t userMetadataSize, unique_fd ashmemFd,
- BufferHubDefs::MetadataHeader* metadataHeader);
-
- BufferHubMetadata(const BufferHubMetadata&) = delete;
- void operator=(const BufferHubMetadata&) = delete;
-
- size_t mUserMetadataSize = 0;
- unique_fd mAshmemFd;
- BufferHubDefs::MetadataHeader* mMetadataHeader = nullptr;
-};
-
-} // namespace android
-
-#endif // ANDROID_BUFFER_HUB_METADATA_H_
diff --git a/libs/ui/include/ui/GraphicBuffer.h b/libs/ui/include/ui/GraphicBuffer.h
index c195342..013505a 100644
--- a/libs/ui/include/ui/GraphicBuffer.h
+++ b/libs/ui/include/ui/GraphicBuffer.h
@@ -38,10 +38,6 @@
namespace android {
-#ifndef LIBUI_IN_VNDK
-class BufferHubBuffer;
-#endif // LIBUI_IN_VNDK
-
class GraphicBufferMapper;
using GraphicBufferDeathCallback = std::function<void(void* /*context*/, uint64_t bufferId)>;
@@ -147,11 +143,6 @@
GraphicBuffer(uint32_t inWidth, uint32_t inHeight, PixelFormat inFormat,
uint32_t inUsage, std::string requestorName = "<Unknown>");
-#ifndef LIBUI_IN_VNDK
- // Create a GraphicBuffer from an existing BufferHubBuffer.
- GraphicBuffer(std::unique_ptr<BufferHubBuffer> buffer);
-#endif // LIBUI_IN_VNDK
-
// return status
status_t initCheck() const;
@@ -163,7 +154,6 @@
uint32_t getLayerCount() const { return static_cast<uint32_t>(layerCount); }
Rect getBounds() const { return Rect(width, height); }
uint64_t getId() const { return mId; }
- int32_t getBufferId() const { return mBufferId; }
uint32_t getGenerationNumber() const { return mGenerationNumber; }
void setGenerationNumber(uint32_t generation) {
@@ -225,11 +215,6 @@
void addDeathCallback(GraphicBufferDeathCallback deathCallback, void* context);
-#ifndef LIBUI_IN_VNDK
- // Returns whether this GraphicBuffer is backed by BufferHubBuffer.
- bool isBufferHubBuffer() const;
-#endif // LIBUI_IN_VNDK
-
private:
~GraphicBuffer();
@@ -275,12 +260,6 @@
uint64_t mId;
- // System unique buffer ID. Note that this is different from mId, which is process unique. For
- // GraphicBuffer backed by BufferHub, the mBufferId is a system unique identifier that stays the
- // same cross process for the same chunck of underlying memory. Also note that this only applies
- // to GraphicBuffers that are backed by BufferHub.
- int32_t mBufferId = -1;
-
// Stores the generation number of this buffer. If this number does not
// match the BufferQueue's internal generation number (set through
// IGBP::setGenerationNumber), attempts to attach the buffer will fail.
@@ -299,22 +278,6 @@
// and informs SurfaceFlinger that it should drop its strong pointer reference to the buffer.
std::vector<std::pair<GraphicBufferDeathCallback, void* /*mDeathCallbackContext*/>>
mDeathCallbacks;
-
-#ifndef LIBUI_IN_VNDK
- // Flatten this GraphicBuffer object if backed by BufferHubBuffer.
- status_t flattenBufferHubBuffer(void*& buffer, size_t& size) const;
-
- // Unflatten into BufferHubBuffer backed GraphicBuffer.
- // Unflatten will fail if the original GraphicBuffer object is destructed. For instance, a
- // GraphicBuffer backed by BufferHubBuffer_1 flatten in process/thread A, transport the token
- // to process/thread B through a socket, BufferHubBuffer_1 dies and bufferhub invalidated the
- // token. Race condition occurs between the invalidation of the token in bufferhub process and
- // process/thread B trying to unflatten and import the buffer with that token.
- status_t unflattenBufferHubBuffer(void const*& buffer, size_t& size);
-
- // Stores a BufferHubBuffer that handles buffer signaling, identification.
- std::unique_ptr<BufferHubBuffer> mBufferHubBuffer;
-#endif // LIBUI_IN_VNDK
};
}; // namespace android
diff --git a/libs/ui/tests/Android.bp b/libs/ui/tests/Android.bp
index 605c5a9..b53342c 100644
--- a/libs/ui/tests/Android.bp
+++ b/libs/ui/tests/Android.bp
@@ -31,7 +31,6 @@
cc_test {
name: "GraphicBufferAllocator_test",
header_libs: [
- "libdvr_headers",
"libnativewindow_headers",
],
static_libs: [
@@ -52,11 +51,9 @@
cc_test {
name: "GraphicBuffer_test",
header_libs: [
- "libdvr_headers",
"libnativewindow_headers",
],
shared_libs: [
- "android.frameworks.bufferhub@1.0",
"libcutils",
"libhidlbase",
"libui",
@@ -71,11 +68,7 @@
name: "GraphicBufferOverBinder_test",
srcs: ["GraphicBufferOverBinder_test.cpp"],
cflags: ["-Wall", "-Werror"],
- header_libs: [
- "libdvr_headers",
- ],
shared_libs: [
- "android.frameworks.bufferhub@1.0",
"libbinder",
"libgui",
"liblog",
@@ -85,31 +78,6 @@
}
cc_test {
- name: "BufferHub_test",
- header_libs: [
- "libdvr_headers",
- "libnativewindow_headers",
- ],
- static_libs: [
- "libgmock",
- ],
- shared_libs: [
- "android.frameworks.bufferhub@1.0",
- "libcutils",
- "libhidlbase",
- "liblog",
- "libui",
- "libutils"
- ],
- srcs: [
- "BufferHubBuffer_test.cpp",
- "BufferHubEventFd_test.cpp",
- "BufferHubMetadata_test.cpp",
- ],
- cflags: ["-Wall", "-Werror"],
-}
-
-cc_test {
name: "Size_test",
test_suites: ["device-tests"],
shared_libs: ["libui"],
diff --git a/libs/ui/tests/BufferHubBuffer_test.cpp b/libs/ui/tests/BufferHubBuffer_test.cpp
deleted file mode 100644
index 0c73a72..0000000
--- a/libs/ui/tests/BufferHubBuffer_test.cpp
+++ /dev/null
@@ -1,477 +0,0 @@
-/*
- * 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.
- */
-
-#define LOG_TAG "BufferHubBufferTest"
-
-#include <errno.h>
-#include <sys/epoll.h>
-
-#include <android/frameworks/bufferhub/1.0/IBufferHub.h>
-#include <android/hardware_buffer.h>
-#include <cutils/native_handle.h>
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-#include <hidl/ServiceManagement.h>
-#include <hwbinder/IPCThreadState.h>
-#include <ui/BufferHubBuffer.h>
-#include <ui/BufferHubEventFd.h>
-
-namespace android {
-
-namespace {
-
-using ::android::BufferHubDefs::isAnyClientAcquired;
-using ::android::BufferHubDefs::isAnyClientGained;
-using ::android::BufferHubDefs::isAnyClientPosted;
-using ::android::BufferHubDefs::isClientAcquired;
-using ::android::BufferHubDefs::isClientGained;
-using ::android::BufferHubDefs::isClientPosted;
-using ::android::BufferHubDefs::isClientReleased;
-using ::android::BufferHubDefs::kMetadataHeaderSize;
-using ::android::frameworks::bufferhub::V1_0::IBufferHub;
-using ::testing::IsNull;
-using ::testing::NotNull;
-
-const int kWidth = 640;
-const int kHeight = 480;
-const int kLayerCount = 1;
-const int kFormat = HAL_PIXEL_FORMAT_RGBA_8888;
-const int kUsage = 0;
-const AHardwareBuffer_Desc kDesc = {kWidth, kHeight, kLayerCount, kFormat,
- kUsage, /*stride=*/0UL, /*rfu0=*/0UL, /*rfu1=*/0ULL};
-const size_t kUserMetadataSize = 1;
-
-class BufferHubBufferTest : public ::testing::Test {
-protected:
- void SetUp() override {
- android::hardware::ProcessState::self()->startThreadPool();
-
- if (!BufferHubServiceRunning()) {
- // TODO(b/112940221): Enforce the test cross all devices once BufferHub lands in Android
- // R for all Android varieties.
- GTEST_SKIP() << "Skip test as the BufferHub service is not running.";
- }
- }
-
- bool BufferHubServiceRunning() {
- sp<IBufferHub> bufferhub = IBufferHub::getService();
- return bufferhub.get() != nullptr;
- }
-};
-
-bool cmpAHardwareBufferDesc(const AHardwareBuffer_Desc& desc, const AHardwareBuffer_Desc& other) {
- // Not comparing stride because it's unknown before allocation
- return desc.format == other.format && desc.height == other.height &&
- desc.layers == other.layers && desc.usage == other.usage && desc.width == other.width;
-}
-
-class BufferHubBufferStateTransitionTest : public BufferHubBufferTest {
-protected:
- void SetUp() override {
- BufferHubBufferTest::SetUp();
-
- if (IsSkipped()) {
- // If the base class' SetUp() stated the test should be skipped, we should short
- // circuit this sub-class' logic.
- return;
- }
-
- CreateTwoClientsOfABuffer();
- }
-
- std::unique_ptr<BufferHubBuffer> b1;
- uint32_t b1ClientMask = 0U;
- std::unique_ptr<BufferHubBuffer> b2;
- uint32_t b2ClientMask = 0U;
-
-private:
- // Creates b1 and b2 as the clients of the same buffer for testing.
- void CreateTwoClientsOfABuffer();
-};
-
-void BufferHubBufferStateTransitionTest::CreateTwoClientsOfABuffer() {
- b1 = BufferHubBuffer::create(kWidth, kHeight, kLayerCount, kFormat, kUsage, kUserMetadataSize);
- ASSERT_THAT(b1, NotNull());
- b1ClientMask = b1->clientStateMask();
- ASSERT_NE(b1ClientMask, 0U);
-
- sp<NativeHandle> token = b1->duplicate();
- ASSERT_THAT(token, NotNull());
-
- b2 = BufferHubBuffer::import(token);
- ASSERT_THAT(b2, NotNull());
-
- b2ClientMask = b2->clientStateMask();
- ASSERT_NE(b2ClientMask, 0U);
- ASSERT_NE(b2ClientMask, b1ClientMask);
-}
-
-TEST_F(BufferHubBufferTest, CreateBufferFails) {
- // Buffer Creation will fail: BLOB format requires height to be 1.
- auto b1 = BufferHubBuffer::create(kWidth, /*height=*/2, kLayerCount,
- /*format=*/HAL_PIXEL_FORMAT_BLOB, kUsage, kUserMetadataSize);
-
- EXPECT_THAT(b1, IsNull());
-
- // Buffer Creation will fail: user metadata size too large.
- auto b2 = BufferHubBuffer::create(kWidth, kHeight, kLayerCount, kFormat, kUsage,
- /*userMetadataSize=*/std::numeric_limits<size_t>::max());
-
- EXPECT_THAT(b2, IsNull());
-
- // Buffer Creation will fail: user metadata size too large.
- const size_t userMetadataSize = std::numeric_limits<size_t>::max() - kMetadataHeaderSize;
- auto b3 = BufferHubBuffer::create(kWidth, kHeight, kLayerCount, kFormat, kUsage,
- userMetadataSize);
-
- EXPECT_THAT(b3, IsNull());
-}
-
-TEST_F(BufferHubBufferTest, CreateBuffer) {
- auto b1 = BufferHubBuffer::create(kWidth, kHeight, kLayerCount, kFormat, kUsage,
- kUserMetadataSize);
- ASSERT_THAT(b1, NotNull());
- EXPECT_TRUE(b1->isConnected());
- EXPECT_TRUE(b1->isValid());
- EXPECT_TRUE(cmpAHardwareBufferDesc(b1->desc(), kDesc));
- EXPECT_EQ(b1->userMetadataSize(), kUserMetadataSize);
-}
-
-TEST_F(BufferHubBufferTest, DuplicateAndImportBuffer) {
- auto b1 = BufferHubBuffer::create(kWidth, kHeight, kLayerCount, kFormat, kUsage,
- kUserMetadataSize);
- ASSERT_THAT(b1, NotNull());
- EXPECT_TRUE(b1->isValid());
-
- sp<NativeHandle> token = b1->duplicate();
- ASSERT_THAT(token, NotNull());
-
- // The detached buffer should still be valid.
- EXPECT_TRUE(b1->isConnected());
- EXPECT_TRUE(b1->isValid());
-
- std::unique_ptr<BufferHubBuffer> b2 = BufferHubBuffer::import(token);
-
- ASSERT_THAT(b2, NotNull());
- EXPECT_TRUE(b2->isValid());
-
- EXPECT_TRUE(cmpAHardwareBufferDesc(b1->desc(), b2->desc()));
- EXPECT_EQ(b1->userMetadataSize(), b2->userMetadataSize());
-
- // These two buffer instances are based on the same physical buffer under the
- // hood, so they should share the same id.
- EXPECT_EQ(b1->id(), b2->id());
- // We use clientStateMask() to tell those two instances apart.
- EXPECT_NE(b1->clientStateMask(), b2->clientStateMask());
-
- // Both buffer instances should be in released state currently.
- EXPECT_TRUE(b1->isReleased());
- EXPECT_TRUE(b2->isReleased());
-
- // The event fd should behave like duped event fds.
- const BufferHubEventFd& eventFd1 = b1->eventFd();
- ASSERT_GE(eventFd1.get(), 0);
- const BufferHubEventFd& eventFd2 = b2->eventFd();
- ASSERT_GE(eventFd2.get(), 0);
-
- base::unique_fd epollFd(epoll_create(64));
- ASSERT_GE(epollFd.get(), 0);
-
- // Add eventFd1 to epoll set, and signal eventFd2.
- epoll_event e = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 0}};
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd1.get(), &e), 0) << strerror(errno);
-
- std::array<epoll_event, 1> events;
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-
- eventFd2.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
-
- // The epoll fd is edge triggered, so it only responds to the eventFd once.
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-
- eventFd2.signal();
- eventFd2.clear();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-}
-
-TEST_F(BufferHubBufferTest, ImportFreedBuffer) {
- auto b1 = BufferHubBuffer::create(kWidth, kHeight, kLayerCount, kFormat, kUsage,
- kUserMetadataSize);
- ASSERT_THAT(b1, NotNull());
- EXPECT_TRUE(b1->isValid());
-
- sp<NativeHandle> token = b1->duplicate();
- ASSERT_THAT(token, NotNull());
-
- // Explicitly destroy b1. Backend buffer should be freed and token becomes invalid
- b1.reset();
-
- std::unique_ptr<BufferHubBuffer> b2 = BufferHubBuffer::import(token);
-
- // Import should fail with INVALID_TOKEN
- EXPECT_THAT(b2, IsNull());
-}
-
-// nullptr must not crash the service
-TEST_F(BufferHubBufferTest, ImportNullToken) {
- auto b1 = BufferHubBuffer::import(nullptr);
- EXPECT_THAT(b1, IsNull());
-}
-
-TEST_F(BufferHubBufferTest, ImportInvalidToken) {
- native_handle_t* token = native_handle_create(/*numFds=*/0, /*numInts=*/1);
- token->data[0] = 0;
-
- sp<NativeHandle> tokenHandle = NativeHandle::create(token, /*ownHandle=*/true);
- auto b1 = BufferHubBuffer::import(tokenHandle);
-
- EXPECT_THAT(b1, IsNull());
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, GainBuffer_fromReleasedState) {
- ASSERT_TRUE(b1->isReleased());
-
- // Successful gaining the buffer should change the buffer state bit of b1 to
- // gained state, other client state bits to released state.
- EXPECT_EQ(b1->gain(), 0);
- EXPECT_TRUE(isClientGained(b1->bufferState(), b1ClientMask));
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, GainBuffer_fromGainedState) {
- ASSERT_EQ(b1->gain(), 0);
- auto currentBufferState = b1->bufferState();
- ASSERT_TRUE(isClientGained(currentBufferState, b1ClientMask));
-
- // Gaining from gained state by the same client should not return error.
- EXPECT_EQ(b1->gain(), 0);
-
- // Gaining from gained state by another client should return error.
- EXPECT_EQ(b2->gain(), -EBUSY);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, GainBuffer_fromAcquiredState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_EQ(b2->acquire(), 0);
- ASSERT_TRUE(isAnyClientAcquired(b1->bufferState()));
-
- // Gaining from acquired state should fail.
- EXPECT_EQ(b1->gain(), -EBUSY);
- EXPECT_EQ(b2->gain(), -EBUSY);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, GainBuffer_fromOtherClientInPostedState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_TRUE(isAnyClientPosted(b1->bufferState()));
-
- // Gaining a buffer who has other posted client should succeed.
- EXPECT_EQ(b1->gain(), 0);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, GainBuffer_fromSelfInPostedState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_TRUE(isAnyClientPosted(b1->bufferState()));
-
- // A posted client should be able to gain the buffer when there is no other clients in
- // acquired state.
- EXPECT_EQ(b2->gain(), 0);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, PostBuffer_fromOtherInGainedState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_TRUE(isClientGained(b1->bufferState(), b1ClientMask));
-
- EXPECT_EQ(b2->post(), -EBUSY);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, PostBuffer_fromSelfInGainedState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_TRUE(isClientGained(b1->bufferState(), b1ClientMask));
-
- EXPECT_EQ(b1->post(), 0);
- auto currentBufferState = b1->bufferState();
- EXPECT_TRUE(isClientReleased(currentBufferState, b1ClientMask));
- EXPECT_TRUE(isClientPosted(currentBufferState, b2ClientMask));
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, PostBuffer_fromPostedState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_TRUE(isAnyClientPosted(b1->bufferState()));
-
- // Post from posted state should fail.
- EXPECT_EQ(b1->post(), -EBUSY);
- EXPECT_EQ(b2->post(), -EBUSY);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, PostBuffer_fromAcquiredState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_EQ(b2->acquire(), 0);
- ASSERT_TRUE(isAnyClientAcquired(b1->bufferState()));
-
- // Posting from acquired state should fail.
- EXPECT_EQ(b1->post(), -EBUSY);
- EXPECT_EQ(b2->post(), -EBUSY);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, PostBuffer_fromReleasedState) {
- ASSERT_TRUE(b1->isReleased());
-
- // Posting from released state should fail.
- EXPECT_EQ(b1->post(), -EBUSY);
- EXPECT_EQ(b2->post(), -EBUSY);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, AcquireBuffer_fromSelfInPostedState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_TRUE(isClientPosted(b1->bufferState(), b2ClientMask));
-
- // Acquire from posted state should pass.
- EXPECT_EQ(b2->acquire(), 0);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, AcquireBuffer_fromOtherInPostedState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_TRUE(isClientPosted(b1->bufferState(), b2ClientMask));
-
- // Acquire from released state should fail, although there are other clients
- // in posted state.
- EXPECT_EQ(b1->acquire(), -EBUSY);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, AcquireBuffer_fromSelfInAcquiredState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_EQ(b2->acquire(), 0);
- auto currentBufferState = b1->bufferState();
- ASSERT_TRUE(isClientAcquired(currentBufferState, b2ClientMask));
-
- // Acquiring from acquired state by the same client should not error out.
- EXPECT_EQ(b2->acquire(), 0);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, AcquireBuffer_fromReleasedState) {
- ASSERT_TRUE(b1->isReleased());
-
- // Acquiring form released state should fail.
- EXPECT_EQ(b1->acquire(), -EBUSY);
- EXPECT_EQ(b2->acquire(), -EBUSY);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, AcquireBuffer_fromGainedState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_TRUE(isAnyClientGained(b1->bufferState()));
-
- // Acquiring from gained state should fail.
- EXPECT_EQ(b1->acquire(), -EBUSY);
- EXPECT_EQ(b2->acquire(), -EBUSY);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, ReleaseBuffer_fromSelfInReleasedState) {
- ASSERT_TRUE(b1->isReleased());
-
- EXPECT_EQ(b1->release(), 0);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, ReleaseBuffer_fromSelfInGainedState) {
- ASSERT_TRUE(b1->isReleased());
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_TRUE(isAnyClientGained(b1->bufferState()));
-
- EXPECT_EQ(b1->release(), 0);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, ReleaseBuffer_fromSelfInPostedState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_TRUE(isAnyClientPosted(b1->bufferState()));
-
- EXPECT_EQ(b2->release(), 0);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, ReleaseBuffer_fromSelfInAcquiredState) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_EQ(b2->acquire(), 0);
- ASSERT_TRUE(isAnyClientAcquired(b1->bufferState()));
-
- EXPECT_EQ(b2->release(), 0);
-}
-
-TEST_F(BufferHubBufferStateTransitionTest, BasicUsage) {
- // 1 producer buffer and 1 consumer buffer initialised in testcase setup.
- // Test if this set of basic operation succeed:
- // Producer post three times to the consumer, and released by consumer.
- for (int i = 0; i < 3; ++i) {
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
- ASSERT_EQ(b2->acquire(), 0);
- ASSERT_EQ(b2->release(), 0);
- }
-}
-
-TEST_F(BufferHubBufferTest, createNewConsumerAfterGain) {
- // Create a poducer buffer and gain.
- std::unique_ptr<BufferHubBuffer> b1 =
- BufferHubBuffer::create(kWidth, kHeight, kLayerCount, kFormat, kUsage,
- kUserMetadataSize);
- ASSERT_THAT(b1, NotNull());
- ASSERT_EQ(b1->gain(), 0);
-
- // Create a consumer of the buffer and test if the consumer can acquire the
- // buffer if producer posts.
- sp<NativeHandle> token = b1->duplicate();
- ASSERT_THAT(token, NotNull());
-
- std::unique_ptr<BufferHubBuffer> b2 = BufferHubBuffer::import(token);
-
- ASSERT_THAT(b2, NotNull());
- ASSERT_NE(b1->clientStateMask(), b2->clientStateMask());
-
- ASSERT_EQ(b1->post(), 0);
- EXPECT_EQ(b2->acquire(), 0);
-}
-
-TEST_F(BufferHubBufferTest, createNewConsumerAfterPost) {
- // Create a poducer buffer and post.
- std::unique_ptr<BufferHubBuffer> b1 =
- BufferHubBuffer::create(kWidth, kHeight, kLayerCount, kFormat, kUsage,
- kUserMetadataSize);
- ASSERT_EQ(b1->gain(), 0);
- ASSERT_EQ(b1->post(), 0);
-
- // Create a consumer of the buffer and test if the consumer can acquire the
- // buffer if producer posts.
- sp<NativeHandle> token = b1->duplicate();
- ASSERT_THAT(token, NotNull());
-
- std::unique_ptr<BufferHubBuffer> b2 = BufferHubBuffer::import(token);
-
- ASSERT_THAT(b2, NotNull());
- ASSERT_NE(b1->clientStateMask(), b2->clientStateMask());
-
- EXPECT_EQ(b2->acquire(), 0);
-}
-
-} // namespace
-
-} // namespace android
diff --git a/libs/ui/tests/BufferHubEventFd_test.cpp b/libs/ui/tests/BufferHubEventFd_test.cpp
deleted file mode 100644
index ef1781f..0000000
--- a/libs/ui/tests/BufferHubEventFd_test.cpp
+++ /dev/null
@@ -1,428 +0,0 @@
-/*
- * 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.
- */
-
-#define LOG_TAG "BufferHubEventFdTest"
-
-#include <sys/epoll.h>
-#include <sys/eventfd.h>
-
-#include <array>
-#include <condition_variable>
-#include <mutex>
-#include <thread>
-
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-#include <log/log.h>
-#include <ui/BufferHubEventFd.h>
-
-namespace android {
-
-namespace {
-
-const int kTimeout = 100;
-const std::chrono::milliseconds kTimeoutMs(kTimeout);
-const int kTestRuns = 5;
-
-using ::testing::Contains;
-using BufferHubEventFdTest = ::testing::Test;
-
-} // namespace
-
-TEST_F(BufferHubEventFdTest, EventFd_testSingleEpollFd) {
- BufferHubEventFd eventFd;
- ASSERT_TRUE(eventFd.isValid());
-
- base::unique_fd epollFd(epoll_create(64));
- ASSERT_GE(epollFd.get(), 0);
-
- epoll_event e = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 0}};
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
-
- std::array<epoll_event, 1> events;
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-
- eventFd.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
-
- // The epoll fd is edge triggered, so it only responds to the eventFd once.
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-
- // Check that it can receive consecutive signal.
- eventFd.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-
- // Check that it can receive consecutive signal from a duplicated eventfd.
- BufferHubEventFd dupEventFd(dup(eventFd.get()));
- ASSERT_TRUE(dupEventFd.isValid());
- dupEventFd.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
- dupEventFd.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-}
-
-TEST_F(BufferHubEventFdTest, EventFd_testCreateEpollFdAndAddSignaledEventFd) {
- BufferHubEventFd eventFd;
- ASSERT_TRUE(eventFd.isValid());
- eventFd.signal();
-
- base::unique_fd epollFd(epoll_create(64));
- ASSERT_GE(epollFd.get(), 0);
-
- // Make sure that the epoll set has not been signal yet.
- std::array<epoll_event, 1> events;
- ASSERT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-
- // Check that adding an signaled fd into this epoll set will trigger the epoll set.
- epoll_event e = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 0}};
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
-
- // The epoll fd is edge triggered, so it only responds to the eventFd once.
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-}
-
-TEST_F(BufferHubEventFdTest, EventFd_testAddSignaledEventFdToEpollFd) {
- BufferHubEventFd eventFd;
- ASSERT_TRUE(eventFd.isValid());
-
- base::unique_fd epollFd(epoll_create(64));
- ASSERT_GE(epollFd.get(), 0);
-
- eventFd.signal();
-
- epoll_event e = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 0}};
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
-
- std::array<epoll_event, 1> events;
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
-
- // The epoll fd is edge triggered, so it only responds to the eventFd once.
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-}
-
-TEST_F(BufferHubEventFdTest, EventFd_testConsecutiveSignalsFromAEventFd) {
- BufferHubEventFd eventFd;
- ASSERT_TRUE(eventFd.isValid());
- base::unique_fd epollFd(epoll_create(64));
- ASSERT_GE(epollFd.get(), 0);
- epoll_event e = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 0}};
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
-
- std::array<epoll_event, 1> events;
- for (int i = 0; i < kTestRuns; ++i) {
- eventFd.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
- }
-}
-
-TEST_F(BufferHubEventFdTest, EventFd_testConsecutiveSignalsFromADuplicatedEventFd) {
- BufferHubEventFd eventFd;
- ASSERT_TRUE(eventFd.isValid());
- base::unique_fd epollFd(epoll_create(64));
- ASSERT_GE(epollFd.get(), 0);
- epoll_event e = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 0}};
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
-
- BufferHubEventFd dupEventFd(dup(eventFd.get()));
- ASSERT_TRUE(dupEventFd.isValid());
-
- std::array<epoll_event, 1> events;
- for (int i = 0; i < kTestRuns; ++i) {
- dupEventFd.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
- }
-}
-
-TEST_F(BufferHubEventFdTest, EventFd_testClear) {
- BufferHubEventFd eventFd;
- ASSERT_TRUE(eventFd.isValid());
-
- base::unique_fd epollFd(epoll_create(64));
- epoll_event e = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 0}};
-
- ASSERT_GE(epollFd.get(), 0);
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
-
- eventFd.signal();
- eventFd.clear();
-
- std::array<epoll_event, 1> events;
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-}
-
-TEST_F(BufferHubEventFdTest, EventFd_testDupEventFd) {
- BufferHubEventFd eventFd;
- ASSERT_TRUE(eventFd.isValid());
-
- base::unique_fd epollFd(epoll_create(64));
- epoll_event e = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 0}};
-
- ASSERT_GE(epollFd.get(), 0);
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
-
- // Technically, the dupliated eventFd and the original eventFd are pointing
- // to the same kernel object. This test signals the duplicated eventFd but epolls the origianl
- // eventFd.
- BufferHubEventFd dupedEventFd(dup(eventFd.get()));
- ASSERT_GE(dupedEventFd.get(), 0);
-
- std::array<epoll_event, 1> events;
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-
- dupedEventFd.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
-
- // The epoll fd is edge triggered, so it only responds to the eventFd once.
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-
- dupedEventFd.signal();
-
- dupedEventFd.clear();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-}
-
-TEST_F(BufferHubEventFdTest, EventFd_testTwoEpollFds) {
- BufferHubEventFd eventFd;
- ASSERT_TRUE(eventFd.isValid());
-
- base::unique_fd epollFd1(epoll_create(64));
- base::unique_fd epollFd2(epoll_create(64));
- epoll_event e = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 0}};
-
- ASSERT_GE(epollFd1.get(), 0);
- ASSERT_GE(epollFd2.get(), 0);
-
- // Register the same eventFd to two EpollFds.
- ASSERT_EQ(epoll_ctl(epollFd1.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
- ASSERT_EQ(epoll_ctl(epollFd2.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
-
- std::array<epoll_event, 1> events;
- EXPECT_EQ(epoll_wait(epollFd1.get(), events.data(), events.size(), 0), 0);
- EXPECT_EQ(epoll_wait(epollFd2.get(), events.data(), events.size(), 0), 0);
-
- eventFd.signal();
- EXPECT_EQ(epoll_wait(epollFd1.get(), events.data(), events.size(), 0), 1);
- EXPECT_EQ(epoll_wait(epollFd2.get(), events.data(), events.size(), 0), 1);
-
- // The epoll fd is edge triggered, so it only responds to the eventFd once.
- EXPECT_EQ(epoll_wait(epollFd1.get(), events.data(), events.size(), 0), 0);
- EXPECT_EQ(epoll_wait(epollFd2.get(), events.data(), events.size(), 0), 0);
-
- eventFd.signal();
- EXPECT_EQ(epoll_wait(epollFd1.get(), events.data(), events.size(), 0), 1);
-
- eventFd.clear();
- EXPECT_EQ(epoll_wait(epollFd1.get(), events.data(), events.size(), 0), 0);
- EXPECT_EQ(epoll_wait(epollFd2.get(), events.data(), events.size(), 0), 0);
-}
-
-TEST_F(BufferHubEventFdTest, EventFd_testTwoEventFds) {
- BufferHubEventFd eventFd1;
- BufferHubEventFd eventFd2;
-
- ASSERT_TRUE(eventFd1.isValid());
- ASSERT_TRUE(eventFd2.isValid());
-
- base::unique_fd epollFd(epoll_create(64));
- epoll_event e1 = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 1}};
- epoll_event e2 = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 2}};
-
- ASSERT_GE(epollFd.get(), 0);
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd1.get(), &e1), 0);
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd2.get(), &e2), 0);
-
- std::array<epoll_event, 2> events;
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-
- // Signal one by one.
- eventFd1.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
- EXPECT_EQ(events[0].data.u32, e1.data.u32);
-
- eventFd2.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
- EXPECT_EQ(events[0].data.u32, e2.data.u32);
-
- // Signal both.
- eventFd1.signal();
- eventFd2.signal();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 2);
-
- uint32_t u32s[] = {events[0].data.u32, events[1].data.u32};
- EXPECT_THAT(u32s, Contains(e1.data.u32));
- EXPECT_THAT(u32s, Contains(e2.data.u32));
-
- // The epoll fd is edge triggered, so it only responds to the eventFd once.
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 0);
-
- eventFd1.signal();
- eventFd2.signal();
- eventFd2.clear();
- EXPECT_EQ(epoll_wait(epollFd.get(), events.data(), events.size(), 0), 1);
-}
-
-TEST_F(BufferHubEventFdTest, EventFd_testPollingThreadWithTwoEventFds) {
- BufferHubEventFd eventFd1;
- BufferHubEventFd eventFd2;
-
- ASSERT_TRUE(eventFd1.isValid());
- ASSERT_TRUE(eventFd2.isValid());
-
- base::unique_fd epollFd(epoll_create(64));
- epoll_event e1 = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 1}};
- epoll_event e2 = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 2}};
-
- ASSERT_GE(epollFd.get(), 0);
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd1.get(), &e1), 0);
- ASSERT_EQ(epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, eventFd2.get(), &e2), 0);
-
- int countEvent1 = 0;
- int countEvent2 = 0;
- std::atomic<bool> stop{false};
- std::mutex mx;
- std::condition_variable cv;
-
- std::thread pollingThread([&] {
- std::array<epoll_event, 2> events;
- while (true) {
- if (stop.load()) {
- break;
- }
- int ret = epoll_wait(epollFd.get(), events.data(), events.size(), kTimeout);
- ALOGE_IF(ret < 0 && errno != ETIMEDOUT, "Epoll failed.");
-
- std::lock_guard<std::mutex> lock(mx);
- for (int i = 0; i < ret; i++) {
- if (events[i].data.u32 == e1.data.u32) {
- countEvent1++;
- cv.notify_one();
- } else if (events[i].data.u32 == e2.data.u32) {
- countEvent2++;
- cv.notify_one();
- }
- }
- }
- });
-
- {
- std::unique_lock<std::mutex> lock(mx);
-
- eventFd1.signal();
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEvent1 == 1; }));
-
- eventFd1.signal();
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEvent1 == 2; }));
-
- eventFd2.signal();
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEvent2 == 1; }));
-
- eventFd1.clear();
- eventFd2.clear();
- EXPECT_EQ(countEvent1, 2);
- EXPECT_EQ(countEvent2, 1);
-
- eventFd1.signal();
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEvent1 == 3; }));
-
- eventFd2.signal();
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEvent2 == 2; }));
- }
-
- stop.store(true);
- pollingThread.join();
-}
-
-TEST_F(BufferHubEventFdTest, EventFd_testTwoPollingThreads) {
- BufferHubEventFd eventFd;
- ASSERT_TRUE(eventFd.isValid());
-
- base::unique_fd epollFd1(epoll_create(64));
- base::unique_fd epollFd2(epoll_create(64));
- epoll_event e = {.events = EPOLLIN | EPOLLET, .data = {.u32 = 0}};
-
- ASSERT_GE(epollFd1.get(), 0);
- ASSERT_GE(epollFd2.get(), 0);
-
- // Register the same eventFd to two EpollFds.
- ASSERT_EQ(epoll_ctl(epollFd1.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
- ASSERT_EQ(epoll_ctl(epollFd2.get(), EPOLL_CTL_ADD, eventFd.get(), &e), 0);
-
- int countEpoll1 = 0;
- int countEpoll2 = 0;
- std::atomic<bool> stop{false};
- std::mutex mx;
- std::condition_variable cv;
-
- std::thread pollingThread1([&] {
- std::array<epoll_event, 1> events;
- while (!stop.load()) {
- int ret = epoll_wait(epollFd1.get(), events.data(), events.size(), kTimeout);
- ALOGE_IF(ret < 0 && errno != ETIMEDOUT, "Epoll failed.");
-
- if (ret > 0) {
- std::lock_guard<std::mutex> lock(mx);
- countEpoll1++;
- cv.notify_one();
- }
- }
- });
-
- std::thread pollingThread2([&] {
- std::array<epoll_event, 1> events;
- while (!stop.load()) {
- int ret = epoll_wait(epollFd2.get(), events.data(), events.size(), kTimeout);
- ALOGE_IF(ret < 0 && errno != ETIMEDOUT, "Epoll failed.");
-
- if (ret > 0) {
- std::lock_guard<std::mutex> lock(mx);
- countEpoll2++;
- cv.notify_one();
- }
- }
- });
-
- {
- std::unique_lock<std::mutex> lock(mx);
-
- eventFd.signal();
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEpoll1 == 1; }));
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEpoll2 == 1; }));
-
- eventFd.signal();
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEpoll1 == 2; }));
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEpoll2 == 2; }));
-
- eventFd.clear();
- EXPECT_EQ(countEpoll1, 2);
- EXPECT_EQ(countEpoll2, 2);
-
- eventFd.signal();
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEpoll1 == 3; }));
- EXPECT_TRUE(cv.wait_for(lock, kTimeoutMs, [&] { return countEpoll2 == 3; }));
- }
-
- stop.store(true);
- pollingThread1.join();
- pollingThread2.join();
-}
-
-} // namespace android
diff --git a/libs/ui/tests/BufferHubMetadata_test.cpp b/libs/ui/tests/BufferHubMetadata_test.cpp
deleted file mode 100644
index eb978ca..0000000
--- a/libs/ui/tests/BufferHubMetadata_test.cpp
+++ /dev/null
@@ -1,98 +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 <gtest/gtest.h>
-#include <ui/BufferHubMetadata.h>
-
-namespace android {
-namespace dvr {
-
-constexpr size_t kEmptyUserMetadataSize = 0;
-
-class BufferHubMetadataTest : public ::testing::Test {};
-
-TEST_F(BufferHubMetadataTest, Create_UserMetdataSizeTooBig) {
- BufferHubMetadata m1 = BufferHubMetadata::create(std::numeric_limits<uint32_t>::max());
- EXPECT_FALSE(m1.isValid());
-}
-
-TEST_F(BufferHubMetadataTest, Create_Success) {
- BufferHubMetadata m1 = BufferHubMetadata::create(kEmptyUserMetadataSize);
- EXPECT_TRUE(m1.isValid());
- EXPECT_NE(m1.metadataHeader(), nullptr);
-}
-
-TEST_F(BufferHubMetadataTest, Import_Success) {
- BufferHubMetadata m1 = BufferHubMetadata::create(kEmptyUserMetadataSize);
- EXPECT_TRUE(m1.isValid());
- EXPECT_NE(m1.metadataHeader(), nullptr);
-
- unique_fd h2 = unique_fd(dup(m1.ashmemFd().get()));
- EXPECT_NE(h2.get(), -1);
-
- BufferHubMetadata m2 = BufferHubMetadata::import(std::move(h2));
- EXPECT_EQ(h2.get(), -1);
- EXPECT_TRUE(m1.isValid());
- BufferHubDefs::MetadataHeader* mh1 = m1.metadataHeader();
- EXPECT_NE(mh1, nullptr);
-
- // Check if the newly allocated buffer is initialized in released state (i.e.
- // state equals to 0U).
- EXPECT_TRUE(mh1->bufferState.load() == 0U);
-
- EXPECT_TRUE(m2.isValid());
- BufferHubDefs::MetadataHeader* mh2 = m2.metadataHeader();
- EXPECT_NE(mh2, nullptr);
-
- // Check if the newly allocated buffer is initialized in released state (i.e.
- // state equals to 0U).
- EXPECT_TRUE(mh2->bufferState.load() == 0U);
-}
-
-TEST_F(BufferHubMetadataTest, MoveMetadataInvalidatesOldOne) {
- BufferHubMetadata m1 = BufferHubMetadata::create(sizeof(int));
- EXPECT_TRUE(m1.isValid());
- EXPECT_NE(m1.metadataHeader(), nullptr);
- EXPECT_NE(m1.ashmemFd().get(), -1);
- EXPECT_EQ(m1.userMetadataSize(), sizeof(int));
-
- BufferHubMetadata m2 = std::move(m1);
-
- // After the move, the metadata header (a raw pointer) should be reset in the older buffer.
- EXPECT_EQ(m1.metadataHeader(), nullptr);
- EXPECT_NE(m2.metadataHeader(), nullptr);
-
- EXPECT_EQ(m1.ashmemFd().get(), -1);
- EXPECT_NE(m2.ashmemFd().get(), -1);
-
- EXPECT_EQ(m1.userMetadataSize(), 0U);
- EXPECT_EQ(m2.userMetadataSize(), sizeof(int));
-
- BufferHubMetadata m3{std::move(m2)};
-
- // After the move, the metadata header (a raw pointer) should be reset in the older buffer.
- EXPECT_EQ(m2.metadataHeader(), nullptr);
- EXPECT_NE(m3.metadataHeader(), nullptr);
-
- EXPECT_EQ(m2.ashmemFd().get(), -1);
- EXPECT_NE(m3.ashmemFd().get(), -1);
-
- EXPECT_EQ(m2.userMetadataSize(), 0U);
- EXPECT_EQ(m3.userMetadataSize(), sizeof(int));
-}
-
-} // namespace dvr
-} // namespace android
diff --git a/libs/ui/tests/GraphicBufferOverBinder_test.cpp b/libs/ui/tests/GraphicBufferOverBinder_test.cpp
index 7c0a44a..126a945 100644
--- a/libs/ui/tests/GraphicBufferOverBinder_test.cpp
+++ b/libs/ui/tests/GraphicBufferOverBinder_test.cpp
@@ -23,7 +23,6 @@
#include <gui/BufferQueue.h>
#include <gui/IGraphicBufferConsumer.h>
#include <gui/IGraphicBufferProducer.h>
-#include <ui/BufferHubBuffer.h>
#include <ui/GraphicBuffer.h>
#include <utils/Log.h>
@@ -37,7 +36,6 @@
static const String16 kTestServiceName = String16("GraphicBufferOverBinderTestService");
enum GraphicBufferOverBinderTestServiceCode {
GRAPHIC_BUFFER = IBinder::FIRST_CALL_TRANSACTION,
- GRAPHIC_BUFFER_FROM_BUFFER_HUB_BUFFER,
};
class GraphicBufferOverBinderTestService : public BBinder {
@@ -46,21 +44,6 @@
// GraphicBuffer
mGraphicBuffer = new GraphicBuffer(kTestWidth, kTestHeight, kTestFormat, kTestLayerCount,
kTestUsage);
- ALOGI("mGraphicBuffer id %" PRIi32, mGraphicBuffer->getBufferId());
-
- // BufferHub-backed GraphicBuffer
- std::unique_ptr<BufferHubBuffer> bufferHubBuffer =
- BufferHubBuffer::create(kTestWidth, kTestHeight, kTestLayerCount, kTestFormat,
- kTestUsage, /*userMetadataSize=*/0);
- mBufferhubBackedGraphicBuffer = new GraphicBuffer(std::move(bufferHubBuffer));
- if (!mBufferhubBackedGraphicBuffer->isBufferHubBuffer()) {
- ALOGE("Failed to back GraphicBuffer with BufferHub.");
- }
- if (bufferHubBuffer != nullptr) {
- ALOGE("Failed to move BufferHubBuffer to GraphicBuffer");
- }
- ALOGI("mBufferhubBackedGraphicBuffer id %" PRIi32,
- mBufferhubBackedGraphicBuffer->getBufferId());
}
~GraphicBufferOverBinderTestService() = default;
@@ -71,9 +54,6 @@
case GRAPHIC_BUFFER: {
return reply->write(*mGraphicBuffer);
}
- case GRAPHIC_BUFFER_FROM_BUFFER_HUB_BUFFER: {
- return reply->write(*mBufferhubBackedGraphicBuffer);
- }
default:
return UNKNOWN_TRANSACTION;
};
@@ -81,7 +61,6 @@
protected:
sp<GraphicBuffer> mGraphicBuffer;
- sp<GraphicBuffer> mBufferhubBackedGraphicBuffer;
};
static int runBinderServer() {
@@ -138,17 +117,6 @@
sp<GraphicBuffer> gb;
EXPECT_EQ(GetGraphicBuffer(&gb, GRAPHIC_BUFFER), OK);
EXPECT_NE(gb, nullptr);
- EXPECT_FALSE(gb->isBufferHubBuffer());
- void* vaddr;
- EXPECT_EQ(gb->lock(kTestUsage, &vaddr), OK);
- EXPECT_EQ(gb->unlock(), OK);
-}
-
-TEST_F(GraphicBufferOverBinderTest, SendGraphicBufferFromBufferHubBufferOverBinder) {
- sp<GraphicBuffer> gb;
- EXPECT_EQ(GetGraphicBuffer(&gb, GRAPHIC_BUFFER_FROM_BUFFER_HUB_BUFFER), NO_ERROR);
- EXPECT_NE(gb, nullptr);
- EXPECT_TRUE(gb->isBufferHubBuffer());
void* vaddr;
EXPECT_EQ(gb->lock(kTestUsage, &vaddr), OK);
EXPECT_EQ(gb->unlock(), OK);
diff --git a/libs/ui/tests/GraphicBuffer_test.cpp b/libs/ui/tests/GraphicBuffer_test.cpp
index 5e0b094..19551b3 100644
--- a/libs/ui/tests/GraphicBuffer_test.cpp
+++ b/libs/ui/tests/GraphicBuffer_test.cpp
@@ -16,7 +16,6 @@
#define LOG_TAG "GraphicBufferTest"
-#include <ui/BufferHubBuffer.h>
#include <ui/GraphicBuffer.h>
#include <gtest/gtest.h>
@@ -27,7 +26,6 @@
constexpr uint32_t kTestWidth = 1024;
constexpr uint32_t kTestHeight = 1;
-constexpr uint32_t kTestFormat = HAL_PIXEL_FORMAT_BLOB;
constexpr uint32_t kTestLayerCount = 1;
constexpr uint64_t kTestUsage = GraphicBuffer::USAGE_SW_WRITE_OFTEN;
@@ -68,88 +66,4 @@
ASSERT_EQ(BAD_VALUE, gb2->initCheck());
}
-TEST_F(GraphicBufferTest, CreateFromBufferHubBuffer) {
- std::unique_ptr<BufferHubBuffer> b1 =
- BufferHubBuffer::create(kTestWidth, kTestHeight, kTestLayerCount, kTestFormat,
- kTestUsage, /*userMetadataSize=*/0);
- ASSERT_NE(b1, nullptr);
- EXPECT_TRUE(b1->isValid());
-
- sp<GraphicBuffer> gb(new GraphicBuffer(std::move(b1)));
- EXPECT_TRUE(gb->isBufferHubBuffer());
-
- EXPECT_EQ(gb->getWidth(), kTestWidth);
- EXPECT_EQ(gb->getHeight(), kTestHeight);
- EXPECT_EQ(static_cast<uint32_t>(gb->getPixelFormat()), kTestFormat);
- EXPECT_EQ(gb->getUsage(), kTestUsage);
- EXPECT_EQ(gb->getLayerCount(), kTestLayerCount);
-}
-
-TEST_F(GraphicBufferTest, InvalidBufferIdForNoneBufferHubBuffer) {
- sp<GraphicBuffer> gb(
- new GraphicBuffer(kTestWidth, kTestHeight, kTestFormat, kTestLayerCount, kTestUsage));
- EXPECT_FALSE(gb->isBufferHubBuffer());
- EXPECT_EQ(gb->getBufferId(), -1);
-}
-
-TEST_F(GraphicBufferTest, BufferIdMatchesBufferHubBufferId) {
- std::unique_ptr<BufferHubBuffer> b1 =
- BufferHubBuffer::create(kTestWidth, kTestHeight, kTestLayerCount, kTestFormat,
- kTestUsage, /*userMetadataSize=*/0);
- EXPECT_NE(b1, nullptr);
- EXPECT_TRUE(b1->isValid());
-
- int b1_id = b1->id();
- EXPECT_GE(b1_id, 0);
-
- sp<GraphicBuffer> gb(new GraphicBuffer(std::move(b1)));
- EXPECT_TRUE(gb->isBufferHubBuffer());
- EXPECT_EQ(gb->getBufferId(), b1_id);
-}
-
-TEST_F(GraphicBufferTest, flattenAndUnflatten) {
- std::unique_ptr<BufferHubBuffer> b1 =
- BufferHubBuffer::create(kTestWidth, kTestHeight, kTestLayerCount, kTestFormat,
- kTestUsage, /*userMetadataSize=*/0);
- ASSERT_NE(b1, nullptr);
- sp<GraphicBuffer> gb1(new GraphicBuffer(std::move(b1)));
- gb1->setGenerationNumber(42);
-
- size_t flattenedSize = gb1->getFlattenedSize();
- EXPECT_EQ(flattenedSize, 48);
- size_t fdCount = gb1->getFdCount();
- EXPECT_EQ(fdCount, 0);
-
- int data[flattenedSize];
- int fds[0];
-
- // Make copies of needed items since flatten modifies them.
- size_t flattenedSizeCopy = flattenedSize;
- size_t fdCountCopy = fdCount;
- void* dataStart = data;
- int* fdsStart = fds;
- status_t err = gb1->flatten(dataStart, flattenedSizeCopy, fdsStart, fdCountCopy);
- ASSERT_EQ(err, NO_ERROR);
- EXPECT_EQ(flattenedSizeCopy, 0);
- EXPECT_EQ(fdCountCopy, 0);
-
- size_t unflattenSize = flattenedSize;
- size_t unflattenFdCount = fdCount;
- const void* unflattenData = static_cast<const void*>(dataStart);
- const int* unflattenFdData = static_cast<const int*>(fdsStart);
-
- GraphicBuffer* gb2 = new GraphicBuffer();
- err = gb2->unflatten(unflattenData, unflattenSize, unflattenFdData, unflattenFdCount);
- ASSERT_EQ(err, NO_ERROR);
- EXPECT_TRUE(gb2->isBufferHubBuffer());
-
- EXPECT_EQ(gb2->getWidth(), kTestWidth);
- EXPECT_EQ(gb2->getHeight(), kTestHeight);
- EXPECT_EQ(static_cast<uint32_t>(gb2->getPixelFormat()), kTestFormat);
- EXPECT_EQ(gb2->getUsage(), kTestUsage);
- EXPECT_EQ(gb2->getLayerCount(), kTestLayerCount);
- EXPECT_EQ(gb1->getBufferId(), gb2->getBufferId());
- EXPECT_EQ(gb2->getGenerationNumber(), 42);
-}
-
} // namespace android
diff --git a/libs/vr/libpdx_uds/service_endpoint.cpp b/libs/vr/libpdx_uds/service_endpoint.cpp
index ecbfdba..9bc70ea 100644
--- a/libs/vr/libpdx_uds/service_endpoint.cpp
+++ b/libs/vr/libpdx_uds/service_endpoint.cpp
@@ -535,13 +535,13 @@
*message = Message{info};
auto* state = static_cast<MessageState*>(message->GetState());
state->request = std::move(request);
- if (request.send_len > 0 && !request.is_impulse) {
- state->request_data.resize(request.send_len);
+ if (state->request.send_len > 0 && !state->request.is_impulse) {
+ state->request_data.resize(state->request.send_len);
status = ReceiveData(channel_fd, state->request_data.data(),
state->request_data.size());
}
- if (status && request.is_impulse)
+ if (status && state->request.is_impulse)
status = ReenableEpollEvent(channel_fd);
if (!status) {
diff --git a/opengl/libs/EGL/FileBlobCache.cpp b/opengl/libs/EGL/FileBlobCache.cpp
index cc42ac7..3284778 100644
--- a/opengl/libs/EGL/FileBlobCache.cpp
+++ b/opengl/libs/EGL/FileBlobCache.cpp
@@ -17,11 +17,13 @@
#include "FileBlobCache.h"
#include <errno.h>
+#include <fcntl.h>
#include <inttypes.h>
-#include <log/log.h>
#include <sys/mman.h>
#include <sys/stat.h>
+#include <unistd.h>
+#include <log/log.h>
// Cache file header
static const char* cacheFileMagic = "EGL$";
diff --git a/opengl/tests/gl2_jni/Android.bp b/opengl/tests/gl2_jni/Android.bp
index 65f89b1..8d4323f 100644
--- a/opengl/tests/gl2_jni/Android.bp
+++ b/opengl/tests/gl2_jni/Android.bp
@@ -17,6 +17,7 @@
"-Werror",
"-Wno-error=unused-parameter",
],
+ header_libs: ["jni_headers"],
srcs: ["jni/gl_code.cpp"],
shared_libs: [
"liblog",
diff --git a/opengl/tests/gl_jni/Android.bp b/opengl/tests/gl_jni/Android.bp
index 5bec336..0cb129a 100644
--- a/opengl/tests/gl_jni/Android.bp
+++ b/opengl/tests/gl_jni/Android.bp
@@ -19,6 +19,7 @@
"-Werror",
"-Wno-error=unused-parameter",
],
+ header_libs: ["jni_headers"],
srcs: ["jni/gl_code.cpp"],
shared_libs: [
"liblog",
diff --git a/opengl/tests/gl_perfapp/Android.bp b/opengl/tests/gl_perfapp/Android.bp
index cf899ac..66afb6a 100644
--- a/opengl/tests/gl_perfapp/Android.bp
+++ b/opengl/tests/gl_perfapp/Android.bp
@@ -17,6 +17,7 @@
"-Werror",
"-Wno-error=unused-parameter",
],
+ header_libs: ["jni_headers"],
srcs: ["jni/gl_code.cpp"],
shared_libs: [
"liblog",
diff --git a/opengl/tests/gldual/Android.bp b/opengl/tests/gldual/Android.bp
index 2432566..1006d44 100644
--- a/opengl/tests/gldual/Android.bp
+++ b/opengl/tests/gldual/Android.bp
@@ -20,6 +20,7 @@
"-Werror",
"-Wno-error=unused-parameter",
],
+ header_libs: ["jni_headers"],
srcs: ["jni/gl_code.cpp"],
shared_libs: [
"liblog",
diff --git a/opengl/tools/glgen/gen b/opengl/tools/glgen/gen
index 41fcf1b..9efd38f 100755
--- a/opengl/tools/glgen/gen
+++ b/opengl/tools/glgen/gen
@@ -1,6 +1,18 @@
#!/bin/bash
set -u
set -e
+
+if [ -z "$ANDROID_BUILD_TOP" ] ; then
+ echo "ANDROID_BUILD_TOP is not set, did you run lunch?"
+ exit 1
+fi
+
+# Avoid spewing files in any location other than the intended one.
+if [ ! -x "$PWD/gen" ] ; then
+ echo "Run this script from its parent directory".
+ exit 1
+fi
+
rm -rf out generated
mkdir out
@@ -92,7 +104,7 @@
# Add UnsupportedAppUsage.java to known sources.
mkdir -p out/android/compat/annotation
-cp ../../../../../tools/platform-compat/annotation/src/java/android/compat/annotation/UnsupportedAppUsage.java out/android/compat/annotation
+cp ${ANDROID_BUILD_TOP}/tools/platform-compat/java/android/compat/annotation/UnsupportedAppUsage.java out/android/compat/annotation
pushd out > /dev/null
mkdir classes
@@ -153,23 +165,23 @@
fi
}
-compareGenerated ../../../../base/core/jni generated/C com_google_android_gles_jni_GLImpl.cpp
-compareGenerated ../../../../base/opengl/java/com/google/android/gles_jni generated/com/google/android/gles_jni GLImpl.java
+compareGenerated ${ANDROID_BUILD_TOP}/frameworks/base/core/jni generated/C com_google_android_gles_jni_GLImpl.cpp
+compareGenerated ${ANDROID_BUILD_TOP}/frameworks/base/opengl/java/com/google/android/gles_jni generated/com/google/android/gles_jni GLImpl.java
for x in GL.java GL10.java GL10Ext.java GL11.java GL11Ext.java GL11ExtensionPack.java
do
- compareGenerated ../../../../base/opengl/java/javax/microedition/khronos/opengles generated/javax/microedition/khronos/opengles $x
+ compareGenerated ${ANDROID_BUILD_TOP}/frameworks/base/opengl/java/javax/microedition/khronos/opengles generated/javax/microedition/khronos/opengles $x
done
for x in EGL14 EGL15 EGLExt GLES10 GLES10Ext GLES11 GLES11Ext GLES20 GLES30 GLES31 GLES31Ext GLES32
do
- compareGenerated ../../../../base/opengl/java/android/opengl generated/android/opengl ${x}.java
- compareGenerated ../../../../base/core/jni generated/C android_opengl_${x}.cpp
+ compareGenerated ${ANDROID_BUILD_TOP}/frameworks/base/opengl/java/android/opengl generated/android/opengl ${x}.java
+ compareGenerated ${ANDROID_BUILD_TOP}/frameworks/base/core/jni generated/C android_opengl_${x}.cpp
done
for x in EGLConfig EGLContext EGLDisplay EGLObjectHandle EGLSurface EGLImage EGLSync
do
- compareGenerated ../../../../base/opengl/java/android/opengl generated/android/opengl ${x}.java
+ compareGenerated ${ANDROID_BUILD_TOP}/frameworks/base/opengl/java/android/opengl generated/android/opengl ${x}.java
done
if [ $KEEP_GENERATED == "0" ] ; then
diff --git a/opengl/tools/glgen/stubs/egl/EGL14Header.java-if b/opengl/tools/glgen/stubs/egl/EGL14Header.java-if
index 9932556..951ecff 100644
--- a/opengl/tools/glgen/stubs/egl/EGL14Header.java-if
+++ b/opengl/tools/glgen/stubs/egl/EGL14Header.java-if
@@ -21,8 +21,8 @@
import android.compat.annotation.UnsupportedAppUsage;
import android.graphics.SurfaceTexture;
import android.view.Surface;
-import android.view.SurfaceView;
import android.view.SurfaceHolder;
+import android.view.SurfaceView;
/**
* EGL 1.4
diff --git a/opengl/tools/glgen/stubs/jsr239/GLImplHeader.java-impl b/opengl/tools/glgen/stubs/jsr239/GLImplHeader.java-impl
index afcc3eb..32c9d7d 100644
--- a/opengl/tools/glgen/stubs/jsr239/GLImplHeader.java-impl
+++ b/opengl/tools/glgen/stubs/jsr239/GLImplHeader.java-impl
@@ -19,6 +19,7 @@
package com.google.android.gles_jni;
import android.app.AppGlobals;
+import android.compat.annotation.UnsupportedAppUsage;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageManager;
import android.os.Build;
@@ -26,6 +27,7 @@
import android.util.Log;
import java.nio.Buffer;
+
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL10Ext;
import javax.microedition.khronos.opengles.GL11;
@@ -55,6 +57,7 @@
private boolean have_OES_framebuffer_object;
private boolean have_OES_texture_cube_map;
+ @UnsupportedAppUsage
public GLImpl() {
}
diff --git a/services/bufferhub/Android.bp b/services/bufferhub/Android.bp
deleted file mode 100644
index 2bb6aef..0000000
--- a/services/bufferhub/Android.bp
+++ /dev/null
@@ -1,77 +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.
-//
-
-cc_library_shared {
- name: "libbufferhubservice",
- cflags: [
- "-DLOG_TAG=\"libbufferhubservice\"",
- "-Wall",
- "-Werror",
- "-Wextra",
- ],
- srcs: [
- "BufferClient.cpp",
- "BufferHubIdGenerator.cpp",
- "BufferHubService.cpp",
- "BufferNode.cpp",
- ],
- header_libs: [
- "libdvr_headers",
- "libnativewindow_headers",
- ],
- shared_libs: [
- "android.frameworks.bufferhub@1.0",
- "libcrypto",
- "libcutils",
- "libhidlbase",
- "liblog",
- "libui",
- "libutils",
- ],
- export_include_dirs: [
- "include"
- ],
-}
-
-cc_binary {
- name: "android.frameworks.bufferhub@1.0-service",
- relative_install_path: "hw",
- srcs: [
- "main_bufferhub.cpp"
- ],
- header_libs: [
- "libdvr_headers",
- "libnativewindow_headers",
- ],
- shared_libs: [
- "android.frameworks.bufferhub@1.0",
- "libbufferhubservice",
- "libcrypto",
- "libcutils",
- "libhidlbase",
- "liblog",
- "libui",
- "libutils",
- ],
- cflags: [
- "-DLOG_TAG=\"bufferhub\"",
- "-Wall",
- "-Werror",
- "-Wextra",
- ],
- init_rc: ["android.frameworks.bufferhub@1.0-service.rc"],
- vintf_fragments: ["android.frameworks.bufferhub@1.0-service.xml"],
-}
diff --git a/services/bufferhub/BufferClient.cpp b/services/bufferhub/BufferClient.cpp
deleted file mode 100644
index ec7e535..0000000
--- a/services/bufferhub/BufferClient.cpp
+++ /dev/null
@@ -1,100 +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 <bufferhub/BufferClient.h>
-#include <bufferhub/BufferHubService.h>
-#include <hidl/HidlSupport.h>
-#include <log/log.h>
-
-namespace android {
-namespace frameworks {
-namespace bufferhub {
-namespace V1_0 {
-namespace implementation {
-
-using hardware::hidl_handle;
-using hardware::Void;
-
-BufferClient* BufferClient::create(BufferHubService* service,
- const std::shared_ptr<BufferNode>& node) {
- if (!service) {
- ALOGE("%s: service cannot be nullptr.", __FUNCTION__);
- return nullptr;
- } else if (!node) {
- ALOGE("%s: node cannot be nullptr.", __FUNCTION__);
- return nullptr;
- }
- return new BufferClient(service, node);
-}
-
-BufferClient::~BufferClient() {
- {
- std::lock_guard<std::mutex> lock(mClosedMutex);
- if (!mClosed) {
- ALOGW("%s: client of buffer #%d destroyed without close. Closing it now.", __FUNCTION__,
- mBufferNode->id());
- }
- }
-
- close();
-}
-
-Return<BufferHubStatus> BufferClient::close() {
- std::lock_guard<std::mutex> lock(mClosedMutex);
- if (mClosed) {
- return BufferHubStatus::CLIENT_CLOSED;
- }
-
- getService()->onClientClosed(this);
- mBufferNode.reset();
- mClosed = true;
- return BufferHubStatus::NO_ERROR;
-}
-
-Return<void> BufferClient::duplicate(duplicate_cb _hidl_cb) {
- std::lock_guard<std::mutex> lock(mClosedMutex);
- if (mClosed) {
- _hidl_cb(/*token=*/hidl_handle(), /*status=*/BufferHubStatus::CLIENT_CLOSED);
- return Void();
- }
-
- if (!mBufferNode) {
- // Should never happen
- ALOGE("%s: node is missing.", __FUNCTION__);
- _hidl_cb(/*token=*/hidl_handle(), /*status=*/BufferHubStatus::BUFFER_FREED);
- return Void();
- }
-
- const hidl_handle token = getService()->registerToken(this);
- _hidl_cb(/*token=*/token, /*status=*/BufferHubStatus::NO_ERROR);
- return Void();
-}
-
-sp<BufferHubService> BufferClient::getService() {
- sp<BufferHubService> service = mService.promote();
- if (service == nullptr) {
- // Should never happen. Kill the process.
- LOG_FATAL("%s: service died.", __FUNCTION__);
- }
-
- return service;
-}
-
-} // namespace implementation
-} // namespace V1_0
-} // namespace bufferhub
-} // namespace frameworks
-} // namespace android
\ No newline at end of file
diff --git a/services/bufferhub/BufferHubIdGenerator.cpp b/services/bufferhub/BufferHubIdGenerator.cpp
deleted file mode 100644
index 2c12f0e..0000000
--- a/services/bufferhub/BufferHubIdGenerator.cpp
+++ /dev/null
@@ -1,59 +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 <bufferhub/BufferHubIdGenerator.h>
-#include <log/log.h>
-
-namespace android {
-namespace frameworks {
-namespace bufferhub {
-namespace V1_0 {
-namespace implementation {
-
-BufferHubIdGenerator& BufferHubIdGenerator::getInstance() {
- static BufferHubIdGenerator generator;
-
- return generator;
-}
-
-int BufferHubIdGenerator::getId() {
- std::lock_guard<std::mutex> lock(mIdsInUseMutex);
-
- do {
- if (++mLastId >= std::numeric_limits<int>::max()) {
- mLastId = 0;
- }
- } while (mIdsInUse.find(mLastId) != mIdsInUse.end());
-
- mIdsInUse.insert(mLastId);
- return mLastId;
-}
-
-void BufferHubIdGenerator::freeId(int id) {
- std::lock_guard<std::mutex> lock(mIdsInUseMutex);
- auto iter = mIdsInUse.find(id);
- if (iter != mIdsInUse.end()) {
- mIdsInUse.erase(iter);
- } else {
- ALOGW("%s: Cannot free nonexistent id #%d", __FUNCTION__, id);
- }
-}
-
-} // namespace implementation
-} // namespace V1_0
-} // namespace bufferhub
-} // namespace frameworks
-} // namespace android
diff --git a/services/bufferhub/BufferHubService.cpp b/services/bufferhub/BufferHubService.cpp
deleted file mode 100644
index 7a3472f..0000000
--- a/services/bufferhub/BufferHubService.cpp
+++ /dev/null
@@ -1,401 +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 <array>
-#include <iomanip>
-#include <random>
-#include <sstream>
-
-#include <android/hardware_buffer.h>
-#include <bufferhub/BufferHubService.h>
-#include <cutils/native_handle.h>
-#include <log/log.h>
-#include <openssl/hmac.h>
-#include <system/graphics-base.h>
-#include <ui/BufferHubDefs.h>
-
-using ::android::BufferHubDefs::MetadataHeader;
-using ::android::hardware::Void;
-
-namespace android {
-namespace frameworks {
-namespace bufferhub {
-namespace V1_0 {
-namespace implementation {
-
-BufferHubService::BufferHubService() {
- std::mt19937_64 randomEngine;
- randomEngine.seed(time(nullptr));
-
- mKey = randomEngine();
-}
-
-Return<void> BufferHubService::allocateBuffer(const HardwareBufferDescription& description,
- const uint32_t userMetadataSize,
- allocateBuffer_cb _hidl_cb) {
- AHardwareBuffer_Desc desc;
- memcpy(&desc, &description, sizeof(AHardwareBuffer_Desc));
-
- std::shared_ptr<BufferNode> node =
- std::make_shared<BufferNode>(desc.width, desc.height, desc.layers, desc.format,
- desc.usage, userMetadataSize,
- BufferHubIdGenerator::getInstance().getId());
- if (node == nullptr || !node->isValid()) {
- ALOGE("%s: creating BufferNode failed.", __FUNCTION__);
- _hidl_cb(/*status=*/BufferHubStatus::ALLOCATION_FAILED, /*bufferClient=*/nullptr,
- /*bufferTraits=*/{});
- return Void();
- }
-
- sp<BufferClient> client = BufferClient::create(this, node);
- // Add it to list for bookkeeping and dumpsys.
- std::lock_guard<std::mutex> lock(mClientSetMutex);
- mClientSet.emplace(client);
-
- // Allocate memory for bufferInfo of type hidl_handle on the stack. See
- // http://aosp/286282 for the usage of NATIVE_HANDLE_DECLARE_STORAGE.
- NATIVE_HANDLE_DECLARE_STORAGE(bufferInfoStorage, BufferHubDefs::kBufferInfoNumFds,
- BufferHubDefs::kBufferInfoNumInts);
- hidl_handle bufferInfo =
- buildBufferInfo(bufferInfoStorage, node->id(), node->addNewActiveClientsBitToMask(),
- node->userMetadataSize(), node->metadata().ashmemFd(),
- node->eventFd().get());
- // During the gralloc allocation carried out by BufferNode, gralloc allocator will populate the
- // fields of its HardwareBufferDescription (i.e. strides) according to the actual
- // gralloc implementation. We need to read those fields back and send them to the client via
- // BufferTraits.
- HardwareBufferDescription allocatedBufferDesc;
- memcpy(&allocatedBufferDesc, &node->bufferDesc(), sizeof(AHardwareBuffer_Desc));
- BufferTraits bufferTraits = {/*bufferDesc=*/allocatedBufferDesc,
- /*bufferHandle=*/hidl_handle(node->bufferHandle()),
- /*bufferInfo=*/std::move(bufferInfo)};
-
- _hidl_cb(/*status=*/BufferHubStatus::NO_ERROR, /*bufferClient=*/client,
- /*bufferTraits=*/std::move(bufferTraits));
- return Void();
-}
-
-Return<void> BufferHubService::importBuffer(const hidl_handle& tokenHandle,
- importBuffer_cb _hidl_cb) {
- if (!tokenHandle.getNativeHandle() || tokenHandle->numFds != 0 || tokenHandle->numInts <= 1) {
- // nullptr handle or wrong format
- _hidl_cb(/*status=*/BufferHubStatus::INVALID_TOKEN, /*bufferClient=*/nullptr,
- /*bufferTraits=*/{});
- return Void();
- }
-
- int tokenId = tokenHandle->data[0];
-
- wp<BufferClient> originClientWp;
- {
- std::lock_guard<std::mutex> lock(mTokenMutex);
- auto iter = mTokenMap.find(tokenId);
- if (iter == mTokenMap.end()) {
- // Token Id not exist
- ALOGD("%s: token #%d not found.", __FUNCTION__, tokenId);
- _hidl_cb(/*status=*/BufferHubStatus::INVALID_TOKEN, /*bufferClient=*/nullptr,
- /*bufferTraits=*/{});
- return Void();
- }
-
- const std::vector<uint8_t>& tokenHMAC = iter->second.first;
-
- int numIntsForHMAC = (int)ceil(tokenHMAC.size() * sizeof(uint8_t) / (double)sizeof(int));
- if (tokenHandle->numInts - 1 != numIntsForHMAC) {
- // HMAC size not match
- ALOGD("%s: token #%d HMAC size not match. Expected: %d Actual: %d", __FUNCTION__,
- tokenId, numIntsForHMAC, tokenHandle->numInts - 1);
- _hidl_cb(/*status=*/BufferHubStatus::INVALID_TOKEN, /*bufferClient=*/nullptr,
- /*bufferTraits=*/{});
- return Void();
- }
-
- size_t hmacSize = tokenHMAC.size() * sizeof(uint8_t);
- if (memcmp(tokenHMAC.data(), &tokenHandle->data[1], hmacSize) != 0) {
- // HMAC not match
- ALOGD("%s: token #%d HMAC not match.", __FUNCTION__, tokenId);
- _hidl_cb(/*status=*/BufferHubStatus::INVALID_TOKEN, /*bufferClient=*/nullptr,
- /*bufferTraits=*/{});
- return Void();
- }
-
- originClientWp = iter->second.second;
- mTokenMap.erase(iter);
- }
-
- // Check if original client is dead
- sp<BufferClient> originClient = originClientWp.promote();
- if (!originClient) {
- // Should not happen since token should be removed if already gone
- ALOGE("%s: original client %p gone!", __FUNCTION__, originClientWp.unsafe_get());
- _hidl_cb(/*status=*/BufferHubStatus::BUFFER_FREED, /*bufferClient=*/nullptr,
- /*bufferTraits=*/{});
- return Void();
- }
-
- sp<BufferClient> client = new BufferClient(*originClient);
- uint32_t clientStateMask = client->getBufferNode()->addNewActiveClientsBitToMask();
- if (clientStateMask == 0U) {
- // Reach max client count
- ALOGE("%s: import failed, BufferNode#%u reached maximum clients.", __FUNCTION__,
- client->getBufferNode()->id());
- _hidl_cb(/*status=*/BufferHubStatus::MAX_CLIENT, /*bufferClient=*/nullptr,
- /*bufferTraits=*/{});
- return Void();
- }
-
- std::lock_guard<std::mutex> lock(mClientSetMutex);
- mClientSet.emplace(client);
-
- std::shared_ptr<BufferNode> node = client->getBufferNode();
-
- HardwareBufferDescription bufferDesc;
- memcpy(&bufferDesc, &node->bufferDesc(), sizeof(HardwareBufferDescription));
-
- // Allocate memory for bufferInfo of type hidl_handle on the stack. See
- // http://aosp/286282 for the usage of NATIVE_HANDLE_DECLARE_STORAGE.
- NATIVE_HANDLE_DECLARE_STORAGE(bufferInfoStorage, BufferHubDefs::kBufferInfoNumFds,
- BufferHubDefs::kBufferInfoNumInts);
- hidl_handle bufferInfo = buildBufferInfo(bufferInfoStorage, node->id(), clientStateMask,
- node->userMetadataSize(), node->metadata().ashmemFd(),
- node->eventFd().get());
- BufferTraits bufferTraits = {/*bufferDesc=*/bufferDesc,
- /*bufferHandle=*/hidl_handle(node->bufferHandle()),
- /*bufferInfo=*/std::move(bufferInfo)};
-
- _hidl_cb(/*status=*/BufferHubStatus::NO_ERROR, /*bufferClient=*/client,
- /*bufferTraits=*/std::move(bufferTraits));
- return Void();
-}
-
-Return<void> BufferHubService::debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) {
- if (fd.getNativeHandle() == nullptr || fd->numFds < 1) {
- ALOGE("%s: missing fd for writing.", __FUNCTION__);
- return Void();
- }
-
- FILE* out = fdopen(dup(fd->data[0]), "w");
-
- if (args.size() != 0) {
- fprintf(out,
- "Note: lshal bufferhub currently does not support args. Input arguments are "
- "ignored.\n");
- }
-
- std::ostringstream stream;
-
- // Get the number of clients of each buffer.
- // Map from bufferId to bufferNode_clientCount pair.
- std::map<int, std::pair<const std::shared_ptr<BufferNode>, uint32_t>> clientCount;
- {
- std::lock_guard<std::mutex> lock(mClientSetMutex);
- for (auto iter = mClientSet.begin(); iter != mClientSet.end(); ++iter) {
- sp<BufferClient> client = iter->promote();
- if (client != nullptr) {
- const std::shared_ptr<BufferNode> node = client->getBufferNode();
- auto mapIter = clientCount.find(node->id());
- if (mapIter != clientCount.end()) {
- ++mapIter->second.second;
- } else {
- clientCount.emplace(node->id(),
- std::pair<std::shared_ptr<BufferNode>, uint32_t>(node, 1U));
- }
- }
- }
- }
-
- stream << "Active Buffers:\n";
- stream << std::right;
- stream << std::setw(6) << "Id";
- stream << " ";
- stream << std::setw(9) << "#Clients";
- stream << " ";
- stream << std::setw(14) << "Geometry";
- stream << " ";
- stream << std::setw(6) << "Format";
- stream << " ";
- stream << std::setw(10) << "Usage";
- stream << " ";
- stream << std::setw(10) << "State";
- stream << " ";
- stream << std::setw(8) << "Index";
- stream << std::endl;
-
- for (auto iter = clientCount.begin(); iter != clientCount.end(); ++iter) {
- const std::shared_ptr<BufferNode> node = std::move(iter->second.first);
- const uint32_t clientCount = iter->second.second;
- AHardwareBuffer_Desc desc = node->bufferDesc();
-
- MetadataHeader* metadataHeader =
- const_cast<BufferHubMetadata*>(&node->metadata())->metadataHeader();
- const uint32_t state = metadataHeader->bufferState.load(std::memory_order_acquire);
- const uint64_t index = metadataHeader->queueIndex;
-
- stream << std::right;
- stream << std::setw(6) << /*Id=*/node->id();
- stream << " ";
- stream << std::setw(9) << /*#Clients=*/clientCount;
- stream << " ";
- if (desc.format == HAL_PIXEL_FORMAT_BLOB) {
- std::string size = std::to_string(desc.width) + " B";
- stream << std::setw(14) << /*Geometry=*/size;
- } else {
- std::string dimensions = std::to_string(desc.width) + "x" +
- std::to_string(desc.height) + "x" + std::to_string(desc.layers);
- stream << std::setw(14) << /*Geometry=*/dimensions;
- }
- stream << " ";
- stream << std::setw(6) << /*Format=*/desc.format;
- stream << " ";
- stream << "0x" << std::hex << std::setfill('0');
- stream << std::setw(8) << /*Usage=*/desc.usage;
- stream << std::dec << std::setfill(' ');
- stream << " ";
- stream << "0x" << std::hex << std::setfill('0');
- stream << std::setw(8) << /*State=*/state;
- stream << std::dec << std::setfill(' ');
- stream << " ";
- stream << std::setw(8) << /*Index=*/index;
- stream << std::endl;
- }
-
- stream << std::endl;
-
- // Get the number of tokens of each buffer.
- // Map from bufferId to tokenCount
- std::map<int, uint32_t> tokenCount;
- {
- std::lock_guard<std::mutex> lock(mTokenMutex);
- for (auto iter = mTokenMap.begin(); iter != mTokenMap.end(); ++iter) {
- sp<BufferClient> client = iter->second.second.promote();
- if (client != nullptr) {
- const std::shared_ptr<BufferNode> node = client->getBufferNode();
- auto mapIter = tokenCount.find(node->id());
- if (mapIter != tokenCount.end()) {
- ++mapIter->second;
- } else {
- tokenCount.emplace(node->id(), 1U);
- }
- }
- }
- }
-
- stream << "Unused Tokens:\n";
- stream << std::right;
- stream << std::setw(8) << "Buffer Id";
- stream << " ";
- stream << std::setw(7) << "#Tokens";
- stream << std::endl;
-
- for (auto iter = tokenCount.begin(); iter != tokenCount.end(); ++iter) {
- stream << std::right;
- stream << std::setw(8) << /*Buffer Id=*/iter->first;
- stream << " ";
- stream << std::setw(7) << /*#Tokens=*/iter->second;
- stream << std::endl;
- }
-
- fprintf(out, "%s", stream.str().c_str());
-
- fclose(out);
- return Void();
-}
-
-hidl_handle BufferHubService::registerToken(const wp<BufferClient>& client) {
- // Find next available token id
- std::lock_guard<std::mutex> lock(mTokenMutex);
- do {
- ++mLastTokenId;
- } while (mTokenMap.find(mLastTokenId) != mTokenMap.end());
-
- std::array<uint8_t, EVP_MAX_MD_SIZE> hmac;
- uint32_t hmacSize = 0U;
-
- HMAC(/*evp_md=*/EVP_sha256(), /*key=*/&mKey, /*key_len=*/kKeyLen,
- /*data=*/(uint8_t*)&mLastTokenId, /*data_len=*/mTokenIdSize,
- /*out=*/hmac.data(), /*out_len=*/&hmacSize);
-
- int numIntsForHMAC = (int)ceil(hmacSize / (double)sizeof(int));
- native_handle_t* handle = native_handle_create(/*numFds=*/0, /*numInts=*/1 + numIntsForHMAC);
- handle->data[0] = mLastTokenId;
- // Set all the the bits of last int to 0 since it might not be fully overwritten
- handle->data[numIntsForHMAC] = 0;
- memcpy(&handle->data[1], hmac.data(), hmacSize);
-
- // returnToken owns the native_handle_t* thus doing lifecycle management
- hidl_handle returnToken;
- returnToken.setTo(handle, /*shoudOwn=*/true);
-
- std::vector<uint8_t> hmacVec;
- hmacVec.resize(hmacSize);
- memcpy(hmacVec.data(), hmac.data(), hmacSize);
- mTokenMap.emplace(mLastTokenId, std::pair(hmacVec, client));
-
- return returnToken;
-}
-
-void BufferHubService::onClientClosed(const BufferClient* client) {
- removeTokenByClient(client);
-
- std::lock_guard<std::mutex> lock(mClientSetMutex);
- auto iter = std::find(mClientSet.begin(), mClientSet.end(), client);
- if (iter != mClientSet.end()) {
- mClientSet.erase(iter);
- }
-}
-
-// Implementation of this function should be consistent with the definition of bufferInfo handle in
-// ui/BufferHubDefs.h.
-hidl_handle BufferHubService::buildBufferInfo(char* bufferInfoStorage, int bufferId,
- uint32_t clientBitMask, uint32_t userMetadataSize,
- int metadataFd, int eventFd) {
- native_handle_t* infoHandle =
- native_handle_init(bufferInfoStorage, BufferHubDefs::kBufferInfoNumFds,
- BufferHubDefs::kBufferInfoNumInts);
-
- infoHandle->data[0] = metadataFd;
- infoHandle->data[1] = eventFd;
- infoHandle->data[2] = bufferId;
- // Use memcpy to convert to int without missing digit.
- // TOOD(b/121345852): use bit_cast to unpack bufferInfo when C++20 becomes available.
- memcpy(&infoHandle->data[3], &clientBitMask, sizeof(clientBitMask));
- memcpy(&infoHandle->data[4], &userMetadataSize, sizeof(userMetadataSize));
-
- hidl_handle bufferInfo;
- bufferInfo.setTo(infoHandle, /*shouldOwn=*/false);
-
- return bufferInfo;
-}
-
-void BufferHubService::removeTokenByClient(const BufferClient* client) {
- std::lock_guard<std::mutex> lock(mTokenMutex);
- auto iter = mTokenMap.begin();
- while (iter != mTokenMap.end()) {
- if (iter->second.second == client) {
- auto oldIter = iter;
- ++iter;
- mTokenMap.erase(oldIter);
- } else {
- ++iter;
- }
- }
-}
-
-} // namespace implementation
-} // namespace V1_0
-} // namespace bufferhub
-} // namespace frameworks
-} // namespace android
diff --git a/services/bufferhub/BufferNode.cpp b/services/bufferhub/BufferNode.cpp
deleted file mode 100644
index 04ca649..0000000
--- a/services/bufferhub/BufferNode.cpp
+++ /dev/null
@@ -1,113 +0,0 @@
-#include <errno.h>
-
-#include <bufferhub/BufferHubService.h>
-#include <bufferhub/BufferNode.h>
-#include <log/log.h>
-#include <ui/GraphicBufferAllocator.h>
-
-namespace android {
-namespace frameworks {
-namespace bufferhub {
-namespace V1_0 {
-namespace implementation {
-
-void BufferNode::initializeMetadata() {
- // Using placement new here to reuse shared memory instead of new allocation
- // Initialize the atomic variables to zero.
- BufferHubDefs::MetadataHeader* metadataHeader = mMetadata.metadataHeader();
- mBufferState = new (&metadataHeader->bufferState) std::atomic<uint32_t>(0);
- mFenceState = new (&metadataHeader->fenceState) std::atomic<uint32_t>(0);
- mActiveClientsBitMask = new (&metadataHeader->activeClientsBitMask) std::atomic<uint32_t>(0);
- // The C++ standard recommends (but does not require) that lock-free atomic operations are
- // also address-free, that is, suitable for communication between processes using shared
- // memory.
- LOG_ALWAYS_FATAL_IF(!std::atomic_is_lock_free(mBufferState) ||
- !std::atomic_is_lock_free(mFenceState) ||
- !std::atomic_is_lock_free(mActiveClientsBitMask),
- "Atomic variables in ashmen are not lock free.");
-}
-
-// Allocates a new BufferNode.
-BufferNode::BufferNode(uint32_t width, uint32_t height, uint32_t layerCount, uint32_t format,
- uint64_t usage, size_t userMetadataSize, int id)
- : mId(id) {
- uint32_t outStride = 0;
- // graphicBufferId is not used in GraphicBufferAllocator::allocate
- // TODO(b/112338294) After move to the service folder, stop using the
- // hardcoded service name "bufferhub".
- int ret = GraphicBufferAllocator::get().allocate(width, height, format, layerCount, usage,
- const_cast<const native_handle_t**>(
- &mBufferHandle),
- &outStride,
- /*graphicBufferId=*/0,
- /*requestor=*/"bufferhub");
-
- if (ret != OK || mBufferHandle == nullptr) {
- ALOGE("%s: Failed to allocate buffer: %s", __FUNCTION__, strerror(-ret));
- return;
- }
-
- mBufferDesc.width = width;
- mBufferDesc.height = height;
- mBufferDesc.layers = layerCount;
- mBufferDesc.format = format;
- mBufferDesc.usage = usage;
- mBufferDesc.stride = outStride;
-
- mMetadata = BufferHubMetadata::create(userMetadataSize);
- if (!mMetadata.isValid()) {
- ALOGE("%s: Failed to allocate metadata.", __FUNCTION__);
- return;
- }
- initializeMetadata();
-}
-
-BufferNode::~BufferNode() {
- // Free the handle
- if (mBufferHandle != nullptr) {
- status_t ret = GraphicBufferAllocator::get().free(mBufferHandle);
- if (ret != OK) {
- ALOGE("%s: Failed to free handle; Got error: %d", __FUNCTION__, ret);
- }
- }
-
- // Free the id, if valid
- if (mId >= 0) {
- BufferHubIdGenerator::getInstance().freeId(mId);
- }
-}
-
-uint32_t BufferNode::getActiveClientsBitMask() const {
- return mActiveClientsBitMask->load(std::memory_order_acquire);
-}
-
-uint32_t BufferNode::addNewActiveClientsBitToMask() {
- uint32_t currentActiveClientsBitMask = getActiveClientsBitMask();
- uint32_t clientStateMask = 0U;
- uint32_t updatedActiveClientsBitMask = 0U;
- do {
- clientStateMask =
- BufferHubDefs::findNextAvailableClientStateMask(currentActiveClientsBitMask);
- if (clientStateMask == 0U) {
- ALOGE("%s: reached the maximum number of channels per buffer node: %d.", __FUNCTION__,
- BufferHubDefs::kMaxNumberOfClients);
- errno = E2BIG;
- return 0U;
- }
- updatedActiveClientsBitMask = currentActiveClientsBitMask | clientStateMask;
- } while (!(mActiveClientsBitMask->compare_exchange_weak(currentActiveClientsBitMask,
- updatedActiveClientsBitMask,
- std::memory_order_acq_rel,
- std::memory_order_acquire)));
- return clientStateMask;
-}
-
-void BufferNode::removeClientsBitFromMask(const uint32_t& value) {
- mActiveClientsBitMask->fetch_and(~value);
-}
-
-} // namespace implementation
-} // namespace V1_0
-} // namespace bufferhub
-} // namespace frameworks
-} // namespace android
diff --git a/services/bufferhub/android.frameworks.bufferhub@1.0-service.rc b/services/bufferhub/android.frameworks.bufferhub@1.0-service.rc
deleted file mode 100644
index 36fbede..0000000
--- a/services/bufferhub/android.frameworks.bufferhub@1.0-service.rc
+++ /dev/null
@@ -1,6 +0,0 @@
-service system_bufferhub /system/bin/hw/android.frameworks.bufferhub@1.0-service
- class hal animation
- user system
- group system graphics
- onrestart restart surfaceflinger
- writepid /dev/cpuset/system-background/tasks
diff --git a/services/bufferhub/android.frameworks.bufferhub@1.0-service.xml b/services/bufferhub/android.frameworks.bufferhub@1.0-service.xml
deleted file mode 100644
index bd958d3..0000000
--- a/services/bufferhub/android.frameworks.bufferhub@1.0-service.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<manifest version="1.0" type="framework">
- <hal>
- <name>android.frameworks.bufferhub</name>
- <transport>hwbinder</transport>
- <version>1.0</version>
- <interface>
- <name>IBufferHub</name>
- <instance>default</instance>
- </interface>
- </hal>
-</manifest>
diff --git a/services/bufferhub/include/bufferhub/BufferClient.h b/services/bufferhub/include/bufferhub/BufferClient.h
deleted file mode 100644
index 644b403..0000000
--- a/services/bufferhub/include/bufferhub/BufferClient.h
+++ /dev/null
@@ -1,75 +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.
- */
-
-#ifndef ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_BUFFER_CLIENT_H
-#define ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_BUFFER_CLIENT_H
-
-#include <mutex>
-
-#include <android/frameworks/bufferhub/1.0/IBufferClient.h>
-#include <bufferhub/BufferNode.h>
-
-namespace android {
-namespace frameworks {
-namespace bufferhub {
-namespace V1_0 {
-namespace implementation {
-
-using hardware::hidl_handle;
-using hardware::Return;
-
-// Forward declaration to avoid circular dependency
-class BufferHubService;
-
-class BufferClient : public IBufferClient {
-public:
- // Creates a server-side buffer client from an existing BufferNode. Note that
- // this function takes ownership of the shared_ptr.
- // Returns a raw pointer to the BufferClient on success, nullptr on failure.
- static BufferClient* create(BufferHubService* service, const std::shared_ptr<BufferNode>& node);
-
- // Creates a BufferClient from an existing BufferClient. Will share the same BufferNode.
- explicit BufferClient(const BufferClient& other)
- : mService(other.mService), mBufferNode(other.mBufferNode) {}
- ~BufferClient();
-
- Return<BufferHubStatus> close() override;
- Return<void> duplicate(duplicate_cb _hidl_cb) override;
-
- // Non-binder functions
- const std::shared_ptr<BufferNode>& getBufferNode() const { return mBufferNode; }
-
-private:
- BufferClient(wp<BufferHubService> service, const std::shared_ptr<BufferNode>& node)
- : mService(service), mBufferNode(node) {}
-
- sp<BufferHubService> getService();
-
- wp<BufferHubService> mService;
-
- std::mutex mClosedMutex;
- bool mClosed GUARDED_BY(mClosedMutex) = false;
-
- std::shared_ptr<BufferNode> mBufferNode;
-};
-
-} // namespace implementation
-} // namespace V1_0
-} // namespace bufferhub
-} // namespace frameworks
-} // namespace android
-
-#endif
diff --git a/services/bufferhub/include/bufferhub/BufferHubIdGenerator.h b/services/bufferhub/include/bufferhub/BufferHubIdGenerator.h
deleted file mode 100644
index ef7c077..0000000
--- a/services/bufferhub/include/bufferhub/BufferHubIdGenerator.h
+++ /dev/null
@@ -1,61 +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.
- */
-
-#ifndef ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_ID_GENERATOR_H
-#define ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_ID_GENERATOR_H
-
-#include <mutex>
-#include <set>
-
-#include <utils/Mutex.h>
-
-namespace android {
-namespace frameworks {
-namespace bufferhub {
-namespace V1_0 {
-namespace implementation {
-
-// A thread-safe, non-negative, incremental, int id generator.
-class BufferHubIdGenerator {
-public:
- // Get the singleton instance of this class
- static BufferHubIdGenerator& getInstance();
-
- // Gets next available id. If next id is greater than std::numeric_limits<int32_t>::max(), it
- // will try to get an id start from 0 again.
- int getId();
-
- // Free a specific id.
- void freeId(int id);
-
-private:
- BufferHubIdGenerator() = default;
- ~BufferHubIdGenerator() = default;
-
- // Start from -1 so all valid ids will be >= 0
- int mLastId = -1;
-
- std::mutex mIdsInUseMutex;
- std::set<int> mIdsInUse GUARDED_BY(mIdsInUseMutex);
-};
-
-} // namespace implementation
-} // namespace V1_0
-} // namespace bufferhub
-} // namespace frameworks
-} // namespace android
-
-#endif // ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_ID_GENERATOR_H
diff --git a/services/bufferhub/include/bufferhub/BufferHubService.h b/services/bufferhub/include/bufferhub/BufferHubService.h
deleted file mode 100644
index edad20b..0000000
--- a/services/bufferhub/include/bufferhub/BufferHubService.h
+++ /dev/null
@@ -1,92 +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.
- */
-
-#ifndef ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_BUFFER_HUB_SERVICE_H
-#define ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_BUFFER_HUB_SERVICE_H
-
-#include <map>
-#include <mutex>
-#include <set>
-#include <vector>
-
-#include <android/frameworks/bufferhub/1.0/IBufferHub.h>
-#include <bufferhub/BufferClient.h>
-#include <bufferhub/BufferHubIdGenerator.h>
-#include <utils/Mutex.h>
-
-namespace android {
-namespace frameworks {
-namespace bufferhub {
-namespace V1_0 {
-namespace implementation {
-
-using hardware::hidl_handle;
-using hardware::hidl_string;
-using hardware::hidl_vec;
-using hardware::Return;
-using hardware::graphics::common::V1_2::HardwareBufferDescription;
-
-class BufferHubService : public IBufferHub {
-public:
- BufferHubService();
-
- Return<void> allocateBuffer(const HardwareBufferDescription& description,
- const uint32_t userMetadataSize,
- allocateBuffer_cb _hidl_cb) override;
- Return<void> importBuffer(const hidl_handle& tokenHandle, importBuffer_cb _hidl_cb) override;
-
- Return<void> debug(const hidl_handle& fd, const hidl_vec<hidl_string>& args) override;
-
- // Non-binder functions
- // Internal help function for IBufferClient::duplicate.
- hidl_handle registerToken(const wp<BufferClient>& client);
-
- void onClientClosed(const BufferClient* client);
-
-private:
- // Helper function to build BufferTraits.bufferInfo handle
- hidl_handle buildBufferInfo(char* bufferInfoStorage, int bufferId, uint32_t clientBitMask,
- uint32_t userMetadataSize, int metadataFd, int eventFd);
-
- // Helper function to remove all the token belongs to a specific client.
- void removeTokenByClient(const BufferClient* client);
-
- // List of active BufferClient for bookkeeping.
- std::mutex mClientSetMutex;
- std::set<wp<BufferClient>> mClientSet GUARDED_BY(mClientSetMutex);
-
- // Token generation related
- // A random number used as private key for HMAC
- uint64_t mKey;
- static constexpr size_t kKeyLen = sizeof(uint64_t);
-
- std::mutex mTokenMutex;
- // The first TokenId will be 1. TokenId could be negative.
- int mLastTokenId GUARDED_BY(mTokenMutex) = 0;
- static constexpr size_t mTokenIdSize = sizeof(int);
- // A map from token id to the token-buffer_client pair. Using token id as the key to reduce
- // looking up time
- std::map<int, std::pair<std::vector<uint8_t>, const wp<BufferClient>>> mTokenMap
- GUARDED_BY(mTokenMutex);
-};
-
-} // namespace implementation
-} // namespace V1_0
-} // namespace bufferhub
-} // namespace frameworks
-} // namespace android
-
-#endif // ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_BUFFER_HUB_SERVICE_H
diff --git a/services/bufferhub/include/bufferhub/BufferNode.h b/services/bufferhub/include/bufferhub/BufferNode.h
deleted file mode 100644
index 62a8d63..0000000
--- a/services/bufferhub/include/bufferhub/BufferNode.h
+++ /dev/null
@@ -1,100 +0,0 @@
-#ifndef ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_BUFFER_NODE_H_
-#define ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_BUFFER_NODE_H_
-
-#include <android/hardware_buffer.h>
-#include <bufferhub/BufferHubIdGenerator.h>
-#include <cutils/native_handle.h>
-#include <ui/BufferHubEventFd.h>
-#include <ui/BufferHubMetadata.h>
-
-namespace android {
-namespace frameworks {
-namespace bufferhub {
-namespace V1_0 {
-namespace implementation {
-
-class BufferNode {
-public:
- // Allocates a new BufferNode.
- BufferNode(uint32_t width, uint32_t height, uint32_t layerCount, uint32_t format,
- uint64_t usage, size_t userMetadataSize, int id = -1);
-
- ~BufferNode();
-
- // Returns whether the object holds a valid metadata.
- bool isValid() const { return mMetadata.isValid(); }
-
- int id() const { return mId; }
-
- size_t userMetadataSize() const { return mMetadata.userMetadataSize(); }
-
- // Accessors of the buffer description and handle
- const native_handle_t* bufferHandle() const { return mBufferHandle; }
- const AHardwareBuffer_Desc& bufferDesc() const { return mBufferDesc; }
-
- // Accessor of event fd.
- const BufferHubEventFd& eventFd() const { return mEventFd; }
-
- // Accessors of mMetadata.
- const BufferHubMetadata& metadata() const { return mMetadata; }
-
- // Gets the current value of mActiveClientsBitMask in mMetadata with
- // std::memory_order_acquire, so that all previous releases of
- // mActiveClientsBitMask from all threads will be returned here.
- uint32_t getActiveClientsBitMask() const;
-
- // Find and add a new client state mask to mActiveClientsBitMask in
- // mMetadata.
- // Return the new client state mask that is added to mActiveClientsBitMask.
- // Return 0U if there are already 16 clients of the buffer.
- uint32_t addNewActiveClientsBitToMask();
-
- // Removes the value from active_clients_bit_mask in mMetadata with
- // std::memory_order_release, so that the change will be visible to any
- // acquire of mActiveClientsBitMask in any threads after the succeed of
- // this operation.
- void removeClientsBitFromMask(const uint32_t& value);
-
-private:
- // Helper method for constructors to initialize atomic metadata header
- // variables in shared memory.
- void initializeMetadata();
-
- // Gralloc buffer handles.
- native_handle_t* mBufferHandle;
- AHardwareBuffer_Desc mBufferDesc;
-
- // Eventfd used for signalling buffer events among the clients of the buffer.
- BufferHubEventFd mEventFd;
-
- // Metadata in shared memory.
- BufferHubMetadata mMetadata;
-
- // A system-unique id generated by bufferhub from 0 to std::numeric_limits<int>::max().
- // BufferNodes not created by bufferhub will have id < 0, meaning "not specified".
- // TODO(b/118891412): remove default id = -1 and update comments after pdx is no longer in use
- const int mId = -1;
-
- // The following variables are atomic variables in mMetadata that are visible
- // to Bn object and Bp objects. Please find more info in
- // BufferHubDefs::MetadataHeader.
-
- // mBufferState tracks the state of the buffer. Buffer can be in one of these
- // four states: gained, posted, acquired, released.
- std::atomic<uint32_t>* mBufferState = nullptr;
-
- // TODO(b/112012161): add comments to mFenceState.
- std::atomic<uint32_t>* mFenceState = nullptr;
-
- // mActiveClientsBitMask tracks all the bp clients of the buffer. It is the
- // union of all client_state_mask of all bp clients.
- std::atomic<uint32_t>* mActiveClientsBitMask = nullptr;
-};
-
-} // namespace implementation
-} // namespace V1_0
-} // namespace bufferhub
-} // namespace frameworks
-} // namespace android
-
-#endif // ANDROID_FRAMEWORKS_BUFFERHUB_V1_0_BUFFER_NODE_H_
diff --git a/services/bufferhub/main_bufferhub.cpp b/services/bufferhub/main_bufferhub.cpp
deleted file mode 100644
index 084460d..0000000
--- a/services/bufferhub/main_bufferhub.cpp
+++ /dev/null
@@ -1,37 +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 <bufferhub/BufferHubService.h>
-#include <hidl/HidlTransportSupport.h>
-#include <hwbinder/IPCThreadState.h>
-#include <log/log.h>
-
-using android::sp;
-using android::frameworks::bufferhub::V1_0::IBufferHub;
-using android::frameworks::bufferhub::V1_0::implementation::BufferHubService;
-
-int main(int /*argc*/, char** /*argv*/) {
- ALOGI("Bootstrap bufferhub HIDL service.");
-
- android::hardware::configureRpcThreadpool(/*numThreads=*/1, /*willJoin=*/true);
-
- sp<IBufferHub> service = new BufferHubService();
- LOG_ALWAYS_FATAL_IF(service->registerAsService() != android::OK, "Failed to register service");
-
- android::hardware::joinRpcThreadpool();
-
- return 0;
-}
diff --git a/services/bufferhub/tests/Android.bp b/services/bufferhub/tests/Android.bp
deleted file mode 100644
index 3033e70..0000000
--- a/services/bufferhub/tests/Android.bp
+++ /dev/null
@@ -1,26 +0,0 @@
-cc_test {
- name: "BufferHubServer_test",
- srcs: [
- "BufferNode_test.cpp",
- "BufferHubIdGenerator_test.cpp",
- ],
- cflags: [
- "-DLOG_TAG=\"BufferHubServer_test\"",
- "-DTRACE=0",
- "-DATRACE_TAG=ATRACE_TAG_GRAPHICS",
- "-Wall",
- "-Werror",
- ],
- compile_multilib: "first",
- header_libs: [
- "libdvr_headers",
- "libnativewindow_headers",
- ],
- shared_libs: [
- "libbufferhubservice",
- "libui",
- ],
- static_libs: [
- "libgmock",
- ],
-}
diff --git a/services/bufferhub/tests/BufferHubIdGenerator_test.cpp b/services/bufferhub/tests/BufferHubIdGenerator_test.cpp
deleted file mode 100644
index fb6de0d..0000000
--- a/services/bufferhub/tests/BufferHubIdGenerator_test.cpp
+++ /dev/null
@@ -1,48 +0,0 @@
-#include <bufferhub/BufferHubIdGenerator.h>
-#include <gtest/gtest.h>
-
-namespace android {
-namespace frameworks {
-namespace bufferhub {
-namespace V1_0 {
-namespace implementation {
-
-namespace {
-
-class BufferHubIdGeneratorTest : public testing::Test {
-protected:
- BufferHubIdGenerator* mIdGenerator = &BufferHubIdGenerator::getInstance();
-};
-
-TEST_F(BufferHubIdGeneratorTest, TestGenerateAndFreeID) {
- int id = mIdGenerator->getId();
- EXPECT_GE(id, 0);
-
- mIdGenerator->freeId(id);
-}
-
-TEST_F(BufferHubIdGeneratorTest, TestGenerateUniqueIncrementalID) {
- // 10 IDs should not overflow the UniqueIdGenerator to cause a roll back to start, so the
- // resulting IDs should still keep incresing.
- const int kTestSize = 10;
- int ids[kTestSize];
- for (int i = 0; i < kTestSize; ++i) {
- ids[i] = mIdGenerator->getId();
- EXPECT_GE(ids[i], 0);
- if (i >= 1) {
- EXPECT_GT(ids[i], ids[i - 1]);
- }
- }
-
- for (int i = 0; i < kTestSize; ++i) {
- mIdGenerator->freeId(ids[i]);
- }
-}
-
-} // namespace
-
-} // namespace implementation
-} // namespace V1_0
-} // namespace bufferhub
-} // namespace frameworks
-} // namespace android
\ No newline at end of file
diff --git a/services/bufferhub/tests/BufferNode_test.cpp b/services/bufferhub/tests/BufferNode_test.cpp
deleted file mode 100644
index 2dfd4fc..0000000
--- a/services/bufferhub/tests/BufferNode_test.cpp
+++ /dev/null
@@ -1,109 +0,0 @@
-#include <errno.h>
-
-#include <bufferhub/BufferNode.h>
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-#include <ui/BufferHubDefs.h>
-#include <ui/GraphicBufferMapper.h>
-
-namespace android {
-namespace frameworks {
-namespace bufferhub {
-namespace V1_0 {
-namespace implementation {
-
-namespace {
-
-using testing::NotNull;
-
-const uint32_t kWidth = 640;
-const uint32_t kHeight = 480;
-const uint32_t kLayerCount = 1;
-const uint32_t kFormat = 1;
-const uint64_t kUsage = 0;
-const size_t kUserMetadataSize = 0;
-
-class BufferNodeTest : public ::testing::Test {
-protected:
- void SetUp() override {
- mBufferNode =
- new BufferNode(kWidth, kHeight, kLayerCount, kFormat, kUsage, kUserMetadataSize);
- ASSERT_TRUE(mBufferNode->isValid());
- }
-
- void TearDown() override {
- if (mBufferNode != nullptr) {
- delete mBufferNode;
- }
- }
-
- BufferNode* mBufferNode = nullptr;
-};
-
-TEST_F(BufferNodeTest, TestCreateBufferNode) {
- EXPECT_EQ(mBufferNode->userMetadataSize(), kUserMetadataSize);
- // Test the handle just allocated is good (i.e. able to be imported)
- GraphicBufferMapper& mapper = GraphicBufferMapper::get();
- const native_handle_t* outHandle;
- status_t ret =
- mapper.importBuffer(mBufferNode->bufferHandle(), mBufferNode->bufferDesc().width,
- mBufferNode->bufferDesc().height, mBufferNode->bufferDesc().layers,
- mBufferNode->bufferDesc().format, mBufferNode->bufferDesc().usage,
- mBufferNode->bufferDesc().stride, &outHandle);
- EXPECT_EQ(ret, OK);
- EXPECT_THAT(outHandle, NotNull());
-}
-
-TEST_F(BufferNodeTest, TestaddNewActiveClientsBitToMask_twoNewClients) {
- uint32_t newClientStateMask1 = mBufferNode->addNewActiveClientsBitToMask();
- EXPECT_EQ(mBufferNode->getActiveClientsBitMask(), newClientStateMask1);
-
- // Request and add a new client_state_mask again.
- // Active clients bit mask should be the union of the two new
- // client_state_masks.
- uint32_t newClientStateMask2 = mBufferNode->addNewActiveClientsBitToMask();
- EXPECT_EQ(mBufferNode->getActiveClientsBitMask(), newClientStateMask1 | newClientStateMask2);
-}
-
-TEST_F(BufferNodeTest, TestaddNewActiveClientsBitToMask_32NewClients) {
- uint32_t newClientStateMask = 0U;
- uint32_t currentMask = 0U;
- uint32_t expectedMask = 0U;
-
- for (int i = 0; i < BufferHubDefs::kMaxNumberOfClients; ++i) {
- newClientStateMask = mBufferNode->addNewActiveClientsBitToMask();
- EXPECT_NE(newClientStateMask, 0U);
- EXPECT_FALSE(newClientStateMask & currentMask);
- expectedMask = currentMask | newClientStateMask;
- currentMask = mBufferNode->getActiveClientsBitMask();
- EXPECT_EQ(currentMask, expectedMask);
- }
-
- // Method should fail upon requesting for more than maximum allowable clients.
- newClientStateMask = mBufferNode->addNewActiveClientsBitToMask();
- EXPECT_EQ(newClientStateMask, 0U);
- EXPECT_EQ(errno, E2BIG);
-}
-
-TEST_F(BufferNodeTest, TestRemoveActiveClientsBitFromMask) {
- mBufferNode->addNewActiveClientsBitToMask();
- uint32_t currentMask = mBufferNode->getActiveClientsBitMask();
- uint32_t newClientStateMask = mBufferNode->addNewActiveClientsBitToMask();
- EXPECT_NE(mBufferNode->getActiveClientsBitMask(), currentMask);
-
- mBufferNode->removeClientsBitFromMask(newClientStateMask);
- EXPECT_EQ(mBufferNode->getActiveClientsBitMask(), currentMask);
-
- // Remove the test_mask again to the active client bit mask should not modify
- // the value of active clients bit mask.
- mBufferNode->removeClientsBitFromMask(newClientStateMask);
- EXPECT_EQ(mBufferNode->getActiveClientsBitMask(), currentMask);
-}
-
-} // namespace
-
-} // namespace implementation
-} // namespace V1_0
-} // namespace bufferhub
-} // namespace frameworks
-} // namespace android
diff --git a/services/sensorservice/SensorDirectConnection.cpp b/services/sensorservice/SensorDirectConnection.cpp
index 1622e77..106efd6 100644
--- a/services/sensorservice/SensorDirectConnection.cpp
+++ b/services/sensorservice/SensorDirectConnection.cpp
@@ -93,23 +93,6 @@
return nullptr;
}
-void SensorService::SensorDirectConnection::updateSensorSubscriptions() {
- if (!hasSensorAccess()) {
- stopAll(true /* backupRecord */);
- } else {
- recoverAll();
- }
-}
-
-void SensorService::SensorDirectConnection::setSensorAccess(bool hasAccess) {
- mHasSensorAccess = hasAccess;
- updateSensorSubscriptions();
-}
-
-bool SensorService::SensorDirectConnection::hasSensorAccess() const {
- return mHasSensorAccess && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
-}
-
status_t SensorService::SensorDirectConnection::enableDisable(
int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
int reservedFlags) {
diff --git a/services/sensorservice/SensorDirectConnection.h b/services/sensorservice/SensorDirectConnection.h
index fa88fbc..ead08d3 100644
--- a/services/sensorservice/SensorDirectConnection.h
+++ b/services/sensorservice/SensorDirectConnection.h
@@ -54,9 +54,6 @@
// called by SensorService when return to NORMAL mode.
void recoverAll();
- void updateSensorSubscriptions();
-
- void setSensorAccess(bool hasAccess);
protected:
virtual ~SensorDirectConnection();
// ISensorEventConnection functions
@@ -69,7 +66,6 @@
virtual int32_t configureChannel(int handle, int rateLevel);
virtual void destroy();
private:
- bool hasSensorAccess() const;
const sp<SensorService> mService;
const uid_t mUid;
const sensors_direct_mem_t mMem;
@@ -80,8 +76,6 @@
std::unordered_map<int, int> mActivated;
std::unordered_map<int, int> mActivatedBackup;
- std::atomic_bool mHasSensorAccess = true;
-
mutable Mutex mDestroyLock;
bool mDestroyed;
};
diff --git a/services/sensorservice/SensorEventConnection.cpp b/services/sensorservice/SensorEventConnection.cpp
index 77d8c11..e799372 100644
--- a/services/sensorservice/SensorEventConnection.cpp
+++ b/services/sensorservice/SensorEventConnection.cpp
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-#include <cinttypes>
#include <sys/socket.h>
#include <utils/threads.h>
@@ -70,17 +69,17 @@
}
bool SensorService::SensorEventConnection::needsWakeLock() {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
return !mDead && mWakeLockRefCount > 0;
}
void SensorService::SensorEventConnection::resetWakeLockRefCount() {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
mWakeLockRefCount = 0;
}
void SensorService::SensorEventConnection::dump(String8& result) {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
result.appendFormat("\tOperating Mode: ");
if (!mService->isWhiteListedPackage(getPackageName())) {
result.append("RESTRICTED\n");
@@ -93,7 +92,7 @@
"max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
mMaxCacheSize);
for (auto& it : mSensorInfo) {
- const FlushInfo& flushInfo = it.second.flushInfo;
+ const FlushInfo& flushInfo = it.second;
result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
mService->getSensorName(it.first).string(),
it.first,
@@ -122,7 +121,7 @@
*/
void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
using namespace service::SensorEventConnectionProto;
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
if (!mService->isWhiteListedPackage(getPackageName())) {
proto->write(OPERATING_MODE, OP_MODE_RESTRICTED);
@@ -137,7 +136,7 @@
proto->write(CACHE_SIZE, int32_t(mCacheSize));
proto->write(MAX_CACHE_SIZE, int32_t(mMaxCacheSize));
for (auto& it : mSensorInfo) {
- const FlushInfo& flushInfo = it.second.flushInfo;
+ const FlushInfo& flushInfo = it.second;
const uint64_t token = proto->start(FLUSH_INFOS);
proto->write(FlushInfoProto::SENSOR_NAME,
std::string(mService->getSensorName(it.first)));
@@ -158,33 +157,28 @@
#endif
}
-bool SensorService::SensorEventConnection::addSensor(
- int32_t handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags) {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
+ Mutex::Autolock _l(mConnectionLock);
sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
if (si == nullptr ||
!canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
mSensorInfo.count(handle) > 0) {
return false;
}
-
- SensorRequest request = {
- .samplingPeriodNs = samplingPeriodNs,
- .maxBatchReportLatencyNs = maxBatchReportLatencyNs,
- .reservedFlags = reservedFlags
- };
-
- mSensorInfo[handle] = request;
+ mSensorInfo[handle] = FlushInfo();
return true;
}
bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
- return mSensorInfo.erase(handle) > 0;
+ Mutex::Autolock _l(mConnectionLock);
+ if (mSensorInfo.erase(handle) >= 0) {
+ return true;
+ }
+ return false;
}
std::vector<int32_t> SensorService::SensorEventConnection::getActiveSensorHandles() const {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
std::vector<int32_t> list;
for (auto& it : mSensorInfo) {
list.push_back(it.first);
@@ -193,17 +187,17 @@
}
bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
- return mSensorInfo.count(handle) + mSensorInfoBackup.count(handle) > 0;
+ Mutex::Autolock _l(mConnectionLock);
+ return mSensorInfo.count(handle) > 0;
}
bool SensorService::SensorEventConnection::hasAnySensor() const {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
- return mSensorInfo.size() + mSensorInfoBackup.size() ? true : false;
+ Mutex::Autolock _l(mConnectionLock);
+ return mSensorInfo.size() ? true : false;
}
bool SensorService::SensorEventConnection::hasOneShotSensors() const {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
for (auto &it : mSensorInfo) {
const int handle = it.first;
sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
@@ -220,15 +214,15 @@
void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
bool value) {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
if (mSensorInfo.count(handle) > 0) {
- FlushInfo& flushInfo = mSensorInfo[handle].flushInfo;
+ FlushInfo& flushInfo = mSensorInfo[handle];
flushInfo.mFirstFlushPending = value;
}
}
void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
updateLooperRegistrationLocked(looper);
}
@@ -279,9 +273,9 @@
}
void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
if (mSensorInfo.count(handle) > 0) {
- FlushInfo& flushInfo = mSensorInfo[handle].flushInfo;
+ FlushInfo& flushInfo = mSensorInfo[handle];
flushInfo.mPendingFlushEventsToSend++;
}
}
@@ -295,7 +289,7 @@
std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
int count = 0;
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
if (scratch) {
size_t i=0;
while (i<numEvents) {
@@ -316,7 +310,7 @@
continue;
}
- FlushInfo& flushInfo = mSensorInfo[sensor_handle].flushInfo;
+ FlushInfo& flushInfo = mSensorInfo[sensor_handle];
// Check if there is a pending flush_complete event for this sensor on this connection.
if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
mapFlushEventsToConnections[i] == this) {
@@ -437,55 +431,9 @@
return size < 0 ? status_t(size) : status_t(NO_ERROR);
}
-void SensorService::SensorEventConnection::updateSensorSubscriptions() {
- if (!hasSensorAccess()) {
- stopAll();
- } else {
- recoverAll();
- }
-}
-
void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
- if (mHasSensorAccess != hasAccess) {
- mHasSensorAccess = hasAccess;
- updateSensorSubscriptions();
- }
-}
-
-void SensorService::SensorEventConnection::stopAll() {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
- if (!mSensorInfo.empty()) {
- mSensorInfoBackup = mSensorInfo;
- mSensorInfo.clear();
-
- for (auto& it : mSensorInfoBackup) {
- int32_t handle = it.first;
-
- status_t err = mService->disable(this, handle);
-
- if (err != NO_ERROR) {
- ALOGE("Error disabling sensor %d", handle);
- }
- }
- }
-}
-
-void SensorService::SensorEventConnection::recoverAll() {
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
- for (auto& it : mSensorInfoBackup) {
- int32_t handle = it.first;
- SensorRequest &request = it.second;
-
- status_t err = mService->enable(
- this, handle, request.samplingPeriodNs, request.maxBatchReportLatencyNs,
- request.reservedFlags, mOpPackageName);
-
- if (err != NO_ERROR) {
- ALOGE("Error recovering sensor %d", handle);
- }
- }
-
- mSensorInfoBackup.clear();
+ Mutex::Autolock _l(mConnectionLock);
+ mHasSensorAccess = hasAccess;
}
bool SensorService::SensorEventConnection::hasSensorAccess() {
@@ -587,7 +535,7 @@
continue;
}
- FlushInfo& flushInfo = it.second.flushInfo;
+ FlushInfo& flushInfo = it.second;
while (flushInfo.mPendingFlushEventsToSend > 0) {
flushCompleteEvent.meta_data.sensor = handle;
bool wakeUpSensor = si->getSensor().isWakeUpSensor();
@@ -612,7 +560,7 @@
// half the size of the socket buffer allocated in BitTube whichever is smaller.
const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
// Send pending flush complete events (if any)
sendPendingFlushEventsLocked();
for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
@@ -679,7 +627,7 @@
continue;
}
- FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor].flushInfo;
+ FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor];
flushInfo.mPendingFlushEventsToSend++;
ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
flushInfo.mPendingFlushEventsToSend);
@@ -715,21 +663,13 @@
} else {
err = mService->disable(this, handle);
}
-
return err;
}
status_t SensorService::SensorEventConnection::setEventRate(
int handle, nsecs_t samplingPeriodNs)
{
- status_t err = mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
-
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
- if (err == NO_ERROR && mSensorInfo.count(handle) > 0) {
- mSensorInfo[handle].samplingPeriodNs = samplingPeriodNs;
- }
-
- return err;
+ return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
}
status_t SensorService::SensorEventConnection::flush() {
@@ -750,7 +690,7 @@
// and remove the fd from Looper. Call checkWakeLockState to know if SensorService
// can release the wake-lock.
ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
mDead = true;
mWakeLockRefCount = 0;
updateLooperRegistrationLocked(mService->getLooper());
@@ -769,7 +709,7 @@
unsigned char buf[sizeof(sensors_event_t)];
ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
{
- std::lock_guard<std::recursive_mutex> _l(mConnectionLock);
+ Mutex::Autolock _l(mConnectionLock);
if (numBytesRead == sizeof(sensors_event_t)) {
if (!mDataInjectionMode) {
ALOGE("Data injected in normal mode, dropping event"
diff --git a/services/sensorservice/SensorEventConnection.h b/services/sensorservice/SensorEventConnection.h
index 3ba5c07..1ca35c0 100644
--- a/services/sensorservice/SensorEventConnection.h
+++ b/services/sensorservice/SensorEventConnection.h
@@ -57,8 +57,7 @@
bool hasSensor(int32_t handle) const;
bool hasAnySensor() const;
bool hasOneShotSensors() const;
- bool addSensor(
- int32_t handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags);
+ bool addSensor(int32_t handle);
bool removeSensor(int32_t handle);
std::vector<int32_t> getActiveSensorHandles() const;
void setFirstFlushPending(int32_t handle, bool value);
@@ -71,7 +70,7 @@
uid_t getUid() const { return mUid; }
void setSensorAccess(const bool hasAccess);
- void updateSensorSubscriptions();
+
private:
virtual ~SensorEventConnection();
virtual void onFirstRef();
@@ -137,16 +136,13 @@
// privacy not being enabled.
bool hasSensorAccess();
- void stopAll();
- void recoverAll();
-
// Call noteOp for the sensor if the sensor requires a permission
bool noteOpIfRequired(const sensors_event_t& event);
sp<SensorService> const mService;
sp<BitTube> mChannel;
uid_t mUid;
- mutable std::recursive_mutex mConnectionLock;
+ mutable Mutex mConnectionLock;
// Number of events from wake up sensors which are still pending and haven't been delivered to
// the corresponding application. It is incremented by one unit for each write to the socket.
uint32_t mWakeLockRefCount;
@@ -173,17 +169,8 @@
FlushInfo() : mPendingFlushEventsToSend(0), mFirstFlushPending(false) {}
};
-
- struct SensorRequest {
- nsecs_t samplingPeriodNs;
- nsecs_t maxBatchReportLatencyNs;
- int reservedFlags;
- FlushInfo flushInfo;
- };
-
// protected by SensorService::mLock. Key for this map is the sensor handle.
- std::unordered_map<int32_t, SensorRequest> mSensorInfo;
- std::unordered_map<int32_t, SensorRequest> mSensorInfoBackup;
+ std::unordered_map<int32_t, FlushInfo> mSensorInfo;
sensors_event_t *mEventCache;
int mCacheSize, mMaxCacheSize;
@@ -198,7 +185,7 @@
mutable Mutex mDestroyLock;
bool mDestroyed;
- std::atomic_bool mHasSensorAccess;
+ bool mHasSensorAccess;
// Store a mapping of sensor handles to required AppOp for a sensor. This map only contains a
// valid mapping for sensors that require a permission in order to reduce the lookup time.
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index 86ab0f8..5fdc74f 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -301,17 +301,7 @@
void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
- const auto& connections = connLock.getActiveConnections();
- const auto& directConnections = connLock.getDirectConnections();
-
- mLock.unlock();
- for (const sp<SensorEventConnection>& conn : connections) {
- if (conn->getUid() == uid) {
- conn->setSensorAccess(hasAccess);
- }
- }
-
- for (const sp<SensorDirectConnection>& conn : directConnections) {
+ for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
if (conn->getUid() == uid) {
conn->setSensorAccess(hasAccess);
}
@@ -648,11 +638,8 @@
void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
SensorDevice& dev(SensorDevice::getInstance());
- for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
- connection->updateSensorSubscriptions();
- }
for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
- connection->updateSensorSubscriptions();
+ connection->stopAll(true /* backupRecord */);
}
dev.disableAllSensors();
// Clear all pending flush connections for all active sensors. If one of the active
@@ -679,11 +666,8 @@
}
SensorDevice& dev(SensorDevice::getInstance());
dev.enableAllSensors();
- for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
- connection->updateSensorSubscriptions();
- }
for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
- connection->updateSensorSubscriptions();
+ connection->recoverAll();
}
}
@@ -1605,7 +1589,7 @@
}
}
- if (connection->addSensor(handle, samplingPeriodNs, maxBatchReportLatencyNs, reservedFlags)) {
+ if (connection->addSensor(handle)) {
BatteryService::enableSensor(connection->getUid(), handle);
// the sensor was added (which means it wasn't already there)
// so, see if this connection becomes active
diff --git a/services/sensorservice/hidl/Android.bp b/services/sensorservice/hidl/Android.bp
index d0c83d6..0e1af59 100644
--- a/services/sensorservice/hidl/Android.bp
+++ b/services/sensorservice/hidl/Android.bp
@@ -10,6 +10,7 @@
"-Wall",
"-Werror",
],
+ header_libs: ["jni_headers"],
shared_libs: [
"libbase",
"libhidlbase",
@@ -24,6 +25,7 @@
export_include_dirs: [
"include/"
],
+ export_header_lib_headers: ["jni_headers"],
local_include_dirs: [
"include/sensorservicehidl/"
]
diff --git a/services/surfaceflinger/OWNERS b/services/surfaceflinger/OWNERS
index f2bc65d..6bb999c 100644
--- a/services/surfaceflinger/OWNERS
+++ b/services/surfaceflinger/OWNERS
@@ -3,7 +3,6 @@
alecmouri@google.com
chaviw@google.com
lpy@google.com
-marissaw@google.com
racarr@google.com
steventhomas@google.com
stoza@google.com
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 06209e6..ddf0775 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -2245,6 +2245,9 @@
}
});
+ mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
+ mTransactionCompletedThread.sendCallbacks();
+
if (displayDevice && displayDevice->isPrimary() &&
displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
mScheduler->addPresentFence(presentFenceTime);
@@ -2325,9 +2328,6 @@
}
}
- mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
- mTransactionCompletedThread.sendCallbacks();
-
if (mLumaSampling && mRegionSamplingThread) {
mRegionSamplingThread->notifyNewContent();
}