diff options
author | 2023-11-01 13:49:41 -0700 | |
---|---|---|
committer | 2023-11-17 14:35:23 -0800 | |
commit | 639490b9ec6535cda7f24403237355c941e9fcb2 (patch) | |
tree | c3554b2f347302ee5ffb08ca0ee84b2fdb6f3db4 /libs/binder | |
parent | 8f33166621a04db00e1c0ec6d67884bc0b7f8849 (diff) |
Binder unique_fd
Test: mma
Bug: 302723053
Change-Id: I52f14cadb027b3f854946d5315dce3d23aa21b19
Diffstat (limited to 'libs/binder')
61 files changed, 552 insertions, 292 deletions
diff --git a/libs/binder/Binder.cpp b/libs/binder/Binder.cpp index 301dbf6cdf..c57c9cdd62 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 @@ status_t IBinder::getDebugPid(pid_t* out) { 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 @@ public: std::set<sp<RpcServerLink>> mRpcServerLinks; BpBinder::ObjectManager mObjects; - android::base::unique_fd mRecordingFd; + unique_fd mRecordingFd; }; // --------------------------------------------------------------------------- @@ -640,7 +641,7 @@ status_t BBinder::setRpcClientDebug(const Parcel& data) { } 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 @@ status_t BBinder::setRpcClientDebug(const Parcel& data) { 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 49038b1974..810285920a 100644 --- a/libs/binder/BpBinder.cpp +++ b/libs/binder/BpBinder.cpp @@ -35,6 +35,8 @@ namespace android { +using android::binder::unique_fd; + // --------------------------------------------------------------------------- RpcMutex BpBinder::sTrackingLock; @@ -318,7 +320,7 @@ status_t BpBinder::pingBinder() 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 895690f9b8..455a4338e5 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 @@ using namespace android::binder::impl; 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 dba1dc9f6d..e4a02839dc 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 @@ private: #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 0000000000..52ae48728f --- /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 bb7caa951b..c5f0730d6b 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 @@ status_t dupFileDescriptor(int oldFd, int* newFd); 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 a3cf117326..28a0d5e930 100644 --- a/libs/binder/OS_unix_base.cpp +++ b/libs/binder/OS_unix_base.cpp @@ -21,13 +21,14 @@ #include <binder/RpcTransportRaw.h> #include <log/log.h> #include <string.h> +#include <sys/socket.h> 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 +42,12 @@ status_t setNonBlocking(android::base::borrowed_fd fd) { } 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 +67,8 @@ std::unique_ptr<RpcTransportCtxFactory> makeDefaultRpcTransportCtxFactory() { 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 +111,8 @@ ssize_t sendMessageOnSocket( 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 +138,7 @@ ssize_t receiveMessageFromSocket( 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/Parcel.cpp b/libs/binder/Parcel.cpp index 94f3631b79..47e3f91ac2 100644 --- a/libs/binder/Parcel.cpp +++ b/libs/binder/Parcel.cpp @@ -93,6 +93,8 @@ static size_t pad_size(size_t s) { 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__ @@ -171,7 +173,7 @@ static void release_object(const sp<ProcessState>& proc, const flat_binder_objec } #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); } @@ -626,7 +628,7 @@ status_t Parcel::appendFrom(const Parcel* parcel, size_t offset, size_t len) { 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) { @@ -1206,9 +1208,16 @@ status_t Parcel::writeUtf8VectorAsUtf16Vector( 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); } @@ -1261,9 +1270,16 @@ status_t Parcel::readUtf8VectorFromUtf16Vector( 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); } @@ -1463,11 +1479,11 @@ status_t Parcel::writeNativeHandle(const native_handle* handle) 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; @@ -1546,7 +1562,7 @@ status_t Parcel::writeDupParcelFileDescriptor(int fd) return err; } -status_t Parcel::writeUniqueFileDescriptor(const base::unique_fd& fd) { +status_t Parcel::writeUniqueFileDescriptor(const unique_fd& fd) { return writeDupFileDescriptor(fd.get()); } @@ -2349,8 +2365,7 @@ int Parcel::readParcelFileDescriptor() const { 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) { @@ -2371,8 +2386,7 @@ status_t Parcel::readUniqueFileDescriptor(base::unique_fd* val) const 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) { @@ -2664,8 +2678,7 @@ void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize, const bin 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 4f8b76f7d9..c3c487442b 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 0344eb04d6..7de94e3c6c 100644 --- a/libs/binder/ProcessState.cpp +++ b/libs/binder/ProcessState.cpp @@ -61,6 +61,7 @@ const char* kDefaultDriver = "/dev/binder"; namespace android { using namespace android::binder::impl; +using android::binder::unique_fd; class PoolThread : public Thread { @@ -514,8 +515,8 @@ String8 ProcessState::getDriverName() { 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 @@ ProcessState::ProcessState(const char* driver) 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 f7b5a55a31..eb3c543773 100644 --- a/libs/binder/RecordedTransaction.cpp +++ b/libs/binder/RecordedTransaction.cpp @@ -15,17 +15,18 @@ */ #include <android-base/file.h> -#include <android-base/unique_fd.h> #include <binder/Functional.h> #include <binder/RecordedTransaction.h> +#include <binder/unique_fd.h> + #include <inttypes.h> #include <sys/mman.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::unique_fd; using android::binder::debug::RecordedTransaction; #define PADDING8(s) ((8 - (s) % 8) % 8) diff --git a/libs/binder/RpcServer.cpp b/libs/binder/RpcServer.cpp index fefaa810d2..d9e926a9d5 100644 --- a/libs/binder/RpcServer.cpp +++ b/libs/binder/RpcServer.cpp @@ -45,7 +45,8 @@ namespace android { 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 @@ void RpcServer::setConnectionFilter(std::function<bool(const void*, size_t)>&& f 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::acceptSocketConnection(const RpcServer& server, RpcTransport 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 @@ unique_fd RpcServer::releaseServer() { } 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 @@ status_t RpcServer::setupExternalServer( 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 cd8f41711f..16a7f9fd48 100644 --- a/libs/binder/RpcSession.cpp +++ b/libs/binder/RpcSession.cpp @@ -51,7 +51,8 @@ extern "C" JavaVM* AndroidRuntimeGetJavaVM(); 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 @@ status_t RpcSession::setupUnixDomainSocketBootstrapClient(unique_fd bootstrapFd) 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 @@ status_t RpcSession::setupInetClient(const char* addr, unsigned int port) { 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 008e5d21f0..fe6e1a3318 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 @@ RpcState::CommandData::CommandData(size_t size) : mSize(size) { 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 @@ status_t RpcState::rpcSend( 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 @@ static void cleanup_reply_data(const uint8_t* data, size_t dataSize, const binde 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 @@ status_t RpcState::getAndExecuteCommand(const sp<RpcSession::RpcConnection>& con 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::drainCommands(const sp<RpcSession::RpcConnection>& connection 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::processCommand( 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 @@ static void do_nothing_to_transact_data(const uint8_t* data, size_t dataSize, 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 2a954e632b..8b84602fee 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 @@ private: 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 @@ private: 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 ffa315191d..aa3a6e506d 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 @@ public: 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 @@ public: 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 188ba3b0cb..3819fb6472 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 @@ public: 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 @@ public: 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 fef4be4545..579694c321 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 @@ int socketFree(BIO* bio) { 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 socketRead(BIO* bio, char* buf, int size) { } 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 @@ int socketWrite(BIO* bio, const char* buf, int size) { } 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 @@ public: 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::pollRead(void) { 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::interruptableWriteFully( 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 a0e502e92a..fcf6675588 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 2f2fe7d276..a445196ca9 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 3db038f03f..ae1a6c44d7 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 @@ std::optional<CommandResult> execute(std::vector<std::string> argStringVec, 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 @@ std::optional<CommandResult> execute(std::vector<std::string> argStringVec, 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 5de0980d8e..b582f17c1a 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 @@ struct CommandResult { 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/include/binder/Binder.h b/libs/binder/include/binder/Binder.h index 744da0f825..7a65ff4e45 100644 --- a/libs/binder/include/binder/Binder.h +++ b/libs/binder/include/binder/Binder.h @@ -102,7 +102,7 @@ public: // 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 d78ea0d6b1..89a4d273ad 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 @@ public: // 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 e75d548bd8..dad9a1782d 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 @@ public: * * 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 6961abc64b..09da6e3c4a 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 @@ public: // 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 @@ public: 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 @@ private: 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 @@ private: // 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 @@ private: 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 @@ private: 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 @@ private: // 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 08d8e43106..c4ef3547e9 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 @@ namespace os { 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 @@ public: 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 eb765fe8ec..505c1992b9 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 @@ namespace binder::debug { 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 @@ public: 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 @@ public: 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 2153f162e5..a07880dd65 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 @@ public: * 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 @@ public: * 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 @@ public: /** * 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 @@ public: * * 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 @@ private: 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 @@ private: 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 e3805ac888..11fbde9ace 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 @@ public: /** * 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 @@ public: * * 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 115a1732d7..a50cdc1db0 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 @@ public: [[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 @@ private: 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 @@ public: 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 0000000000..439b8a2e4e --- /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 118409eeff..ddd82e8ef7 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::RpcSession; 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 c15bcf968d..88ce5f4d9b 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::IBinder; 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 3f59dab3a9..08321e7c8f 100644 --- a/libs/binder/rust/tests/serialization.cpp +++ b/libs/binder/rust/tests/serialization.cpp @@ -14,6 +14,9 @@ * limitations under the License. */ +#include "serialization.hpp" +#include "../../FdUtils.h" + #include <android/binder_ibinder_platform.h> #include <android/binder_libbinder.h> #include <binder/IServiceManager.h> @@ -25,7 +28,6 @@ #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, SerializeString) { 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/tests/binderLibTest.cpp b/libs/binder/tests/binderLibTest.cpp index f3969f1a01..cb1a1ee443 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::string_literals; 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 @@ TEST_F(BinderLibTest, PassParcelFileDescriptor) { 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 @@ TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) { 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 @@ public: 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 @@ public: 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 @@ public: 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 @@ public: 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 0a0dae0f59..34fc43f926 100644 --- a/libs/binder/tests/binderParcelUnitTest.cpp +++ b/libs/binder/tests/binderParcelUnitTest.cpp @@ -29,8 +29,8 @@ using android::sp; 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 d08a9bb430..ea89e381ab 100644 --- a/libs/binder/tests/binderRecordReplayTest.cpp +++ b/libs/binder/tests/binderRecordReplayTest.cpp @@ -17,13 +17,13 @@ #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> @@ -37,7 +37,9 @@ 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 @@ public: 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 @@ std::vector<uint8_t> retrieveData(base::borrowed_fd fd) { } 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 @@ public: 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 30172cce87..6eb78d037d 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 624edba9cd..5d304f4bd2 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,8 @@ using namespace std::chrono_literals; using namespace std::placeholders; +using android::binder::borrowed_fd; +using android::binder::unique_fd; using testing::AssertionFailure; using testing::AssertionResult; using testing::AssertionSuccess; @@ -83,12 +86,11 @@ public: 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 +112,8 @@ public: } } } - 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 +127,8 @@ public: 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 +144,9 @@ static unsigned int allocateVsockPort() { 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 +205,8 @@ public: 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 +219,15 @@ static base::unique_fd connectTo(const RpcSocketAddress& addr) { } #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) { @@ -264,7 +265,7 @@ std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc( 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 +274,13 @@ std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc( } 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 +375,7 @@ std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc( 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 +392,14 @@ std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc( // 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; @@ -1152,7 +1153,7 @@ bool testSupportVsockLoopback() { // 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 +1180,7 @@ bool testSupportVsockLoopback() { // 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 +1194,7 @@ bool testSupportVsockLoopback() { 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 +1424,14 @@ public: }; 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 +1477,12 @@ public: // 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 +1511,8 @@ public: }; } 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 +1555,7 @@ public: 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 +1563,7 @@ public: } 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 +1587,13 @@ public: 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 +1602,7 @@ public: } 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 +1610,13 @@ public: 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 b2b63e4bf3..eeb26e0978 100644 --- a/libs/binder/tests/binderRpcTestCommon.h +++ b/libs/binder/tests/binderRpcTestCommon.h @@ -58,6 +58,7 @@ #include "../BuildFlags.h" #include "../FdTrigger.h" +#include "../FdUtils.h" #include "../RpcState.h" // for debugging #include "format.h" #include "utils/Errors.h" @@ -156,13 +157,13 @@ struct BinderRpcOptions { }; #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())); } -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))); std::string ret(length, '\0'); @@ -170,14 +171,14 @@ static inline std::string readString(android::base::borrowed_fd fd) { 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,9 +209,9 @@ static inline std::unique_ptr<RpcTransportCtxFactory> newTlsFactory( } // 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)) { diff --git a/libs/binder/tests/binderRpcTestService.cpp b/libs/binder/tests/binderRpcTestService.cpp index 5025bd617f..5b7a5d2f4d 100644 --- a/libs/binder/tests/binderRpcTestService.cpp +++ b/libs/binder/tests/binderRpcTestService.cpp @@ -17,6 +17,7 @@ #include "binderRpcTestCommon.h" using namespace android; +using android::binder::unique_fd; class MyBinderRpcTestAndroid : public MyBinderRpcTestBase { public: @@ -72,10 +73,10 @@ public: 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 +102,8 @@ int main(int argc, char* argv[]) { __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 +124,7 @@ int main(int argc, char* argv[]) { 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 8acaae6e95..18751cc089 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 @@ std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc( 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 cbbbe74bb5..41cb552e4c 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 @@ bool fdsAreEquivalent(int a, int b) { 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/parcel_fuzzer/binder.cpp b/libs/binder/tests/parcel_fuzzer/binder.cpp index ffeca2d13e..08fe071bfb 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 @@ std::vector<ParcelRead<::android::Parcel>> BINDER_PARCEL_READ_FUNCTIONS { }, 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 c0fdaea0a8..dabee7afa9 100644 --- a/libs/binder/tests/parcel_fuzzer/binder2corpus/binder2corpus.cpp +++ b/libs/binder/tests/parcel_fuzzer/binder2corpus/binder2corpus.cpp @@ -16,8 +16,8 @@ #include <android-base/file.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> @@ -25,7 +25,7 @@ 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 +49,7 @@ status_t generateCorpus(const char* recordingPath, const char* corpusDir) { 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 6ea970825b..8d1299d92a 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 @@ namespace android { // 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 27587a9162..2812da79fa 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 @@ namespace android { 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 071250ddf1..b3db035610 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 @@ -40,6 +40,6 @@ void writeReversedBuffer(std::vector<std::byte>& integralBuffer, T min, T max, T 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 38e6f32cb9..02e69cc371 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 @@ void fuzzService(const std::vector<sp<IBinder>>& binders, FuzzedDataProvider&& p 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 4a9bd07c6e..c7d15337b5 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 f367b419af..4e58dc4899 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 @@ void fillRandomParcel(Parcel* p, FuzzedDataProvider&& provider, RandomParcelOpti } 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 @@ void fillRandomParcel(Parcel* p, FuzzedDataProvider&& provider, RandomParcelOpti 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 9e3e2aba77..f031137e9a 100644 --- a/libs/binder/tests/parcel_fuzzer/random_parcel_seeds.cpp +++ b/libs/binder/tests/parcel_fuzzer/random_parcel_seeds.cpp @@ -22,6 +22,7 @@ #include <fuzzseeds/random_parcel_seeds.h> using android::base::WriteFully; +using android::binder::borrowed_fd; namespace android { namespace impl { @@ -64,7 +65,7 @@ void writeReversedBuffer(std::vector<uint8_t>& integralBuffer, T val) { } // 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/main.cpp b/libs/binder/tests/rpc_fuzzer/main.cpp index dcc8b8ebf7..15157322db 100644 --- a/libs/binder/tests/rpc_fuzzer/main.cpp +++ b/libs/binder/tests/rpc_fuzzer/main.cpp @@ -16,7 +16,6 @@ #include <android-base/file.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,6 +23,7 @@ #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> @@ -31,6 +31,9 @@ #include <sys/resource.h> #include <sys/un.h> +using android::base::GetExecutableDirectory; +using android::binder::unique_fd; + namespace android { static const std::string kSock = std::string(getenv("TMPDIR") ?: "/tmp") + @@ -129,7 +132,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { 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 +143,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { 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 8d2b714b5c..993418adcc 100644 --- a/libs/binder/tests/unit_fuzzers/BinderFuzzFunctions.h +++ b/libs/binder/tests/unit_fuzzers/BinderFuzzFunctions.h @@ -74,7 +74,7 @@ static const std::vector<std::function<void(FuzzedDataProvider*, const sp<BBinde 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 070618294f..87b0fb6662 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 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { 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 9289f6ac90..fa939e68e4 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 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { 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/trusty/OS.cpp b/libs/binder/trusty/OS.cpp index 0d18b0b94d..ca14286d74 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 @@ 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 */) { + 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 8f643230d1..0872b9014c 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 @@ int RpcServerTrusty::handleConnect(const tipc_port* port, handle_t chan, const u 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 6bb45e2e11..c74ba0a65e 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 @@ public: 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 @@ public: 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 @@ public: 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 aa476f946a..7382a303fe 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> |