Merge "InputDispatcherSingleWindowAnr: Send events via InputListener instead of injection" into main
diff --git a/include/binder/unique_fd.h b/include/binder/unique_fd.h
new file mode 120000
index 0000000..433c968
--- /dev/null
+++ b/include/binder/unique_fd.h
@@ -0,0 +1 @@
+../../libs/binder/include/binder/unique_fd.h
\ No newline at end of file
diff --git a/include/input/InputTransport.h b/include/input/InputTransport.h
index 4f53c36..59b9495 100644
--- a/include/input/InputTransport.h
+++ b/include/input/InputTransport.h
@@ -240,7 +240,7 @@
android::base::unique_fd fd, sp<IBinder> token);
InputChannel() = default;
InputChannel(const InputChannel& other)
- : mName(other.mName), mFd(::dup(other.mFd)), mToken(other.mToken){};
+ : mName(other.mName), mFd(other.dupFd()), mToken(other.mToken){};
InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token);
~InputChannel() override;
/**
@@ -310,7 +310,7 @@
if (fstat(mFd.get(), &lhs) != 0) {
return false;
}
- if (fstat(inputChannel.getFd(), &rhs) != 0) {
+ if (fstat(inputChannel.getFd().get(), &rhs) != 0) {
return false;
}
// If file descriptors are pointing to same inode they are duplicated fds.
@@ -322,7 +322,7 @@
base::unique_fd dupFd() const;
std::string mName;
- android::base::unique_fd mFd;
+ base::unique_fd mFd;
sp<IBinder> mToken;
};
diff --git a/libs/binder/Android.bp b/libs/binder/Android.bp
index f90c618..eccd5db 100644
--- a/libs/binder/Android.bp
+++ b/libs/binder/Android.bp
@@ -92,6 +92,7 @@
"TextOutput.cpp",
"Trace.cpp",
"Utils.cpp",
+ "file.cpp",
],
shared_libs: [
@@ -653,4 +654,7 @@
"libutils",
"android.debug_aidl-cpp",
],
+ static_libs: [
+ "libc++fs",
+ ],
}
diff --git a/libs/binder/Binder.cpp b/libs/binder/Binder.cpp
index 301dbf6..c57c9cd 100644
--- a/libs/binder/Binder.cpp
+++ b/libs/binder/Binder.cpp
@@ -19,7 +19,6 @@
#include <atomic>
#include <set>
-#include <android-base/unique_fd.h>
#include <binder/BpBinder.h>
#include <binder/IInterface.h>
#include <binder/IPCThreadState.h>
@@ -28,6 +27,7 @@
#include <binder/Parcel.h>
#include <binder/RecordedTransaction.h>
#include <binder/RpcServer.h>
+#include <binder/unique_fd.h>
#include <pthread.h>
#include <inttypes.h>
@@ -43,6 +43,8 @@
namespace android {
+using android::binder::unique_fd;
+
constexpr uid_t kUidRoot = 0;
// Service implementations inherit from BBinder and IBinder, and this is frozen
@@ -167,8 +169,7 @@
return OK;
}
-status_t IBinder::setRpcClientDebug(android::base::unique_fd socketFd,
- const sp<IBinder>& keepAliveBinder) {
+status_t IBinder::setRpcClientDebug(unique_fd socketFd, const sp<IBinder>& keepAliveBinder) {
if (!kEnableRpcDevServers) {
ALOGW("setRpcClientDebug disallowed because RPC is not enabled");
return INVALID_OPERATION;
@@ -273,7 +274,7 @@
std::set<sp<RpcServerLink>> mRpcServerLinks;
BpBinder::ObjectManager mObjects;
- android::base::unique_fd mRecordingFd;
+ unique_fd mRecordingFd;
};
// ---------------------------------------------------------------------------
@@ -640,7 +641,7 @@
}
status_t status;
bool hasSocketFd;
- android::base::unique_fd clientFd;
+ unique_fd clientFd;
if (status = data.readBool(&hasSocketFd); status != OK) return status;
if (hasSocketFd) {
@@ -652,8 +653,7 @@
return setRpcClientDebug(std::move(clientFd), keepAliveBinder);
}
-status_t BBinder::setRpcClientDebug(android::base::unique_fd socketFd,
- const sp<IBinder>& keepAliveBinder) {
+status_t BBinder::setRpcClientDebug(unique_fd socketFd, const sp<IBinder>& keepAliveBinder) {
if (!kEnableRpcDevServers) {
ALOGW("%s: disallowed because RPC is not enabled", __PRETTY_FUNCTION__);
return INVALID_OPERATION;
diff --git a/libs/binder/BpBinder.cpp b/libs/binder/BpBinder.cpp
index 49038b1..42dd691 100644
--- a/libs/binder/BpBinder.cpp
+++ b/libs/binder/BpBinder.cpp
@@ -27,14 +27,15 @@
#include <stdio.h>
#include "BuildFlags.h"
-
-#include <android-base/file.h>
+#include "file.h"
//#undef ALOGV
//#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
namespace android {
+using android::binder::unique_fd;
+
// ---------------------------------------------------------------------------
RpcMutex BpBinder::sTrackingLock;
@@ -318,7 +319,7 @@
return transact(PING_TRANSACTION, data, &reply);
}
-status_t BpBinder::startRecordingBinder(const android::base::unique_fd& fd) {
+status_t BpBinder::startRecordingBinder(const unique_fd& fd) {
Parcel send, reply;
send.writeUniqueFileDescriptor(fd);
return transact(START_RECORDING_TRANSACTION, send, &reply);
diff --git a/libs/binder/FdTrigger.cpp b/libs/binder/FdTrigger.cpp
index 895690f..455a433 100644
--- a/libs/binder/FdTrigger.cpp
+++ b/libs/binder/FdTrigger.cpp
@@ -23,6 +23,7 @@
#include <binder/Functional.h>
+#include "FdUtils.h"
#include "RpcState.h"
#include "Utils.h"
@@ -33,7 +34,7 @@
std::unique_ptr<FdTrigger> FdTrigger::make() {
auto ret = std::make_unique<FdTrigger>();
#ifndef BINDER_RPC_SINGLE_THREADED
- if (!android::base::Pipe(&ret->mRead, &ret->mWrite)) {
+ if (!binder::Pipe(&ret->mRead, &ret->mWrite)) {
ALOGE("Could not create pipe %s", strerror(errno));
return nullptr;
}
diff --git a/libs/binder/FdTrigger.h b/libs/binder/FdTrigger.h
index dba1dc9..e4a0283 100644
--- a/libs/binder/FdTrigger.h
+++ b/libs/binder/FdTrigger.h
@@ -17,10 +17,10 @@
#include <memory>
-#include <android-base/unique_fd.h>
#include <utils/Errors.h>
#include <binder/RpcTransport.h>
+#include <binder/unique_fd.h>
namespace android {
@@ -61,8 +61,8 @@
#ifdef BINDER_RPC_SINGLE_THREADED
bool mTriggered = false;
#else
- base::unique_fd mWrite;
- base::unique_fd mRead;
+ binder::unique_fd mWrite;
+ binder::unique_fd mRead;
#endif
};
} // namespace android
diff --git a/libs/binder/FdUtils.h b/libs/binder/FdUtils.h
new file mode 100644
index 0000000..52ae487
--- /dev/null
+++ b/libs/binder/FdUtils.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <binder/unique_fd.h>
+
+#if defined(_WIN32) || defined(__TRUSTY__)
+// Pipe and Socketpair are missing there
+#elif !defined(BINDER_NO_LIBBASE)
+
+namespace android::binder {
+using android::base::Pipe;
+using android::base::Socketpair;
+} // namespace android::binder
+
+#else // BINDER_NO_LIBBASE
+
+#include <sys/socket.h>
+
+namespace android::binder {
+
+// Inline functions, so that they can be used header-only.
+
+// See pipe(2).
+// This helper hides the details of converting to unique_fd, and also hides the
+// fact that macOS doesn't support O_CLOEXEC or O_NONBLOCK directly.
+inline bool Pipe(unique_fd* read, unique_fd* write, int flags = O_CLOEXEC) {
+ int pipefd[2];
+
+#if defined(__APPLE__)
+ if (flags & ~(O_CLOEXEC | O_NONBLOCK)) {
+ return false;
+ }
+ if (pipe(pipefd) != 0) {
+ return false;
+ }
+
+ if (flags & O_CLOEXEC) {
+ if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) != 0 ||
+ fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) != 0) {
+ close(pipefd[0]);
+ close(pipefd[1]);
+ return false;
+ }
+ }
+ if (flags & O_NONBLOCK) {
+ if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) != 0 ||
+ fcntl(pipefd[1], F_SETFL, O_NONBLOCK) != 0) {
+ close(pipefd[0]);
+ close(pipefd[1]);
+ return false;
+ }
+ }
+#else
+ if (pipe2(pipefd, flags) != 0) {
+ return false;
+ }
+#endif
+
+ read->reset(pipefd[0]);
+ write->reset(pipefd[1]);
+ return true;
+}
+
+// See socketpair(2).
+// This helper hides the details of converting to unique_fd.
+inline bool Socketpair(int domain, int type, int protocol, unique_fd* left, unique_fd* right) {
+ int sockfd[2];
+ if (socketpair(domain, type, protocol, sockfd) != 0) {
+ return false;
+ }
+ left->reset(sockfd[0]);
+ right->reset(sockfd[1]);
+ return true;
+}
+
+// See socketpair(2).
+// This helper hides the details of converting to unique_fd.
+inline bool Socketpair(int type, unique_fd* left, unique_fd* right) {
+ return Socketpair(AF_UNIX, type, 0, left, right);
+}
+
+} // namespace android::binder
+
+#endif // BINDER_NO_LIBBASE
diff --git a/libs/binder/OS.h b/libs/binder/OS.h
index bb7caa9..c5f0730 100644
--- a/libs/binder/OS.h
+++ b/libs/binder/OS.h
@@ -18,13 +18,13 @@
#include <stddef.h>
#include <cstdint>
-#include <android-base/unique_fd.h>
#include <binder/RpcTransport.h>
+#include <binder/unique_fd.h>
#include <utils/Errors.h>
namespace android::binder::os {
-status_t setNonBlocking(android::base::borrowed_fd fd);
+status_t setNonBlocking(borrowed_fd fd);
status_t getRandomBytes(uint8_t* data, size_t size);
@@ -32,13 +32,11 @@
std::unique_ptr<RpcTransportCtxFactory> makeDefaultRpcTransportCtxFactory();
-ssize_t sendMessageOnSocket(
- const RpcTransportFd& socket, iovec* iovs, int niovs,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds);
+ssize_t sendMessageOnSocket(const RpcTransportFd& socket, iovec* iovs, int niovs,
+ const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds);
-ssize_t receiveMessageFromSocket(
- const RpcTransportFd& socket, iovec* iovs, int niovs,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds);
+ssize_t receiveMessageFromSocket(const RpcTransportFd& socket, iovec* iovs, int niovs,
+ std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds);
uint64_t GetThreadId();
diff --git a/libs/binder/OS_unix_base.cpp b/libs/binder/OS_unix_base.cpp
index a3cf117..ca998d4 100644
--- a/libs/binder/OS_unix_base.cpp
+++ b/libs/binder/OS_unix_base.cpp
@@ -16,18 +16,21 @@
#include "OS.h"
#include "Utils.h"
+#include "file.h"
-#include <android-base/file.h>
#include <binder/RpcTransportRaw.h>
#include <log/log.h>
#include <string.h>
+#include <sys/socket.h>
+
+using android::binder::ReadFully;
namespace android::binder::os {
// Linux kernel supports up to 253 (from SCM_MAX_FD) for unix sockets.
constexpr size_t kMaxFdsPerMsg = 253;
-status_t setNonBlocking(android::base::borrowed_fd fd) {
+status_t setNonBlocking(borrowed_fd fd) {
int flags = TEMP_FAILURE_RETRY(fcntl(fd.get(), F_GETFL));
if (flags == -1) {
PLOGE("Failed setNonBlocking: Could not get flags for fd");
@@ -41,13 +44,12 @@
}
status_t getRandomBytes(uint8_t* data, size_t size) {
- int ret = TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
- if (ret == -1) {
+ unique_fd fd(TEMP_FAILURE_RETRY(open("/dev/urandom", O_RDONLY | O_CLOEXEC | O_NOFOLLOW)));
+ if (!fd.ok()) {
return -errno;
}
- base::unique_fd fd(ret);
- if (!base::ReadFully(fd, data, size)) {
+ if (!ReadFully(fd, data, size)) {
return -errno;
}
return OK;
@@ -67,9 +69,8 @@
return RpcTransportCtxFactoryRaw::make();
}
-ssize_t sendMessageOnSocket(
- const RpcTransportFd& socket, iovec* iovs, int niovs,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
+ssize_t sendMessageOnSocket(const RpcTransportFd& socket, iovec* iovs, int niovs,
+ const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) {
if (ancillaryFds != nullptr && !ancillaryFds->empty()) {
if (ancillaryFds->size() > kMaxFdsPerMsg) {
errno = EINVAL;
@@ -112,9 +113,8 @@
return TEMP_FAILURE_RETRY(sendmsg(socket.fd.get(), &msg, MSG_NOSIGNAL));
}
-ssize_t receiveMessageFromSocket(
- const RpcTransportFd& socket, iovec* iovs, int niovs,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
+ssize_t receiveMessageFromSocket(const RpcTransportFd& socket, iovec* iovs, int niovs,
+ std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) {
if (ancillaryFds != nullptr) {
int fdBuffer[kMaxFdsPerMsg];
alignas(struct cmsghdr) char msgControlBuf[CMSG_SPACE(sizeof(fdBuffer))];
@@ -140,7 +140,7 @@
size_t fdCount = dataLen / sizeof(int);
ancillaryFds->reserve(ancillaryFds->size() + fdCount);
for (size_t i = 0; i < fdCount; i++) {
- ancillaryFds->emplace_back(base::unique_fd(fdBuffer[i]));
+ ancillaryFds->emplace_back(unique_fd(fdBuffer[i]));
}
break;
}
diff --git a/libs/binder/OWNERS b/libs/binder/OWNERS
index bb17683..a70b558 100644
--- a/libs/binder/OWNERS
+++ b/libs/binder/OWNERS
@@ -1,4 +1,5 @@
# Bug component: 32456
-maco@google.com
+
smoreland@google.com
-tkjos@google.com
+tkjos@google.com # kernel
+maco@google.com # historical
diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp
index 3349402..146ddef 100644
--- a/libs/binder/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -97,6 +97,8 @@
namespace android {
using namespace android::binder::impl;
+using binder::borrowed_fd;
+using binder::unique_fd;
// many things compile this into prebuilts on the stack
#ifdef __LP64__
@@ -211,7 +213,7 @@
}
#endif // BINDER_WITH_KERNEL_IPC
-static int toRawFd(const std::variant<base::unique_fd, base::borrowed_fd>& v) {
+static int toRawFd(const std::variant<unique_fd, borrowed_fd>& v) {
return std::visit([](const auto& fd) { return fd.get(); }, v);
}
@@ -667,7 +669,7 @@
if (status_t status = binder::os::dupFileDescriptor(oldFd, &newFd); status != OK) {
ALOGW("Failed to duplicate file descriptor %d: %s", oldFd, strerror(-status));
}
- rpcFields->mFds->emplace_back(base::unique_fd(newFd));
+ rpcFields->mFds->emplace_back(unique_fd(newFd));
// Fixup the index in the data.
mDataPos = newDataPos + 4;
if (status_t status = writeInt32(rpcFields->mFds->size() - 1); status != OK) {
@@ -1247,9 +1249,16 @@
const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) { return writeData(val); }
status_t Parcel::writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val) { return writeData(val); }
-status_t Parcel::writeUniqueFileDescriptorVector(const std::vector<base::unique_fd>& val) { return writeData(val); }
-status_t Parcel::writeUniqueFileDescriptorVector(const std::optional<std::vector<base::unique_fd>>& val) { return writeData(val); }
-status_t Parcel::writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<base::unique_fd>>& val) { return writeData(val); }
+status_t Parcel::writeUniqueFileDescriptorVector(const std::vector<unique_fd>& val) {
+ return writeData(val);
+}
+status_t Parcel::writeUniqueFileDescriptorVector(const std::optional<std::vector<unique_fd>>& val) {
+ return writeData(val);
+}
+status_t Parcel::writeUniqueFileDescriptorVector(
+ const std::unique_ptr<std::vector<unique_fd>>& val) {
+ return writeData(val);
+}
status_t Parcel::writeStrongBinderVector(const std::vector<sp<IBinder>>& val) { return writeData(val); }
status_t Parcel::writeStrongBinderVector(const std::optional<std::vector<sp<IBinder>>>& val) { return writeData(val); }
@@ -1302,9 +1311,16 @@
std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const { return readData(val); }
status_t Parcel::readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const { return readData(val); }
-status_t Parcel::readUniqueFileDescriptorVector(std::optional<std::vector<base::unique_fd>>* val) const { return readData(val); }
-status_t Parcel::readUniqueFileDescriptorVector(std::unique_ptr<std::vector<base::unique_fd>>* val) const { return readData(val); }
-status_t Parcel::readUniqueFileDescriptorVector(std::vector<base::unique_fd>* val) const { return readData(val); }
+status_t Parcel::readUniqueFileDescriptorVector(std::optional<std::vector<unique_fd>>* val) const {
+ return readData(val);
+}
+status_t Parcel::readUniqueFileDescriptorVector(
+ std::unique_ptr<std::vector<unique_fd>>* val) const {
+ return readData(val);
+}
+status_t Parcel::readUniqueFileDescriptorVector(std::vector<unique_fd>* val) const {
+ return readData(val);
+}
status_t Parcel::readStrongBinderVector(std::optional<std::vector<sp<IBinder>>>* val) const { return readData(val); }
status_t Parcel::readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const { return readData(val); }
@@ -1504,11 +1520,11 @@
status_t Parcel::writeFileDescriptor(int fd, bool takeOwnership) {
if (auto* rpcFields = maybeRpcFields()) {
- std::variant<base::unique_fd, base::borrowed_fd> fdVariant;
+ std::variant<unique_fd, borrowed_fd> fdVariant;
if (takeOwnership) {
- fdVariant = base::unique_fd(fd);
+ fdVariant = unique_fd(fd);
} else {
- fdVariant = base::borrowed_fd(fd);
+ fdVariant = borrowed_fd(fd);
}
if (!mAllowFds) {
return FDS_NOT_ALLOWED;
@@ -1587,7 +1603,7 @@
return err;
}
-status_t Parcel::writeUniqueFileDescriptor(const base::unique_fd& fd) {
+status_t Parcel::writeUniqueFileDescriptor(const unique_fd& fd) {
return writeDupFileDescriptor(fd.get());
}
@@ -2390,8 +2406,7 @@
return fd;
}
-status_t Parcel::readUniqueFileDescriptor(base::unique_fd* val) const
-{
+status_t Parcel::readUniqueFileDescriptor(unique_fd* val) const {
int got = readFileDescriptor();
if (got == BAD_TYPE) {
@@ -2412,8 +2427,7 @@
return OK;
}
-status_t Parcel::readUniqueParcelFileDescriptor(base::unique_fd* val) const
-{
+status_t Parcel::readUniqueParcelFileDescriptor(unique_fd* val) const {
int got = readParcelFileDescriptor();
if (got == BAD_TYPE) {
@@ -2710,8 +2724,7 @@
status_t Parcel::rpcSetDataReference(
const sp<RpcSession>& session, const uint8_t* data, size_t dataSize,
const uint32_t* objectTable, size_t objectTableSize,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds,
- release_func relFunc) {
+ std::vector<std::variant<unique_fd, borrowed_fd>>&& ancillaryFds, release_func relFunc) {
// this code uses 'mOwner == nullptr' to understand whether it owns memory
LOG_ALWAYS_FATAL_IF(relFunc == nullptr, "must provide cleanup function");
diff --git a/libs/binder/ParcelFileDescriptor.cpp b/libs/binder/ParcelFileDescriptor.cpp
index 4f8b76f..c3c4874 100644
--- a/libs/binder/ParcelFileDescriptor.cpp
+++ b/libs/binder/ParcelFileDescriptor.cpp
@@ -19,9 +19,11 @@
namespace android {
namespace os {
+using android::binder::unique_fd;
+
ParcelFileDescriptor::ParcelFileDescriptor() = default;
-ParcelFileDescriptor::ParcelFileDescriptor(android::base::unique_fd fd) : mFd(std::move(fd)) {}
+ParcelFileDescriptor::ParcelFileDescriptor(unique_fd fd) : mFd(std::move(fd)) {}
ParcelFileDescriptor::~ParcelFileDescriptor() = default;
diff --git a/libs/binder/ProcessState.cpp b/libs/binder/ProcessState.cpp
index 0344eb0..7de94e3 100644
--- a/libs/binder/ProcessState.cpp
+++ b/libs/binder/ProcessState.cpp
@@ -61,6 +61,7 @@
namespace android {
using namespace android::binder::impl;
+using android::binder::unique_fd;
class PoolThread : public Thread
{
@@ -514,8 +515,8 @@
return mDriverName;
}
-static base::unique_fd open_driver(const char* driver) {
- auto fd = base::unique_fd(open(driver, O_RDWR | O_CLOEXEC));
+static unique_fd open_driver(const char* driver) {
+ auto fd = unique_fd(open(driver, O_RDWR | O_CLOEXEC));
if (!fd.ok()) {
PLOGE("Opening '%s' failed", driver);
return {};
@@ -563,7 +564,7 @@
mThreadPoolStarted(false),
mThreadPoolSeq(1),
mCallRestriction(CallRestriction::NONE) {
- base::unique_fd opened = open_driver(driver);
+ unique_fd opened = open_driver(driver);
if (opened.ok()) {
// mmap the binder, providing a chunk of virtual address space to receive transactions.
diff --git a/libs/binder/RecordedTransaction.cpp b/libs/binder/RecordedTransaction.cpp
index f7b5a55..525ba2e 100644
--- a/libs/binder/RecordedTransaction.cpp
+++ b/libs/binder/RecordedTransaction.cpp
@@ -14,18 +14,23 @@
* limitations under the License.
*/
-#include <android-base/file.h>
-#include <android-base/unique_fd.h>
+#include "file.h"
+
#include <binder/Functional.h>
#include <binder/RecordedTransaction.h>
+#include <binder/unique_fd.h>
+
#include <inttypes.h>
#include <sys/mman.h>
+#include <sys/stat.h>
#include <algorithm>
using namespace android::binder::impl;
using android::Parcel;
-using android::base::borrowed_fd;
-using android::base::unique_fd;
+using android::binder::borrowed_fd;
+using android::binder::ReadFully;
+using android::binder::unique_fd;
+using android::binder::WriteFully;
using android::binder::debug::RecordedTransaction;
#define PADDING8(s) ((8 - (s) % 8) % 8)
@@ -182,7 +187,7 @@
return std::nullopt;
}
- if (!android::base::ReadFully(fd, &chunk, sizeof(ChunkDescriptor))) {
+ if (!ReadFully(fd, &chunk, sizeof(ChunkDescriptor))) {
ALOGE("Failed to read ChunkDescriptor from fd %d. %s", fd.get(), strerror(errno));
return std::nullopt;
}
@@ -317,7 +322,7 @@
buffer.insert(buffer.end(), checksumBytes, checksumBytes + sizeof(transaction_checksum_t));
// Write buffer to file
- if (!android::base::WriteFully(fd, buffer.data(), buffer.size())) {
+ if (!WriteFully(fd, buffer.data(), buffer.size())) {
ALOGE("Failed to write chunk fd %d", fd.get());
return UNKNOWN_ERROR;
}
diff --git a/libs/binder/RpcServer.cpp b/libs/binder/RpcServer.cpp
index fefaa81..d9e926a 100644
--- a/libs/binder/RpcServer.cpp
+++ b/libs/binder/RpcServer.cpp
@@ -45,7 +45,8 @@
constexpr size_t kSessionIdBytes = 32;
using namespace android::binder::impl;
-using base::unique_fd;
+using android::binder::borrowed_fd;
+using android::binder::unique_fd;
RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
RpcServer::~RpcServer() {
@@ -166,7 +167,7 @@
mConnectionFilter = std::move(filter);
}
-void RpcServer::setServerSocketModifier(std::function<void(base::borrowed_fd)>&& modifier) {
+void RpcServer::setServerSocketModifier(std::function<void(borrowed_fd)>&& modifier) {
RpcMutexLockGuard _l(mLock);
LOG_ALWAYS_FATAL_IF(mServer.fd.ok(), "Already started");
mServerSocketModifier = std::move(modifier);
@@ -213,7 +214,7 @@
status_t RpcServer::recvmsgSocketConnection(const RpcServer& server, RpcTransportFd* out) {
int zero = 0;
iovec iov{&zero, sizeof(zero)};
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
+ std::vector<std::variant<unique_fd, borrowed_fd>> fds;
ssize_t num_bytes = binder::os::receiveMessageFromSocket(server.mServer, &iov, 1, &fds);
if (num_bytes < 0) {
@@ -644,8 +645,7 @@
}
status_t RpcServer::setupExternalServer(
- base::unique_fd serverFd,
- std::function<status_t(const RpcServer&, RpcTransportFd*)>&& acceptFn) {
+ unique_fd serverFd, std::function<status_t(const RpcServer&, RpcTransportFd*)>&& acceptFn) {
RpcMutexLockGuard _l(mLock);
if (mServer.fd.ok()) {
ALOGE("Each RpcServer can only have one server.");
@@ -656,7 +656,7 @@
return OK;
}
-status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
+status_t RpcServer::setupExternalServer(unique_fd serverFd) {
return setupExternalServer(std::move(serverFd), &RpcServer::acceptSocketConnection);
}
diff --git a/libs/binder/RpcSession.cpp b/libs/binder/RpcSession.cpp
index cd8f417..16a7f9f 100644
--- a/libs/binder/RpcSession.cpp
+++ b/libs/binder/RpcSession.cpp
@@ -51,7 +51,8 @@
namespace android {
using namespace android::binder::impl;
-using base::unique_fd;
+using android::binder::borrowed_fd;
+using android::binder::unique_fd;
RpcSession::RpcSession(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {
LOG_RPC_DETAIL("RpcSession created %p", this);
@@ -157,7 +158,7 @@
int zero = 0;
iovec iov{&zero, sizeof(zero)};
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
+ std::vector<std::variant<unique_fd, borrowed_fd>> fds;
fds.push_back(std::move(serverFd));
status_t status = mBootstrapTransport->interruptableWriteFully(mShutdownTrigger.get(), &iov,
@@ -186,8 +187,7 @@
return NAME_NOT_FOUND;
}
-status_t RpcSession::setupPreconnectedClient(base::unique_fd fd,
- std::function<unique_fd()>&& request) {
+status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
if (!fd.ok()) {
fd = request();
diff --git a/libs/binder/RpcState.cpp b/libs/binder/RpcState.cpp
index 008e5d2..fe6e1a3 100644
--- a/libs/binder/RpcState.cpp
+++ b/libs/binder/RpcState.cpp
@@ -39,6 +39,8 @@
namespace android {
using namespace android::binder::impl;
+using android::binder::borrowed_fd;
+using android::binder::unique_fd;
#if RPC_FLAKE_PRONE
void rpcMaybeWaitToFlake() {
@@ -355,11 +357,10 @@
mData.reset(new (std::nothrow) uint8_t[size]);
}
-status_t RpcState::rpcSend(
- const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
- const char* what, iovec* iovs, int niovs,
- const std::optional<SmallFunction<status_t()>>& altPoll,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
+status_t RpcState::rpcSend(const sp<RpcSession::RpcConnection>& connection,
+ const sp<RpcSession>& session, const char* what, iovec* iovs, int niovs,
+ const std::optional<SmallFunction<status_t()>>& altPoll,
+ const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) {
for (int i = 0; i < niovs; i++) {
LOG_RPC_DETAIL("Sending %s (part %d of %d) on RpcTransport %p: %s",
what, i + 1, niovs, connection->rpcTransport.get(),
@@ -380,10 +381,9 @@
return OK;
}
-status_t RpcState::rpcRec(
- const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
- const char* what, iovec* iovs, int niovs,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
+status_t RpcState::rpcRec(const sp<RpcSession::RpcConnection>& connection,
+ const sp<RpcSession>& session, const char* what, iovec* iovs, int niovs,
+ std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) {
if (status_t status =
connection->rpcTransport->interruptableReadFully(session->mShutdownTrigger.get(),
iovs, niovs, std::nullopt,
@@ -649,7 +649,7 @@
status_t RpcState::waitForReply(const sp<RpcSession::RpcConnection>& connection,
const sp<RpcSession>& session, Parcel* reply) {
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
+ std::vector<std::variant<unique_fd, borrowed_fd>> ancillaryFds;
RpcWireHeader command;
while (true) {
iovec iov{&command, sizeof(command)};
@@ -767,7 +767,7 @@
const sp<RpcSession>& session, CommandType type) {
LOG_RPC_DETAIL("getAndExecuteCommand on RpcTransport %p", connection->rpcTransport.get());
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
+ std::vector<std::variant<unique_fd, borrowed_fd>> ancillaryFds;
RpcWireHeader command;
iovec iov{&command, sizeof(command)};
if (status_t status =
@@ -796,7 +796,7 @@
status_t RpcState::processCommand(
const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
const RpcWireHeader& command, CommandType type,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
+ std::vector<std::variant<unique_fd, borrowed_fd>>&& ancillaryFds) {
#ifdef BINDER_WITH_KERNEL_IPC
IPCThreadState* kernelBinderState = IPCThreadState::selfOrNull();
IPCThreadState::SpGuard spGuard{
@@ -836,7 +836,7 @@
status_t RpcState::processTransact(
const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
const RpcWireHeader& command,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
+ std::vector<std::variant<unique_fd, borrowed_fd>>&& ancillaryFds) {
LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
CommandData transactionData(command.bodySize);
@@ -863,7 +863,7 @@
status_t RpcState::processTransactInternal(
const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
CommandData transactionData,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds) {
+ std::vector<std::variant<unique_fd, borrowed_fd>>&& ancillaryFds) {
// for 'recursive' calls to this, we have already read and processed the
// binder from the transaction data and taken reference counts into account,
// so it is cached here.
diff --git a/libs/binder/RpcState.h b/libs/binder/RpcState.h
index 2a954e6..8b84602 100644
--- a/libs/binder/RpcState.h
+++ b/libs/binder/RpcState.h
@@ -15,12 +15,12 @@
*/
#pragma once
-#include <android-base/unique_fd.h>
#include <binder/Functional.h>
#include <binder/IBinder.h>
#include <binder/Parcel.h>
#include <binder/RpcSession.h>
#include <binder/RpcThreads.h>
+#include <binder/unique_fd.h>
#include <map>
#include <optional>
@@ -192,27 +192,28 @@
const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
const char* what, iovec* iovs, int niovs,
const std::optional<binder::impl::SmallFunction<status_t()>>& altPoll,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds =
+ const std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>* ancillaryFds =
nullptr);
- [[nodiscard]] status_t rpcRec(
- const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
- const char* what, iovec* iovs, int niovs,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds = nullptr);
+ [[nodiscard]] status_t rpcRec(const sp<RpcSession::RpcConnection>& connection,
+ const sp<RpcSession>& session, const char* what, iovec* iovs,
+ int niovs,
+ std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>*
+ ancillaryFds = nullptr);
[[nodiscard]] status_t waitForReply(const sp<RpcSession::RpcConnection>& connection,
const sp<RpcSession>& session, Parcel* reply);
[[nodiscard]] status_t processCommand(
const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
const RpcWireHeader& command, CommandType type,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds);
+ std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>&& ancillaryFds);
[[nodiscard]] status_t processTransact(
const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
const RpcWireHeader& command,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds);
+ std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>&& ancillaryFds);
[[nodiscard]] status_t processTransactInternal(
const sp<RpcSession::RpcConnection>& connection, const sp<RpcSession>& session,
CommandData transactionData,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds);
+ std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>&& ancillaryFds);
[[nodiscard]] status_t processDecStrong(const sp<RpcSession::RpcConnection>& connection,
const sp<RpcSession>& session,
const RpcWireHeader& command);
@@ -254,7 +255,7 @@
struct AsyncTodo {
sp<IBinder> ref;
CommandData data;
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>> ancillaryFds;
+ std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>> ancillaryFds;
uint64_t asyncNumber = 0;
bool operator<(const AsyncTodo& o) const {
diff --git a/libs/binder/RpcTransportRaw.cpp b/libs/binder/RpcTransportRaw.cpp
index ffa3151..aa3a6e5 100644
--- a/libs/binder/RpcTransportRaw.cpp
+++ b/libs/binder/RpcTransportRaw.cpp
@@ -19,6 +19,7 @@
#include <poll.h>
#include <stddef.h>
+#include <sys/socket.h>
#include <binder/RpcTransportRaw.h>
@@ -30,6 +31,8 @@
namespace android {
using namespace android::binder::impl;
+using android::binder::borrowed_fd;
+using android::binder::unique_fd;
// RpcTransport with TLS disabled.
class RpcTransportRaw : public RpcTransport {
@@ -57,8 +60,7 @@
status_t interruptableWriteFully(
FdTrigger* fdTrigger, iovec* iovs, int niovs,
const std::optional<SmallFunction<status_t()>>& altPoll,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds)
- override {
+ const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) override {
bool sentFds = false;
auto send = [&](iovec* iovs, int niovs) -> ssize_t {
ssize_t ret = binder::os::sendMessageOnSocket(mSocket, iovs, niovs,
@@ -73,7 +75,7 @@
status_t interruptableReadFully(
FdTrigger* fdTrigger, iovec* iovs, int niovs,
const std::optional<SmallFunction<status_t()>>& altPoll,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) override {
+ std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) override {
auto recv = [&](iovec* iovs, int niovs) -> ssize_t {
return binder::os::receiveMessageFromSocket(mSocket, iovs, niovs, ancillaryFds);
};
diff --git a/libs/binder/RpcTransportTipcAndroid.cpp b/libs/binder/RpcTransportTipcAndroid.cpp
index 188ba3b..3819fb6 100644
--- a/libs/binder/RpcTransportTipcAndroid.cpp
+++ b/libs/binder/RpcTransportTipcAndroid.cpp
@@ -27,6 +27,8 @@
#include "RpcTransportUtils.h"
using namespace android::binder::impl;
+using android::binder::borrowed_fd;
+using android::binder::unique_fd;
namespace android {
@@ -75,8 +77,7 @@
status_t interruptableWriteFully(
FdTrigger* fdTrigger, iovec* iovs, int niovs,
const std::optional<SmallFunction<status_t()>>& altPoll,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds)
- override {
+ const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) override {
auto writeFn = [&](iovec* iovs, size_t niovs) -> ssize_t {
// TODO: send ancillaryFds. For now, we just abort if anyone tries
// to send any.
@@ -93,8 +94,7 @@
status_t interruptableReadFully(
FdTrigger* fdTrigger, iovec* iovs, int niovs,
const std::optional<SmallFunction<status_t()>>& altPoll,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* /*ancillaryFds*/)
- override {
+ std::vector<std::variant<unique_fd, borrowed_fd>>* /*ancillaryFds*/) override {
auto readFn = [&](iovec* iovs, size_t niovs) -> ssize_t {
// Fill the read buffer at most once per readFn call, then try to
// return as much of it as possible. If the input iovecs are spread
diff --git a/libs/binder/RpcTransportTls.cpp b/libs/binder/RpcTransportTls.cpp
index fef4be4..579694c 100644
--- a/libs/binder/RpcTransportTls.cpp
+++ b/libs/binder/RpcTransportTls.cpp
@@ -18,6 +18,7 @@
#include <log/log.h>
#include <poll.h>
+#include <sys/socket.h>
#include <openssl/bn.h>
#include <openssl/ssl.h>
@@ -42,6 +43,8 @@
namespace android {
using namespace android::binder::impl;
+using android::binder::borrowed_fd;
+using android::binder::unique_fd;
namespace {
@@ -56,7 +59,7 @@
return 1;
}
int socketRead(BIO* bio, char* buf, int size) {
- android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
+ borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
int ret = TEMP_FAILURE_RETRY(::recv(fd.get(), buf, size, MSG_NOSIGNAL));
BIO_clear_retry_flags(bio);
if (errno == EAGAIN || errno == EWOULDBLOCK) {
@@ -66,7 +69,7 @@
}
int socketWrite(BIO* bio, const char* buf, int size) {
- android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
+ borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
int ret = TEMP_FAILURE_RETRY(::send(fd.get(), buf, size, MSG_NOSIGNAL));
BIO_clear_retry_flags(bio);
if (errno == EAGAIN || errno == EWOULDBLOCK) {
@@ -76,13 +79,13 @@
}
long socketCtrl(BIO* bio, int cmd, long num, void*) { // NOLINT
- android::base::borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
+ borrowed_fd fd(static_cast<int>(reinterpret_cast<intptr_t>(BIO_get_data(bio))));
if (cmd == BIO_CTRL_FLUSH) return 1;
LOG_ALWAYS_FATAL("sockCtrl(fd=%d, %d, %ld)", fd.get(), cmd, num);
return 0;
}
-bssl::UniquePtr<BIO> newSocketBio(android::base::borrowed_fd fd) {
+bssl::UniquePtr<BIO> newSocketBio(borrowed_fd fd) {
static const BIO_METHOD* gMethods = ([] {
auto methods = BIO_meth_new(BIO_get_new_index(), "socket_no_signal");
LOG_ALWAYS_FATAL_IF(0 == BIO_meth_set_write(methods, socketWrite), "BIO_meth_set_write");
@@ -289,12 +292,11 @@
status_t interruptableWriteFully(
FdTrigger* fdTrigger, iovec* iovs, int niovs,
const std::optional<SmallFunction<status_t()>>& altPoll,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds)
- override;
+ const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) override;
status_t interruptableReadFully(
FdTrigger* fdTrigger, iovec* iovs, int niovs,
const std::optional<SmallFunction<status_t()>>& altPoll,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) override;
+ std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) override;
bool isWaiting() override { return mSocket.isInPollingState(); };
@@ -325,7 +327,7 @@
status_t RpcTransportTls::interruptableWriteFully(
FdTrigger* fdTrigger, iovec* iovs, int niovs,
const std::optional<SmallFunction<status_t()>>& altPoll,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
+ const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) {
(void)ancillaryFds;
MAYBE_WAIT_IN_FLAKE_MODE;
@@ -371,7 +373,7 @@
status_t RpcTransportTls::interruptableReadFully(
FdTrigger* fdTrigger, iovec* iovs, int niovs,
const std::optional<SmallFunction<status_t()>>& altPoll,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) {
+ std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) {
(void)ancillaryFds;
MAYBE_WAIT_IN_FLAKE_MODE;
diff --git a/libs/binder/RpcTransportUtils.h b/libs/binder/RpcTransportUtils.h
index a0e502e..fcf6675 100644
--- a/libs/binder/RpcTransportUtils.h
+++ b/libs/binder/RpcTransportUtils.h
@@ -15,7 +15,7 @@
*/
#pragma once
-#include <android-base/unique_fd.h>
+#include <binder/unique_fd.h>
#include <poll.h>
#include "FdTrigger.h"
diff --git a/libs/binder/RpcTrusty.cpp b/libs/binder/RpcTrusty.cpp
index 2f2fe7d..a445196 100644
--- a/libs/binder/RpcTrusty.cpp
+++ b/libs/binder/RpcTrusty.cpp
@@ -16,14 +16,14 @@
#define LOG_TAG "RpcTrusty"
-#include <android-base/unique_fd.h>
#include <binder/RpcSession.h>
#include <binder/RpcTransportTipcAndroid.h>
+#include <binder/unique_fd.h>
#include <trusty/tipc.h>
namespace android {
-using android::base::unique_fd;
+using android::binder::unique_fd;
sp<RpcSession> RpcTrustyConnectWithSessionInitializer(
const char* device, const char* port,
diff --git a/libs/binder/UtilsHost.cpp b/libs/binder/UtilsHost.cpp
index 3db038f..ae1a6c4 100644
--- a/libs/binder/UtilsHost.cpp
+++ b/libs/binder/UtilsHost.cpp
@@ -25,10 +25,13 @@
#include <log/log.h>
+#include "FdUtils.h"
#include "Utils.h"
namespace android {
+using android::binder::unique_fd;
+
CommandResult::~CommandResult() {
if (!pid.has_value()) return;
if (*pid == 0) {
@@ -83,13 +86,13 @@
argv.push_back(nullptr);
CommandResult ret;
- android::base::unique_fd outWrite;
- if (!android::base::Pipe(&ret.outPipe, &outWrite)) {
+ unique_fd outWrite;
+ if (!binder::Pipe(&ret.outPipe, &outWrite)) {
PLOGE("pipe() for outPipe");
return {};
}
- android::base::unique_fd errWrite;
- if (!android::base::Pipe(&ret.errPipe, &errWrite)) {
+ unique_fd errWrite;
+ if (!binder::Pipe(&ret.errPipe, &errWrite)) {
PLOGE("pipe() for errPipe");
return {};
}
@@ -120,7 +123,7 @@
errWrite.reset();
ret.pid = pid;
- auto handlePoll = [](android::base::unique_fd* fd, const pollfd* pfd, std::string* s) {
+ auto handlePoll = [](unique_fd* fd, const pollfd* pfd, std::string* s) {
if (!fd->ok()) return true;
if (pfd->revents & POLLIN) {
char buf[1024];
diff --git a/libs/binder/UtilsHost.h b/libs/binder/UtilsHost.h
index 5de0980..b582f17 100644
--- a/libs/binder/UtilsHost.h
+++ b/libs/binder/UtilsHost.h
@@ -23,7 +23,7 @@
#include <vector>
#include <android-base/macros.h>
-#include <android-base/unique_fd.h>
+#include <binder/unique_fd.h>
#include <utils/Errors.h>
/**
@@ -46,8 +46,8 @@
std::string stdoutStr;
std::string stderrStr;
- android::base::unique_fd outPipe;
- android::base::unique_fd errPipe;
+ binder::unique_fd outPipe;
+ binder::unique_fd errPipe;
CommandResult() = default;
CommandResult(CommandResult&& other) noexcept { (*this) = std::move(other); }
diff --git a/libs/binder/file.cpp b/libs/binder/file.cpp
new file mode 100644
index 0000000..bac667e
--- /dev/null
+++ b/libs/binder/file.cpp
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2023 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 "file.h"
+
+#ifdef BINDER_NO_LIBBASE
+
+#include <stdint.h>
+
+// clang-format off
+
+namespace android::binder {
+
+bool ReadFully(borrowed_fd fd, void* data, size_t byte_count) {
+ uint8_t* p = reinterpret_cast<uint8_t*>(data);
+ size_t remaining = byte_count;
+ while (remaining > 0) {
+ ssize_t n = TEMP_FAILURE_RETRY(read(fd.get(), p, remaining));
+ if (n == 0) { // EOF
+ errno = ENODATA;
+ return false;
+ }
+ if (n == -1) return false;
+ p += n;
+ remaining -= n;
+ }
+ return true;
+}
+
+bool WriteFully(borrowed_fd fd, const void* data, size_t byte_count) {
+ const uint8_t* p = reinterpret_cast<const uint8_t*>(data);
+ size_t remaining = byte_count;
+ while (remaining > 0) {
+ ssize_t n = TEMP_FAILURE_RETRY(write(fd.get(), p, remaining));
+ if (n == -1) return false;
+ p += n;
+ remaining -= n;
+ }
+ return true;
+}
+
+} // namespace android::binder
+
+#endif // BINDER_NO_LIBBASE
diff --git a/libs/binder/file.h b/libs/binder/file.h
new file mode 100644
index 0000000..bcbfa31
--- /dev/null
+++ b/libs/binder/file.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#ifndef BINDER_NO_LIBBASE
+
+#include <android-base/file.h>
+
+namespace android::binder {
+using android::base::ReadFully;
+using android::base::WriteFully;
+} // namespace android::binder
+
+#else // BINDER_NO_LIBBASE
+
+#include <binder/unique_fd.h>
+
+#include <string_view>
+
+namespace android::binder {
+
+bool ReadFully(borrowed_fd fd, void* data, size_t byte_count);
+bool WriteFully(borrowed_fd fd, const void* data, size_t byte_count);
+
+} // namespace android::binder
+
+#endif // BINDER_NO_LIBBASE
diff --git a/libs/binder/include/binder/Binder.h b/libs/binder/include/binder/Binder.h
index 744da0f..7a65ff4 100644
--- a/libs/binder/include/binder/Binder.h
+++ b/libs/binder/include/binder/Binder.h
@@ -102,7 +102,7 @@
// to another process.
void setParceled();
- [[nodiscard]] status_t setRpcClientDebug(android::base::unique_fd clientFd,
+ [[nodiscard]] status_t setRpcClientDebug(binder::unique_fd clientFd,
const sp<IBinder>& keepAliveBinder);
protected:
diff --git a/libs/binder/include/binder/BpBinder.h b/libs/binder/include/binder/BpBinder.h
index d78ea0d..89a4d27 100644
--- a/libs/binder/include/binder/BpBinder.h
+++ b/libs/binder/include/binder/BpBinder.h
@@ -16,9 +16,9 @@
#pragma once
-#include <android-base/unique_fd.h>
#include <binder/IBinder.h>
#include <binder/RpcThreads.h>
+#include <binder/unique_fd.h>
#include <map>
#include <optional>
@@ -94,7 +94,7 @@
// Start recording transactions to the unique_fd.
// See RecordedTransaction.h for more details.
- status_t startRecordingBinder(const android::base::unique_fd& fd);
+ status_t startRecordingBinder(const binder::unique_fd& fd);
// Stop the current recording.
status_t stopRecordingBinder();
diff --git a/libs/binder/include/binder/IBinder.h b/libs/binder/include/binder/IBinder.h
index e75d548..dad9a17 100644
--- a/libs/binder/include/binder/IBinder.h
+++ b/libs/binder/include/binder/IBinder.h
@@ -16,7 +16,7 @@
#pragma once
-#include <android-base/unique_fd.h>
+#include <binder/unique_fd.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
#include <utils/String16.h>
@@ -175,7 +175,7 @@
*
* On death of @a keepAliveBinder, the RpcServer shuts down.
*/
- [[nodiscard]] status_t setRpcClientDebug(android::base::unique_fd socketFd,
+ [[nodiscard]] status_t setRpcClientDebug(binder::unique_fd socketFd,
const sp<IBinder>& keepAliveBinder);
// NOLINTNEXTLINE(google-default-arguments)
diff --git a/libs/binder/include/binder/Parcel.h b/libs/binder/include/binder/Parcel.h
index 6961abc..09da6e3 100644
--- a/libs/binder/include/binder/Parcel.h
+++ b/libs/binder/include/binder/Parcel.h
@@ -25,7 +25,7 @@
#include <variant>
#include <vector>
-#include <android-base/unique_fd.h>
+#include <binder/unique_fd.h>
#ifndef BINDER_DISABLE_NATIVE_HANDLE
#include <cutils/native_handle.h>
#endif
@@ -354,17 +354,16 @@
// Place a file descriptor into the parcel. This will not affect the
// semantics of the smart file descriptor. A new descriptor will be
// created, and will be closed when the parcel is destroyed.
- status_t writeUniqueFileDescriptor(
- const base::unique_fd& fd);
+ status_t writeUniqueFileDescriptor(const binder::unique_fd& fd);
// 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) __attribute__((deprecated("use std::optional version instead")));
- status_t writeUniqueFileDescriptorVector(
- const std::vector<base::unique_fd>& val);
+ status_t writeUniqueFileDescriptorVector(
+ const std::optional<std::vector<binder::unique_fd>>& val);
+ status_t writeUniqueFileDescriptorVector(
+ const std::unique_ptr<std::vector<binder::unique_fd>>& val)
+ __attribute__((deprecated("use std::optional version instead")));
+ status_t writeUniqueFileDescriptorVector(const std::vector<binder::unique_fd>& val);
// Writes a blob to the parcel.
// If the blob is small, then it is stored in-place, otherwise it is
@@ -579,20 +578,17 @@
int readParcelFileDescriptor() const;
// Retrieve a smart file descriptor from the parcel.
- status_t readUniqueFileDescriptor(
- base::unique_fd* val) const;
+ status_t readUniqueFileDescriptor(binder::unique_fd* val) const;
// Retrieve a Java "parcel file descriptor" from the parcel.
- status_t readUniqueParcelFileDescriptor(base::unique_fd* val) const;
-
+ status_t readUniqueParcelFileDescriptor(binder::unique_fd* val) const;
// 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 __attribute__((deprecated("use std::optional version instead")));
- status_t readUniqueFileDescriptorVector(
- std::vector<base::unique_fd>* val) const;
+ status_t readUniqueFileDescriptorVector(
+ std::optional<std::vector<binder::unique_fd>>* val) const;
+ status_t readUniqueFileDescriptorVector(std::unique_ptr<std::vector<binder::unique_fd>>* val)
+ const __attribute__((deprecated("use std::optional version instead")));
+ status_t readUniqueFileDescriptorVector(std::vector<binder::unique_fd>* val) const;
// Reads a blob from the parcel.
// The caller should call release() on the blob after reading its contents.
@@ -629,7 +625,7 @@
status_t rpcSetDataReference(
const sp<RpcSession>& session, const uint8_t* data, size_t dataSize,
const uint32_t* objectTable, size_t objectTableSize,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>&& ancillaryFds,
+ std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>&& ancillaryFds,
release_func relFunc);
status_t finishWrite(size_t len);
@@ -706,7 +702,7 @@
// 5) Nullable objects contained in std::optional, std::unique_ptr, or std::shared_ptr.
//
// And active objects from the Android ecosystem such as:
- // 6) File descriptors, base::unique_fd (kernel object handles)
+ // 6) File descriptors, unique_fd (kernel object handles)
// 7) Binder objects, sp<IBinder> (active Android RPC handles)
//
// Objects from (1) through (5) serialize into the mData buffer.
@@ -957,9 +953,7 @@
return writeUtf8AsUtf16(t);
}
- status_t writeData(const base::unique_fd& t) {
- return writeUniqueFileDescriptor(t);
- }
+ status_t writeData(const binder::unique_fd& t) { return writeUniqueFileDescriptor(t); }
status_t writeData(const Parcelable& t) { // std::is_base_of_v<Parcelable, T>
// implemented here. writeParcelable() calls this.
@@ -1106,9 +1100,7 @@
return readUtf8FromUtf16(t);
}
- status_t readData(base::unique_fd* t) const {
- return readUniqueFileDescriptor(t);
- }
+ status_t readData(binder::unique_fd* t) const { return readUniqueFileDescriptor(t); }
status_t readData(Parcelable* t) const { // std::is_base_of_v<Parcelable, T>
// implemented here. readParcelable() calls this.
@@ -1328,7 +1320,7 @@
// same order as `mObjectPositions`.
//
// Boxed to save space. Lazy allocated.
- std::unique_ptr<std::vector<std::variant<base::unique_fd, base::borrowed_fd>>> mFds;
+ std::unique_ptr<std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>> mFds;
};
std::variant<KernelFields, RpcFields> mVariantFields;
diff --git a/libs/binder/include/binder/ParcelFileDescriptor.h b/libs/binder/include/binder/ParcelFileDescriptor.h
index 08d8e43..c4ef354 100644
--- a/libs/binder/include/binder/ParcelFileDescriptor.h
+++ b/libs/binder/include/binder/ParcelFileDescriptor.h
@@ -16,9 +16,9 @@
#pragma once
-#include <android-base/unique_fd.h>
#include <binder/Parcel.h>
#include <binder/Parcelable.h>
+#include <binder/unique_fd.h>
namespace android {
namespace os {
@@ -29,14 +29,14 @@
class ParcelFileDescriptor : public android::Parcelable {
public:
ParcelFileDescriptor();
- explicit ParcelFileDescriptor(android::base::unique_fd fd);
+ explicit ParcelFileDescriptor(binder::unique_fd fd);
ParcelFileDescriptor(ParcelFileDescriptor&& other) noexcept : mFd(std::move(other.mFd)) { }
ParcelFileDescriptor& operator=(ParcelFileDescriptor&& other) noexcept = default;
~ParcelFileDescriptor() override;
int get() const { return mFd.get(); }
- android::base::unique_fd release() { return std::move(mFd); }
- void reset(android::base::unique_fd fd = android::base::unique_fd()) { mFd = std::move(fd); }
+ binder::unique_fd release() { return std::move(mFd); }
+ void reset(binder::unique_fd fd = binder::unique_fd()) { mFd = std::move(fd); }
// android::Parcelable override:
android::status_t writeToParcel(android::Parcel* parcel) const override;
@@ -62,7 +62,7 @@
return mFd.get() >= rhs.mFd.get();
}
private:
- android::base::unique_fd mFd;
+ binder::unique_fd mFd;
};
} // namespace os
diff --git a/libs/binder/include/binder/RecordedTransaction.h b/libs/binder/include/binder/RecordedTransaction.h
index eb765fe..505c199 100644
--- a/libs/binder/include/binder/RecordedTransaction.h
+++ b/libs/binder/include/binder/RecordedTransaction.h
@@ -16,8 +16,8 @@
#pragma once
-#include <android-base/unique_fd.h>
#include <binder/Parcel.h>
+#include <binder/unique_fd.h>
#include <mutex>
namespace android {
@@ -31,7 +31,8 @@
class RecordedTransaction {
public:
// Filled with the first transaction from fd.
- static std::optional<RecordedTransaction> fromFile(const android::base::unique_fd& fd);
+
+ static std::optional<RecordedTransaction> fromFile(const binder::unique_fd& fd);
// Filled with the arguments.
static std::optional<RecordedTransaction> fromDetails(const String16& interfaceName,
uint32_t code, uint32_t flags,
@@ -39,7 +40,7 @@
const Parcel& reply, status_t err);
RecordedTransaction(RecordedTransaction&& t) noexcept;
- [[nodiscard]] status_t dumpToFile(const android::base::unique_fd& fd) const;
+ [[nodiscard]] status_t dumpToFile(const binder::unique_fd& fd) const;
const std::string& getInterfaceName() const;
uint32_t getCode() const;
@@ -53,8 +54,8 @@
private:
RecordedTransaction() = default;
- android::status_t writeChunk(const android::base::borrowed_fd, uint32_t chunkType,
- size_t byteCount, const uint8_t* data) const;
+ android::status_t writeChunk(const binder::borrowed_fd, uint32_t chunkType, size_t byteCount,
+ const uint8_t* data) const;
#pragma clang diagnostic push
#pragma clang diagnostic error "-Wpadded"
diff --git a/libs/binder/include/binder/RpcServer.h b/libs/binder/include/binder/RpcServer.h
index 2153f16..a07880d 100644
--- a/libs/binder/include/binder/RpcServer.h
+++ b/libs/binder/include/binder/RpcServer.h
@@ -15,11 +15,11 @@
*/
#pragma once
-#include <android-base/unique_fd.h>
#include <binder/IBinder.h>
#include <binder/RpcSession.h>
#include <binder/RpcThreads.h>
#include <binder/RpcTransport.h>
+#include <binder/unique_fd.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
@@ -59,7 +59,7 @@
* to RpcSession::setupUnixDomainSocketBootstrapClient. Multiple client
* session can be created from the client end of the pair.
*/
- [[nodiscard]] status_t setupUnixDomainSocketBootstrapServer(base::unique_fd serverFd);
+ [[nodiscard]] status_t setupUnixDomainSocketBootstrapServer(binder::unique_fd serverFd);
/**
* This represents a session for responses, e.g.:
@@ -79,7 +79,7 @@
* This method is used in the libbinder_rpc_unstable API
* RunInitUnixDomainRpcServer().
*/
- [[nodiscard]] status_t setupRawSocketServer(base::unique_fd socket_fd);
+ [[nodiscard]] status_t setupRawSocketServer(binder::unique_fd socket_fd);
/**
* Creates an RPC server binding to the given CID at the given port.
@@ -111,13 +111,13 @@
/**
* If hasServer(), return the server FD. Otherwise return invalid FD.
*/
- [[nodiscard]] base::unique_fd releaseServer();
+ [[nodiscard]] binder::unique_fd releaseServer();
/**
* Set up server using an external FD previously set up by releaseServer().
* Return false if there's already a server.
*/
- [[nodiscard]] status_t setupExternalServer(base::unique_fd serverFd);
+ [[nodiscard]] status_t setupExternalServer(binder::unique_fd serverFd);
/**
* This must be called before adding a client session. This corresponds
@@ -193,7 +193,7 @@
*
* The only argument is a successfully created file descriptor, not bound to an address yet.
*/
- void setServerSocketModifier(std::function<void(base::borrowed_fd)>&& modifier);
+ void setServerSocketModifier(std::function<void(binder::borrowed_fd)>&& modifier);
/**
* See RpcTransportCtx::getCertificate
@@ -249,7 +249,7 @@
void onSessionIncomingThreadEnded() override;
status_t setupExternalServer(
- base::unique_fd serverFd,
+ binder::unique_fd serverFd,
std::function<status_t(const RpcServer&, RpcTransportFd*)>&& acceptFn);
static constexpr size_t kRpcAddressSize = 128;
@@ -279,7 +279,7 @@
wp<IBinder> mRootObjectWeak;
std::function<sp<IBinder>(wp<RpcSession>, const void*, size_t)> mRootObjectFactory;
std::function<bool(const void*, size_t)> mConnectionFilter;
- std::function<void(base::borrowed_fd)> mServerSocketModifier;
+ std::function<void(binder::borrowed_fd)> mServerSocketModifier;
std::map<std::vector<uint8_t>, sp<RpcSession>> mSessions;
std::unique_ptr<FdTrigger> mShutdownTrigger;
RpcConditionVariable mShutdownCv;
diff --git a/libs/binder/include/binder/RpcSession.h b/libs/binder/include/binder/RpcSession.h
index e3805ac..11fbde9 100644
--- a/libs/binder/include/binder/RpcSession.h
+++ b/libs/binder/include/binder/RpcSession.h
@@ -15,10 +15,10 @@
*/
#pragma once
-#include <android-base/unique_fd.h>
#include <binder/IBinder.h>
#include <binder/RpcThreads.h>
#include <binder/RpcTransport.h>
+#include <binder/unique_fd.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
@@ -123,7 +123,7 @@
/**
* Connects to an RPC server over a nameless Unix domain socket pair.
*/
- [[nodiscard]] status_t setupUnixDomainSocketBootstrapClient(base::unique_fd bootstrap);
+ [[nodiscard]] status_t setupUnixDomainSocketBootstrapClient(binder::unique_fd bootstrap);
/**
* Connects to an RPC server at the CVD & port.
@@ -145,8 +145,8 @@
*
* For future compatibility, 'request' should not reference any stack data.
*/
- [[nodiscard]] status_t setupPreconnectedClient(base::unique_fd fd,
- std::function<base::unique_fd()>&& request);
+ [[nodiscard]] status_t setupPreconnectedClient(binder::unique_fd fd,
+ std::function<binder::unique_fd()>&& request);
/**
* For debugging!
diff --git a/libs/binder/include/binder/RpcTransport.h b/libs/binder/include/binder/RpcTransport.h
index 115a173..a50cdc1 100644
--- a/libs/binder/include/binder/RpcTransport.h
+++ b/libs/binder/include/binder/RpcTransport.h
@@ -25,12 +25,12 @@
#include <variant>
#include <vector>
-#include <android-base/unique_fd.h>
#include <utils/Errors.h>
#include <binder/Functional.h>
#include <binder/RpcCertificateFormat.h>
#include <binder/RpcThreads.h>
+#include <binder/unique_fd.h>
#include <sys/uio.h>
@@ -87,11 +87,12 @@
[[nodiscard]] virtual status_t interruptableWriteFully(
FdTrigger* fdTrigger, iovec* iovs, int niovs,
const std::optional<binder::impl::SmallFunction<status_t()>>& altPoll,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) = 0;
+ const std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>*
+ ancillaryFds) = 0;
[[nodiscard]] virtual status_t interruptableReadFully(
FdTrigger* fdTrigger, iovec* iovs, int niovs,
const std::optional<binder::impl::SmallFunction<status_t()>>& altPoll,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) = 0;
+ std::vector<std::variant<binder::unique_fd, binder::borrowed_fd>>* ancillaryFds) = 0;
/**
* Check whether any threads are blocked while polling the transport
@@ -177,10 +178,10 @@
void setPollingState(bool state) const { isPolling = state; }
public:
- base::unique_fd fd;
+ binder::unique_fd fd;
RpcTransportFd() = default;
- explicit RpcTransportFd(base::unique_fd &&descriptor)
+ explicit RpcTransportFd(binder::unique_fd&& descriptor)
: isPolling(false), fd(std::move(descriptor)) {}
RpcTransportFd(RpcTransportFd &&transportFd) noexcept
@@ -192,7 +193,7 @@
return *this;
}
- RpcTransportFd &operator=(base::unique_fd &&descriptor) noexcept {
+ RpcTransportFd& operator=(binder::unique_fd&& descriptor) noexcept {
fd = std::move(descriptor);
isPolling = false;
return *this;
diff --git a/libs/binder/include/binder/unique_fd.h b/libs/binder/include/binder/unique_fd.h
new file mode 100644
index 0000000..439b8a2
--- /dev/null
+++ b/libs/binder/include/binder/unique_fd.h
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#ifndef BINDER_NO_LIBBASE
+
+#include <android-base/unique_fd.h>
+
+namespace android::binder {
+using android::base::borrowed_fd;
+using android::base::unique_fd;
+} // namespace android::binder
+
+#else // BINDER_NO_LIBBASE
+
+#include <errno.h>
+#include <fcntl.h> // not needed for unique_fd, but a lot of users depend on open(3)
+#include <unistd.h>
+
+namespace android::binder {
+
+// Container for a file descriptor that automatically closes the descriptor as
+// it goes out of scope.
+//
+// unique_fd ufd(open("/some/path", "r"));
+// if (!ufd.ok()) return error;
+//
+// // Do something useful with ufd.get(), possibly including early 'return'.
+//
+// return 0; // Descriptor is closed for you.
+//
+class unique_fd final {
+public:
+ unique_fd() {}
+
+ explicit unique_fd(int fd) { reset(fd); }
+ ~unique_fd() { reset(); }
+
+ unique_fd(const unique_fd&) = delete;
+ void operator=(const unique_fd&) = delete;
+ unique_fd(unique_fd&& other) noexcept { reset(other.release()); }
+ unique_fd& operator=(unique_fd&& s) noexcept {
+ int fd = s.fd_;
+ s.fd_ = -1;
+ reset(fd);
+ return *this;
+ }
+
+ [[clang::reinitializes]] void reset(int new_value = -1) {
+ int previous_errno = errno;
+
+ if (fd_ != -1) {
+ ::close(fd_);
+ }
+
+ fd_ = new_value;
+ errno = previous_errno;
+ }
+
+ int get() const { return fd_; }
+
+ bool ok() const { return get() >= 0; }
+
+ [[nodiscard]] int release() {
+ int ret = fd_;
+ fd_ = -1;
+ return ret;
+ }
+
+private:
+ int fd_ = -1;
+};
+
+// A wrapper type that can be implicitly constructed from either int or
+// unique_fd. This supports cases where you don't actually own the file
+// descriptor, and can't take ownership, but are temporarily acting as if
+// you're the owner.
+//
+// One example would be a function that needs to also allow
+// STDERR_FILENO, not just a newly-opened fd. Another example would be JNI code
+// that's using a file descriptor that's actually owned by a
+// ParcelFileDescriptor or whatever on the Java side, but where the JNI code
+// would like to enforce this weaker sense of "temporary ownership".
+//
+// If you think of unique_fd as being like std::string in that represents
+// ownership, borrowed_fd is like std::string_view (and int is like const
+// char*).
+struct borrowed_fd {
+ /* implicit */ borrowed_fd(int fd) : fd_(fd) {} // NOLINT
+ /* implicit */ borrowed_fd(const unique_fd& ufd) : fd_(ufd.get()) {} // NOLINT
+
+ int get() const { return fd_; }
+
+private:
+ int fd_ = -1;
+};
+
+} // namespace android::binder
+
+#endif // BINDER_NO_LIBBASE
diff --git a/libs/binder/libbinder_rpc_unstable.cpp b/libs/binder/libbinder_rpc_unstable.cpp
index 118409e..ddd82e8 100644
--- a/libs/binder/libbinder_rpc_unstable.cpp
+++ b/libs/binder/libbinder_rpc_unstable.cpp
@@ -16,10 +16,10 @@
#include <binder_rpc_unstable.hpp>
-#include <android-base/unique_fd.h>
#include <android/binder_libbinder.h>
#include <binder/RpcServer.h>
#include <binder/RpcSession.h>
+#include <binder/unique_fd.h>
#include <cutils/sockets.h>
#include <linux/vm_sockets.h>
@@ -29,7 +29,7 @@
using android::sp;
using android::status_t;
using android::statusToString;
-using android::base::unique_fd;
+using android::binder::unique_fd;
// Opaque handle for RpcServer.
struct ARpcServer {};
diff --git a/libs/binder/ndk/parcel.cpp b/libs/binder/ndk/parcel.cpp
index c15bcf9..88ce5f4 100644
--- a/libs/binder/ndk/parcel.cpp
+++ b/libs/binder/ndk/parcel.cpp
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-#include <android-base/unique_fd.h>
#include <android/binder_parcel.h>
#include <android/binder_parcel_platform.h>
#include <binder/Parcel.h>
#include <binder/ParcelFileDescriptor.h>
+#include <binder/unique_fd.h>
#include <inttypes.h>
#include <utils/Unicode.h>
@@ -32,7 +32,7 @@
using ::android::Parcel;
using ::android::sp;
using ::android::status_t;
-using ::android::base::unique_fd;
+using ::android::binder::unique_fd;
using ::android::os::ParcelFileDescriptor;
template <typename T>
diff --git a/libs/binder/rust/tests/serialization.cpp b/libs/binder/rust/tests/serialization.cpp
index 3f59dab..0cdf8c5 100644
--- a/libs/binder/rust/tests/serialization.cpp
+++ b/libs/binder/rust/tests/serialization.cpp
@@ -14,6 +14,10 @@
* limitations under the License.
*/
+#include "serialization.hpp"
+#include "../../FdUtils.h"
+#include "../../tests/FileUtils.h"
+
#include <android/binder_ibinder_platform.h>
#include <android/binder_libbinder.h>
#include <binder/IServiceManager.h>
@@ -24,8 +28,6 @@
#include <gtest/gtest.h>
#include <utils/Errors.h>
#include <utils/String16.h>
-#include "android-base/file.h"
-#include "serialization.hpp"
#include <cmath>
#include <cstdint>
@@ -34,7 +36,7 @@
using namespace std;
using namespace android;
-using android::base::unique_fd;
+using android::binder::unique_fd;
using android::os::ParcelFileDescriptor;
// defined in Rust
@@ -349,7 +351,7 @@
TEST_F(SerializationTest, SerializeFileDescriptor) {
unique_fd out_file, in_file;
- ASSERT_TRUE(base::Pipe(&out_file, &in_file));
+ ASSERT_TRUE(binder::Pipe(&out_file, &in_file));
vector<ParcelFileDescriptor> file_descriptors;
file_descriptors.push_back(ParcelFileDescriptor(std::move(out_file)));
diff --git a/libs/binder/servicedispatcher.cpp b/libs/binder/servicedispatcher.cpp
index f2693dd..18b178b 100644
--- a/libs/binder/servicedispatcher.cpp
+++ b/libs/binder/servicedispatcher.cpp
@@ -17,9 +17,9 @@
#include <sysexits.h>
#include <unistd.h>
+#include <filesystem>
#include <iostream>
-#include <android-base/file.h>
#include <android-base/logging.h>
#include <android-base/properties.h>
#include <android/debug/BnAdbCallback.h>
@@ -30,6 +30,8 @@
#include <binder/ProcessState.h>
#include <binder/RpcServer.h>
+#include "file.h"
+
using android::BBinder;
using android::defaultServiceManager;
using android::OK;
@@ -38,7 +40,6 @@
using android::status_t;
using android::statusToString;
using android::String16;
-using android::base::Basename;
using android::base::GetBoolProperty;
using android::base::InitLogging;
using android::base::LogdLogger;
@@ -53,8 +54,8 @@
using ServiceRetriever = decltype(&android::IServiceManager::checkService);
using android::debug::IAdbManager;
-int Usage(const char* program) {
- auto basename = Basename(program);
+int Usage(std::filesystem::path program) {
+ auto basename = program.filename();
// clang-format off
LOG(ERROR) << R"(dispatch calls to RPC service.
Usage:
@@ -253,7 +254,8 @@
mLogdLogger(id, severity, tag, file, line, message);
if (severity >= LogSeverity::WARNING) {
std::cout << std::flush;
- std::cerr << Basename(getprogname()) << ": " << message << std::endl;
+ auto progname = std::filesystem::path(getprogname()).filename();
+ std::cerr << progname << ": " << message << std::endl;
}
}
diff --git a/libs/binder/tests/Android.bp b/libs/binder/tests/Android.bp
index cd3e7c0..ba8fb39 100644
--- a/libs/binder/tests/Android.bp
+++ b/libs/binder/tests/Android.bp
@@ -172,6 +172,30 @@
],
}
+cc_library_static {
+ name: "libbinder_test_utils",
+ host_supported: true,
+ vendor_available: true,
+ target: {
+ darwin: {
+ enabled: false,
+ },
+ },
+ defaults: [
+ "binder_test_defaults",
+ ],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
+ srcs: [
+ "FileUtils.cpp",
+ ],
+ visibility: [
+ ":__subpackages__",
+ ],
+}
+
cc_defaults {
name: "binderRpcTest_common_defaults",
host_supported: true,
@@ -185,6 +209,7 @@
],
static_libs: [
+ "libbinder_test_utils",
"libbinder_tls_static",
"libbinder_tls_test_utils",
"binderRpcTestIface-cpp",
diff --git a/libs/binder/tests/FileUtils.cpp b/libs/binder/tests/FileUtils.cpp
new file mode 100644
index 0000000..61509fe
--- /dev/null
+++ b/libs/binder/tests/FileUtils.cpp
@@ -0,0 +1,99 @@
+/*
+ * Copyright (C) 2023 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 "FileUtils.h"
+
+#ifdef BINDER_NO_LIBBASE
+
+#include <sys/stat.h>
+#include <filesystem>
+
+#if defined(__APPLE__)
+#include <mach-o/dyld.h>
+#endif
+#if defined(_WIN32)
+#include <direct.h>
+#include <windows.h>
+#endif
+
+namespace android::binder {
+
+bool ReadFdToString(borrowed_fd fd, std::string* content) {
+ content->clear();
+
+ // Although original we had small files in mind, this code gets used for
+ // very large files too, where the std::string growth heuristics might not
+ // be suitable. https://code.google.com/p/android/issues/detail?id=258500.
+ struct stat sb;
+ if (fstat(fd.get(), &sb) != -1 && sb.st_size > 0) {
+ content->reserve(sb.st_size);
+ }
+
+ char buf[4096] __attribute__((__uninitialized__));
+ ssize_t n;
+ while ((n = TEMP_FAILURE_RETRY(read(fd.get(), &buf[0], sizeof(buf)))) > 0) {
+ content->append(buf, n);
+ }
+ return (n == 0) ? true : false;
+}
+
+bool WriteStringToFd(std::string_view content, borrowed_fd fd) {
+ const char* p = content.data();
+ size_t left = content.size();
+ while (left > 0) {
+ ssize_t n = TEMP_FAILURE_RETRY(write(fd.get(), p, left));
+ if (n == -1) {
+ return false;
+ }
+ p += n;
+ left -= n;
+ }
+ return true;
+}
+
+static std::filesystem::path GetExecutablePath2() {
+#if defined(__linux__)
+ return std::filesystem::read_symlink("/proc/self/exe");
+#elif defined(__APPLE__)
+ char path[PATH_MAX + 1];
+ uint32_t path_len = sizeof(path);
+ int rc = _NSGetExecutablePath(path, &path_len);
+ if (rc < 0) {
+ std::unique_ptr<char> path_buf(new char[path_len]);
+ _NSGetExecutablePath(path_buf.get(), &path_len);
+ return path_buf.get();
+ }
+ return path;
+#elif defined(_WIN32)
+ char path[PATH_MAX + 1];
+ DWORD result = GetModuleFileName(NULL, path, sizeof(path) - 1);
+ if (result == 0 || result == sizeof(path) - 1) return "";
+ path[PATH_MAX - 1] = 0;
+ return path;
+#elif defined(__EMSCRIPTEN__)
+ abort();
+#else
+#error unknown OS
+#endif
+}
+
+std::string GetExecutableDirectory() {
+ return GetExecutablePath2().parent_path();
+}
+
+} // namespace android::binder
+
+#endif // BINDER_NO_LIBBASE
diff --git a/libs/binder/tests/FileUtils.h b/libs/binder/tests/FileUtils.h
new file mode 100644
index 0000000..2cbe5e7
--- /dev/null
+++ b/libs/binder/tests/FileUtils.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include "../file.h"
+
+#ifndef BINDER_NO_LIBBASE
+
+namespace android::binder {
+using android::base::GetExecutableDirectory;
+using android::base::ReadFdToString;
+using android::base::WriteStringToFd;
+} // namespace android::binder
+
+#else // BINDER_NO_LIBBASE
+
+#include <binder/unique_fd.h>
+
+#include <string_view>
+
+#if !defined(_WIN32) && !defined(O_BINARY)
+/** Windows needs O_BINARY, but Unix never mangles line endings. */
+#define O_BINARY 0
+#endif
+
+namespace android::binder {
+
+bool ReadFdToString(borrowed_fd fd, std::string* content);
+bool WriteStringToFd(std::string_view content, borrowed_fd fd);
+
+std::string GetExecutableDirectory();
+
+} // namespace android::binder
+
+#endif // BINDER_NO_LIBBASE
diff --git a/libs/binder/tests/binderLibTest.cpp b/libs/binder/tests/binderLibTest.cpp
index f3969f1..cb1a1ee 100644
--- a/libs/binder/tests/binderLibTest.cpp
+++ b/libs/binder/tests/binderLibTest.cpp
@@ -30,7 +30,6 @@
#include <android-base/properties.h>
#include <android-base/result-gmock.h>
#include <android-base/strings.h>
-#include <android-base/unique_fd.h>
#include <binder/Binder.h>
#include <binder/BpBinder.h>
#include <binder/Functional.h>
@@ -39,6 +38,7 @@
#include <binder/IServiceManager.h>
#include <binder/RpcServer.h>
#include <binder/RpcSession.h>
+#include <binder/unique_fd.h>
#include <utils/Flattenable.h>
#include <linux/sched.h>
@@ -57,6 +57,7 @@
using namespace std::chrono_literals;
using android::base::testing::HasValue;
using android::base::testing::Ok;
+using android::binder::unique_fd;
using testing::ExplainMatchResult;
using testing::Matcher;
using testing::Not;
@@ -847,7 +848,7 @@
writebuf[i] = i;
}
- android::base::unique_fd read_end, write_end;
+ unique_fd read_end, write_end;
{
int pipefd[2];
ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
@@ -1177,7 +1178,7 @@
Parcel reply;
EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
StatusEq(NO_ERROR));
- base::unique_fd fd;
+ unique_fd fd;
EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
const int result = fcntl(fd.get(), F_GETFL);
@@ -1486,7 +1487,7 @@
BinderLibTest::SetUp();
}
- std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
+ std::tuple<unique_fd, unsigned int> CreateSocket() {
auto rpcServer = RpcServer::make();
EXPECT_NE(nullptr, rpcServer);
if (rpcServer == nullptr) return {};
@@ -1553,7 +1554,7 @@
TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
auto binder = GetService();
ASSERT_TRUE(binder != nullptr);
- EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
+ EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
Debuggable(StatusEq(BAD_VALUE)));
}
@@ -1823,7 +1824,7 @@
int ret;
int32_t size;
const void *buf;
- android::base::unique_fd fd;
+ unique_fd fd;
ret = data.readUniqueParcelFileDescriptor(&fd);
if (ret != NO_ERROR) {
@@ -1888,7 +1889,7 @@
ALOGE("Could not make socket non-blocking: %s", strerror(errno));
return UNKNOWN_ERROR;
}
- base::unique_fd out(sockets[0]);
+ unique_fd out(sockets[0]);
status_t writeResult = reply->writeUniqueFileDescriptor(out);
if (writeResult != NO_ERROR) {
ALOGE("Could not write unique_fd");
diff --git a/libs/binder/tests/binderParcelUnitTest.cpp b/libs/binder/tests/binderParcelUnitTest.cpp
index 0a0dae0..34fc43f 100644
--- a/libs/binder/tests/binderParcelUnitTest.cpp
+++ b/libs/binder/tests/binderParcelUnitTest.cpp
@@ -29,8 +29,8 @@
using android::status_t;
using android::String16;
using android::String8;
-using android::base::unique_fd;
using android::binder::Status;
+using android::binder::unique_fd;
TEST(Parcel, NonNullTerminatedString8) {
String8 kTestString = String8("test-is-good");
diff --git a/libs/binder/tests/binderRecordReplayTest.cpp b/libs/binder/tests/binderRecordReplayTest.cpp
index d08a9bb..73c0a94 100644
--- a/libs/binder/tests/binderRecordReplayTest.cpp
+++ b/libs/binder/tests/binderRecordReplayTest.cpp
@@ -15,15 +15,14 @@
*/
#include <BnBinderRecordReplayTest.h>
-#include <android-base/file.h>
#include <android-base/logging.h>
-#include <android-base/unique_fd.h>
#include <binder/Binder.h>
#include <binder/BpBinder.h>
#include <binder/IBinder.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <binder/RecordedTransaction.h>
+#include <binder/unique_fd.h>
#include <fuzzbinder/libbinder_driver.h>
#include <fuzzer/FuzzedDataProvider.h>
@@ -33,11 +32,14 @@
#include <sys/prctl.h>
+#include "../file.h"
#include "parcelables/SingleDataParcelable.h"
using namespace android;
using android::generateSeedsFromRecording;
+using android::binder::borrowed_fd;
using android::binder::Status;
+using android::binder::unique_fd;
using android::binder::debug::RecordedTransaction;
using parcelables::SingleDataParcelable;
@@ -91,7 +93,7 @@
GENERATE_GETTER_SETTER(SingleDataParcelableArray, std::vector<SingleDataParcelable>);
};
-std::vector<uint8_t> retrieveData(base::borrowed_fd fd) {
+std::vector<uint8_t> retrieveData(borrowed_fd fd) {
struct stat fdStat;
EXPECT_TRUE(fstat(fd.get(), &fdStat) != -1);
EXPECT_TRUE(fdStat.st_size != 0);
@@ -103,8 +105,8 @@
}
void replayFuzzService(const sp<BpBinder>& binder, const RecordedTransaction& transaction) {
- base::unique_fd seedFd(open("/data/local/tmp/replayFuzzService",
- O_RDWR | O_CREAT | O_CLOEXEC | O_TRUNC, 0666));
+ unique_fd seedFd(open("/data/local/tmp/replayFuzzService",
+ O_RDWR | O_CREAT | O_CLOEXEC | O_TRUNC, 0666));
ASSERT_TRUE(seedFd.ok());
// generate corpus from this transaction.
@@ -148,8 +150,8 @@
Status (IBinderRecordReplayTest::*get)(U*), U changedValue) {
auto replayFunctions = {&replayBinder, &replayFuzzService};
for (auto replayFunc : replayFunctions) {
- base::unique_fd fd(open("/data/local/tmp/binderRecordReplayTest.rec",
- O_RDWR | O_CREAT | O_CLOEXEC, 0666));
+ unique_fd fd(open("/data/local/tmp/binderRecordReplayTest.rec",
+ O_RDWR | O_CREAT | O_CLOEXEC, 0666));
ASSERT_TRUE(fd.ok());
// record a transaction
diff --git a/libs/binder/tests/binderRecordedTransactionTest.cpp b/libs/binder/tests/binderRecordedTransactionTest.cpp
index 30172cc..6eb78d0 100644
--- a/libs/binder/tests/binderRecordedTransactionTest.cpp
+++ b/libs/binder/tests/binderRecordedTransactionTest.cpp
@@ -20,7 +20,7 @@
using android::Parcel;
using android::status_t;
-using android::base::unique_fd;
+using android::binder::unique_fd;
using android::binder::debug::RecordedTransaction;
TEST(BinderRecordedTransaction, RoundTripEncoding) {
diff --git a/libs/binder/tests/binderRpcTest.cpp b/libs/binder/tests/binderRpcTest.cpp
index 624edba..2769a88 100644
--- a/libs/binder/tests/binderRpcTest.cpp
+++ b/libs/binder/tests/binderRpcTest.cpp
@@ -25,6 +25,7 @@
#include <thread>
#include <type_traits>
+#include <dirent.h>
#include <dlfcn.h>
#include <poll.h>
#include <sys/prctl.h>
@@ -41,6 +42,10 @@
using namespace std::chrono_literals;
using namespace std::placeholders;
+using android::binder::borrowed_fd;
+using android::binder::GetExecutableDirectory;
+using android::binder::ReadFdToString;
+using android::binder::unique_fd;
using testing::AssertionFailure;
using testing::AssertionResult;
using testing::AssertionSuccess;
@@ -83,12 +88,11 @@
mPid = other.mPid;
other.mPid = 0;
}
- Process(const std::function<void(android::base::borrowed_fd /* writeEnd */,
- android::base::borrowed_fd /* readEnd */)>& f) {
- android::base::unique_fd childWriteEnd;
- android::base::unique_fd childReadEnd;
- if (!android::base::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
- if (!android::base::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
+ Process(const std::function<void(borrowed_fd /* writeEnd */, borrowed_fd /* readEnd */)>& f) {
+ unique_fd childWriteEnd;
+ unique_fd childReadEnd;
+ if (!binder::Pipe(&mReadEnd, &childWriteEnd, 0)) PLOGF("child write pipe failed");
+ if (!binder::Pipe(&childReadEnd, &mWriteEnd, 0)) PLOGF("child read pipe failed");
if (0 == (mPid = fork())) {
// racey: assume parent doesn't crash before this is set
prctl(PR_SET_PDEATHSIG, SIGHUP);
@@ -110,8 +114,8 @@
}
}
}
- android::base::borrowed_fd readEnd() { return mReadEnd; }
- android::base::borrowed_fd writeEnd() { return mWriteEnd; }
+ borrowed_fd readEnd() { return mReadEnd; }
+ borrowed_fd writeEnd() { return mWriteEnd; }
void setCustomExitStatusCheck(std::function<void(int wstatus)> f) {
mCustomExitStatusCheck = std::move(f);
@@ -125,8 +129,8 @@
private:
std::function<void(int wstatus)> mCustomExitStatusCheck;
pid_t mPid = 0;
- android::base::unique_fd mReadEnd;
- android::base::unique_fd mWriteEnd;
+ unique_fd mReadEnd;
+ unique_fd mWriteEnd;
};
static std::string allocateSocketAddress() {
@@ -142,10 +146,9 @@
return vsockPort++;
}
-static base::unique_fd initUnixSocket(std::string addr) {
+static unique_fd initUnixSocket(std::string addr) {
auto socket_addr = UnixSocketAddress(addr.c_str());
- base::unique_fd fd(
- TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
+ unique_fd fd(TEMP_FAILURE_RETRY(socket(socket_addr.addr()->sa_family, SOCK_STREAM, AF_UNIX)));
if (!fd.ok()) PLOGF("initUnixSocket failed to create socket");
if (0 != TEMP_FAILURE_RETRY(bind(fd.get(), socket_addr.addr(), socket_addr.addrSize()))) {
PLOGF("initUnixSocket failed to bind");
@@ -204,8 +207,8 @@
void terminate() override { host.terminate(); }
};
-static base::unique_fd connectTo(const RpcSocketAddress& addr) {
- base::unique_fd serverFd(
+static unique_fd connectTo(const RpcSocketAddress& addr) {
+ unique_fd serverFd(
TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
if (!serverFd.ok()) {
PLOGF("Could not create socket %s", addr.toString().c_str());
@@ -218,15 +221,15 @@
}
#ifndef BINDER_RPC_TO_TRUSTY_TEST
-static base::unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
- base::unique_fd sockClient, sockServer;
- if (!base::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
+static unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) {
+ unique_fd sockClient, sockServer;
+ if (!binder::Socketpair(SOCK_STREAM, &sockClient, &sockServer)) {
PLOGF("Failed socketpair()");
}
int zero = 0;
iovec iov{&zero, sizeof(zero)};
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
+ std::vector<std::variant<unique_fd, borrowed_fd>> fds;
fds.emplace_back(std::move(sockServer));
if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) {
@@ -259,12 +262,12 @@
bool singleThreaded = GetParam().singleThreaded;
bool noKernel = GetParam().noKernel;
- std::string path = android::base::GetExecutableDirectory();
+ std::string path = GetExecutableDirectory();
auto servicePath =
std::format("{}/binder_rpc_test_service{}{}", path,
singleThreaded ? "_single_threaded" : "", noKernel ? "_no_kernel" : "");
- base::unique_fd bootstrapClientFd, socketFd;
+ unique_fd bootstrapClientFd, socketFd;
auto addr = allocateSocketAddress();
// Initializes the socket before the fork/exec.
@@ -273,13 +276,13 @@
} else if (socketType == SocketType::UNIX_BOOTSTRAP) {
// Do not set O_CLOEXEC, bootstrapServerFd needs to survive fork/exec.
// This is because we cannot pass ParcelFileDescriptor over a pipe.
- if (!base::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
+ if (!binder::Socketpair(SOCK_STREAM, &bootstrapClientFd, &socketFd)) {
PLOGF("Failed socketpair()");
}
}
auto ret = std::make_unique<LinuxProcessSession>(
- Process([=](android::base::borrowed_fd writeEnd, android::base::borrowed_fd readEnd) {
+ Process([=](borrowed_fd writeEnd, borrowed_fd readEnd) {
if (socketType == SocketType::TIPC) {
// Trusty has a single persistent service
return;
@@ -374,7 +377,7 @@
break;
case SocketType::UNIX_BOOTSTRAP:
status = session->setupUnixDomainSocketBootstrapClient(
- base::unique_fd(dup(bootstrapClientFd.get())));
+ unique_fd(dup(bootstrapClientFd.get())));
break;
case SocketType::VSOCK:
status = session->setupVsockClient(VMADDR_CID_LOCAL, serverConfig.vsockPort);
@@ -391,14 +394,14 @@
// in case the service is slow to start
int tipcFd = tipc_connect(kTrustyIpcDevice, port.c_str());
if (tipcFd >= 0) {
- return android::base::unique_fd(tipcFd);
+ return unique_fd(tipcFd);
}
usleep(50000);
}
- return android::base::unique_fd();
+ return unique_fd();
#else
LOG_ALWAYS_FATAL("Tried to connect to Trusty outside of vendor");
- return android::base::unique_fd();
+ return unique_fd();
#endif
});
break;
@@ -590,12 +593,12 @@
android::os::ParcelFileDescriptor fdA;
EXPECT_OK(proc.rootIface->blockingRecvFd(&fdA));
std::string result;
- ASSERT_TRUE(android::base::ReadFdToString(fdA.get(), &result));
+ ASSERT_TRUE(ReadFdToString(fdA.get(), &result));
EXPECT_EQ(result, "a");
android::os::ParcelFileDescriptor fdB;
EXPECT_OK(proc.rootIface->blockingRecvFd(&fdB));
- ASSERT_TRUE(android::base::ReadFdToString(fdB.get(), &result));
+ ASSERT_TRUE(ReadFdToString(fdB.get(), &result));
EXPECT_EQ(result, "b");
saturateThreadPool(kNumServerThreads, proc.rootIface);
@@ -952,7 +955,7 @@
ASSERT_TRUE(status.isOk()) << status;
std::string result;
- ASSERT_TRUE(android::base::ReadFdToString(out.get(), &result));
+ ASSERT_TRUE(ReadFdToString(out.get(), &result));
ASSERT_EQ(result, "hello");
}
@@ -982,7 +985,7 @@
ASSERT_TRUE(status.isOk()) << status;
std::string result;
- EXPECT_TRUE(android::base::ReadFdToString(out.get(), &result));
+ EXPECT_TRUE(ReadFdToString(out.get(), &result));
EXPECT_EQ(result, "123abcd");
}
@@ -1007,7 +1010,7 @@
ASSERT_TRUE(status.isOk()) << status;
std::string result;
- EXPECT_TRUE(android::base::ReadFdToString(out.get(), &result));
+ EXPECT_TRUE(ReadFdToString(out.get(), &result));
EXPECT_EQ(result, std::string(253, 'a'));
}
@@ -1152,7 +1155,7 @@
// We don't need to enable TLS to know if vsock is supported.
unsigned int vsockPort = allocateVsockPort();
- android::base::unique_fd serverFd(
+ unique_fd serverFd(
TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
if (errno == EAFNOSUPPORT) {
@@ -1179,7 +1182,7 @@
// to see if the kernel supports it. It's safe to use a blocking
// connect because vsock sockets have a 2 second connection timeout,
// and they return ETIMEDOUT after that.
- android::base::unique_fd connectFd(
+ unique_fd connectFd(
TEMP_FAILURE_RETRY(socket(AF_VSOCK, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
LOG_ALWAYS_FATAL_IF(!connectFd.ok(), "Could not create socket for port %u: %s", vsockPort,
strerror(errno));
@@ -1193,7 +1196,7 @@
ret = TEMP_FAILURE_RETRY(connect(connectFd.get(), reinterpret_cast<sockaddr*>(&connectAddr),
sizeof(connectAddr)));
if (ret != 0 && (errno == EAGAIN || errno == EINPROGRESS)) {
- android::base::unique_fd acceptFd;
+ unique_fd acceptFd;
while (true) {
pollfd pfd[]{
{.fd = serverFd.get(), .events = POLLIN, .revents = 0},
@@ -1423,14 +1426,14 @@
};
TEST_P(BinderRpcServerOnly, SetExternalServerTest) {
- base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
+ unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
int sinkFd = sink.get();
auto server = RpcServer::make(newTlsFactory(std::get<0>(GetParam())));
ASSERT_TRUE(server->setProtocolVersion(std::get<1>(GetParam())));
ASSERT_FALSE(server->hasServer());
ASSERT_EQ(OK, server->setupExternalServer(std::move(sink)));
ASSERT_TRUE(server->hasServer());
- base::unique_fd retrieved = server->releaseServer();
+ unique_fd retrieved = server->releaseServer();
ASSERT_FALSE(server->hasServer());
ASSERT_EQ(sinkFd, retrieved.get());
}
@@ -1476,12 +1479,12 @@
// in the client half of the tests.
using Param =
std::tuple<SocketType, RpcSecurity, std::optional<RpcCertificateFormat>, uint32_t>;
- using ConnectToServer = std::function<base::unique_fd()>;
+ using ConnectToServer = std::function<unique_fd()>;
// A server that handles client socket connections.
class Server {
public:
- using AcceptConnection = std::function<base::unique_fd(Server*)>;
+ using AcceptConnection = std::function<unique_fd(Server*)>;
explicit Server() {}
Server(Server&&) = default;
@@ -1510,8 +1513,8 @@
};
} break;
case SocketType::UNIX_BOOTSTRAP: {
- base::unique_fd bootstrapFdClient, bootstrapFdServer;
- if (!base::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
+ unique_fd bootstrapFdClient, bootstrapFdServer;
+ if (!binder::Socketpair(SOCK_STREAM, &bootstrapFdClient, &bootstrapFdServer)) {
return AssertionFailure() << "Socketpair() failed";
}
auto status = rpcServer->setupUnixDomainSocketBootstrapServer(
@@ -1554,7 +1557,7 @@
mConnectToServer = [port] {
const char* addr = kLocalInetAddress;
auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
- if (aiStart == nullptr) return base::unique_fd{};
+ if (aiStart == nullptr) return unique_fd{};
for (auto ai = aiStart.get(); ai != nullptr; ai = ai->ai_next) {
auto fd = connectTo(
InetSocketAddress(ai->ai_addr, ai->ai_addrlen, addr, port));
@@ -1562,7 +1565,7 @@
}
ALOGE("None of the socket address resolved for %s:%u can be connected",
addr, port);
- return base::unique_fd{};
+ return unique_fd{};
};
} break;
case SocketType::TIPC: {
@@ -1586,13 +1589,13 @@
mThread = std::make_unique<std::thread>(&Server::run, this);
}
- base::unique_fd acceptServerConnection() {
- return base::unique_fd(TEMP_FAILURE_RETRY(
+ unique_fd acceptServerConnection() {
+ return unique_fd(TEMP_FAILURE_RETRY(
accept4(mFd.fd.get(), nullptr, nullptr, SOCK_CLOEXEC | SOCK_NONBLOCK)));
}
- base::unique_fd recvmsgServerConnection() {
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
+ unique_fd recvmsgServerConnection() {
+ std::vector<std::variant<unique_fd, borrowed_fd>> fds;
int buf;
iovec iov{&buf, sizeof(buf)};
@@ -1601,7 +1604,7 @@
}
LOG_ALWAYS_FATAL_IF(fds.size() != 1, "Expected one FD from receiveMessage(), got %zu",
fds.size());
- return std::move(std::get<base::unique_fd>(fds[0]));
+ return std::move(std::get<unique_fd>(fds[0]));
}
void run() {
@@ -1609,13 +1612,13 @@
std::vector<std::thread> threads;
while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
- base::unique_fd acceptedFd = mAcceptConnection(this);
+ unique_fd acceptedFd = mAcceptConnection(this);
threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
}
for (auto& thread : threads) thread.join();
}
- void handleOne(android::base::unique_fd acceptedFd) {
+ void handleOne(unique_fd acceptedFd) {
ASSERT_TRUE(acceptedFd.ok());
RpcTransportFd transportFd(std::move(acceptedFd));
auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
diff --git a/libs/binder/tests/binderRpcTestCommon.h b/libs/binder/tests/binderRpcTestCommon.h
index b2b63e4..a55edd2 100644
--- a/libs/binder/tests/binderRpcTestCommon.h
+++ b/libs/binder/tests/binderRpcTestCommon.h
@@ -41,7 +41,6 @@
#endif
#ifndef __TRUSTY__
-#include <android-base/file.h>
#include <android/binder_auto_utils.h>
#include <android/binder_libbinder.h>
#include <binder/ProcessState.h>
@@ -58,7 +57,9 @@
#include "../BuildFlags.h"
#include "../FdTrigger.h"
+#include "../FdUtils.h"
#include "../RpcState.h" // for debugging
+#include "FileUtils.h"
#include "format.h"
#include "utils/Errors.h"
@@ -156,28 +157,28 @@
};
#ifndef __TRUSTY__
-static inline void writeString(android::base::borrowed_fd fd, std::string_view str) {
+static inline void writeString(binder::borrowed_fd fd, std::string_view str) {
uint64_t length = str.length();
- LOG_ALWAYS_FATAL_IF(!android::base::WriteFully(fd, &length, sizeof(length)));
- LOG_ALWAYS_FATAL_IF(!android::base::WriteFully(fd, str.data(), str.length()));
+ LOG_ALWAYS_FATAL_IF(!android::binder::WriteFully(fd, &length, sizeof(length)));
+ LOG_ALWAYS_FATAL_IF(!android::binder::WriteFully(fd, str.data(), str.length()));
}
-static inline std::string readString(android::base::borrowed_fd fd) {
+static inline std::string readString(binder::borrowed_fd fd) {
uint64_t length;
- LOG_ALWAYS_FATAL_IF(!android::base::ReadFully(fd, &length, sizeof(length)));
+ LOG_ALWAYS_FATAL_IF(!android::binder::ReadFully(fd, &length, sizeof(length)));
std::string ret(length, '\0');
- LOG_ALWAYS_FATAL_IF(!android::base::ReadFully(fd, ret.data(), length));
+ LOG_ALWAYS_FATAL_IF(!android::binder::ReadFully(fd, ret.data(), length));
return ret;
}
-static inline void writeToFd(android::base::borrowed_fd fd, const Parcelable& parcelable) {
+static inline void writeToFd(binder::borrowed_fd fd, const Parcelable& parcelable) {
Parcel parcel;
LOG_ALWAYS_FATAL_IF(OK != parcelable.writeToParcel(&parcel));
writeString(fd, std::string(reinterpret_cast<const char*>(parcel.data()), parcel.dataSize()));
}
template <typename T>
-static inline T readFromFd(android::base::borrowed_fd fd) {
+static inline T readFromFd(binder::borrowed_fd fd) {
std::string data = readString(fd);
Parcel parcel;
LOG_ALWAYS_FATAL_IF(OK !=
@@ -208,12 +209,12 @@
}
// Create an FD that returns `contents` when read.
-static inline base::unique_fd mockFileDescriptor(std::string contents) {
- android::base::unique_fd readFd, writeFd;
- LOG_ALWAYS_FATAL_IF(!android::base::Pipe(&readFd, &writeFd), "%s", strerror(errno));
+static inline binder::unique_fd mockFileDescriptor(std::string contents) {
+ binder::unique_fd readFd, writeFd;
+ LOG_ALWAYS_FATAL_IF(!binder::Pipe(&readFd, &writeFd), "%s", strerror(errno));
RpcMaybeThread([writeFd = std::move(writeFd), contents = std::move(contents)]() {
signal(SIGPIPE, SIG_IGN); // ignore possible SIGPIPE from the write
- if (!WriteStringToFd(contents, writeFd)) {
+ if (!android::binder::WriteStringToFd(contents, writeFd)) {
int savedErrno = errno;
LOG_ALWAYS_FATAL_IF(EPIPE != savedErrno, "mockFileDescriptor write failed: %s",
strerror(savedErrno));
diff --git a/libs/binder/tests/binderRpcTestService.cpp b/libs/binder/tests/binderRpcTestService.cpp
index 5025bd6..28125f1 100644
--- a/libs/binder/tests/binderRpcTestService.cpp
+++ b/libs/binder/tests/binderRpcTestService.cpp
@@ -17,6 +17,8 @@
#include "binderRpcTestCommon.h"
using namespace android;
+using android::binder::ReadFdToString;
+using android::binder::unique_fd;
class MyBinderRpcTestAndroid : public MyBinderRpcTestBase {
public:
@@ -65,17 +67,17 @@
std::string acc;
for (const auto& file : files) {
std::string result;
- LOG_ALWAYS_FATAL_IF(!android::base::ReadFdToString(file.get(), &result));
+ LOG_ALWAYS_FATAL_IF(!ReadFdToString(file.get(), &result));
acc.append(result);
}
out->reset(mockFileDescriptor(acc));
return Status::ok();
}
- HandoffChannel<android::base::unique_fd> mFdChannel;
+ HandoffChannel<unique_fd> mFdChannel;
Status blockingSendFdOneway(const android::os::ParcelFileDescriptor& fd) override {
- mFdChannel.write(android::base::unique_fd(fcntl(fd.get(), F_DUPFD_CLOEXEC, 0)));
+ mFdChannel.write(unique_fd(fcntl(fd.get(), F_DUPFD_CLOEXEC, 0)));
return Status::ok();
}
@@ -101,8 +103,8 @@
__android_log_set_logger(__android_log_stderr_logger);
LOG_ALWAYS_FATAL_IF(argc != 3, "Invalid number of arguments: %d", argc);
- base::unique_fd writeEnd(atoi(argv[1]));
- base::unique_fd readEnd(atoi(argv[2]));
+ unique_fd writeEnd(atoi(argv[1]));
+ unique_fd readEnd(atoi(argv[2]));
auto serverConfig = readFromFd<BinderRpcTestServerConfig>(readEnd);
auto socketType = static_cast<SocketType>(serverConfig.socketType);
@@ -123,7 +125,7 @@
server->setSupportedFileDescriptorTransportModes(serverSupportedFileDescriptorTransportModes);
unsigned int outPort = 0;
- base::unique_fd socketFd(serverConfig.socketFd);
+ unique_fd socketFd(serverConfig.socketFd);
switch (socketType) {
case SocketType::PRECONNECTED:
diff --git a/libs/binder/tests/binderRpcTestTrusty.cpp b/libs/binder/tests/binderRpcTestTrusty.cpp
index 8acaae6..18751cc 100644
--- a/libs/binder/tests/binderRpcTestTrusty.cpp
+++ b/libs/binder/tests/binderRpcTestTrusty.cpp
@@ -22,6 +22,8 @@
#include "binderRpcTestFixture.h"
+using android::binder::unique_fd;
+
namespace android {
// Destructors need to be defined, even if pure virtual
@@ -74,7 +76,7 @@
auto port = trustyIpcPort(serverVersion);
int rc = connect(port.c_str(), IPC_CONNECT_WAIT_FOR_PORT);
LOG_ALWAYS_FATAL_IF(rc < 0, "Failed to connect to service: %d", rc);
- return base::unique_fd(rc);
+ return unique_fd(rc);
});
if (options.allowConnectFailure && status != OK) {
ret->sessions.clear();
diff --git a/libs/binder/tests/binderSafeInterfaceTest.cpp b/libs/binder/tests/binderSafeInterfaceTest.cpp
index cbbbe74..41cb552 100644
--- a/libs/binder/tests/binderSafeInterfaceTest.cpp
+++ b/libs/binder/tests/binderSafeInterfaceTest.cpp
@@ -41,6 +41,7 @@
#include <sys/prctl.h>
using namespace std::chrono_literals; // NOLINT - google-build-using-namespace
+using android::binder::unique_fd;
namespace android {
namespace tests {
@@ -685,7 +686,7 @@
TEST_F(SafeInterfaceTest, TestIncrementNativeHandle) {
// Create an fd we can use to send and receive from the remote process
- base::unique_fd eventFd{eventfd(0 /*initval*/, 0 /*flags*/)};
+ unique_fd eventFd{eventfd(0 /*initval*/, 0 /*flags*/)};
ASSERT_NE(-1, eventFd);
// Determine the maximum number of fds this process can have open
diff --git a/libs/binder/tests/binderTextOutputTest.cpp b/libs/binder/tests/binderTextOutputTest.cpp
index b37030e..a648c08 100644
--- a/libs/binder/tests/binderTextOutputTest.cpp
+++ b/libs/binder/tests/binderTextOutputTest.cpp
@@ -20,13 +20,14 @@
#include <limits>
#include <cstddef>
-#include "android-base/file.h"
#include "android-base/test_utils.h"
#include <gtest/gtest.h>
#include <binder/Parcel.h>
#include <binder/TextOutput.h>
+#include "../file.h"
+
static void CheckMessage(CapturedStderr& cap,
const char* expected,
bool singleline) {
diff --git a/libs/binder/tests/parcel_fuzzer/binder.cpp b/libs/binder/tests/parcel_fuzzer/binder.cpp
index ffeca2d..08fe071 100644
--- a/libs/binder/tests/parcel_fuzzer/binder.cpp
+++ b/libs/binder/tests/parcel_fuzzer/binder.cpp
@@ -29,8 +29,9 @@
#include "../../Utils.h"
-using ::android::status_t;
using ::android::HexString;
+using ::android::status_t;
+using ::android::binder::unique_fd;
enum ByteEnum : int8_t {};
enum IntEnum : int32_t {};
@@ -307,11 +308,12 @@
},
PARCEL_READ_NO_STATUS(int, readFileDescriptor),
PARCEL_READ_NO_STATUS(int, readParcelFileDescriptor),
- PARCEL_READ_WITH_STATUS(android::base::unique_fd, readUniqueFileDescriptor),
+ PARCEL_READ_WITH_STATUS(unique_fd, readUniqueFileDescriptor),
- PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<android::base::unique_fd>>, readUniqueFileDescriptorVector),
- PARCEL_READ_WITH_STATUS(std::optional<std::vector<android::base::unique_fd>>, readUniqueFileDescriptorVector),
- PARCEL_READ_WITH_STATUS(std::vector<android::base::unique_fd>, readUniqueFileDescriptorVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<unique_fd>>,
+ readUniqueFileDescriptorVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<unique_fd>>, readUniqueFileDescriptorVector),
+ PARCEL_READ_WITH_STATUS(std::vector<unique_fd>, readUniqueFileDescriptorVector),
[] (const ::android::Parcel& p, FuzzedDataProvider& provider) {
size_t len = provider.ConsumeIntegral<size_t>();
diff --git a/libs/binder/tests/parcel_fuzzer/binder2corpus/binder2corpus.cpp b/libs/binder/tests/parcel_fuzzer/binder2corpus/binder2corpus.cpp
index c0fdaea..57521f4 100644
--- a/libs/binder/tests/parcel_fuzzer/binder2corpus/binder2corpus.cpp
+++ b/libs/binder/tests/parcel_fuzzer/binder2corpus/binder2corpus.cpp
@@ -14,18 +14,20 @@
* limitations under the License.
*/
-#include <android-base/file.h>
+#include "../../FileUtils.h"
+
#include <android-base/logging.h>
-#include <android-base/unique_fd.h>
#include <binder/RecordedTransaction.h>
+#include <binder/unique_fd.h>
#include <fuzzseeds/random_parcel_seeds.h>
#include <sys/prctl.h>
+#include <sys/stat.h>
using android::generateSeedsFromRecording;
using android::status_t;
-using android::base::unique_fd;
+using android::binder::unique_fd;
using android::binder::debug::RecordedTransaction;
status_t generateCorpus(const char* recordingPath, const char* corpusDir) {
@@ -49,7 +51,7 @@
std::string filePath = std::string(corpusDir) + std::string("transaction_") +
std::to_string(transactionNumber);
constexpr int openFlags = O_WRONLY | O_CREAT | O_BINARY | O_CLOEXEC;
- android::base::unique_fd corpusFd(open(filePath.c_str(), openFlags, 0666));
+ unique_fd corpusFd(open(filePath.c_str(), openFlags, 0666));
if (!corpusFd.ok()) {
std::cerr << "Failed to open fd. Path " << filePath
<< " with error: " << strerror(errno) << std::endl;
diff --git a/libs/binder/tests/parcel_fuzzer/include_random_parcel/fuzzbinder/random_fd.h b/libs/binder/tests/parcel_fuzzer/include_random_parcel/fuzzbinder/random_fd.h
index 6ea9708..8d1299d 100644
--- a/libs/binder/tests/parcel_fuzzer/include_random_parcel/fuzzbinder/random_fd.h
+++ b/libs/binder/tests/parcel_fuzzer/include_random_parcel/fuzzbinder/random_fd.h
@@ -16,7 +16,7 @@
#pragma once
-#include <android-base/unique_fd.h>
+#include <binder/unique_fd.h>
#include <fuzzer/FuzzedDataProvider.h>
#include <vector>
@@ -27,6 +27,6 @@
// get a random FD for use in fuzzing, of a few different specific types
//
// may return multiple FDs (e.g. pipe), but will always return at least one
-std::vector<base::unique_fd> getRandomFds(FuzzedDataProvider* provider);
+std::vector<binder::unique_fd> getRandomFds(FuzzedDataProvider* provider);
} // namespace android
diff --git a/libs/binder/tests/parcel_fuzzer/include_random_parcel/fuzzbinder/random_parcel.h b/libs/binder/tests/parcel_fuzzer/include_random_parcel/fuzzbinder/random_parcel.h
index 27587a9..2812da7 100644
--- a/libs/binder/tests/parcel_fuzzer/include_random_parcel/fuzzbinder/random_parcel.h
+++ b/libs/binder/tests/parcel_fuzzer/include_random_parcel/fuzzbinder/random_parcel.h
@@ -27,7 +27,7 @@
struct RandomParcelOptions {
std::function<void(Parcel* p, FuzzedDataProvider& provider)> writeHeader;
std::vector<sp<IBinder>> extraBinders;
- std::vector<base::unique_fd> extraFds;
+ std::vector<binder::unique_fd> extraFds;
};
/**
diff --git a/libs/binder/tests/parcel_fuzzer/include_random_parcel_seeds/fuzzseeds/random_parcel_seeds.h b/libs/binder/tests/parcel_fuzzer/include_random_parcel_seeds/fuzzseeds/random_parcel_seeds.h
index 071250d..694b68d 100644
--- a/libs/binder/tests/parcel_fuzzer/include_random_parcel_seeds/fuzzseeds/random_parcel_seeds.h
+++ b/libs/binder/tests/parcel_fuzzer/include_random_parcel_seeds/fuzzseeds/random_parcel_seeds.h
@@ -14,7 +14,8 @@
* limitations under the License.
*/
-#include <android-base/file.h>
+#include "../../../../file.h"
+
#include <android-base/logging.h>
#include <binder/Binder.h>
@@ -40,6 +41,6 @@
template <typename T>
void writeReversedBuffer(std::vector<std::byte>& integralBuffer, T val);
} // namespace impl
-void generateSeedsFromRecording(base::borrowed_fd fd,
+void generateSeedsFromRecording(binder::borrowed_fd fd,
const binder::debug::RecordedTransaction& transaction);
} // namespace android
diff --git a/libs/binder/tests/parcel_fuzzer/libbinder_driver.cpp b/libs/binder/tests/parcel_fuzzer/libbinder_driver.cpp
index 38e6f32..02e69cc 100644
--- a/libs/binder/tests/parcel_fuzzer/libbinder_driver.cpp
+++ b/libs/binder/tests/parcel_fuzzer/libbinder_driver.cpp
@@ -23,6 +23,8 @@
#include <private/android_filesystem_config.h>
+using android::binder::unique_fd;
+
namespace android {
void fuzzService(const sp<IBinder>& binder, FuzzedDataProvider&& provider) {
@@ -103,7 +105,7 @@
retBinders.end());
auto retFds = reply.debugReadAllFileDescriptors();
for (size_t i = 0; i < retFds.size(); i++) {
- options.extraFds.push_back(base::unique_fd(dup(retFds[i])));
+ options.extraFds.push_back(unique_fd(dup(retFds[i])));
}
}
diff --git a/libs/binder/tests/parcel_fuzzer/random_fd.cpp b/libs/binder/tests/parcel_fuzzer/random_fd.cpp
index 4a9bd07..c7d1533 100644
--- a/libs/binder/tests/parcel_fuzzer/random_fd.cpp
+++ b/libs/binder/tests/parcel_fuzzer/random_fd.cpp
@@ -23,7 +23,7 @@
namespace android {
-using base::unique_fd;
+using binder::unique_fd;
std::vector<unique_fd> getRandomFds(FuzzedDataProvider* provider) {
const char* fdType;
diff --git a/libs/binder/tests/parcel_fuzzer/random_parcel.cpp b/libs/binder/tests/parcel_fuzzer/random_parcel.cpp
index f367b41..4e58dc4 100644
--- a/libs/binder/tests/parcel_fuzzer/random_parcel.cpp
+++ b/libs/binder/tests/parcel_fuzzer/random_parcel.cpp
@@ -23,6 +23,8 @@
#include <fuzzbinder/random_fd.h>
#include <utils/String16.h>
+using android::binder::unique_fd;
+
namespace android {
static void fillRandomParcelData(Parcel* p, FuzzedDataProvider&& provider) {
@@ -72,7 +74,7 @@
}
if (options->extraFds.size() > 0 && provider.ConsumeBool()) {
- const base::unique_fd& fd = options->extraFds.at(
+ const unique_fd& fd = options->extraFds.at(
provider.ConsumeIntegralInRange<size_t>(0,
options->extraFds.size() -
1));
@@ -83,7 +85,7 @@
return;
}
- std::vector<base::unique_fd> fds = getRandomFds(&provider);
+ std::vector<unique_fd> fds = getRandomFds(&provider);
CHECK(OK ==
p->writeFileDescriptor(fds.begin()->release(),
true /*takeOwnership*/));
diff --git a/libs/binder/tests/parcel_fuzzer/random_parcel_seeds.cpp b/libs/binder/tests/parcel_fuzzer/random_parcel_seeds.cpp
index 9e3e2ab..7b3c806 100644
--- a/libs/binder/tests/parcel_fuzzer/random_parcel_seeds.cpp
+++ b/libs/binder/tests/parcel_fuzzer/random_parcel_seeds.cpp
@@ -14,14 +14,16 @@
* limitations under the License.
*/
-#include <android-base/file.h>
#include <android-base/logging.h>
#include <binder/RecordedTransaction.h>
#include <fuzzseeds/random_parcel_seeds.h>
-using android::base::WriteFully;
+#include "../../file.h"
+
+using android::binder::borrowed_fd;
+using android::binder::WriteFully;
namespace android {
namespace impl {
@@ -64,7 +66,7 @@
} // namespace impl
-void generateSeedsFromRecording(base::borrowed_fd fd,
+void generateSeedsFromRecording(borrowed_fd fd,
const binder::debug::RecordedTransaction& transaction) {
// Write Reserved bytes for future use
std::vector<uint8_t> reservedBytes(8);
diff --git a/libs/binder/tests/rpc_fuzzer/Android.bp b/libs/binder/tests/rpc_fuzzer/Android.bp
index 71e847f..ab72bfd 100644
--- a/libs/binder/tests/rpc_fuzzer/Android.bp
+++ b/libs/binder/tests/rpc_fuzzer/Android.bp
@@ -25,13 +25,14 @@
"libbase",
"libcutils",
"liblog",
+ "libbinder_test_utils",
"libbinder_tls_static",
"libbinder_tls_test_utils",
"libssl_fuzz_unsafe",
"libcrypto_fuzz_unsafe",
],
cflags: [
- "-DBORINGSSL_UNSAFE_DETERMINISTIC_MODE" // for RAND_reset_for_fuzzing
+ "-DBORINGSSL_UNSAFE_DETERMINISTIC_MODE", // for RAND_reset_for_fuzzing
],
target: {
android: {
diff --git a/libs/binder/tests/rpc_fuzzer/main.cpp b/libs/binder/tests/rpc_fuzzer/main.cpp
index dcc8b8e..50fc2f2 100644
--- a/libs/binder/tests/rpc_fuzzer/main.cpp
+++ b/libs/binder/tests/rpc_fuzzer/main.cpp
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-#include <android-base/file.h>
+#include "../FileUtils.h"
+
#include <android-base/logging.h>
-#include <android-base/unique_fd.h>
#include <binder/Binder.h>
#include <binder/Parcel.h>
#include <binder/RpcServer.h>
@@ -24,13 +24,18 @@
#include <binder/RpcTransport.h>
#include <binder/RpcTransportRaw.h>
#include <binder/RpcTransportTls.h>
+#include <binder/unique_fd.h>
#include <fuzzer/FuzzedDataProvider.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <sys/resource.h>
+#include <sys/socket.h>
#include <sys/un.h>
+using android::binder::GetExecutableDirectory;
+using android::binder::unique_fd;
+
namespace android {
static const std::string kSock = std::string(getenv("TMPDIR") ?: "/tmp") +
@@ -76,12 +81,12 @@
ServerAuth readServerKeyAndCert() {
ServerAuth ret;
- auto keyPath = android::base::GetExecutableDirectory() + "/data/server.key";
+ auto keyPath = GetExecutableDirectory() + "/data/server.key";
bssl::UniquePtr<BIO> keyBio(BIO_new_file(keyPath.c_str(), "r"));
ret.pkey.reset(PEM_read_bio_PrivateKey(keyBio.get(), nullptr, passwordCallback, nullptr));
CHECK_NE(ret.pkey.get(), nullptr);
- auto certPath = android::base::GetExecutableDirectory() + "/data/server.crt";
+ auto certPath = GetExecutableDirectory() + "/data/server.crt";
bssl::UniquePtr<BIO> certBio(BIO_new_file(certPath.c_str(), "r"));
ret.cert.reset(PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
CHECK_NE(ret.cert.get(), nullptr);
@@ -129,7 +134,7 @@
CHECK_LT(kSock.size(), sizeof(addr.sun_path));
memcpy(&addr.sun_path, kSock.c_str(), kSock.size());
- std::vector<base::unique_fd> connections;
+ std::vector<unique_fd> connections;
bool hangupBeforeShutdown = provider.ConsumeBool();
@@ -140,7 +145,7 @@
while (provider.remaining_bytes() > 0) {
if (connections.empty() ||
(connections.size() < kMaxConnections && provider.ConsumeBool())) {
- base::unique_fd fd(TEMP_FAILURE_RETRY(socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)));
+ unique_fd fd(TEMP_FAILURE_RETRY(socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)));
CHECK_NE(fd.get(), -1);
CHECK_EQ(0,
TEMP_FAILURE_RETRY(
diff --git a/libs/binder/tests/unit_fuzzers/BinderFuzzFunctions.h b/libs/binder/tests/unit_fuzzers/BinderFuzzFunctions.h
index 8d2b714..993418a 100644
--- a/libs/binder/tests/unit_fuzzers/BinderFuzzFunctions.h
+++ b/libs/binder/tests/unit_fuzzers/BinderFuzzFunctions.h
@@ -74,7 +74,7 @@
bbinder->getDebugPid();
},
[](FuzzedDataProvider*, const sp<BBinder>& bbinder) -> void {
- (void)bbinder->setRpcClientDebug(android::base::unique_fd(),
+ (void)bbinder->setRpcClientDebug(binder::unique_fd(),
sp<BBinder>::make());
}};
diff --git a/libs/binder/tests/unit_fuzzers/RecordedTransactionFileFuzz.cpp b/libs/binder/tests/unit_fuzzers/RecordedTransactionFileFuzz.cpp
index 0706182..87b0fb6 100644
--- a/libs/binder/tests/unit_fuzzers/RecordedTransactionFileFuzz.cpp
+++ b/libs/binder/tests/unit_fuzzers/RecordedTransactionFileFuzz.cpp
@@ -19,13 +19,15 @@
#include "fuzzer/FuzzedDataProvider.h"
+using android::binder::unique_fd;
+
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
std::FILE* intermediateFile = std::tmpfile();
fwrite(data, sizeof(uint8_t), size, intermediateFile);
rewind(intermediateFile);
int fileNumber = fileno(intermediateFile);
- android::base::unique_fd fd(dup(fileNumber));
+ unique_fd fd(dup(fileNumber));
auto transaction = android::binder::debug::RecordedTransaction::fromFile(fd);
@@ -34,7 +36,7 @@
if (transaction.has_value()) {
intermediateFile = std::tmpfile();
- android::base::unique_fd fdForWriting(dup(fileno(intermediateFile)));
+ unique_fd fdForWriting(dup(fileno(intermediateFile)));
auto writeStatus [[maybe_unused]] = transaction.value().dumpToFile(fdForWriting);
std::fclose(intermediateFile);
diff --git a/libs/binder/tests/unit_fuzzers/RecordedTransactionFuzz.cpp b/libs/binder/tests/unit_fuzzers/RecordedTransactionFuzz.cpp
index 9289f6a..fa939e6 100644
--- a/libs/binder/tests/unit_fuzzers/RecordedTransactionFuzz.cpp
+++ b/libs/binder/tests/unit_fuzzers/RecordedTransactionFuzz.cpp
@@ -22,6 +22,7 @@
#include "fuzzer/FuzzedDataProvider.h"
using android::fillRandomParcel;
+using android::binder::unique_fd;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
FuzzedDataProvider provider = FuzzedDataProvider(data, size);
@@ -53,7 +54,7 @@
if (transaction.has_value()) {
std::FILE* intermediateFile = std::tmpfile();
- android::base::unique_fd fdForWriting(dup(fileno(intermediateFile)));
+ unique_fd fdForWriting(dup(fileno(intermediateFile)));
auto writeStatus [[maybe_unused]] = transaction.value().dumpToFile(fdForWriting);
std::fclose(intermediateFile);
diff --git a/libs/binder/tests/unit_fuzzers/TextOutputFuzz.cpp b/libs/binder/tests/unit_fuzzers/TextOutputFuzz.cpp
index 5e3502a..fe09978 100644
--- a/libs/binder/tests/unit_fuzzers/TextOutputFuzz.cpp
+++ b/libs/binder/tests/unit_fuzzers/TextOutputFuzz.cpp
@@ -14,11 +14,12 @@
* limitations under the License.
*/
+#include "../../file.h"
+
#include <fuzzer/FuzzedDataProvider.h>
#include <binder/Parcel.h>
#include <binder/TextOutput.h>
-#include "android-base/file.h"
#include "android-base/test_utils.h"
#include <fcntl.h>
diff --git a/libs/binder/trusty/OS.cpp b/libs/binder/trusty/OS.cpp
index 0d18b0b..ca14286 100644
--- a/libs/binder/trusty/OS.cpp
+++ b/libs/binder/trusty/OS.cpp
@@ -26,9 +26,12 @@
#include "../OS.h"
#include "TrustyStatus.h"
+using android::binder::borrowed_fd;
+using android::binder::unique_fd;
+
namespace android::binder::os {
-status_t setNonBlocking(android::base::borrowed_fd /*fd*/) {
+status_t setNonBlocking(borrowed_fd /*fd*/) {
// Trusty IPC syscalls are all non-blocking by default.
return OK;
}
@@ -59,14 +62,14 @@
ssize_t sendMessageOnSocket(
const RpcTransportFd& /* socket */, iovec* /* iovs */, int /* niovs */,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* /* ancillaryFds */) {
+ const std::vector<std::variant<unique_fd, borrowed_fd>>* /* ancillaryFds */) {
errno = ENOTSUP;
return -1;
}
ssize_t receiveMessageFromSocket(
const RpcTransportFd& /* socket */, iovec* /* iovs */, int /* niovs */,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* /* ancillaryFds */) {
+ std::vector<std::variant<unique_fd, borrowed_fd>>* /* ancillaryFds */) {
errno = ENOTSUP;
return -1;
}
diff --git a/libs/binder/trusty/RpcServerTrusty.cpp b/libs/binder/trusty/RpcServerTrusty.cpp
index 8f64323..0872b90 100644
--- a/libs/binder/trusty/RpcServerTrusty.cpp
+++ b/libs/binder/trusty/RpcServerTrusty.cpp
@@ -28,6 +28,7 @@
#include "TrustyStatus.h"
using android::base::unexpected;
+using android::binder::unique_fd;
namespace android {
@@ -129,7 +130,7 @@
if (chanDup < 0) {
return chanDup;
}
- base::unique_fd clientFd(chanDup);
+ unique_fd clientFd(chanDup);
android::RpcTransportFd transportFd(std::move(clientFd));
std::array<uint8_t, RpcServer::kRpcAddressSize> addr;
diff --git a/libs/binder/trusty/RpcTransportTipcTrusty.cpp b/libs/binder/trusty/RpcTransportTipcTrusty.cpp
index 6bb45e2..c74ba0a 100644
--- a/libs/binder/trusty/RpcTransportTipcTrusty.cpp
+++ b/libs/binder/trusty/RpcTransportTipcTrusty.cpp
@@ -30,6 +30,8 @@
namespace android {
using namespace android::binder::impl;
+using android::binder::borrowed_fd;
+using android::binder::unique_fd;
// RpcTransport for Trusty.
class RpcTransportTipcTrusty : public RpcTransport {
@@ -48,8 +50,7 @@
status_t interruptableWriteFully(
FdTrigger* /*fdTrigger*/, iovec* iovs, int niovs,
const std::optional<SmallFunction<status_t()>>& /*altPoll*/,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds)
- override {
+ const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) override {
if (niovs < 0) {
return BAD_VALUE;
}
@@ -118,7 +119,7 @@
status_t interruptableReadFully(
FdTrigger* /*fdTrigger*/, iovec* iovs, int niovs,
const std::optional<SmallFunction<status_t()>>& /*altPoll*/,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) override {
+ std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds) override {
if (niovs < 0) {
return BAD_VALUE;
}
@@ -170,7 +171,7 @@
if (ancillaryFds != nullptr) {
ancillaryFds->reserve(ancillaryFds->size() + mMessageInfo.num_handles);
for (size_t i = 0; i < mMessageInfo.num_handles; i++) {
- ancillaryFds->emplace_back(base::unique_fd(msgHandles[i]));
+ ancillaryFds->emplace_back(unique_fd(msgHandles[i]));
}
// Clear the saved number of handles so we don't accidentally
diff --git a/libs/binder/trusty/include/binder/RpcServerTrusty.h b/libs/binder/trusty/include/binder/RpcServerTrusty.h
index aa476f9..7382a30 100644
--- a/libs/binder/trusty/include/binder/RpcServerTrusty.h
+++ b/libs/binder/trusty/include/binder/RpcServerTrusty.h
@@ -17,11 +17,11 @@
#pragma once
#include <android-base/expected.h>
-#include <android-base/unique_fd.h>
#include <binder/IBinder.h>
#include <binder/RpcServer.h>
#include <binder/RpcSession.h>
#include <binder/RpcTransport.h>
+#include <binder/unique_fd.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
diff --git a/libs/binder/trusty/rules.mk b/libs/binder/trusty/rules.mk
index 9cad556..dbddbe1 100644
--- a/libs/binder/trusty/rules.mk
+++ b/libs/binder/trusty/rules.mk
@@ -43,6 +43,7 @@
$(LIBBINDER_DIR)/Stability.cpp \
$(LIBBINDER_DIR)/Status.cpp \
$(LIBBINDER_DIR)/Utils.cpp \
+ $(LIBBINDER_DIR)/file.cpp \
$(LIBBASE_DIR)/hex.cpp \
$(LIBBASE_DIR)/stringprintf.cpp \
$(LIBUTILS_DIR)/binder/Errors.cpp \
diff --git a/libs/input/InputTransport.cpp b/libs/input/InputTransport.cpp
index 30cedb0..09e98d0 100644
--- a/libs/input/InputTransport.cpp
+++ b/libs/input/InputTransport.cpp
@@ -446,7 +446,7 @@
msg->getSanitizedCopy(&cleanMsg);
ssize_t nWrite;
do {
- nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
+ nWrite = ::send(getFd().get(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
} while (nWrite == -1 && errno == EINTR);
if (nWrite < 0) {
@@ -478,7 +478,7 @@
status_t InputChannel::receiveMessage(InputMessage* msg) {
ssize_t nRead;
do {
- nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
+ nRead = ::recv(getFd().get(), msg, sizeof(InputMessage), MSG_DONTWAIT);
} while (nRead == -1 && errno == EINTR);
if (nRead < 0) {
@@ -551,7 +551,7 @@
}
base::unique_fd InputChannel::dupFd() const {
- android::base::unique_fd newFd(::dup(getFd()));
+ base::unique_fd newFd(::dup(getFd().get()));
if (!newFd.ok()) {
ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
strerror(errno));
diff --git a/services/inputflinger/dispatcher/InputDispatcher.cpp b/services/inputflinger/dispatcher/InputDispatcher.cpp
index 2a71125..54da8e8 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.cpp
+++ b/services/inputflinger/dispatcher/InputDispatcher.cpp
@@ -5887,7 +5887,7 @@
{ // acquire lock
std::scoped_lock _l(mLock);
const sp<IBinder>& token = serverChannel->getConnectionToken();
- int fd = serverChannel->getFd();
+ auto&& fd = serverChannel->getFd();
std::shared_ptr<Connection> connection =
std::make_shared<Connection>(std::move(serverChannel), /*monitor=*/false,
mIdGenerator);
@@ -5900,7 +5900,7 @@
std::function<int(int events)> callback = std::bind(&InputDispatcher::handleReceiveCallback,
this, std::placeholders::_1, token);
- mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
+ mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
nullptr);
} // release lock
@@ -5930,7 +5930,7 @@
std::shared_ptr<Connection> connection =
std::make_shared<Connection>(serverChannel, /*monitor=*/true, mIdGenerator);
const sp<IBinder>& token = serverChannel->getConnectionToken();
- const int fd = serverChannel->getFd();
+ auto&& fd = serverChannel->getFd();
if (mConnectionsByToken.find(token) != mConnectionsByToken.end()) {
ALOGE("Created a new connection, but the token %p is already known", token.get());
@@ -5941,7 +5941,7 @@
mGlobalMonitorsByDisplay[displayId].emplace_back(serverChannel, pid);
- mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
+ mLooper->addFd(fd.get(), 0, ALOOPER_EVENT_INPUT, sp<LooperEventCallback>::make(callback),
nullptr);
}
@@ -5980,7 +5980,7 @@
removeMonitorChannelLocked(connectionToken);
}
- mLooper->removeFd(connection->inputChannel->getFd());
+ mLooper->removeFd(connection->inputChannel->getFd().get());
nsecs_t currentTime = now();
abortBrokenDispatchCycleLocked(currentTime, connection, notify);
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayColorProfile.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayColorProfile.h
index 9c80cac..a74c5fe 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayColorProfile.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayColorProfile.h
@@ -36,7 +36,7 @@
namespace compositionengine {
/**
- * Encapsulates all the state and functionality for how colors should be
+ * Encapsulates all the states and functionality for how colors should be
* transformed for a display
*/
class DisplayColorProfile {
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
index 40ebf44..422a799 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
@@ -61,7 +61,7 @@
} // namespace impl
/**
- * Encapsulates all the state involved with composing layers for an output
+ * Encapsulates all the states involved with composing layers for an output
*/
class Output {
public:
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h
index 7b0af3a..6c419da 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h
@@ -90,7 +90,7 @@
// The source crop for this layer on this output
FloatRect sourceCrop;
- // The buffer transform to use for this layer o on this output.
+ // The buffer transform to use for this layer on this output.
Hwc2::Transform bufferTransform{static_cast<Hwc2::Transform>(0)};
// The dataspace for this layer
diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp
index 2ffe92b..7fdf9e7 100644
--- a/services/surfaceflinger/DisplayDevice.cpp
+++ b/services/surfaceflinger/DisplayDevice.cpp
@@ -63,14 +63,14 @@
mDisplayToken(args.displayToken),
mSequenceId(args.sequenceId),
mCompositionDisplay{args.compositionDisplay},
- mActiveModeFPSTrace(concatId("ActiveModeFPS")),
- mActiveModeFPSHwcTrace(concatId("ActiveModeFPS_HWC")),
- mRenderFrameRateFPSTrace(concatId("RenderRateFPS")),
+ mPendingModeFpsTrace(concatId("PendingModeFps")),
+ mActiveModeFpsTrace(concatId("ActiveModeFps")),
+ mRenderRateFpsTrace(concatId("RenderRateFps")),
mPhysicalOrientation(args.physicalOrientation),
mIsPrimary(args.isPrimary),
mRequestedRefreshRate(args.requestedRefreshRate),
mRefreshRateSelector(std::move(args.refreshRateSelector)),
- mDesiredActiveModeChanged(concatId("DesiredActiveModeChanged"), false) {
+ mDesiredModeChanged(concatId("DesiredModeChanged"), false) {
mCompositionDisplay->editState().isSecure = args.isSecure;
mCompositionDisplay->createRenderSurface(
compositionengine::RenderSurfaceCreationArgsBuilder()
@@ -210,16 +210,16 @@
}
void DisplayDevice::setActiveMode(DisplayModeId modeId, Fps vsyncRate, Fps renderFps) {
- ATRACE_INT(mActiveModeFPSTrace.c_str(), vsyncRate.getIntValue());
- ATRACE_INT(mRenderFrameRateFPSTrace.c_str(), renderFps.getIntValue());
+ ATRACE_INT(mActiveModeFpsTrace.c_str(), vsyncRate.getIntValue());
+ ATRACE_INT(mRenderRateFpsTrace.c_str(), renderFps.getIntValue());
mRefreshRateSelector->setActiveMode(modeId, renderFps);
updateRefreshRateOverlayRate(vsyncRate, renderFps);
}
-status_t DisplayDevice::initiateModeChange(const ActiveModeInfo& info,
- const hal::VsyncPeriodChangeConstraints& constraints,
- hal::VsyncPeriodChangeTimeline* outTimeline) {
+bool DisplayDevice::initiateModeChange(const ActiveModeInfo& info,
+ const hal::VsyncPeriodChangeConstraints& constraints,
+ hal::VsyncPeriodChangeTimeline& outTimeline) {
if (!info.modeOpt || info.modeOpt->modePtr->getPhysicalDisplayId() != getPhysicalId()) {
ALOGE("Trying to initiate a mode change to invalid mode %s on display %s",
info.modeOpt ? std::to_string(info.modeOpt->modePtr->getId().value()).c_str()
@@ -227,14 +227,18 @@
to_string(getId()).c_str());
return BAD_VALUE;
}
- mUpcomingActiveMode = info;
+ mPendingMode = info;
mIsModeSetPending = true;
- const auto& pendingMode = *info.modeOpt->modePtr;
- ATRACE_INT(mActiveModeFPSHwcTrace.c_str(), pendingMode.getVsyncRate().getIntValue());
+ const auto& mode = *info.modeOpt->modePtr;
- return mHwComposer.setActiveModeWithConstraints(getPhysicalId(), pendingMode.getHwcId(),
- constraints, outTimeline);
+ if (mHwComposer.setActiveModeWithConstraints(getPhysicalId(), mode.getHwcId(), constraints,
+ &outTimeline) != OK) {
+ return false;
+ }
+
+ ATRACE_INT(mPendingModeFpsTrace.c_str(), mode.getVsyncRate().getIntValue());
+ return true;
}
void DisplayDevice::finalizeModeChange(DisplayModeId modeId, Fps vsyncRate, Fps renderFps) {
@@ -524,8 +528,7 @@
}
}
-auto DisplayDevice::setDesiredActiveMode(const ActiveModeInfo& info, bool force)
- -> DesiredActiveModeAction {
+auto DisplayDevice::setDesiredMode(const ActiveModeInfo& info, bool force) -> DesiredModeAction {
ATRACE_CALL();
LOG_ALWAYS_FATAL_IF(!info.modeOpt, "desired mode not provided");
@@ -534,49 +537,50 @@
ALOGV("%s(%s)", __func__, to_string(*info.modeOpt->modePtr).c_str());
- std::scoped_lock lock(mActiveModeLock);
- if (mDesiredActiveModeChanged) {
- // If a mode change is pending, just cache the latest request in mDesiredActiveMode
- const auto prevConfig = mDesiredActiveMode.event;
- mDesiredActiveMode = info;
- mDesiredActiveMode.event = mDesiredActiveMode.event | prevConfig;
- return DesiredActiveModeAction::None;
+ std::scoped_lock lock(mDesiredModeLock);
+ if (mDesiredModeChanged) {
+ // A mode transition was already scheduled, so just override the desired mode.
+ const auto event = mDesiredMode.event;
+ mDesiredMode = info;
+ mDesiredMode.event = mDesiredMode.event | event;
+ return DesiredModeAction::None;
}
const auto& desiredMode = *info.modeOpt->modePtr;
- // Check if we are already at the desired mode
- const auto currentMode = refreshRateSelector().getActiveMode();
- if (!force && currentMode.modePtr->getId() == desiredMode.getId()) {
- if (currentMode == info.modeOpt) {
- return DesiredActiveModeAction::None;
+ // If the desired mode is already active...
+ const auto activeMode = refreshRateSelector().getActiveMode();
+ if (!force && activeMode.modePtr->getId() == desiredMode.getId()) {
+ if (activeMode == info.modeOpt) {
+ return DesiredModeAction::None;
}
+ // ...but the render rate changed:
setActiveMode(desiredMode.getId(), desiredMode.getVsyncRate(), info.modeOpt->fps);
- return DesiredActiveModeAction::InitiateRenderRateSwitch;
+ return DesiredModeAction::InitiateRenderRateSwitch;
}
- // Set the render frame rate to the current physical refresh rate to schedule the next
+ // Set the render frame rate to the active physical refresh rate to schedule the next
// frame as soon as possible.
- setActiveMode(currentMode.modePtr->getId(), currentMode.modePtr->getVsyncRate(),
- currentMode.modePtr->getVsyncRate());
+ setActiveMode(activeMode.modePtr->getId(), activeMode.modePtr->getVsyncRate(),
+ activeMode.modePtr->getVsyncRate());
// Initiate a mode change.
- mDesiredActiveModeChanged = true;
- mDesiredActiveMode = info;
- return DesiredActiveModeAction::InitiateDisplayModeSwitch;
+ mDesiredModeChanged = true;
+ mDesiredMode = info;
+ return DesiredModeAction::InitiateDisplayModeSwitch;
}
-std::optional<DisplayDevice::ActiveModeInfo> DisplayDevice::getDesiredActiveMode() const {
- std::scoped_lock lock(mActiveModeLock);
- if (mDesiredActiveModeChanged) return mDesiredActiveMode;
+auto DisplayDevice::getDesiredMode() const -> ftl::Optional<ActiveModeInfo> {
+ std::scoped_lock lock(mDesiredModeLock);
+ if (mDesiredModeChanged) return mDesiredMode;
return std::nullopt;
}
-void DisplayDevice::clearDesiredActiveModeState() {
- std::scoped_lock lock(mActiveModeLock);
- mDesiredActiveMode.event = scheduler::DisplayModeEvent::None;
- mDesiredActiveModeChanged = false;
+void DisplayDevice::clearDesiredMode() {
+ std::scoped_lock lock(mDesiredModeLock);
+ mDesiredMode.event = scheduler::DisplayModeEvent::None;
+ mDesiredModeChanged = false;
}
void DisplayDevice::adjustRefreshRate(Fps pacesetterDisplayRefreshRate) {
diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h
index a40f310..a061fca 100644
--- a/services/surfaceflinger/DisplayDevice.h
+++ b/services/surfaceflinger/DisplayDevice.h
@@ -17,7 +17,6 @@
#pragma once
#include <memory>
-#include <optional>
#include <string>
#include <unordered_map>
@@ -25,6 +24,7 @@
#include <android/native_window.h>
#include <binder/IBinder.h>
#include <ftl/concat.h>
+#include <ftl/optional.h>
#include <gui/LayerState.h>
#include <math/mat4.h>
#include <renderengine/RenderEngine.h>
@@ -51,6 +51,7 @@
#include "ThreadContext.h"
#include "TracedOrdinal.h"
#include "Utils/Dumper.h"
+
namespace android {
class Fence;
@@ -205,19 +206,15 @@
}
};
- enum class DesiredActiveModeAction {
- None,
- InitiateDisplayModeSwitch,
- InitiateRenderRateSwitch
- };
- DesiredActiveModeAction setDesiredActiveMode(const ActiveModeInfo&, bool force = false)
- EXCLUDES(mActiveModeLock);
- std::optional<ActiveModeInfo> getDesiredActiveMode() const EXCLUDES(mActiveModeLock);
- void clearDesiredActiveModeState() EXCLUDES(mActiveModeLock);
- ActiveModeInfo getUpcomingActiveMode() const REQUIRES(kMainThreadContext) {
- return mUpcomingActiveMode;
- }
+ enum class DesiredModeAction { None, InitiateDisplayModeSwitch, InitiateRenderRateSwitch };
+ DesiredModeAction setDesiredMode(const ActiveModeInfo&, bool force = false)
+ EXCLUDES(mDesiredModeLock);
+
+ ftl::Optional<ActiveModeInfo> getDesiredMode() const EXCLUDES(mDesiredModeLock);
+ void clearDesiredMode() EXCLUDES(mDesiredModeLock);
+
+ ActiveModeInfo getPendingMode() const REQUIRES(kMainThreadContext) { return mPendingMode; }
bool isModeSetPending() const REQUIRES(kMainThreadContext) { return mIsModeSetPending; }
scheduler::FrameRateMode getActiveMode() const REQUIRES(kMainThreadContext) {
@@ -226,9 +223,8 @@
void setActiveMode(DisplayModeId, Fps vsyncRate, Fps renderFps);
- status_t initiateModeChange(const ActiveModeInfo&,
- const hal::VsyncPeriodChangeConstraints& constraints,
- hal::VsyncPeriodChangeTimeline* outTimeline)
+ bool initiateModeChange(const ActiveModeInfo&, const hal::VsyncPeriodChangeConstraints&,
+ hal::VsyncPeriodChangeTimeline& outTimeline)
REQUIRES(kMainThreadContext);
void finalizeModeChange(DisplayModeId, Fps vsyncRate, Fps renderFps)
@@ -282,9 +278,9 @@
const std::shared_ptr<compositionengine::Display> mCompositionDisplay;
std::string mDisplayName;
- std::string mActiveModeFPSTrace;
- std::string mActiveModeFPSHwcTrace;
- std::string mRenderFrameRateFPSTrace;
+ std::string mPendingModeFpsTrace;
+ std::string mActiveModeFpsTrace;
+ std::string mRenderRateFpsTrace;
const ui::Rotation mPhysicalOrientation;
ui::Rotation mOrientation = ui::ROTATION_0;
@@ -319,11 +315,11 @@
// This parameter is only used for hdr/sdr ratio overlay
float mHdrSdrRatio = 1.0f;
- mutable std::mutex mActiveModeLock;
- ActiveModeInfo mDesiredActiveMode GUARDED_BY(mActiveModeLock);
- TracedOrdinal<bool> mDesiredActiveModeChanged GUARDED_BY(mActiveModeLock);
+ mutable std::mutex mDesiredModeLock;
+ ActiveModeInfo mDesiredMode GUARDED_BY(mDesiredModeLock);
+ TracedOrdinal<bool> mDesiredModeChanged GUARDED_BY(mDesiredModeLock);
- ActiveModeInfo mUpcomingActiveMode GUARDED_BY(kMainThreadContext);
+ ActiveModeInfo mPendingMode GUARDED_BY(kMainThreadContext);
bool mIsModeSetPending GUARDED_BY(kMainThreadContext) = false;
};
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.cpp b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
index 9aaaa95..26c0d67 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
@@ -945,6 +945,10 @@
std::optional<Period> timeoutOpt) {
RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
auto& displayData = mDisplayData[displayId];
+ if (!displayData.hwcDisplay) {
+ // Display setup has not completed yet
+ return BAD_INDEX;
+ }
{
std::scoped_lock lock{displayData.expectedPresentLock};
const auto lastExpectedPresentTimestamp = displayData.lastExpectedPresentTimestamp;
diff --git a/services/surfaceflinger/FrontEnd/LayerLifecycleManager.cpp b/services/surfaceflinger/FrontEnd/LayerLifecycleManager.cpp
index a826ec1..0983e7c 100644
--- a/services/surfaceflinger/FrontEnd/LayerLifecycleManager.cpp
+++ b/services/surfaceflinger/FrontEnd/LayerLifecycleManager.cpp
@@ -433,4 +433,15 @@
}
}
+bool LayerLifecycleManager::isLayerSecure(uint32_t layerId) const {
+ if (layerId == UNASSIGNED_LAYER_ID) {
+ return false;
+ }
+
+ if (getLayerFromId(layerId)->flags & layer_state_t::eLayerSecure) {
+ return true;
+ }
+ return isLayerSecure(getLayerFromId(layerId)->parentId);
+}
+
} // namespace android::surfaceflinger::frontend
diff --git a/services/surfaceflinger/FrontEnd/LayerLifecycleManager.h b/services/surfaceflinger/FrontEnd/LayerLifecycleManager.h
index 9aff78e..330da9a 100644
--- a/services/surfaceflinger/FrontEnd/LayerLifecycleManager.h
+++ b/services/surfaceflinger/FrontEnd/LayerLifecycleManager.h
@@ -80,6 +80,7 @@
const std::vector<RequestedLayerState*>& getChangedLayers() const;
const ftl::Flags<RequestedLayerState::Changes> getGlobalChanges() const;
const RequestedLayerState* getLayerFromId(uint32_t) const;
+ bool isLayerSecure(uint32_t) const;
private:
friend class LayerLifecycleManagerTest;
diff --git a/services/surfaceflinger/FrontEnd/LayerSnapshotBuilder.cpp b/services/surfaceflinger/FrontEnd/LayerSnapshotBuilder.cpp
index 9476ff4..743cbf3 100644
--- a/services/surfaceflinger/FrontEnd/LayerSnapshotBuilder.cpp
+++ b/services/surfaceflinger/FrontEnd/LayerSnapshotBuilder.cpp
@@ -365,7 +365,7 @@
return snapshot;
}
-LayerSnapshotBuilder::LayerSnapshotBuilder() : mRootSnapshot(getRootSnapshot()) {}
+LayerSnapshotBuilder::LayerSnapshotBuilder() {}
LayerSnapshotBuilder::LayerSnapshotBuilder(Args args) : LayerSnapshotBuilder() {
args.forceUpdate = ForceUpdateFlags::ALL;
@@ -417,19 +417,20 @@
void LayerSnapshotBuilder::updateSnapshots(const Args& args) {
ATRACE_NAME("UpdateSnapshots");
+ LayerSnapshot rootSnapshot = args.rootSnapshot;
if (args.parentCrop) {
- mRootSnapshot.geomLayerBounds = *args.parentCrop;
+ rootSnapshot.geomLayerBounds = *args.parentCrop;
} else if (args.forceUpdate == ForceUpdateFlags::ALL || args.displayChanges) {
- mRootSnapshot.geomLayerBounds = getMaxDisplayBounds(args.displays);
+ rootSnapshot.geomLayerBounds = getMaxDisplayBounds(args.displays);
}
if (args.displayChanges) {
- mRootSnapshot.changes = RequestedLayerState::Changes::AffectsChildren |
+ rootSnapshot.changes = RequestedLayerState::Changes::AffectsChildren |
RequestedLayerState::Changes::Geometry;
}
if (args.forceUpdate == ForceUpdateFlags::HIERARCHY) {
- mRootSnapshot.changes |=
+ rootSnapshot.changes |=
RequestedLayerState::Changes::Hierarchy | RequestedLayerState::Changes::Visibility;
- mRootSnapshot.clientChanges |= layer_state_t::eReparent;
+ rootSnapshot.clientChanges |= layer_state_t::eReparent;
}
for (auto& snapshot : mSnapshots) {
@@ -444,13 +445,13 @@
// multiple children.
LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root, args.root.getLayer()->id,
LayerHierarchy::Variant::Attached);
- updateSnapshotsInHierarchy(args, args.root, root, mRootSnapshot, /*depth=*/0);
+ updateSnapshotsInHierarchy(args, args.root, root, rootSnapshot, /*depth=*/0);
} else {
for (auto& [childHierarchy, variant] : args.root.mChildren) {
LayerHierarchy::ScopedAddToTraversalPath addChildToPath(root,
childHierarchy->getLayer()->id,
variant);
- updateSnapshotsInHierarchy(args, *childHierarchy, root, mRootSnapshot, /*depth=*/0);
+ updateSnapshotsInHierarchy(args, *childHierarchy, root, rootSnapshot, /*depth=*/0);
}
}
@@ -459,7 +460,6 @@
updateTouchableRegionCrop(args);
const bool hasUnreachableSnapshots = sortSnapshotsByZ(args);
- clearChanges(mRootSnapshot);
// Destroy unreachable snapshots for clone layers. And destroy snapshots for non-clone
// layers if the layer have been destroyed.
diff --git a/services/surfaceflinger/FrontEnd/LayerSnapshotBuilder.h b/services/surfaceflinger/FrontEnd/LayerSnapshotBuilder.h
index 1506913..1cec018 100644
--- a/services/surfaceflinger/FrontEnd/LayerSnapshotBuilder.h
+++ b/services/surfaceflinger/FrontEnd/LayerSnapshotBuilder.h
@@ -33,6 +33,9 @@
// The builder also uses a fast path to update
// snapshots when there are only buffer updates.
class LayerSnapshotBuilder {
+private:
+ static LayerSnapshot getRootSnapshot();
+
public:
enum class ForceUpdateFlags {
NONE,
@@ -55,6 +58,7 @@
const std::unordered_map<std::string, bool>& supportedLayerGenericMetadata;
const std::unordered_map<std::string, uint32_t>& genericLayerMetadataKeyMap;
bool skipRoundCornersWhenProtected = false;
+ LayerSnapshot rootSnapshot = getRootSnapshot();
};
LayerSnapshotBuilder();
@@ -87,7 +91,6 @@
private:
friend class LayerSnapshotTest;
- static LayerSnapshot getRootSnapshot();
// return true if we were able to successfully update the snapshots via
// the fast path.
@@ -130,7 +133,6 @@
std::unordered_set<LayerHierarchy::TraversalPath, LayerHierarchy::TraversalPathHash>
mNeedsTouchableRegionCrop;
std::vector<std::unique_ptr<LayerSnapshot>> mSnapshots;
- LayerSnapshot mRootSnapshot;
bool mResortSnapshots = false;
int mNumInterestingSnapshots = 0;
};
diff --git a/services/surfaceflinger/FrontEnd/RequestedLayerState.cpp b/services/surfaceflinger/FrontEnd/RequestedLayerState.cpp
index 0e49b75..b1a18ae 100644
--- a/services/surfaceflinger/FrontEnd/RequestedLayerState.cpp
+++ b/services/surfaceflinger/FrontEnd/RequestedLayerState.cpp
@@ -98,7 +98,6 @@
z = 0;
layerStack = ui::DEFAULT_LAYER_STACK;
transformToDisplayInverse = false;
- dataspace = ui::Dataspace::UNKNOWN;
desiredHdrSdrRatio = 1.f;
currentHdrSdrRatio = 1.f;
dataspaceRequested = false;
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 4c2da91..f587e9d 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -4326,7 +4326,6 @@
prepareBasicGeometryCompositionState();
prepareGeometryCompositionState();
snapshot->roundedCorner = getRoundedCornerState();
- snapshot->stretchEffect = getStretchEffect();
snapshot->transformedBounds = mScreenBounds;
if (mEffectiveShadowRadius > 0.f) {
snapshot->shadowSettings = mFlinger->mDrawingState.globalShadowSettings;
diff --git a/services/surfaceflinger/Scheduler/RefreshRateSelector.cpp b/services/surfaceflinger/Scheduler/RefreshRateSelector.cpp
index 47c8ef9..6a7063e 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateSelector.cpp
+++ b/services/surfaceflinger/Scheduler/RefreshRateSelector.cpp
@@ -36,7 +36,6 @@
#include <scheduler/FrameRateMode.h>
#include <utils/Trace.h>
-#include "../SurfaceFlingerProperties.h"
#include "RefreshRateSelector.h"
#include <com_android_graphics_surfaceflinger_flags.h>
@@ -971,17 +970,21 @@
}
ftl::Optional<FrameRateMode> RefreshRateSelector::onKernelTimerChanged(
- std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const {
+ ftl::Optional<DisplayModeId> desiredModeIdOpt, bool timerExpired) const {
std::lock_guard lock(mLock);
- const auto current = [&]() REQUIRES(mLock) -> FrameRateMode {
- if (desiredActiveModeId) {
- const auto& modePtr = mDisplayModes.get(*desiredActiveModeId)->get();
- return FrameRateMode{modePtr->getPeakFps(), ftl::as_non_null(modePtr)};
- }
-
- return getActiveModeLocked();
- }();
+ const auto current =
+ desiredModeIdOpt
+ .and_then([this](DisplayModeId modeId)
+ REQUIRES(mLock) { return mDisplayModes.get(modeId); })
+ .transform([](const DisplayModePtr& modePtr) {
+ return FrameRateMode{modePtr->getPeakFps(), ftl::as_non_null(modePtr)};
+ })
+ .or_else([this] {
+ ftl::FakeGuard guard(mLock);
+ return std::make_optional(getActiveModeLocked());
+ })
+ .value();
const DisplayModePtr& min = mMinRefreshRateModeIt->second;
if (current.modePtr->getId() == min->getId()) {
diff --git a/services/surfaceflinger/Scheduler/RefreshRateSelector.h b/services/surfaceflinger/Scheduler/RefreshRateSelector.h
index 545b939..40e9a83 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateSelector.h
+++ b/services/surfaceflinger/Scheduler/RefreshRateSelector.h
@@ -16,9 +16,6 @@
#pragma once
-#include <algorithm>
-#include <numeric>
-#include <set>
#include <type_traits>
#include <utility>
#include <variant>
@@ -258,9 +255,8 @@
mMaxRefreshRateModeIt->second->getPeakFps()};
}
- ftl::Optional<FrameRateMode> onKernelTimerChanged(
- std::optional<DisplayModeId> desiredActiveModeId, bool timerExpired) const
- EXCLUDES(mLock);
+ ftl::Optional<FrameRateMode> onKernelTimerChanged(ftl::Optional<DisplayModeId> desiredModeIdOpt,
+ bool timerExpired) const EXCLUDES(mLock);
void setActiveMode(DisplayModeId, Fps renderFrameRate) EXCLUDES(mLock);
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 644b6ef..c15e74f 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -1177,7 +1177,7 @@
return NO_ERROR;
}
-void SurfaceFlinger::setDesiredActiveMode(display::DisplayModeRequest&& request, bool force) {
+void SurfaceFlinger::setDesiredMode(display::DisplayModeRequest&& request, bool force) {
const auto displayId = request.mode.modePtr->getPhysicalDisplayId();
ATRACE_NAME(ftl::Concat(__func__, ' ', displayId.value).c_str());
@@ -1190,10 +1190,9 @@
const auto mode = request.mode;
const bool emitEvent = request.emitEvent;
- switch (display->setDesiredActiveMode(DisplayDevice::ActiveModeInfo(std::move(request)),
- force)) {
- case DisplayDevice::DesiredActiveModeAction::InitiateDisplayModeSwitch:
- // Set the render rate as setDesiredActiveMode updated it.
+ switch (display->setDesiredMode(DisplayDevice::ActiveModeInfo(std::move(request)), force)) {
+ case DisplayDevice::DesiredModeAction::InitiateDisplayModeSwitch:
+ // DisplayDevice::setDesiredMode updated the render rate, so inform Scheduler.
mScheduler->setRenderRate(displayId,
display->refreshRateSelector().getActiveMode().fps);
@@ -1215,7 +1214,7 @@
mScheduler->setModeChangePending(true);
break;
- case DisplayDevice::DesiredActiveModeAction::InitiateRenderRateSwitch:
+ case DisplayDevice::DesiredModeAction::InitiateRenderRateSwitch:
mScheduler->setRenderRate(displayId, mode.fps);
if (displayId == mActiveDisplayId) {
@@ -1227,7 +1226,7 @@
dispatchDisplayModeChangeEvent(displayId, mode);
}
break;
- case DisplayDevice::DesiredActiveModeAction::None:
+ case DisplayDevice::DesiredModeAction::None:
break;
}
}
@@ -1287,27 +1286,27 @@
const auto displayId = display.getPhysicalId();
ATRACE_NAME(ftl::Concat(__func__, ' ', displayId.value).c_str());
- const auto upcomingModeInfo = display.getUpcomingActiveMode();
- if (!upcomingModeInfo.modeOpt) {
+ const auto pendingMode = display.getPendingMode();
+ if (!pendingMode.modeOpt) {
// There is no pending mode change. This can happen if the active
// display changed and the mode change happened on a different display.
return;
}
if (display.getActiveMode().modePtr->getResolution() !=
- upcomingModeInfo.modeOpt->modePtr->getResolution()) {
+ pendingMode.modeOpt->modePtr->getResolution()) {
auto& state = mCurrentState.displays.editValueFor(display.getDisplayToken());
// We need to generate new sequenceId in order to recreate the display (and this
// way the framebuffer).
state.sequenceId = DisplayDeviceState{}.sequenceId;
- state.physical->activeMode = upcomingModeInfo.modeOpt->modePtr.get();
+ state.physical->activeMode = pendingMode.modeOpt->modePtr.get();
processDisplayChangesLocked();
// processDisplayChangesLocked will update all necessary components so we're done here.
return;
}
- const auto& activeMode = *upcomingModeInfo.modeOpt;
+ const auto& activeMode = *pendingMode.modeOpt;
display.finalizeModeChange(activeMode.modePtr->getId(), activeMode.modePtr->getVsyncRate(),
activeMode.fps);
@@ -1316,26 +1315,26 @@
updatePhaseConfiguration(activeMode.fps);
}
- if (upcomingModeInfo.event != scheduler::DisplayModeEvent::None) {
+ if (pendingMode.event != scheduler::DisplayModeEvent::None) {
dispatchDisplayModeChangeEvent(displayId, activeMode);
}
}
-void SurfaceFlinger::clearDesiredActiveModeState(const sp<DisplayDevice>& display) {
- display->clearDesiredActiveModeState();
+void SurfaceFlinger::dropModeRequest(const sp<DisplayDevice>& display) {
+ display->clearDesiredMode();
if (display->getPhysicalId() == mActiveDisplayId) {
// TODO(b/255635711): Check for pending mode changes on other displays.
mScheduler->setModeChangePending(false);
}
}
-void SurfaceFlinger::desiredActiveModeChangeDone(const sp<DisplayDevice>& display) {
- const auto desiredActiveMode = display->getDesiredActiveMode();
- const auto& modeOpt = desiredActiveMode->modeOpt;
+void SurfaceFlinger::applyActiveMode(const sp<DisplayDevice>& display) {
+ const auto desiredModeOpt = display->getDesiredMode();
+ const auto& modeOpt = desiredModeOpt->modeOpt;
const auto displayId = modeOpt->modePtr->getPhysicalDisplayId();
const auto vsyncRate = modeOpt->modePtr->getVsyncRate();
const auto renderFps = modeOpt->fps;
- clearDesiredActiveModeState(display);
+ dropModeRequest(display);
mScheduler->resyncToHardwareVsync(displayId, true /* allowToEnable */, vsyncRate);
mScheduler->setRenderRate(displayId, renderFps);
@@ -1353,25 +1352,23 @@
const auto display = getDisplayDeviceLocked(id);
if (!display) continue;
- // Store the local variable to release the lock.
- const auto desiredActiveMode = display->getDesiredActiveMode();
- if (!desiredActiveMode) {
- // No desired active mode pending to be applied.
+ const auto desiredModeOpt = display->getDesiredMode();
+ if (!desiredModeOpt) {
continue;
}
if (!shouldApplyRefreshRateSelectorPolicy(*display)) {
- clearDesiredActiveModeState(display);
+ dropModeRequest(display);
continue;
}
- const auto desiredModeId = desiredActiveMode->modeOpt->modePtr->getId();
+ const auto desiredModeId = desiredModeOpt->modeOpt->modePtr->getId();
const auto displayModePtrOpt = physical.snapshot().displayModes().get(desiredModeId);
if (!displayModePtrOpt) {
ALOGW("Desired display mode is no longer supported. Mode ID = %d",
desiredModeId.value());
- clearDesiredActiveModeState(display);
+ dropModeRequest(display);
continue;
}
@@ -1379,9 +1376,8 @@
to_string(displayModePtrOpt->get()->getVsyncRate()).c_str(),
to_string(display->getId()).c_str());
- if (display->getActiveMode() == desiredActiveMode->modeOpt) {
- // we are already in the requested mode, there is nothing left to do
- desiredActiveModeChangeDone(display);
+ if (display->getActiveMode() == desiredModeOpt->modeOpt) {
+ applyActiveMode(display);
continue;
}
@@ -1389,9 +1385,9 @@
// allowed modes might have changed by the time we process the refresh.
// Make sure the desired mode is still allowed
const auto displayModeAllowed =
- display->refreshRateSelector().isModeAllowed(*desiredActiveMode->modeOpt);
+ display->refreshRateSelector().isModeAllowed(*desiredModeOpt->modeOpt);
if (!displayModeAllowed) {
- clearDesiredActiveModeState(display);
+ dropModeRequest(display);
continue;
}
@@ -1401,13 +1397,7 @@
constraints.seamlessRequired = false;
hal::VsyncPeriodChangeTimeline outTimeline;
- const auto status =
- display->initiateModeChange(*desiredActiveMode, constraints, &outTimeline);
-
- if (status != NO_ERROR) {
- // initiateModeChange may fail if a hotplug event is just about
- // to be sent. We just log the error in this case.
- ALOGW("initiateModeChange failed: %d", status);
+ if (!display->initiateModeChange(*desiredModeOpt, constraints, outTimeline)) {
continue;
}
@@ -1428,9 +1418,9 @@
const auto display = getDisplayDeviceLocked(*displayToUpdateImmediately);
finalizeDisplayModeChange(*display);
- const auto desiredActiveMode = display->getDesiredActiveMode();
- if (desiredActiveMode && display->getActiveMode() == desiredActiveMode->modeOpt) {
- desiredActiveModeChangeDone(display);
+ const auto desiredModeOpt = display->getDesiredMode();
+ if (desiredModeOpt && display->getActiveMode() == desiredModeOpt->modeOpt) {
+ applyActiveMode(display);
}
}
}
@@ -4016,7 +4006,7 @@
}
if (display->refreshRateSelector().isModeAllowed(request.mode)) {
- setDesiredActiveMode(std::move(request));
+ setDesiredMode(std::move(request));
} else {
ALOGV("%s: Mode %d is disallowed for display %s", __func__, modePtr->getId().value(),
to_string(displayId).c_str());
@@ -7283,15 +7273,14 @@
}
if (!display->isRefreshRateOverlayEnabled()) return;
- const auto desiredActiveMode = display->getDesiredActiveMode();
- const std::optional<DisplayModeId> desiredModeId = desiredActiveMode
- ? std::make_optional(desiredActiveMode->modeOpt->modePtr->getId())
-
- : std::nullopt;
+ const auto desiredModeIdOpt =
+ display->getDesiredMode().transform([](const DisplayDevice::ActiveModeInfo& info) {
+ return info.modeOpt->modePtr->getId();
+ });
const bool timerExpired = mKernelIdleTimerEnabled && expired;
- if (display->onKernelTimerChanged(desiredModeId, timerExpired)) {
+ if (display->onKernelTimerChanged(desiredModeIdOpt, timerExpired)) {
mScheduler->scheduleFrame();
}
}));
@@ -8239,18 +8228,19 @@
auto preferredMode = std::move(*preferredModeOpt);
const auto preferredModeId = preferredMode.modePtr->getId();
+ const Fps preferredFps = preferredMode.fps;
ALOGV("Switching to Scheduler preferred mode %d (%s)", preferredModeId.value(),
- to_string(preferredMode.fps).c_str());
+ to_string(preferredFps).c_str());
if (!selector.isModeAllowed(preferredMode)) {
ALOGE("%s: Preferred mode %d is disallowed", __func__, preferredModeId.value());
return INVALID_OPERATION;
}
- setDesiredActiveMode({preferredMode, .emitEvent = true}, force);
+ setDesiredMode({std::move(preferredMode), .emitEvent = true}, force);
// Update the frameRateOverride list as the display render rate might have changed
- if (mScheduler->updateFrameRateOverrides(/*consideredSignals*/ {}, preferredMode.fps)) {
+ if (mScheduler->updateFrameRateOverrides(scheduler::GlobalSignals{}, preferredFps)) {
triggerOnFrameRateOverridesChanged();
}
@@ -8587,7 +8577,7 @@
const DisplayDevice& activeDisplay) {
ATRACE_CALL();
- // For the first display activated during boot, there is no need to force setDesiredActiveMode,
+ // For the first display activated during boot, there is no need to force setDesiredMode,
// because DM is about to send its policy via setDesiredDisplayModeSpecs.
bool forceApplyPolicy = false;
@@ -8611,9 +8601,9 @@
sActiveDisplayRotationFlags = ui::Transform::toRotationFlags(activeDisplay.getOrientation());
// The policy of the new active/pacesetter display may have changed while it was inactive. In
- // that case, its preferred mode has not been propagated to HWC (via setDesiredActiveMode). In
- // either case, the Scheduler's cachedModeChangedParams must be initialized to the newly active
- // mode, and the kernel idle timer of the newly active display must be toggled.
+ // that case, its preferred mode has not been propagated to HWC (via setDesiredMode). In either
+ // case, the Scheduler's cachedModeChangedParams must be initialized to the newly active mode,
+ // and the kernel idle timer of the newly active display must be toggled.
applyRefreshRateSelectorPolicy(mActiveDisplayId, activeDisplay.refreshRateSelector(),
forceApplyPolicy);
}
@@ -8958,6 +8948,7 @@
.genericLayerMetadataKeyMap = getGenericLayerMetadataKeyMap(),
.skipRoundCornersWhenProtected =
!getRenderEngine().supportsProtectedContent()};
+ args.rootSnapshot.isSecure = mLayerLifecycleManager.isLayerSecure(rootLayerId);
mLayerSnapshotBuilder.update(args);
auto getLayerSnapshotsFn =
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 9e6da3f..75fd25a 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -686,8 +686,7 @@
// Show hdr sdr ratio overlay
bool mHdrSdrRatioOverlay = false;
- void setDesiredActiveMode(display::DisplayModeRequest&&, bool force = false)
- REQUIRES(mStateLock);
+ void setDesiredMode(display::DisplayModeRequest&&, bool force = false) REQUIRES(mStateLock);
status_t setActiveModeFromBackdoor(const sp<display::DisplayToken>&, DisplayModeId, Fps minFps,
Fps maxFps);
@@ -695,9 +694,10 @@
void initiateDisplayModeChanges() REQUIRES(mStateLock, kMainThreadContext);
void finalizeDisplayModeChange(DisplayDevice&) REQUIRES(mStateLock, kMainThreadContext);
- void clearDesiredActiveModeState(const sp<DisplayDevice>&) REQUIRES(mStateLock);
- // Called when active mode is no longer is progress
- void desiredActiveModeChangeDone(const sp<DisplayDevice>&) REQUIRES(mStateLock);
+ // TODO(b/241285191): Replace DisplayDevice with DisplayModeRequest, and move to Scheduler.
+ void dropModeRequest(const sp<DisplayDevice>&) REQUIRES(mStateLock);
+ void applyActiveMode(const sp<DisplayDevice>&) REQUIRES(mStateLock);
+
// Called on the main thread in response to setPowerMode()
void setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode)
REQUIRES(mStateLock, kMainThreadContext);
diff --git a/services/surfaceflinger/tests/ScreenCapture_test.cpp b/services/surfaceflinger/tests/ScreenCapture_test.cpp
index 79864e0..061e121 100644
--- a/services/surfaceflinger/tests/ScreenCapture_test.cpp
+++ b/services/surfaceflinger/tests/ScreenCapture_test.cpp
@@ -154,6 +154,133 @@
sc.expectColor(Rect(0, 0, 10, 10), Color::BLUE);
}
+/**
+ * If a parent layer sets the secure flag, but the screenshot requests is for the child hierarchy,
+ * we need to ensure the secure flag is respected from the parent even though the parent isn't
+ * in the captured sub-hierarchy
+ */
+TEST_F(ScreenCaptureTest, CaptureChildRespectsParentSecureFlag) {
+ Rect size(0, 0, 100, 100);
+ Transaction().hide(mBGSurfaceControl).hide(mFGSurfaceControl).apply();
+ sp<SurfaceControl> parentLayer;
+ ASSERT_NO_FATAL_FAILURE(parentLayer = createLayer("parent-test", 0, 0,
+ ISurfaceComposerClient::eHidden,
+ mRootSurfaceControl.get()));
+
+ sp<SurfaceControl> childLayer;
+ ASSERT_NO_FATAL_FAILURE(childLayer = createLayer("child-test", 0, 0,
+ ISurfaceComposerClient::eFXSurfaceBufferState,
+ parentLayer.get()));
+ ASSERT_NO_FATAL_FAILURE(
+ fillBufferLayerColor(childLayer, Color::GREEN, size.width(), size.height()));
+
+ // hide the parent layer to ensure secure flag is passed down to child when screenshotting
+ Transaction().setLayer(parentLayer, INT32_MAX).show(childLayer).apply(true);
+ Transaction()
+ .setFlags(parentLayer, layer_state_t::eLayerSecure, layer_state_t::eLayerSecure)
+ .apply();
+ LayerCaptureArgs captureArgs;
+ captureArgs.layerHandle = childLayer->getHandle();
+ captureArgs.sourceCrop = size;
+ captureArgs.captureSecureLayers = false;
+ {
+ SCOPED_TRACE("parent hidden");
+ ASSERT_EQ(NO_ERROR, ScreenCapture::captureLayers(captureArgs, mCaptureResults));
+ ASSERT_TRUE(mCaptureResults.capturedSecureLayers);
+ ScreenCapture sc(mCaptureResults.buffer, mCaptureResults.capturedHdrLayers);
+ sc.expectColor(size, Color::BLACK);
+ }
+
+ captureArgs.captureSecureLayers = true;
+ {
+ SCOPED_TRACE("capture secure parent not visible");
+ ASSERT_EQ(NO_ERROR, ScreenCapture::captureLayers(captureArgs, mCaptureResults));
+ ASSERT_TRUE(mCaptureResults.capturedSecureLayers);
+ ScreenCapture sc(mCaptureResults.buffer, mCaptureResults.capturedHdrLayers);
+ sc.expectColor(size, Color::GREEN);
+ }
+
+ Transaction().show(parentLayer).apply();
+ captureArgs.captureSecureLayers = false;
+ {
+ SCOPED_TRACE("parent visible");
+ ASSERT_EQ(NO_ERROR, ScreenCapture::captureLayers(captureArgs, mCaptureResults));
+ ASSERT_TRUE(mCaptureResults.capturedSecureLayers);
+ ScreenCapture sc(mCaptureResults.buffer, mCaptureResults.capturedHdrLayers);
+ sc.expectColor(size, Color::BLACK);
+ }
+
+ captureArgs.captureSecureLayers = true;
+ {
+ SCOPED_TRACE("capture secure parent visible");
+ ASSERT_EQ(NO_ERROR, ScreenCapture::captureLayers(captureArgs, mCaptureResults));
+ ASSERT_TRUE(mCaptureResults.capturedSecureLayers);
+ ScreenCapture sc(mCaptureResults.buffer, mCaptureResults.capturedHdrLayers);
+ sc.expectColor(size, Color::GREEN);
+ }
+}
+
+TEST_F(ScreenCaptureTest, CaptureOffscreenChildRespectsParentSecureFlag) {
+ Rect size(0, 0, 100, 100);
+ Transaction().hide(mBGSurfaceControl).hide(mFGSurfaceControl).apply();
+ // Parent layer should be offscreen.
+ sp<SurfaceControl> parentLayer;
+ ASSERT_NO_FATAL_FAILURE(
+ parentLayer = createLayer("parent-test", 0, 0, ISurfaceComposerClient::eHidden));
+
+ sp<SurfaceControl> childLayer;
+ ASSERT_NO_FATAL_FAILURE(childLayer = createLayer("child-test", 0, 0,
+ ISurfaceComposerClient::eFXSurfaceBufferState,
+ parentLayer.get()));
+ ASSERT_NO_FATAL_FAILURE(
+ fillBufferLayerColor(childLayer, Color::GREEN, size.width(), size.height()));
+
+ // hide the parent layer to ensure secure flag is passed down to child when screenshotting
+ Transaction().setLayer(parentLayer, INT32_MAX).show(childLayer).apply(true);
+ Transaction()
+ .setFlags(parentLayer, layer_state_t::eLayerSecure, layer_state_t::eLayerSecure)
+ .apply();
+ LayerCaptureArgs captureArgs;
+ captureArgs.layerHandle = childLayer->getHandle();
+ captureArgs.sourceCrop = size;
+ captureArgs.captureSecureLayers = false;
+ {
+ SCOPED_TRACE("parent hidden");
+ ASSERT_EQ(NO_ERROR, ScreenCapture::captureLayers(captureArgs, mCaptureResults));
+ ASSERT_TRUE(mCaptureResults.capturedSecureLayers);
+ ScreenCapture sc(mCaptureResults.buffer, mCaptureResults.capturedHdrLayers);
+ sc.expectColor(size, Color::BLACK);
+ }
+
+ captureArgs.captureSecureLayers = true;
+ {
+ SCOPED_TRACE("capture secure parent not visible");
+ ASSERT_EQ(NO_ERROR, ScreenCapture::captureLayers(captureArgs, mCaptureResults));
+ ASSERT_TRUE(mCaptureResults.capturedSecureLayers);
+ ScreenCapture sc(mCaptureResults.buffer, mCaptureResults.capturedHdrLayers);
+ sc.expectColor(size, Color::GREEN);
+ }
+
+ Transaction().show(parentLayer).apply();
+ captureArgs.captureSecureLayers = false;
+ {
+ SCOPED_TRACE("parent visible");
+ ASSERT_EQ(NO_ERROR, ScreenCapture::captureLayers(captureArgs, mCaptureResults));
+ ASSERT_TRUE(mCaptureResults.capturedSecureLayers);
+ ScreenCapture sc(mCaptureResults.buffer, mCaptureResults.capturedHdrLayers);
+ sc.expectColor(size, Color::BLACK);
+ }
+
+ captureArgs.captureSecureLayers = true;
+ {
+ SCOPED_TRACE("capture secure parent visible");
+ ASSERT_EQ(NO_ERROR, ScreenCapture::captureLayers(captureArgs, mCaptureResults));
+ ASSERT_TRUE(mCaptureResults.capturedSecureLayers);
+ ScreenCapture sc(mCaptureResults.buffer, mCaptureResults.capturedHdrLayers);
+ sc.expectColor(size, Color::GREEN);
+ }
+}
+
TEST_F(ScreenCaptureTest, CaptureSingleLayer) {
LayerCaptureArgs captureArgs;
captureArgs.layerHandle = mBGSurfaceControl->getHandle();
diff --git a/services/surfaceflinger/tests/unittests/DisplayDevice_InitiateModeChange.cpp b/services/surfaceflinger/tests/unittests/DisplayDevice_InitiateModeChange.cpp
index 2d87ddd..3873b0c 100644
--- a/services/surfaceflinger/tests/unittests/DisplayDevice_InitiateModeChange.cpp
+++ b/services/surfaceflinger/tests/unittests/DisplayDevice_InitiateModeChange.cpp
@@ -30,7 +30,7 @@
class InitiateModeChangeTest : public DisplayTransactionTest {
public:
- using Action = DisplayDevice::DesiredActiveModeAction;
+ using Action = DisplayDevice::DesiredModeAction;
using Event = scheduler::DisplayModeEvent;
void SetUp() override {
@@ -66,108 +66,93 @@
ftl::as_non_null(createDisplayMode(kModeId120, 120_Hz));
};
-TEST_F(InitiateModeChangeTest, setDesiredActiveMode_setCurrentMode) {
+TEST_F(InitiateModeChangeTest, setDesiredModeToActiveMode) {
EXPECT_EQ(Action::None,
- mDisplay->setDesiredActiveMode(
- {scheduler::FrameRateMode{60_Hz, kMode60}, Event::None}));
- EXPECT_EQ(std::nullopt, mDisplay->getDesiredActiveMode());
+ mDisplay->setDesiredMode({scheduler::FrameRateMode{60_Hz, kMode60}, Event::None}));
+ EXPECT_FALSE(mDisplay->getDesiredMode());
}
-TEST_F(InitiateModeChangeTest, setDesiredActiveMode_setNewMode) {
+TEST_F(InitiateModeChangeTest, setDesiredMode) {
EXPECT_EQ(Action::InitiateDisplayModeSwitch,
- mDisplay->setDesiredActiveMode(
- {scheduler::FrameRateMode{90_Hz, kMode90}, Event::None}));
- ASSERT_NE(std::nullopt, mDisplay->getDesiredActiveMode());
- EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getDesiredActiveMode()->modeOpt);
- EXPECT_EQ(Event::None, mDisplay->getDesiredActiveMode()->event);
+ mDisplay->setDesiredMode({scheduler::FrameRateMode{90_Hz, kMode90}, Event::None}));
+ ASSERT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getDesiredMode()->modeOpt);
+ EXPECT_EQ(Event::None, mDisplay->getDesiredMode()->event);
- // Setting another mode should be cached but return None
+ // Setting another mode should be cached but return None.
EXPECT_EQ(Action::None,
- mDisplay->setDesiredActiveMode(
- {scheduler::FrameRateMode{120_Hz, kMode120}, Event::None}));
- ASSERT_NE(std::nullopt, mDisplay->getDesiredActiveMode());
- EXPECT_FRAME_RATE_MODE(kMode120, 120_Hz, *mDisplay->getDesiredActiveMode()->modeOpt);
- EXPECT_EQ(Event::None, mDisplay->getDesiredActiveMode()->event);
+ mDisplay->setDesiredMode({scheduler::FrameRateMode{120_Hz, kMode120}, Event::None}));
+ ASSERT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_FRAME_RATE_MODE(kMode120, 120_Hz, *mDisplay->getDesiredMode()->modeOpt);
+ EXPECT_EQ(Event::None, mDisplay->getDesiredMode()->event);
}
-TEST_F(InitiateModeChangeTest, clearDesiredActiveModeState) {
+TEST_F(InitiateModeChangeTest, clearDesiredMode) {
EXPECT_EQ(Action::InitiateDisplayModeSwitch,
- mDisplay->setDesiredActiveMode(
- {scheduler::FrameRateMode{90_Hz, kMode90}, Event::None}));
- ASSERT_NE(std::nullopt, mDisplay->getDesiredActiveMode());
+ mDisplay->setDesiredMode({scheduler::FrameRateMode{90_Hz, kMode90}, Event::None}));
+ EXPECT_TRUE(mDisplay->getDesiredMode());
- mDisplay->clearDesiredActiveModeState();
- ASSERT_EQ(std::nullopt, mDisplay->getDesiredActiveMode());
+ mDisplay->clearDesiredMode();
+ EXPECT_FALSE(mDisplay->getDesiredMode());
}
-TEST_F(InitiateModeChangeTest, initiateModeChange) NO_THREAD_SAFETY_ANALYSIS {
+TEST_F(InitiateModeChangeTest, initiateModeChange) REQUIRES(kMainThreadContext) {
EXPECT_EQ(Action::InitiateDisplayModeSwitch,
- mDisplay->setDesiredActiveMode(
- {scheduler::FrameRateMode{90_Hz, kMode90}, Event::None}));
- ASSERT_NE(std::nullopt, mDisplay->getDesiredActiveMode());
- EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getDesiredActiveMode()->modeOpt);
- EXPECT_EQ(Event::None, mDisplay->getDesiredActiveMode()->event);
+ mDisplay->setDesiredMode({scheduler::FrameRateMode{90_Hz, kMode90}, Event::None}));
+ ASSERT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getDesiredMode()->modeOpt);
+ EXPECT_EQ(Event::None, mDisplay->getDesiredMode()->event);
- hal::VsyncPeriodChangeConstraints constraints{
+ const hal::VsyncPeriodChangeConstraints constraints{
.desiredTimeNanos = systemTime(),
.seamlessRequired = false,
};
hal::VsyncPeriodChangeTimeline timeline;
- EXPECT_EQ(OK,
- mDisplay->initiateModeChange(*mDisplay->getDesiredActiveMode(), constraints,
- &timeline));
- EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getUpcomingActiveMode().modeOpt);
- EXPECT_EQ(Event::None, mDisplay->getUpcomingActiveMode().event);
+ EXPECT_TRUE(mDisplay->initiateModeChange(*mDisplay->getDesiredMode(), constraints, timeline));
+ EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getPendingMode().modeOpt);
+ EXPECT_EQ(Event::None, mDisplay->getPendingMode().event);
- mDisplay->clearDesiredActiveModeState();
- ASSERT_EQ(std::nullopt, mDisplay->getDesiredActiveMode());
+ mDisplay->clearDesiredMode();
+ EXPECT_FALSE(mDisplay->getDesiredMode());
}
-TEST_F(InitiateModeChangeTest, initiateRenderRateChange) {
+TEST_F(InitiateModeChangeTest, initiateRenderRateSwitch) {
EXPECT_EQ(Action::InitiateRenderRateSwitch,
- mDisplay->setDesiredActiveMode(
- {scheduler::FrameRateMode{30_Hz, kMode60}, Event::None}));
- EXPECT_EQ(std::nullopt, mDisplay->getDesiredActiveMode());
+ mDisplay->setDesiredMode({scheduler::FrameRateMode{30_Hz, kMode60}, Event::None}));
+ EXPECT_FALSE(mDisplay->getDesiredMode());
}
-TEST_F(InitiateModeChangeTest, getUpcomingActiveMode_desiredActiveModeChanged)
-NO_THREAD_SAFETY_ANALYSIS {
+TEST_F(InitiateModeChangeTest, initiateDisplayModeSwitch) FTL_FAKE_GUARD(kMainThreadContext) {
EXPECT_EQ(Action::InitiateDisplayModeSwitch,
- mDisplay->setDesiredActiveMode(
- {scheduler::FrameRateMode{90_Hz, kMode90}, Event::None}));
- ASSERT_NE(std::nullopt, mDisplay->getDesiredActiveMode());
- EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getDesiredActiveMode()->modeOpt);
- EXPECT_EQ(Event::None, mDisplay->getDesiredActiveMode()->event);
+ mDisplay->setDesiredMode({scheduler::FrameRateMode{90_Hz, kMode90}, Event::None}));
+ ASSERT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getDesiredMode()->modeOpt);
+ EXPECT_EQ(Event::None, mDisplay->getDesiredMode()->event);
- hal::VsyncPeriodChangeConstraints constraints{
+ const hal::VsyncPeriodChangeConstraints constraints{
.desiredTimeNanos = systemTime(),
.seamlessRequired = false,
};
hal::VsyncPeriodChangeTimeline timeline;
- EXPECT_EQ(OK,
- mDisplay->initiateModeChange(*mDisplay->getDesiredActiveMode(), constraints,
- &timeline));
- EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getUpcomingActiveMode().modeOpt);
- EXPECT_EQ(Event::None, mDisplay->getUpcomingActiveMode().event);
+ EXPECT_TRUE(mDisplay->initiateModeChange(*mDisplay->getDesiredMode(), constraints, timeline));
+ EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getPendingMode().modeOpt);
+ EXPECT_EQ(Event::None, mDisplay->getPendingMode().event);
EXPECT_EQ(Action::None,
- mDisplay->setDesiredActiveMode(
- {scheduler::FrameRateMode{120_Hz, kMode120}, Event::None}));
- ASSERT_NE(std::nullopt, mDisplay->getDesiredActiveMode());
- EXPECT_FRAME_RATE_MODE(kMode120, 120_Hz, *mDisplay->getDesiredActiveMode()->modeOpt);
- EXPECT_EQ(Event::None, mDisplay->getDesiredActiveMode()->event);
+ mDisplay->setDesiredMode({scheduler::FrameRateMode{120_Hz, kMode120}, Event::None}));
+ ASSERT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_FRAME_RATE_MODE(kMode120, 120_Hz, *mDisplay->getDesiredMode()->modeOpt);
+ EXPECT_EQ(Event::None, mDisplay->getDesiredMode()->event);
- EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getUpcomingActiveMode().modeOpt);
- EXPECT_EQ(Event::None, mDisplay->getUpcomingActiveMode().event);
+ EXPECT_FRAME_RATE_MODE(kMode90, 90_Hz, *mDisplay->getPendingMode().modeOpt);
+ EXPECT_EQ(Event::None, mDisplay->getPendingMode().event);
- EXPECT_EQ(OK,
- mDisplay->initiateModeChange(*mDisplay->getDesiredActiveMode(), constraints,
- &timeline));
- EXPECT_FRAME_RATE_MODE(kMode120, 120_Hz, *mDisplay->getUpcomingActiveMode().modeOpt);
- EXPECT_EQ(Event::None, mDisplay->getUpcomingActiveMode().event);
+ EXPECT_TRUE(mDisplay->initiateModeChange(*mDisplay->getDesiredMode(), constraints, timeline));
+ EXPECT_FRAME_RATE_MODE(kMode120, 120_Hz, *mDisplay->getPendingMode().modeOpt);
+ EXPECT_EQ(Event::None, mDisplay->getPendingMode().event);
- mDisplay->clearDesiredActiveModeState();
- ASSERT_EQ(std::nullopt, mDisplay->getDesiredActiveMode());
+ mDisplay->clearDesiredMode();
+ EXPECT_FALSE(mDisplay->getDesiredMode());
}
} // namespace
diff --git a/services/surfaceflinger/tests/unittests/LayerSnapshotTest.cpp b/services/surfaceflinger/tests/unittests/LayerSnapshotTest.cpp
index 2cc6dc7..16143e3 100644
--- a/services/surfaceflinger/tests/unittests/LayerSnapshotTest.cpp
+++ b/services/surfaceflinger/tests/unittests/LayerSnapshotTest.cpp
@@ -1055,4 +1055,23 @@
EXPECT_FALSE(getSnapshot(1)->isFrontBuffered());
}
+TEST_F(LayerSnapshotTest, setSecureRootSnapshot) {
+ setFlags(1, layer_state_t::eLayerSecure, layer_state_t::eLayerSecure);
+ LayerSnapshotBuilder::Args args{.root = mHierarchyBuilder.getHierarchy(),
+ .layerLifecycleManager = mLifecycleManager,
+ .includeMetadata = false,
+ .displays = mFrontEndDisplayInfos,
+ .displayChanges = false,
+ .globalShadowSettings = globalShadowSettings,
+ .supportsBlur = true,
+ .supportedLayerGenericMetadata = {},
+ .genericLayerMetadataKeyMap = {}};
+ args.rootSnapshot.isSecure = true;
+ update(mSnapshotBuilder, args);
+
+ EXPECT_TRUE(getSnapshot(1)->isSecure);
+ // Ensure child is also marked as secure
+ EXPECT_TRUE(getSnapshot(11)->isSecure);
+}
+
} // namespace android::surfaceflinger::frontend
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateSelectorTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateSelectorTest.cpp
index a00e886..dc13a8d 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateSelectorTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateSelectorTest.cpp
@@ -34,6 +34,7 @@
#include "mock/DisplayHardware/MockDisplayMode.h"
#include "mock/MockFrameRateMode.h"
+#include "FlagUtils.h"
#include "libsurfaceflinger_unittest_main.h"
#include <com_android_graphics_surfaceflinger_flags.h>
@@ -1543,6 +1544,7 @@
return;
}
+ SET_FLAG_FOR_TEST(flags::vrr_config, false);
// VRR compatibility is determined by the presence of a vrr config in the DisplayMode.
auto selector = createSelector(makeModes(kMode60, kMode120), kModeId120);
@@ -1610,6 +1612,7 @@
return;
}
+ SET_FLAG_FOR_TEST(flags::vrr_config, true);
// VRR compatibility is determined by the presence of a vrr config in the DisplayMode.
auto selector = createSelector(kVrrModes_60_120, kModeId120);
@@ -1624,15 +1627,15 @@
// Note that `smoothSwitchOnly` should not have an effect.
const std::initializer_list<Case> testCases = {
- {FrameRateCategory::Default, false, 240_Hz},
+ {FrameRateCategory::Default, false, 120_Hz},
// TODO(b/266481656): Once this bug is fixed, NoPreference should be a lower frame rate.
- {FrameRateCategory::NoPreference, false, 240_Hz},
+ {FrameRateCategory::NoPreference, false, 120_Hz},
{FrameRateCategory::Low, false, 30_Hz},
{FrameRateCategory::Normal, false, 60_Hz},
{FrameRateCategory::High, false, 120_Hz},
- {FrameRateCategory::Default, true, 240_Hz},
+ {FrameRateCategory::Default, true, 120_Hz},
// TODO(b/266481656): Once this bug is fixed, NoPreference should be a lower frame rate.
- {FrameRateCategory::NoPreference, true, 240_Hz},
+ {FrameRateCategory::NoPreference, true, 120_Hz},
{FrameRateCategory::Low, true, 30_Hz},
{FrameRateCategory::Normal, true, 60_Hz},
{FrameRateCategory::High, true, 120_Hz},
@@ -3486,10 +3489,11 @@
// VRR tests
TEST_P(RefreshRateSelectorTest, singleMinMaxRateForVrr) {
- if (GetParam() != Config::FrameRateOverride::Enabled || !flags::vrr_config()) {
+ if (GetParam() != Config::FrameRateOverride::Enabled) {
return;
}
+ SET_FLAG_FOR_TEST(flags::vrr_config, true);
auto selector = createSelector(kVrrMode_120, kModeId120);
EXPECT_TRUE(selector.supportsFrameRateOverride());
@@ -3505,10 +3509,11 @@
}
TEST_P(RefreshRateSelectorTest, renderRateChangesWithPolicyChangeForVrr) {
- if (GetParam() != Config::FrameRateOverride::Enabled || !flags::vrr_config()) {
+ if (GetParam() != Config::FrameRateOverride::Enabled) {
return;
}
+ SET_FLAG_FOR_TEST(flags::vrr_config, true);
auto selector = createSelector(kVrrModes_60_120, kModeId120);
const FpsRange only120 = {120_Hz, 120_Hz};
@@ -3562,10 +3567,11 @@
}
TEST_P(RefreshRateSelectorTest, modeChangesWithPolicyChangeForVrr) {
- if (GetParam() != Config::FrameRateOverride::Enabled || !flags::vrr_config()) {
+ if (GetParam() != Config::FrameRateOverride::Enabled) {
return;
}
+ SET_FLAG_FOR_TEST(flags::vrr_config, true);
auto selector = createSelector(kVrrModes_60_120, kModeId120);
const FpsRange range120 = {0_Hz, 120_Hz};
@@ -3585,10 +3591,11 @@
}
TEST_P(RefreshRateSelectorTest, getFrameRateOverridesForVrr) {
- if (GetParam() != Config::FrameRateOverride::Enabled || !flags::vrr_config()) {
+ if (GetParam() != Config::FrameRateOverride::Enabled) {
return;
}
+ SET_FLAG_FOR_TEST(flags::vrr_config, true);
auto selector = createSelector(kVrrMode_120, kModeId120);
// TODO(b/297600226) Run at lower than 30 Fps for dVRR
const std::vector<Fps> desiredRefreshRates = {30_Hz, 34.285_Hz, 40_Hz, 48_Hz,
@@ -3614,10 +3621,11 @@
}
TEST_P(RefreshRateSelectorTest, renderFrameRatesForVrr) {
- if (GetParam() != Config::FrameRateOverride::Enabled || !flags::vrr_config()) {
+ if (GetParam() != Config::FrameRateOverride::Enabled) {
return;
}
+ SET_FLAG_FOR_TEST(flags::vrr_config, true);
auto selector = createSelector(kVrrMode_120, kModeId120);
const FpsRange only120 = {120_Hz, 120_Hz};
const FpsRange range120 = {0_Hz, 120_Hz};
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
index aeac80d..075f974 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
@@ -145,11 +145,11 @@
TestableSurfaceFlinger::SchedulerCallbackImpl::kNoOp);
}
-TEST_F(DisplayModeSwitchingTest, changeRefreshRate_OnActiveDisplay_WithRefreshRequired) {
+TEST_F(DisplayModeSwitchingTest, changeRefreshRateOnActiveDisplayWithRefreshRequired) {
ftl::FakeGuard guard(kMainThreadContext);
- ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
+ EXPECT_FALSE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
mFlinger.onActiveDisplayChanged(nullptr, *mDisplay);
@@ -157,9 +157,9 @@
mock::createDisplayModeSpecs(kModeId90.value(), false, 0,
120));
- ASSERT_TRUE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId90);
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
+ ASSERT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getDesiredMode()->modeOpt->modePtr->getId(), kModeId90);
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
// Verify that next commit will call setActiveConfigWithConstraints in HWC
const VsyncPeriodChangeTimeline timeline{.refreshRequired = true};
@@ -171,8 +171,9 @@
mFlinger.commit();
Mock::VerifyAndClearExpectations(mComposer);
- ASSERT_TRUE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
+
+ EXPECT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
// Verify that the next commit will complete the mode change and send
// a onModeChanged event to the framework.
@@ -182,14 +183,14 @@
mFlinger.commit();
Mock::VerifyAndClearExpectations(mAppEventThread);
- ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId90);
+ EXPECT_FALSE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId90);
}
-TEST_F(DisplayModeSwitchingTest, changeRefreshRate_OnActiveDisplay_WithoutRefreshRequired) {
+TEST_F(DisplayModeSwitchingTest, changeRefreshRateOnActiveDisplayWithoutRefreshRequired) {
ftl::FakeGuard guard(kMainThreadContext);
- ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
+ EXPECT_FALSE(mDisplay->getDesiredMode());
mFlinger.onActiveDisplayChanged(nullptr, *mDisplay);
@@ -197,9 +198,9 @@
mock::createDisplayModeSpecs(kModeId90.value(), true, 0,
120));
- ASSERT_TRUE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId90);
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
+ ASSERT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getDesiredMode()->modeOpt->modePtr->getId(), kModeId90);
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
// Verify that next commit will call setActiveConfigWithConstraints in HWC
// and complete the mode change.
@@ -214,8 +215,8 @@
mFlinger.commit();
- ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId90);
+ EXPECT_FALSE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId90);
}
TEST_F(DisplayModeSwitchingTest, twoConsecutiveSetDesiredDisplayModeSpecs) {
@@ -224,8 +225,8 @@
// Test that if we call setDesiredDisplayModeSpecs while a previous mode change
// is still being processed the later call will be respected.
- ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
+ EXPECT_FALSE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
mFlinger.onActiveDisplayChanged(nullptr, *mDisplay);
@@ -245,8 +246,8 @@
mock::createDisplayModeSpecs(kModeId120.value(), false, 0,
180));
- ASSERT_TRUE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId120);
+ ASSERT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getDesiredMode()->modeOpt->modePtr->getId(), kModeId120);
EXPECT_CALL(*mComposer,
setActiveConfigWithConstraints(PrimaryDisplayVariant::HWC_DISPLAY_ID,
@@ -255,20 +256,20 @@
mFlinger.commit();
- ASSERT_TRUE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId120);
+ ASSERT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getDesiredMode()->modeOpt->modePtr->getId(), kModeId120);
mFlinger.commit();
- ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId120);
+ EXPECT_FALSE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId120);
}
-TEST_F(DisplayModeSwitchingTest, changeResolution_OnActiveDisplay_WithoutRefreshRequired) {
+TEST_F(DisplayModeSwitchingTest, changeResolutionOnActiveDisplayWithoutRefreshRequired) {
ftl::FakeGuard guard(kMainThreadContext);
- ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
+ EXPECT_FALSE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
mFlinger.onActiveDisplayChanged(nullptr, *mDisplay);
@@ -276,9 +277,9 @@
mock::createDisplayModeSpecs(kModeId90_4K.value(), false, 0,
120));
- ASSERT_TRUE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId90_4K);
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
+ ASSERT_TRUE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getDesiredMode()->modeOpt->modePtr->getId(), kModeId90_4K);
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId60);
// Verify that next commit will call setActiveConfigWithConstraints in HWC
// and complete the mode change.
@@ -312,18 +313,18 @@
// so we need to update with the new instance.
mDisplay = mFlinger.getDisplay(displayToken);
- ASSERT_FALSE(mDisplay->getDesiredActiveMode().has_value());
- ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId90_4K);
+ EXPECT_FALSE(mDisplay->getDesiredMode());
+ EXPECT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId90_4K);
}
MATCHER_P2(ModeSwitchingTo, flinger, modeId, "") {
- if (!arg->getDesiredActiveMode()) {
- *result_listener << "No desired active mode";
+ if (!arg->getDesiredMode()) {
+ *result_listener << "No desired mode";
return false;
}
- if (arg->getDesiredActiveMode()->modeOpt->modePtr->getId() != modeId) {
- *result_listener << "Unexpected desired active mode " << modeId;
+ if (arg->getDesiredMode()->modeOpt->modePtr->getId() != modeId) {
+ *result_listener << "Unexpected desired mode " << modeId;
return false;
}
@@ -336,9 +337,8 @@
}
MATCHER_P(ModeSettledTo, modeId, "") {
- if (const auto desiredOpt = arg->getDesiredActiveMode()) {
- *result_listener << "Unsettled desired active mode "
- << desiredOpt->modeOpt->modePtr->getId();
+ if (const auto desiredOpt = arg->getDesiredMode()) {
+ *result_listener << "Unsettled desired mode " << desiredOpt->modeOpt->modePtr->getId();
return false;
}
diff --git a/services/vibratorservice/Android.bp b/services/vibratorservice/Android.bp
index 5403baf..2002bdf 100644
--- a/services/vibratorservice/Android.bp
+++ b/services/vibratorservice/Android.bp
@@ -59,12 +59,6 @@
"-Wunreachable-code",
],
- // FIXME: Workaround LTO build breakage
- // http://b/241699694
- lto: {
- never: true,
- },
-
local_include_dirs: ["include"],
export_include_dirs: ["include"],