Merge "Run distinct command to dump HIGH connectivity"
diff --git a/cmds/bugreport/OWNERS b/cmds/bugreport/OWNERS
index 2a9b681..5f56531 100644
--- a/cmds/bugreport/OWNERS
+++ b/cmds/bugreport/OWNERS
@@ -1,4 +1,5 @@
set noparent
+gavincorkery@google.com
nandana@google.com
jsharkey@android.com
diff --git a/cmds/bugreportz/OWNERS b/cmds/bugreportz/OWNERS
index 2a9b681..5f56531 100644
--- a/cmds/bugreportz/OWNERS
+++ b/cmds/bugreportz/OWNERS
@@ -1,4 +1,5 @@
set noparent
+gavincorkery@google.com
nandana@google.com
jsharkey@android.com
diff --git a/cmds/dumpstate/OWNERS b/cmds/dumpstate/OWNERS
index 2a9b681..5f56531 100644
--- a/cmds/dumpstate/OWNERS
+++ b/cmds/dumpstate/OWNERS
@@ -1,4 +1,5 @@
set noparent
+gavincorkery@google.com
nandana@google.com
jsharkey@android.com
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index 4beba1c..c9a7c7b 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -1640,6 +1640,10 @@
MYLOGD("Skipping 'lsmod' because /proc/modules does not exist\n");
} else {
RunCommand("LSMOD", {"lsmod"});
+ RunCommand("MODULES INFO",
+ {"sh", "-c", "cat /proc/modules | cut -d' ' -f1 | "
+ " while read MOD ; do echo modinfo:$MOD ; modinfo $MOD ; "
+ "done"}, CommandOptions::AS_ROOT);
}
if (android::base::GetBoolProperty("ro.logd.kernel", false)) {
@@ -1965,6 +1969,8 @@
RunDumpsys("DUMPSYS", {"connectivity"}, CommandOptions::WithTimeout(90).Build(),
SEC_TO_MSEC(10));
+ RunDumpsys("DUMPSYS", {"vcn_management"}, CommandOptions::WithTimeout(90).Build(),
+ SEC_TO_MSEC(10));
if (include_sensitive_info) {
// Carrier apps' services will be dumped below in dumpsys activity service all-non-platform.
RunDumpsys("DUMPSYS", {"carrier_config"}, CommandOptions::WithTimeout(90).Build(),
diff --git a/cmds/dumpsys/OWNERS b/cmds/dumpsys/OWNERS
index 4f6a89e..97a63ca 100644
--- a/cmds/dumpsys/OWNERS
+++ b/cmds/dumpsys/OWNERS
@@ -1,5 +1,6 @@
set noparent
+gavincorkery@google.com
nandana@google.com
jsharkey@android.com
diff --git a/cmds/installd/OWNERS b/cmds/installd/OWNERS
index fc745d0..d6807ff 100644
--- a/cmds/installd/OWNERS
+++ b/cmds/installd/OWNERS
@@ -9,3 +9,4 @@
ngeoffray@google.com
rpl@google.com
toddke@google.com
+patb@google.com
diff --git a/libs/binder/Android.bp b/libs/binder/Android.bp
index 31227ab..f157aa2 100644
--- a/libs/binder/Android.bp
+++ b/libs/binder/Android.bp
@@ -64,6 +64,9 @@
"PermissionCache.cpp",
"PermissionController.cpp",
]
+libbinder_no_vendor_interface_sources = [
+ ":packagemanager_aidl",
+]
cc_library {
name: "libbinder",
@@ -123,9 +126,8 @@
"Status.cpp",
"TextOutput.cpp",
"Utils.cpp",
- ":packagemanager_aidl",
":libbinder_aidl",
- ],
+ ] + libbinder_no_vendor_interface_sources,
target: {
android: {
@@ -137,7 +139,7 @@
},
},
vendor: {
- exclude_srcs: libbinder_device_interface_sources,
+ exclude_srcs: libbinder_device_interface_sources + libbinder_no_vendor_interface_sources,
},
darwin: {
enabled: false,
diff --git a/libs/binder/LazyServiceRegistrar.cpp b/libs/binder/LazyServiceRegistrar.cpp
index b503beb..6165911 100644
--- a/libs/binder/LazyServiceRegistrar.cpp
+++ b/libs/binder/LazyServiceRegistrar.cpp
@@ -123,16 +123,20 @@
std::string regStr = (reRegister) ? "Re-registering" : "Registering";
ALOGI("%s service %s", regStr.c_str(), name.c_str());
- if (!manager->addService(name.c_str(), service, allowIsolated, dumpFlags).isOk()) {
- ALOGE("Failed to register service %s", name.c_str());
+ if (Status status = manager->addService(name.c_str(), service, allowIsolated, dumpFlags);
+ !status.isOk()) {
+ ALOGE("Failed to register service %s (%s)", name.c_str(), status.toString8().c_str());
return false;
}
if (!reRegister) {
- if (!manager->registerClientCallback(name, service,
- sp<android::os::IClientCallback>::fromExisting(this))
- .isOk()) {
- ALOGE("Failed to add client callback for service %s", name.c_str());
+ if (Status status =
+ manager->registerClientCallback(name, service,
+ sp<android::os::IClientCallback>::fromExisting(
+ this));
+ !status.isOk()) {
+ ALOGE("Failed to add client callback for service %s (%s)", name.c_str(),
+ status.toString8().c_str());
return false;
}
@@ -171,10 +175,10 @@
auto manager = interface_cast<AidlServiceManager>(asBinder(defaultServiceManager()));
for (auto& [name, entry] : mRegisteredServices) {
- bool success = manager->tryUnregisterService(name, entry.service).isOk();
+ Status status = manager->tryUnregisterService(name, entry.service);
- if (!success) {
- ALOGI("Failed to unregister service %s", name.c_str());
+ if (!status.isOk()) {
+ ALOGI("Failed to unregister service %s (%s)", name.c_str(), status.toString8().c_str());
return false;
}
entry.registered = false;
diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp
index e4dfa52..9795348 100644
--- a/libs/binder/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -1466,6 +1466,29 @@
return nullptr;
}
+status_t Parcel::readOutVectorSizeWithCheck(size_t elmSize, int32_t* size) const {
+ if (status_t status = readInt32(size); status != OK) return status;
+ if (*size < 0) return OK; // may be null, client to handle
+
+ LOG_ALWAYS_FATAL_IF(elmSize > INT32_MAX, "Cannot have element as big as %zu", elmSize);
+
+ // approximation, can't know max element size (e.g. if it makes heap
+ // allocations)
+ static_assert(sizeof(int) == sizeof(int32_t), "Android is LP64");
+ int32_t allocationSize;
+ if (__builtin_smul_overflow(elmSize, *size, &allocationSize)) return NO_MEMORY;
+
+ // High limit of 1MB since something this big could never be returned. Could
+ // probably scope this down, but might impact very specific usecases.
+ constexpr int32_t kMaxAllocationSize = 1 * 1000 * 1000;
+
+ if (allocationSize >= kMaxAllocationSize) {
+ return NO_MEMORY;
+ }
+
+ return OK;
+}
+
template<class T>
status_t Parcel::readAligned(T *pArg) const {
static_assert(PAD_SIZE_UNSAFE(sizeof(T)) == sizeof(T));
diff --git a/libs/binder/RpcServer.cpp b/libs/binder/RpcServer.cpp
index 786e2db..59659bd 100644
--- a/libs/binder/RpcServer.cpp
+++ b/libs/binder/RpcServer.cpp
@@ -22,6 +22,7 @@
#include <thread>
#include <vector>
+#include <android-base/scopeguard.h>
#include <binder/Parcel.h>
#include <binder/RpcServer.h>
#include <log/log.h>
@@ -32,6 +33,7 @@
namespace android {
+using base::ScopeGuard;
using base::unique_fd;
RpcServer::RpcServer() {}
@@ -49,8 +51,6 @@
return setupSocketServer(UnixSocketAddress(path));
}
-#ifdef __BIONIC__
-
bool RpcServer::setupVsockServer(unsigned int port) {
// realizing value w/ this type at compile time to avoid ubsan abort
constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
@@ -58,8 +58,6 @@
return setupSocketServer(VsockSocketAddress(kAnyCid, port));
}
-#endif // __BIONIC__
-
bool RpcServer::setupInetServer(unsigned int port, unsigned int* assignedPort) {
const char* kAddr = "127.0.0.1";
@@ -111,66 +109,51 @@
void RpcServer::setRootObject(const sp<IBinder>& binder) {
std::lock_guard<std::mutex> _l(mLock);
- mRootObject = binder;
+ mRootObjectWeak = mRootObject = binder;
+}
+
+void RpcServer::setRootObjectWeak(const wp<IBinder>& binder) {
+ std::lock_guard<std::mutex> _l(mLock);
+ mRootObject.clear();
+ mRootObjectWeak = binder;
}
sp<IBinder> RpcServer::getRootObject() {
std::lock_guard<std::mutex> _l(mLock);
- return mRootObject;
+ bool hasWeak = mRootObjectWeak.unsafe_get();
+ sp<IBinder> ret = mRootObjectWeak.promote();
+ ALOGW_IF(hasWeak && ret == nullptr, "RpcServer root object is freed, returning nullptr");
+ return ret;
}
void RpcServer::join() {
- LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
+ while (true) {
+ (void)acceptOne();
+ }
+}
- std::vector<std::thread> pool;
+bool RpcServer::acceptOne() {
+ LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
+ LOG_ALWAYS_FATAL_IF(!hasServer(), "RpcServer must be setup to join.");
+
+ unique_fd clientFd(
+ TEMP_FAILURE_RETRY(accept4(mServer.get(), nullptr, nullptr /*length*/, SOCK_CLOEXEC)));
+
+ if (clientFd < 0) {
+ ALOGE("Could not accept4 socket: %s", strerror(errno));
+ return false;
+ }
+ LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
+
{
std::lock_guard<std::mutex> _l(mLock);
- LOG_ALWAYS_FATAL_IF(mServer.get() == -1, "RpcServer must be setup to join.");
+ std::thread thread =
+ std::thread(&RpcServer::establishConnection, this,
+ std::move(sp<RpcServer>::fromExisting(this)), std::move(clientFd));
+ mConnectingThreads[thread.get_id()] = std::move(thread);
}
- while (true) {
- unique_fd clientFd(
- TEMP_FAILURE_RETRY(accept4(mServer.get(), nullptr, 0 /*length*/, SOCK_CLOEXEC)));
-
- if (clientFd < 0) {
- ALOGE("Could not accept4 socket: %s", strerror(errno));
- continue;
- }
- LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
-
- // TODO(b/183988761): cannot trust this simple ID
- LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
- int32_t id;
- if (sizeof(id) != read(clientFd.get(), &id, sizeof(id))) {
- ALOGE("Could not read ID from fd %d", clientFd.get());
- continue;
- }
-
- {
- std::lock_guard<std::mutex> _l(mLock);
-
- sp<RpcSession> session;
- if (id == RPC_SESSION_ID_NEW) {
- // new client!
- LOG_ALWAYS_FATAL_IF(mSessionIdCounter >= INT32_MAX, "Out of session IDs");
- mSessionIdCounter++;
-
- session = RpcSession::make();
- session->setForServer(wp<RpcServer>::fromExisting(this), mSessionIdCounter);
-
- mSessions[mSessionIdCounter] = session;
- } else {
- auto it = mSessions.find(id);
- if (it == mSessions.end()) {
- ALOGE("Cannot add thread, no record of session with ID %d", id);
- continue;
- }
- session = it->second;
- }
-
- session->startThread(std::move(clientFd));
- }
- }
+ return true;
}
std::vector<sp<RpcSession>> RpcServer::listSessions() {
@@ -183,14 +166,74 @@
return sessions;
}
-bool RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
- LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
+size_t RpcServer::numUninitializedSessions() {
+ std::lock_guard<std::mutex> _l(mLock);
+ return mConnectingThreads.size();
+}
+void RpcServer::establishConnection(sp<RpcServer>&& server, base::unique_fd clientFd) {
+ LOG_ALWAYS_FATAL_IF(this != server.get(), "Must pass same ownership object");
+
+ // TODO(b/183988761): cannot trust this simple ID
+ LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
+ bool idValid = true;
+ int32_t id;
+ if (sizeof(id) != read(clientFd.get(), &id, sizeof(id))) {
+ ALOGE("Could not read ID from fd %d", clientFd.get());
+ idValid = false;
+ }
+
+ std::thread thisThread;
+ sp<RpcSession> session;
{
std::lock_guard<std::mutex> _l(mLock);
- LOG_ALWAYS_FATAL_IF(mServer.get() != -1, "Each RpcServer can only have one server.");
+
+ auto threadId = mConnectingThreads.find(std::this_thread::get_id());
+ LOG_ALWAYS_FATAL_IF(threadId == mConnectingThreads.end(),
+ "Must establish connection on owned thread");
+ thisThread = std::move(threadId->second);
+ ScopeGuard detachGuard = [&]() { thisThread.detach(); };
+ mConnectingThreads.erase(threadId);
+
+ if (!idValid) {
+ return;
+ }
+
+ if (id == RPC_SESSION_ID_NEW) {
+ LOG_ALWAYS_FATAL_IF(mSessionIdCounter >= INT32_MAX, "Out of session IDs");
+ mSessionIdCounter++;
+
+ session = RpcSession::make();
+ session->setForServer(wp<RpcServer>::fromExisting(this), mSessionIdCounter);
+
+ mSessions[mSessionIdCounter] = session;
+ } else {
+ auto it = mSessions.find(id);
+ if (it == mSessions.end()) {
+ ALOGE("Cannot add thread, no record of session with ID %d", id);
+ return;
+ }
+ session = it->second;
+ }
+
+ detachGuard.Disable();
+ session->preJoin(std::move(thisThread));
}
+ // avoid strong cycle
+ server = nullptr;
+ //
+ //
+ // DO NOT ACCESS MEMBER VARIABLES BELOW
+ //
+
+ session->join(std::move(clientFd));
+}
+
+bool RpcServer::setupSocketServer(const RpcSocketAddress& addr) {
+ LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
+ LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
+
unique_fd serverFd(
TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
if (serverFd == -1) {
@@ -212,6 +255,44 @@
LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
+ if (!setupExternalServer(std::move(serverFd))) {
+ ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
+ return false;
+ }
+ return true;
+}
+
+void RpcServer::onSessionTerminating(const sp<RpcSession>& session) {
+ auto id = session->mId;
+ LOG_ALWAYS_FATAL_IF(id == std::nullopt, "Server sessions must be initialized with ID");
+ LOG_RPC_DETAIL("Dropping session %d", *id);
+
+ std::lock_guard<std::mutex> _l(mLock);
+ auto it = mSessions.find(*id);
+ LOG_ALWAYS_FATAL_IF(it == mSessions.end(), "Bad state, unknown session id %d", *id);
+ LOG_ALWAYS_FATAL_IF(it->second != session, "Bad state, session has id mismatch %d", *id);
+ (void)mSessions.erase(it);
+}
+
+bool RpcServer::hasServer() {
+ LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
+ std::lock_guard<std::mutex> _l(mLock);
+ return mServer.ok();
+}
+
+unique_fd RpcServer::releaseServer() {
+ LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
+ std::lock_guard<std::mutex> _l(mLock);
+ return std::move(mServer);
+}
+
+bool RpcServer::setupExternalServer(base::unique_fd serverFd) {
+ LOG_ALWAYS_FATAL_IF(!mAgreedExperimental, "no!");
+ std::lock_guard<std::mutex> _l(mLock);
+ if (mServer.ok()) {
+ ALOGE("Each RpcServer can only have one server.");
+ return false;
+ }
mServer = std::move(serverFd);
return true;
}
diff --git a/libs/binder/RpcSession.cpp b/libs/binder/RpcSession.cpp
index 09ec20d..05fa49e 100644
--- a/libs/binder/RpcSession.cpp
+++ b/libs/binder/RpcSession.cpp
@@ -24,6 +24,7 @@
#include <string_view>
#include <binder/Parcel.h>
+#include <binder/RpcServer.h>
#include <binder/Stability.h>
#include <utils/String8.h>
@@ -48,7 +49,7 @@
LOG_RPC_DETAIL("RpcSession destroyed %p", this);
std::lock_guard<std::mutex> _l(mMutex);
- LOG_ALWAYS_FATAL_IF(mServers.size() != 0,
+ LOG_ALWAYS_FATAL_IF(mServerConnections.size() != 0,
"Should not be able to destroy a session with servers in use.");
}
@@ -60,14 +61,10 @@
return setupSocketClient(UnixSocketAddress(path));
}
-#ifdef __BIONIC__
-
bool RpcSession::setupVsockClient(unsigned int cid, unsigned int port) {
return setupSocketClient(VsockSocketAddress(cid, port));
}
-#endif // __BIONIC__
-
bool RpcSession::setupInetClient(const char* addr, unsigned int port) {
auto aiStart = InetSocketAddress::getAddrInfo(addr, port);
if (aiStart == nullptr) return false;
@@ -87,7 +84,7 @@
return false;
}
- addClient(std::move(serverFd));
+ addClientConnection(std::move(serverFd));
return true;
}
@@ -96,7 +93,7 @@
return state()->getRootObject(connection.fd(), sp<RpcSession>::fromExisting(this));
}
-status_t RpcSession::getMaxThreads(size_t* maxThreads) {
+status_t RpcSession::getRemoteMaxThreads(size_t* maxThreads) {
ExclusiveConnection connection(sp<RpcSession>::fromExisting(this), ConnectionUse::CLIENT);
return state()->getMaxThreads(connection.fd(), sp<RpcSession>::fromExisting(this), maxThreads);
}
@@ -134,19 +131,13 @@
return OK;
}
-void RpcSession::startThread(unique_fd client) {
- std::lock_guard<std::mutex> _l(mMutex);
- sp<RpcSession> holdThis = sp<RpcSession>::fromExisting(this);
- int fd = client.release();
- auto thread = std::thread([=] {
- holdThis->join(unique_fd(fd));
- {
- std::lock_guard<std::mutex> _l(holdThis->mMutex);
- size_t erased = mThreads.erase(std::this_thread::get_id());
- LOG_ALWAYS_FATAL_IF(erased != 0, "Could not erase thread.");
- }
- });
- mThreads[thread.get_id()] = std::move(thread);
+void RpcSession::preJoin(std::thread thread) {
+ LOG_ALWAYS_FATAL_IF(thread.get_id() != std::this_thread::get_id(), "Must own this thread");
+
+ {
+ std::lock_guard<std::mutex> _l(mMutex);
+ mThreads[thread.get_id()] = std::move(thread);
+ }
}
void RpcSession::join(unique_fd client) {
@@ -166,6 +157,30 @@
LOG_ALWAYS_FATAL_IF(!removeServerConnection(connection),
"bad state: connection object guaranteed to be in list");
+
+ {
+ std::lock_guard<std::mutex> _l(mMutex);
+ auto it = mThreads.find(std::this_thread::get_id());
+ LOG_ALWAYS_FATAL_IF(it == mThreads.end());
+ it->second.detach();
+ mThreads.erase(it);
+ }
+}
+
+void RpcSession::terminateLocked() {
+ // TODO(b/185167543):
+ // - kindly notify other side of the connection of termination (can't be
+ // locked)
+ // - prevent new client/servers from being added
+ // - stop all threads which are currently reading/writing
+ // - terminate RpcState?
+
+ if (mTerminated) return;
+
+ sp<RpcServer> server = mForServer.promote();
+ if (server) {
+ server->onSessionTerminating(sp<RpcSession>::fromExisting(this));
+ }
}
wp<RpcServer> RpcSession::server() {
@@ -175,9 +190,9 @@
bool RpcSession::setupSocketClient(const RpcSocketAddress& addr) {
{
std::lock_guard<std::mutex> _l(mMutex);
- LOG_ALWAYS_FATAL_IF(mClients.size() != 0,
+ LOG_ALWAYS_FATAL_IF(mClientConnections.size() != 0,
"Must only setup session once, but already has %zu clients",
- mClients.size());
+ mClientConnections.size());
}
if (!setupOneSocketClient(addr, RPC_SESSION_ID_NEW)) return false;
@@ -186,7 +201,7 @@
// instead of all at once.
// TODO(b/186470974): first risk of blocking
size_t numThreadsAvailable;
- if (status_t status = getMaxThreads(&numThreadsAvailable); status != OK) {
+ if (status_t status = getRemoteMaxThreads(&numThreadsAvailable); status != OK) {
ALOGE("Could not get max threads after initial session to %s: %s", addr.toString().c_str(),
statusToString(status).c_str());
return false;
@@ -200,49 +215,59 @@
// we've already setup one client
for (size_t i = 0; i + 1 < numThreadsAvailable; i++) {
- // TODO(b/185167543): avoid race w/ accept4 not being called on server
- for (size_t tries = 0; tries < 5; tries++) {
- if (setupOneSocketClient(addr, mId.value())) break;
- usleep(10000);
- }
+ // TODO(b/185167543): shutdown existing connections?
+ if (!setupOneSocketClient(addr, mId.value())) return false;
}
return true;
}
bool RpcSession::setupOneSocketClient(const RpcSocketAddress& addr, int32_t id) {
- unique_fd serverFd(
- TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
- if (serverFd == -1) {
- int savedErrno = errno;
- ALOGE("Could not create socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
- return false;
+ for (size_t tries = 0; tries < 5; tries++) {
+ if (tries > 0) usleep(10000);
+
+ unique_fd serverFd(
+ TEMP_FAILURE_RETRY(socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC, 0)));
+ if (serverFd == -1) {
+ int savedErrno = errno;
+ ALOGE("Could not create socket at %s: %s", addr.toString().c_str(),
+ strerror(savedErrno));
+ return false;
+ }
+
+ if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
+ if (errno == ECONNRESET) {
+ ALOGW("Connection reset on %s", addr.toString().c_str());
+ continue;
+ }
+ int savedErrno = errno;
+ ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(),
+ strerror(savedErrno));
+ return false;
+ }
+
+ if (sizeof(id) != TEMP_FAILURE_RETRY(write(serverFd.get(), &id, sizeof(id)))) {
+ int savedErrno = errno;
+ ALOGE("Could not write id to socket at %s: %s", addr.toString().c_str(),
+ strerror(savedErrno));
+ return false;
+ }
+
+ LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
+
+ addClientConnection(std::move(serverFd));
+ return true;
}
- if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
- int savedErrno = errno;
- ALOGE("Could not connect socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
- return false;
- }
-
- if (sizeof(id) != TEMP_FAILURE_RETRY(write(serverFd.get(), &id, sizeof(id)))) {
- int savedErrno = errno;
- ALOGE("Could not write id to socket at %s: %s", addr.toString().c_str(),
- strerror(savedErrno));
- return false;
- }
-
- LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
-
- addClient(std::move(serverFd));
- return true;
+ ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
+ return false;
}
-void RpcSession::addClient(unique_fd fd) {
+void RpcSession::addClientConnection(unique_fd fd) {
std::lock_guard<std::mutex> _l(mMutex);
sp<RpcConnection> session = sp<RpcConnection>::make();
session->fd = std::move(fd);
- mClients.push_back(session);
+ mClientConnections.push_back(session);
}
void RpcSession::setForServer(const wp<RpcServer>& server, int32_t sessionId) {
@@ -255,15 +280,19 @@
sp<RpcConnection> session = sp<RpcConnection>::make();
session->fd = std::move(fd);
session->exclusiveTid = gettid();
- mServers.push_back(session);
+ mServerConnections.push_back(session);
return session;
}
bool RpcSession::removeServerConnection(const sp<RpcConnection>& connection) {
std::lock_guard<std::mutex> _l(mMutex);
- if (auto it = std::find(mServers.begin(), mServers.end(), connection); it != mServers.end()) {
- mServers.erase(it);
+ if (auto it = std::find(mServerConnections.begin(), mServerConnections.end(), connection);
+ it != mServerConnections.end()) {
+ mServerConnections.erase(it);
+ if (mServerConnections.size() == 0) {
+ terminateLocked();
+ }
return true;
}
return false;
@@ -283,10 +312,11 @@
// CHECK FOR DEDICATED CLIENT SOCKET
//
// A server/looper should always use a dedicated session if available
- findConnection(tid, &exclusive, &available, mSession->mClients, mSession->mClientsOffset);
+ findConnection(tid, &exclusive, &available, mSession->mClientConnections,
+ mSession->mClientConnectionsOffset);
// WARNING: this assumes a server cannot request its client to send
- // a transaction, as mServers is excluded below.
+ // a transaction, as mServerConnections is excluded below.
//
// Imagine we have more than one thread in play, and a single thread
// sends a synchronous, then an asynchronous command. Imagine the
@@ -296,7 +326,8 @@
// command. So, we move to considering the second available thread
// for subsequent calls.
if (use == ConnectionUse::CLIENT_ASYNC && (exclusive != nullptr || available != nullptr)) {
- mSession->mClientsOffset = (mSession->mClientsOffset + 1) % mSession->mClients.size();
+ mSession->mClientConnectionsOffset =
+ (mSession->mClientConnectionsOffset + 1) % mSession->mClientConnections.size();
}
// USE SERVING SOCKET (for nested transaction)
@@ -304,7 +335,7 @@
// asynchronous calls cannot be nested
if (use != ConnectionUse::CLIENT_ASYNC) {
// server connections are always assigned to a thread
- findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServers,
+ findConnection(tid, &exclusive, nullptr /*available*/, mSession->mServerConnections,
0 /* index hint */);
}
@@ -320,13 +351,13 @@
}
// in regular binder, this would usually be a deadlock :)
- LOG_ALWAYS_FATAL_IF(mSession->mClients.size() == 0,
+ LOG_ALWAYS_FATAL_IF(mSession->mClientConnections.size() == 0,
"Not a client of any session. You must create a session to an "
"RPC server to make any non-nested (e.g. oneway or on another thread) "
"calls.");
LOG_RPC_DETAIL("No available session (have %zu clients and %zu servers). Waiting...",
- mSession->mClients.size(), mSession->mServers.size());
+ mSession->mClientConnections.size(), mSession->mServerConnections.size());
mSession->mAvailableConnectionCv.wait(_l);
}
mSession->mWaitingThreads--;
diff --git a/libs/binder/RpcSocketAddress.h b/libs/binder/RpcSocketAddress.h
index c6a06cf..c7ba5d9 100644
--- a/libs/binder/RpcSocketAddress.h
+++ b/libs/binder/RpcSocketAddress.h
@@ -24,9 +24,7 @@
#include <sys/types.h>
#include <sys/un.h>
-#ifdef __BIONIC__
-#include <linux/vm_sockets.h>
-#endif
+#include "vm_sockets.h"
namespace android {
@@ -59,8 +57,6 @@
sockaddr_un mAddr;
};
-#ifdef __BIONIC__
-
class VsockSocketAddress : public RpcSocketAddress {
public:
VsockSocketAddress(unsigned int cid, unsigned int port)
@@ -80,8 +76,6 @@
sockaddr_vm mAddr;
};
-#endif // __BIONIC__
-
class InetSocketAddress : public RpcSocketAddress {
public:
InetSocketAddress(const sockaddr* sockAddr, size_t size, const char* addr, unsigned int port)
diff --git a/libs/binder/RpcState.cpp b/libs/binder/RpcState.cpp
index 96190dc..2ba9fa2 100644
--- a/libs/binder/RpcState.cpp
+++ b/libs/binder/RpcState.cpp
@@ -182,6 +182,27 @@
}
}
+RpcState::CommandData::CommandData(size_t size) : mSize(size) {
+ // The maximum size for regular binder is 1MB for all concurrent
+ // transactions. A very small proportion of transactions are even
+ // larger than a page, but we need to avoid allocating too much
+ // data on behalf of an arbitrary client, or we could risk being in
+ // a position where a single additional allocation could run out of
+ // memory.
+ //
+ // Note, this limit may not reflect the total amount of data allocated for a
+ // transaction (in some cases, additional fixed size amounts are added),
+ // though for rough consistency, we should avoid cases where this data type
+ // is used for multiple dynamic allocations for a single transaction.
+ constexpr size_t kMaxTransactionAllocation = 100 * 1000;
+ if (size == 0) return;
+ if (size > kMaxTransactionAllocation) {
+ ALOGW("Transaction requested too much data allocation %zu", size);
+ return;
+ }
+ mData.reset(new (std::nothrow) uint8_t[size]);
+}
+
bool RpcState::rpcSend(const base::unique_fd& fd, const char* what, const void* data, size_t size) {
LOG_RPC_DETAIL("Sending %s on fd %d: %s", what, fd.get(), hexString(data, size).c_str());
@@ -326,7 +347,11 @@
.asyncNumber = asyncNumber,
};
- std::vector<uint8_t> transactionData(sizeof(RpcWireTransaction) + data.dataSize());
+ CommandData transactionData(sizeof(RpcWireTransaction) + data.dataSize());
+ if (!transactionData.valid()) {
+ return NO_MEMORY;
+ }
+
memcpy(transactionData.data() + 0, &transaction, sizeof(RpcWireTransaction));
memcpy(transactionData.data() + sizeof(RpcWireTransaction), data.data(), data.dataSize());
@@ -379,9 +404,12 @@
if (status != OK) return status;
}
- uint8_t* data = new uint8_t[command.bodySize];
+ CommandData data(command.bodySize);
+ if (!data.valid()) {
+ return NO_MEMORY;
+ }
- if (!rpcRec(fd, "reply body", data, command.bodySize)) {
+ if (!rpcRec(fd, "reply body", data.data(), command.bodySize)) {
return DEAD_OBJECT;
}
@@ -391,9 +419,10 @@
terminate();
return BAD_VALUE;
}
- RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data);
+ RpcWireReply* rpcReply = reinterpret_cast<RpcWireReply*>(data.data());
if (rpcReply->status != OK) return rpcReply->status;
+ data.release();
reply->ipcSetDataReference(rpcReply->data, command.bodySize - offsetof(RpcWireReply, data),
nullptr, 0, cleanup_reply_data);
@@ -461,7 +490,10 @@
const RpcWireHeader& command) {
LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_TRANSACT, "command: %d", command.command);
- std::vector<uint8_t> transactionData(command.bodySize);
+ CommandData transactionData(command.bodySize);
+ if (!transactionData.valid()) {
+ return NO_MEMORY;
+ }
if (!rpcRec(fd, "transaction body", transactionData.data(), transactionData.size())) {
return DEAD_OBJECT;
}
@@ -479,7 +511,7 @@
}
status_t RpcState::processTransactInternal(const base::unique_fd& fd, const sp<RpcSession>& session,
- std::vector<uint8_t>&& transactionData) {
+ CommandData transactionData) {
if (transactionData.size() < sizeof(RpcWireTransaction)) {
ALOGE("Expecting %zu but got %zu bytes for RpcWireTransaction. Terminating!",
sizeof(RpcWireTransaction), transactionData.size());
@@ -500,7 +532,6 @@
auto it = mNodeForAddress.find(addr);
if (it == mNodeForAddress.end()) {
ALOGE("Unknown binder address %s.", addr.toString().c_str());
- dump();
replyStatus = BAD_VALUE;
} else {
target = it->second.binder.promote();
@@ -630,7 +661,7 @@
// justification for const_cast (consider avoiding priority_queue):
// - AsyncTodo operator< doesn't depend on 'data' object
// - gotta go fast
- std::vector<uint8_t> data = std::move(
+ CommandData data = std::move(
const_cast<BinderNode::AsyncTodo&>(it->second.asyncTodo.top()).data);
it->second.asyncTodo.pop();
_l.unlock();
@@ -644,7 +675,10 @@
.status = replyStatus,
};
- std::vector<uint8_t> replyData(sizeof(RpcWireReply) + reply.dataSize());
+ CommandData replyData(sizeof(RpcWireReply) + reply.dataSize());
+ if (!replyData.valid()) {
+ return NO_MEMORY;
+ }
memcpy(replyData.data() + 0, &rpcReply, sizeof(RpcWireReply));
memcpy(replyData.data() + sizeof(RpcWireReply), reply.data(), reply.dataSize());
@@ -671,7 +705,10 @@
status_t RpcState::processDecStrong(const base::unique_fd& fd, const RpcWireHeader& command) {
LOG_ALWAYS_FATAL_IF(command.command != RPC_COMMAND_DEC_STRONG, "command: %d", command.command);
- std::vector<uint8_t> commandData(command.bodySize);
+ CommandData commandData(command.bodySize);
+ if (!commandData.valid()) {
+ return NO_MEMORY;
+ }
if (!rpcRec(fd, "dec ref body", commandData.data(), commandData.size())) {
return DEAD_OBJECT;
}
@@ -690,7 +727,6 @@
auto it = mNodeForAddress.find(addr);
if (it == mNodeForAddress.end()) {
ALOGE("Unknown binder address %s for dec strong.", addr.toString().c_str());
- dump();
return OK;
}
diff --git a/libs/binder/RpcState.h b/libs/binder/RpcState.h
index 3f3eb1c..31f8a22 100644
--- a/libs/binder/RpcState.h
+++ b/libs/binder/RpcState.h
@@ -21,6 +21,7 @@
#include <binder/RpcSession.h>
#include <map>
+#include <optional>
#include <queue>
namespace android {
@@ -100,6 +101,20 @@
*/
void terminate();
+ // Alternative to std::vector<uint8_t> that doesn't abort on allocation failure and caps
+ // large allocations to avoid being requested from allocating too much data.
+ struct CommandData {
+ explicit CommandData(size_t size);
+ bool valid() { return mSize == 0 || mData != nullptr; }
+ size_t size() { return mSize; }
+ uint8_t* data() { return mData.get(); }
+ uint8_t* release() { return mData.release(); }
+
+ private:
+ std::unique_ptr<uint8_t[]> mData;
+ size_t mSize;
+ };
+
[[nodiscard]] bool rpcSend(const base::unique_fd& fd, const char* what, const void* data,
size_t size);
[[nodiscard]] bool rpcRec(const base::unique_fd& fd, const char* what, void* data, size_t size);
@@ -113,7 +128,7 @@
const RpcWireHeader& command);
[[nodiscard]] status_t processTransactInternal(const base::unique_fd& fd,
const sp<RpcSession>& session,
- std::vector<uint8_t>&& transactionData);
+ CommandData transactionData);
[[nodiscard]] status_t processDecStrong(const base::unique_fd& fd,
const RpcWireHeader& command);
@@ -148,7 +163,7 @@
// async transaction queue, _only_ for local binder
struct AsyncTodo {
- std::vector<uint8_t> data; // most convenient format, to move it here
+ CommandData data;
uint64_t asyncNumber = 0;
bool operator<(const AsyncTodo& o) const {
diff --git a/libs/binder/include/binder/LazyServiceRegistrar.h b/libs/binder/include/binder/LazyServiceRegistrar.h
index 9659732..f3ba830 100644
--- a/libs/binder/include/binder/LazyServiceRegistrar.h
+++ b/libs/binder/include/binder/LazyServiceRegistrar.h
@@ -50,8 +50,12 @@
int dumpFlags = IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
/**
* Force the service to persist, even when it has 0 clients.
- * If setting this flag from the server side, make sure to do so before calling registerService,
- * or there may be a race with the default dynamic shutdown.
+ * If setting this flag from the server side, make sure to do so before calling
+ * registerService, or there may be a race with the default dynamic shutdown.
+ *
+ * This should only be used if it is every eventually set to false. If a
+ * service needs to persist but doesn't need to dynamically shut down,
+ * prefer to control it with another mechanism such as ctl.start.
*/
void forcePersist(bool persist);
diff --git a/libs/binder/include/binder/Parcel.h b/libs/binder/include/binder/Parcel.h
index 5aaaa0c..02052ad 100644
--- a/libs/binder/include/binder/Parcel.h
+++ b/libs/binder/include/binder/Parcel.h
@@ -561,6 +561,8 @@
status_t flattenBinder(const sp<IBinder>& binder);
status_t unflattenBinder(sp<IBinder>* out) const;
+ status_t readOutVectorSizeWithCheck(size_t elmSize, int32_t* size) const;
+
template<class T>
status_t readAligned(T *pArg) const;
@@ -1315,7 +1317,7 @@
template<typename T>
status_t Parcel::resizeOutVector(std::vector<T>* val) const {
int32_t size;
- status_t err = readInt32(&size);
+ status_t err = readOutVectorSizeWithCheck(sizeof(T), &size);
if (err != NO_ERROR) {
return err;
}
@@ -1330,7 +1332,7 @@
template<typename T>
status_t Parcel::resizeOutVector(std::optional<std::vector<T>>* val) const {
int32_t size;
- status_t err = readInt32(&size);
+ status_t err = readOutVectorSizeWithCheck(sizeof(T), &size);
if (err != NO_ERROR) {
return err;
}
@@ -1346,7 +1348,7 @@
template<typename T>
status_t Parcel::resizeOutVector(std::unique_ptr<std::vector<T>>* val) const {
int32_t size;
- status_t err = readInt32(&size);
+ status_t err = readOutVectorSizeWithCheck(sizeof(T), &size);
if (err != NO_ERROR) {
return err;
}
diff --git a/libs/binder/include/binder/RpcServer.h b/libs/binder/include/binder/RpcServer.h
index c98151d..8f0c6fd 100644
--- a/libs/binder/include/binder/RpcServer.h
+++ b/libs/binder/include/binder/RpcServer.h
@@ -22,6 +22,7 @@
#include <utils/RefBase.h>
#include <mutex>
+#include <thread>
// WARNING: This is a feature which is still in development, and it is subject
// to radical change. Any production use of this may subject your code to any
@@ -57,12 +58,10 @@
*/
[[nodiscard]] bool setupUnixDomainServer(const char* path);
-#ifdef __BIONIC__
/**
* Creates an RPC server at the current port.
*/
[[nodiscard]] bool setupVsockServer(unsigned int port);
-#endif // __BIONIC__
/**
* Creates an RPC server at the current port using IPv4.
@@ -75,6 +74,22 @@
*/
[[nodiscard]] bool setupInetServer(unsigned int port, unsigned int* assignedPort);
+ /**
+ * If setup*Server has been successful, return true. Otherwise return false.
+ */
+ [[nodiscard]] bool hasServer();
+
+ /**
+ * If hasServer(), return the server FD. Otherwise return invalid FD.
+ */
+ [[nodiscard]] base::unique_fd releaseServer();
+
+ /**
+ * Set up server using an external FD previously set up by releaseServer().
+ * Return false if there's already a server.
+ */
+ bool setupExternalServer(base::unique_fd serverFd);
+
void iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
/**
@@ -91,8 +106,14 @@
/**
* The root object can be retrieved by any client, without any
* authentication. TODO(b/183988761)
+ *
+ * Holds a strong reference to the root object.
*/
void setRootObject(const sp<IBinder>& binder);
+ /**
+ * Holds a weak reference to the root object.
+ */
+ void setRootObjectWeak(const wp<IBinder>& binder);
sp<IBinder> getRootObject();
/**
@@ -103,16 +124,28 @@
void join();
/**
+ * Accept one connection on this server. You must have at least one client
+ * session before calling this.
+ */
+ [[nodiscard]] bool acceptOne();
+
+ /**
* For debugging!
*/
std::vector<sp<RpcSession>> listSessions();
+ size_t numUninitializedSessions();
~RpcServer();
+ // internal use only
+
+ void onSessionTerminating(const sp<RpcSession>& session);
+
private:
friend sp<RpcServer>;
RpcServer();
+ void establishConnection(sp<RpcServer>&& session, base::unique_fd clientFd);
bool setupSocketServer(const RpcSocketAddress& address);
bool mAgreedExperimental = false;
@@ -121,7 +154,9 @@
base::unique_fd mServer; // socket we are accepting sessions on
std::mutex mLock; // for below
+ std::map<std::thread::id, std::thread> mConnectingThreads;
sp<IBinder> mRootObject;
+ wp<IBinder> mRootObjectWeak;
std::map<int32_t, sp<RpcSession>> mSessions;
int32_t mSessionIdCounter = 0;
};
diff --git a/libs/binder/include/binder/RpcSession.h b/libs/binder/include/binder/RpcSession.h
index 3f58b2c..bcc213c 100644
--- a/libs/binder/include/binder/RpcSession.h
+++ b/libs/binder/include/binder/RpcSession.h
@@ -52,12 +52,10 @@
*/
[[nodiscard]] bool setupUnixDomainClient(const char* path);
-#ifdef __BIONIC__
/**
* Connects to an RPC server at the CVD & port.
*/
[[nodiscard]] bool setupVsockClient(unsigned int cvd, unsigned int port);
-#endif // __BIONIC__
/**
* Connects to an RPC server at the given address and port.
@@ -83,7 +81,7 @@
* Query the other side of the session for the maximum number of threads
* it supports (maximum number of concurrent non-nested synchronous transactions)
*/
- status_t getMaxThreads(size_t* maxThreads);
+ status_t getRemoteMaxThreads(size_t* maxThreads);
[[nodiscard]] status_t transact(const RpcAddress& address, uint32_t code, const Parcel& data,
Parcel* reply, uint32_t flags);
@@ -116,8 +114,11 @@
status_t readId();
- void startThread(base::unique_fd client);
+ // transfer ownership of thread
+ void preJoin(std::thread thread);
+ // join on thread passed to preJoin
void join(base::unique_fd client);
+ void terminateLocked();
struct RpcConnection : public RefBase {
base::unique_fd fd;
@@ -129,7 +130,7 @@
bool setupSocketClient(const RpcSocketAddress& address);
bool setupOneSocketClient(const RpcSocketAddress& address, int32_t sessionId);
- void addClient(base::unique_fd fd);
+ void addClientConnection(base::unique_fd fd);
void setForServer(const wp<RpcServer>& server, int32_t sessionId);
sp<RpcConnection> assignServerToThisThread(base::unique_fd fd);
bool removeServerConnection(const sp<RpcConnection>& connection);
@@ -162,13 +163,13 @@
bool mReentrant = false;
};
- // On the other side of a session, for each of mClients here, there should
- // be one of mServers on the other side (and vice versa).
+ // On the other side of a session, for each of mClientConnections here, there should
+ // be one of mServerConnections on the other side (and vice versa).
//
// For the simplest session, a single server with one client, you would
// have:
- // - the server has a single 'mServers' and a thread listening on this
- // - the client has a single 'mClients' and makes calls to this
+ // - the server has a single 'mServerConnections' and a thread listening on this
+ // - the client has a single 'mClientConnections' and makes calls to this
// - here, when the client makes a call, the server can call back into it
// (nested calls), but outside of this, the client will only ever read
// calls from the server when it makes a call itself.
@@ -187,15 +188,17 @@
std::condition_variable mAvailableConnectionCv; // for mWaitingThreads
size_t mWaitingThreads = 0;
- size_t mClientsOffset = 0; // hint index into clients, ++ when sending an async transaction
- std::vector<sp<RpcConnection>> mClients;
- std::vector<sp<RpcConnection>> mServers;
+ // hint index into clients, ++ when sending an async transaction
+ size_t mClientConnectionsOffset = 0;
+ std::vector<sp<RpcConnection>> mClientConnections;
+ std::vector<sp<RpcConnection>> mServerConnections;
// TODO(b/185167543): use for reverse sessions (allow client to also
// serve calls on a session).
// TODO(b/185167543): allow sharing between different sessions in a
- // process? (or combine with mServers)
+ // process? (or combine with mServerConnections)
std::map<std::thread::id, std::thread> mThreads;
+ bool mTerminated = false;
};
} // namespace android
diff --git a/libs/binder/ndk/include_cpp/android/binder_parcel_utils.h b/libs/binder/ndk/include_cpp/android/binder_parcel_utils.h
index 83190aa..5092d87 100644
--- a/libs/binder/ndk/include_cpp/android/binder_parcel_utils.h
+++ b/libs/binder/ndk/include_cpp/android/binder_parcel_utils.h
@@ -910,6 +910,9 @@
if (err != STATUS_OK) return err;
if (size < 0) return STATUS_UNEXPECTED_NULL;
+ // TODO(b/188215728): delegate to libbinder_ndk
+ if (size > 1000000) return STATUS_NO_MEMORY;
+
vec->resize(static_cast<size_t>(size));
return STATUS_OK;
}
@@ -931,6 +934,9 @@
return STATUS_OK;
}
+ // TODO(b/188215728): delegate to libbinder_ndk
+ if (size > 1000000) return STATUS_NO_MEMORY;
+
*vec = std::optional<std::vector<T>>(std::vector<T>{});
(*vec)->resize(static_cast<size_t>(size));
return STATUS_OK;
diff --git a/libs/binder/ndk/include_platform/android/binder_manager.h b/libs/binder/ndk/include_platform/android/binder_manager.h
index a90b4aa..2a66941 100644
--- a/libs/binder/ndk/include_platform/android/binder_manager.h
+++ b/libs/binder/ndk/include_platform/android/binder_manager.h
@@ -35,7 +35,7 @@
* \return EX_NONE on success.
*/
__attribute__((warn_unused_result)) binder_exception_t AServiceManager_addService(
- AIBinder* binder, const char* instance);
+ AIBinder* binder, const char* instance) __INTRODUCED_IN(29);
/**
* Gets a binder object with this specific instance name. Will return nullptr immediately if the
@@ -47,7 +47,8 @@
*
* \param instance identifier of the service used to lookup the service.
*/
-__attribute__((warn_unused_result)) AIBinder* AServiceManager_checkService(const char* instance);
+__attribute__((warn_unused_result)) AIBinder* AServiceManager_checkService(const char* instance)
+ __INTRODUCED_IN(29);
/**
* Gets a binder object with this specific instance name. Blocks for a couple of seconds waiting on
@@ -59,7 +60,8 @@
*
* \param instance identifier of the service used to lookup the service.
*/
-__attribute__((warn_unused_result)) AIBinder* AServiceManager_getService(const char* instance);
+__attribute__((warn_unused_result)) AIBinder* AServiceManager_getService(const char* instance)
+ __INTRODUCED_IN(29);
/**
* Registers a lazy service with the default service manager under the 'instance' name.
@@ -135,6 +137,10 @@
/**
* Prevent lazy services without client from shutting down their process
*
+ * This should only be used if it is every eventually set to false. If a
+ * service needs to persist but doesn't need to dynamically shut down,
+ * prefer to control it with another mechanism.
+ *
* \param persist 'true' if the process should not exit.
*/
void AServiceManager_forceLazyServicesPersist(bool persist) __INTRODUCED_IN(31);
diff --git a/libs/binder/ndk/parcel.cpp b/libs/binder/ndk/parcel.cpp
index ec7c7d8..b2f21c7 100644
--- a/libs/binder/ndk/parcel.cpp
+++ b/libs/binder/ndk/parcel.cpp
@@ -46,7 +46,8 @@
template <typename T>
using ArraySetter = void (*)(void* arrayData, size_t index, T value);
-binder_status_t WriteAndValidateArraySize(AParcel* parcel, bool isNullArray, int32_t length) {
+static binder_status_t WriteAndValidateArraySize(AParcel* parcel, bool isNullArray,
+ int32_t length) {
// only -1 can be used to represent a null array
if (length < -1) return STATUS_BAD_VALUE;
@@ -61,12 +62,24 @@
Parcel* rawParcel = parcel->get();
- status_t status = rawParcel->writeInt32(static_cast<int32_t>(length));
+ status_t status = rawParcel->writeInt32(length);
if (status != STATUS_OK) return PruneStatusT(status);
return STATUS_OK;
}
+static binder_status_t ReadAndValidateArraySize(const AParcel* parcel, int32_t* length) {
+ if (status_t status = parcel->get()->readInt32(length); status != STATUS_OK) {
+ return PruneStatusT(status);
+ }
+
+ if (*length < -1) return STATUS_BAD_VALUE; // libbinder_ndk reserves these
+ if (*length <= 0) return STATUS_OK; // null
+ if (static_cast<size_t>(*length) > parcel->get()->dataAvail()) return STATUS_NO_MEMORY;
+
+ return STATUS_OK;
+}
+
template <typename T>
binder_status_t WriteArray(AParcel* parcel, const T* array, int32_t length) {
binder_status_t status = WriteAndValidateArraySize(parcel, array == nullptr, length);
@@ -111,10 +124,9 @@
const Parcel* rawParcel = parcel->get();
int32_t length;
- status_t status = rawParcel->readInt32(&length);
-
- if (status != STATUS_OK) return PruneStatusT(status);
- if (length < -1) return STATUS_BAD_VALUE;
+ if (binder_status_t status = ReadAndValidateArraySize(parcel, &length); status != STATUS_OK) {
+ return status;
+ }
T* array;
if (!allocator(arrayData, length, &array)) return STATUS_NO_MEMORY;
@@ -140,10 +152,9 @@
const Parcel* rawParcel = parcel->get();
int32_t length;
- status_t status = rawParcel->readInt32(&length);
-
- if (status != STATUS_OK) return PruneStatusT(status);
- if (length < -1) return STATUS_BAD_VALUE;
+ if (binder_status_t status = ReadAndValidateArraySize(parcel, &length); status != STATUS_OK) {
+ return status;
+ }
char16_t* array;
if (!allocator(arrayData, length, &array)) return STATUS_NO_MEMORY;
@@ -155,7 +166,7 @@
if (__builtin_smul_overflow(sizeof(char16_t), length, &size)) return STATUS_NO_MEMORY;
for (int32_t i = 0; i < length; i++) {
- status = rawParcel->readChar(array + i);
+ status_t status = rawParcel->readChar(array + i);
if (status != STATUS_OK) return PruneStatusT(status);
}
@@ -189,10 +200,9 @@
const Parcel* rawParcel = parcel->get();
int32_t length;
- status_t status = rawParcel->readInt32(&length);
-
- if (status != STATUS_OK) return PruneStatusT(status);
- if (length < -1) return STATUS_BAD_VALUE;
+ if (binder_status_t status = ReadAndValidateArraySize(parcel, &length); status != STATUS_OK) {
+ return status;
+ }
if (!allocator(arrayData, length)) return STATUS_NO_MEMORY;
@@ -200,7 +210,7 @@
for (int32_t i = 0; i < length; i++) {
T readTarget;
- status = (rawParcel->*read)(&readTarget);
+ status_t status = (rawParcel->*read)(&readTarget);
if (status != STATUS_OK) return PruneStatusT(status);
setter(arrayData, i, readTarget);
@@ -402,13 +412,10 @@
binder_status_t AParcel_readStringArray(const AParcel* parcel, void* arrayData,
AParcel_stringArrayAllocator allocator,
AParcel_stringArrayElementAllocator elementAllocator) {
- const Parcel* rawParcel = parcel->get();
-
int32_t length;
- status_t status = rawParcel->readInt32(&length);
-
- if (status != STATUS_OK) return PruneStatusT(status);
- if (length < -1) return STATUS_BAD_VALUE;
+ if (binder_status_t status = ReadAndValidateArraySize(parcel, &length); status != STATUS_OK) {
+ return status;
+ }
if (!allocator(arrayData, length)) return STATUS_NO_MEMORY;
@@ -449,13 +456,10 @@
binder_status_t AParcel_readParcelableArray(const AParcel* parcel, void* arrayData,
AParcel_parcelableArrayAllocator allocator,
AParcel_readParcelableElement elementReader) {
- const Parcel* rawParcel = parcel->get();
-
int32_t length;
- status_t status = rawParcel->readInt32(&length);
-
- if (status != STATUS_OK) return PruneStatusT(status);
- if (length < -1) return STATUS_BAD_VALUE;
+ if (binder_status_t status = ReadAndValidateArraySize(parcel, &length); status != STATUS_OK) {
+ return status;
+ }
if (!allocator(arrayData, length)) return STATUS_NO_MEMORY;
diff --git a/libs/binder/rust/Android.bp b/libs/binder/rust/Android.bp
index 49d3401..7d655d8 100644
--- a/libs/binder/rust/Android.bp
+++ b/libs/binder/rust/Android.bp
@@ -26,6 +26,7 @@
},
apex_available: [
"//apex_available:platform",
+ "com.android.compos",
"com.android.virt",
],
}
@@ -48,6 +49,7 @@
},
apex_available: [
"//apex_available:platform",
+ "com.android.compos",
"com.android.virt",
],
lints: "none",
@@ -99,6 +101,7 @@
},
apex_available: [
"//apex_available:platform",
+ "com.android.compos",
"com.android.virt",
],
}
diff --git a/libs/binder/tests/Android.bp b/libs/binder/tests/Android.bp
index c0f7c99..ec231b2 100644
--- a/libs/binder/tests/Android.bp
+++ b/libs/binder/tests/Android.bp
@@ -63,6 +63,9 @@
"libbinder",
"libutils",
],
+ static_libs: [
+ "libgmock",
+ ],
compile_multilib: "32",
multilib: { lib32: { suffix: "" } },
cflags: ["-DBINDER_IPC_32BIT=1"],
@@ -101,6 +104,9 @@
"libbinder",
"libutils",
],
+ static_libs: [
+ "libgmock",
+ ],
test_suites: ["device-tests", "vts"],
require_root: true,
}
diff --git a/libs/binder/tests/binderLibTest.cpp b/libs/binder/tests/binderLibTest.cpp
index 5676bd1..0c3fbcd 100644
--- a/libs/binder/tests/binderLibTest.cpp
+++ b/libs/binder/tests/binderLibTest.cpp
@@ -23,6 +23,7 @@
#include <stdlib.h>
#include <thread>
+#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <binder/Binder.h>
@@ -41,6 +42,13 @@
#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
using namespace android;
+using testing::Not;
+
+// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
+MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
+ *result_listener << statusToString(arg);
+ return expected == arg;
+}
static ::testing::AssertionResult IsPageAligned(void *buf) {
if (((unsigned long)buf & ((unsigned long)PAGE_SIZE - 1)) == 0)
@@ -205,19 +213,16 @@
protected:
sp<IBinder> addServerEtc(int32_t *idPtr, int code)
{
- int ret;
int32_t id;
Parcel data, reply;
sp<IBinder> binder;
- ret = m_server->transact(code, data, &reply);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
EXPECT_FALSE(binder != nullptr);
binder = reply.readStrongBinder();
EXPECT_TRUE(binder != nullptr);
- ret = reply.readInt32(&id);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
if (idPtr)
*idPtr = id;
return binder;
@@ -401,29 +406,25 @@
};
TEST_F(BinderLibTest, NopTransaction) {
- status_t ret;
Parcel data, reply;
- ret = m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
+ StatusEq(NO_ERROR));
}
TEST_F(BinderLibTest, NopTransactionOneway) {
- status_t ret;
Parcel data, reply;
- ret = m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
+ StatusEq(NO_ERROR));
}
TEST_F(BinderLibTest, NopTransactionClear) {
- status_t ret;
Parcel data, reply;
// make sure it accepts the transaction flag
- ret = m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
+ StatusEq(NO_ERROR));
}
TEST_F(BinderLibTest, Freeze) {
- status_t ret;
Parcel data, reply, replypid;
std::ifstream freezer_file("/sys/fs/cgroup/freezer/cgroup.freeze");
@@ -442,9 +443,8 @@
return;
}
- ret = m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid);
+ EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
int32_t pid = replypid.readInt32();
- EXPECT_EQ(NO_ERROR, ret);
for (int i = 0; i < 10; i++) {
EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
}
@@ -468,42 +468,36 @@
TEST_F(BinderLibTest, SetError) {
int32_t testValue[] = { 0, -123, 123 };
for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
- status_t ret;
Parcel data, reply;
data.writeInt32(testValue[i]);
- ret = m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply);
- EXPECT_EQ(testValue[i], ret);
+ EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
+ StatusEq(testValue[i]));
}
}
TEST_F(BinderLibTest, GetId) {
- status_t ret;
int32_t id;
Parcel data, reply;
- ret = m_server->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
- EXPECT_EQ(NO_ERROR, ret);
- ret = reply.readInt32(&id);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply),
+ StatusEq(NO_ERROR));
+ EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
EXPECT_EQ(0, id);
}
TEST_F(BinderLibTest, PtrSize) {
- status_t ret;
int32_t ptrsize;
Parcel data, reply;
sp<IBinder> server = addServer();
ASSERT_TRUE(server != nullptr);
- ret = server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply);
- EXPECT_EQ(NO_ERROR, ret);
- ret = reply.readInt32(&ptrsize);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
+ StatusEq(NO_ERROR));
+ EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
RecordProperty("TestPtrSize", sizeof(void *));
RecordProperty("ServerPtrSize", sizeof(void *));
}
TEST_F(BinderLibTest, IndirectGetId2)
{
- status_t ret;
int32_t id;
int32_t count;
Parcel data, reply;
@@ -521,22 +515,19 @@
datai.appendTo(&data);
}
- ret = m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply);
- ASSERT_EQ(NO_ERROR, ret);
+ ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
+ StatusEq(NO_ERROR));
- ret = reply.readInt32(&id);
- ASSERT_EQ(NO_ERROR, ret);
+ ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
EXPECT_EQ(0, id);
- ret = reply.readInt32(&count);
- ASSERT_EQ(NO_ERROR, ret);
+ ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
for (size_t i = 0; i < (size_t)count; i++) {
BinderLibTestBundle replyi(&reply);
EXPECT_TRUE(replyi.isValid());
- ret = replyi.readInt32(&id);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
EXPECT_EQ(serverId[i], id);
EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
}
@@ -546,7 +537,6 @@
TEST_F(BinderLibTest, IndirectGetId3)
{
- status_t ret;
int32_t id;
int32_t count;
Parcel data, reply;
@@ -571,15 +561,13 @@
datai.appendTo(&data);
}
- ret = m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply);
- ASSERT_EQ(NO_ERROR, ret);
+ ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
+ StatusEq(NO_ERROR));
- ret = reply.readInt32(&id);
- ASSERT_EQ(NO_ERROR, ret);
+ ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
EXPECT_EQ(0, id);
- ret = reply.readInt32(&count);
- ASSERT_EQ(NO_ERROR, ret);
+ ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
for (size_t i = 0; i < (size_t)count; i++) {
@@ -587,18 +575,15 @@
BinderLibTestBundle replyi(&reply);
EXPECT_TRUE(replyi.isValid());
- ret = replyi.readInt32(&id);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
EXPECT_EQ(serverId[i], id);
- ret = replyi.readInt32(&counti);
- ASSERT_EQ(NO_ERROR, ret);
+ ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
EXPECT_EQ(1, counti);
BinderLibTestBundle replyi2(&replyi);
EXPECT_TRUE(replyi2.isValid());
- ret = replyi2.readInt32(&id);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
EXPECT_EQ(0, id);
EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
@@ -610,16 +595,13 @@
TEST_F(BinderLibTest, CallBack)
{
- status_t ret;
Parcel data, reply;
sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
data.writeStrongBinder(callBack);
- ret = m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY);
- EXPECT_EQ(NO_ERROR, ret);
- ret = callBack->waitEvent(5);
- EXPECT_EQ(NO_ERROR, ret);
- ret = callBack->getResult();
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
+ StatusEq(NO_ERROR));
+ EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
+ EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
}
TEST_F(BinderLibTest, AddServer)
@@ -630,7 +612,6 @@
TEST_F(BinderLibTest, DeathNotificationStrongRef)
{
- status_t ret;
sp<IBinder> sbinder;
sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
@@ -638,20 +619,17 @@
{
sp<IBinder> binder = addServer();
ASSERT_TRUE(binder != nullptr);
- ret = binder->linkToDeath(testDeathRecipient);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
sbinder = binder;
}
{
Parcel data, reply;
- ret = sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
- EXPECT_EQ(0, ret);
+ EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
+ StatusEq(OK));
}
IPCThreadState::self()->flushCommands();
- ret = testDeathRecipient->waitEvent(5);
- EXPECT_EQ(NO_ERROR, ret);
- ret = sbinder->unlinkToDeath(testDeathRecipient);
- EXPECT_EQ(DEAD_OBJECT, ret);
+ EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
+ EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
}
TEST_F(BinderLibTest, DeathNotificationMultiple)
@@ -674,8 +652,9 @@
callBack[i] = new BinderLibTestCallBack();
data.writeStrongBinder(target);
data.writeStrongBinder(callBack[i]);
- ret = linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply, TF_ONE_WAY);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
+ &reply, TF_ONE_WAY),
+ StatusEq(NO_ERROR));
}
{
Parcel data, reply;
@@ -683,8 +662,9 @@
passiveclient[i] = addServer();
ASSERT_TRUE(passiveclient[i] != nullptr);
data.writeStrongBinder(target);
- ret = passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply, TF_ONE_WAY);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
+ &reply, TF_ONE_WAY),
+ StatusEq(NO_ERROR));
}
}
{
@@ -694,10 +674,8 @@
}
for (int i = 0; i < clientcount; i++) {
- ret = callBack[i]->waitEvent(5);
- EXPECT_EQ(NO_ERROR, ret);
- ret = callBack[i]->getResult();
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
+ EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
}
}
@@ -712,8 +690,7 @@
sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
- ret = target->linkToDeath(testDeathRecipient);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
{
Parcel data, reply;
@@ -750,14 +727,13 @@
callback = new BinderLibTestCallBack();
data.writeStrongBinder(target);
data.writeStrongBinder(callback);
- ret = client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply, TF_ONE_WAY);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
+ TF_ONE_WAY),
+ StatusEq(NO_ERROR));
}
- ret = callback->waitEvent(5);
- EXPECT_EQ(NO_ERROR, ret);
- ret = callback->getResult();
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
+ EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
}
TEST_F(BinderLibTest, PassFile) {
@@ -773,17 +749,14 @@
Parcel data, reply;
uint8_t writebuf[1] = { write_value };
- ret = data.writeFileDescriptor(pipefd[1], true);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
- ret = data.writeInt32(sizeof(writebuf));
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
- ret = data.write(writebuf, sizeof(writebuf));
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
- ret = m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
+ StatusEq(NO_ERROR));
}
ret = read(pipefd[0], buf, sizeof(buf));
@@ -864,11 +837,10 @@
}
TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
- status_t ret;
Parcel data, reply;
- ret = m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
+ StatusEq(NO_ERROR));
const flat_binder_object *fb = reply.readObject(false);
ASSERT_TRUE(fb != nullptr);
@@ -888,8 +860,8 @@
wp<IBinder> keepFreedBinder;
{
Parcel data, reply;
- ret = server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply);
- ASSERT_EQ(NO_ERROR, ret);
+ ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
+ StatusEq(NO_ERROR));
struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
freedHandle = freed->handle;
/* Add a weak ref to the freed binder so the driver does not
@@ -950,7 +922,6 @@
}
TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
- status_t ret;
Parcel data, reply;
sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
for (int i = 0; i < 2; i++) {
@@ -964,13 +935,12 @@
datai.appendTo(&data);
}
- ret = m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
+ StatusEq(NO_ERROR));
}
TEST_F(BinderLibTest, OnewayQueueing)
{
- status_t ret;
Parcel data, data2;
sp<IBinder> pollServer = addPollServer();
@@ -983,25 +953,21 @@
data2.writeStrongBinder(callBack2);
data2.writeInt32(0); // delay in us
- ret = pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
+ StatusEq(NO_ERROR));
// The delay ensures that this second transaction will end up on the async_todo list
// (for a single-threaded server)
- ret = pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
+ StatusEq(NO_ERROR));
// The server will ensure that the two transactions are handled in the expected order;
// If the ordering is not as expected, an error will be returned through the callbacks.
- ret = callBack->waitEvent(2);
- EXPECT_EQ(NO_ERROR, ret);
- ret = callBack->getResult();
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
+ EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
- ret = callBack2->waitEvent(2);
- EXPECT_EQ(NO_ERROR, ret);
- ret = callBack2->getResult();
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
+ EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
}
TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
@@ -1120,8 +1086,8 @@
ASSERT_TRUE(server != nullptr);
Parcel data, reply;
- status_t ret = server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
+ StatusEq(NO_ERROR));
int policy = reply.readInt32();
int priority = reply.readInt32();
@@ -1140,8 +1106,8 @@
EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, ¶m));
Parcel data, reply;
- status_t ret = server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
+ StatusEq(NO_ERROR));
int policy = reply.readInt32();
int priority = reply.readInt32();
@@ -1158,10 +1124,9 @@
std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
data.writeUint64Vector(testValue);
- status_t ret = server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply);
- EXPECT_EQ(NO_ERROR, ret);
+ EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
std::vector<uint64_t> readValue;
- ret = reply.readUint64Vector(&readValue);
+ EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
EXPECT_EQ(readValue, testValue);
}
@@ -1186,19 +1151,18 @@
memcpy(parcelData, &obj, sizeof(obj));
data.setDataSize(sizeof(obj));
- status_t ret = server->transact(BINDER_LIB_TEST_REJECT_BUF, data, &reply);
// Either the kernel should reject this transaction (if it's correct), but
// if it's not, the server implementation should return an error if it
// finds an object in the received Parcel.
- EXPECT_NE(NO_ERROR, ret);
+ EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_BUF, data, &reply),
+ Not(StatusEq(NO_ERROR)));
}
TEST_F(BinderLibTest, GotSid) {
sp<IBinder> server = addServer();
Parcel data;
- status_t ret = server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr);
- EXPECT_EQ(OK, ret);
+ EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
}
class BinderLibTestService : public BBinder
diff --git a/libs/binder/tests/binderRpcTest.cpp b/libs/binder/tests/binderRpcTest.cpp
index 8d10727..a96deb5 100644
--- a/libs/binder/tests/binderRpcTest.cpp
+++ b/libs/binder/tests/binderRpcTest.cpp
@@ -34,14 +34,11 @@
#include <iostream>
#include <thread>
-#ifdef __BIONIC__
-#include <linux/vm_sockets.h>
-#endif //__BIONIC__
-
#include <sys/prctl.h>
#include <unistd.h>
-#include "../RpcState.h" // for debugging
+#include "../RpcState.h" // for debugging
+#include "../vm_sockets.h" // for VMADDR_*
namespace android {
@@ -52,6 +49,19 @@
EXPECT_DEATH(p.markForBinder(sp<BBinder>::make()), "");
}
+TEST(BinderRpc, SetExternalServer) {
+ base::unique_fd sink(TEMP_FAILURE_RETRY(open("/dev/null", O_RDWR)));
+ int sinkFd = sink.get();
+ auto server = RpcServer::make();
+ server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
+ ASSERT_FALSE(server->hasServer());
+ ASSERT_TRUE(server->setupExternalServer(std::move(sink)));
+ ASSERT_TRUE(server->hasServer());
+ base::unique_fd retrieved = server->releaseServer();
+ ASSERT_FALSE(server->hasServer());
+ ASSERT_EQ(sinkFd, retrieved.get());
+}
+
using android::binder::Status;
#define EXPECT_OK(status) \
@@ -291,19 +301,15 @@
enum class SocketType {
UNIX,
-#ifdef __BIONIC__
VSOCK,
-#endif // __BIONIC__
INET,
};
static inline std::string PrintSocketType(const testing::TestParamInfo<SocketType>& info) {
switch (info.param) {
case SocketType::UNIX:
return "unix_domain_socket";
-#ifdef __BIONIC__
case SocketType::VSOCK:
return "vm_socket";
-#endif // __BIONIC__
case SocketType::INET:
return "inet_socket";
default:
@@ -334,59 +340,53 @@
server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
server->setMaxThreads(numThreads);
+ unsigned int outPort = 0;
+
switch (socketType) {
case SocketType::UNIX:
CHECK(server->setupUnixDomainServer(addr.c_str())) << addr;
break;
-#ifdef __BIONIC__
case SocketType::VSOCK:
CHECK(server->setupVsockServer(vsockPort));
break;
-#endif // __BIONIC__
case SocketType::INET: {
- unsigned int outPort = 0;
CHECK(server->setupInetServer(0, &outPort));
CHECK_NE(0, outPort);
- CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort,
- sizeof(outPort)));
break;
}
default:
LOG_ALWAYS_FATAL("Unknown socket type");
}
+ CHECK(android::base::WriteFully(pipe->writeEnd(), &outPort, sizeof(outPort)));
+
configure(server);
server->join();
}),
};
- unsigned int inetPort = 0;
+ // always read socket, so that we have waited for the server to start
+ unsigned int outPort = 0;
+ CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &outPort, sizeof(outPort)));
if (socketType == SocketType::INET) {
- CHECK(android::base::ReadFully(ret.host.getPipe()->readEnd(), &inetPort,
- sizeof(inetPort)));
- CHECK_NE(0, inetPort);
+ CHECK_NE(0, outPort);
}
for (size_t i = 0; i < numSessions; i++) {
sp<RpcSession> session = RpcSession::make();
- for (size_t tries = 0; tries < 10; tries++) {
- usleep(10000);
- switch (socketType) {
- case SocketType::UNIX:
- if (session->setupUnixDomainClient(addr.c_str())) goto success;
- break;
-#ifdef __BIONIC__
- case SocketType::VSOCK:
- if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
- break;
-#endif // __BIONIC__
- case SocketType::INET:
- if (session->setupInetClient("127.0.0.1", inetPort)) goto success;
- break;
- default:
- LOG_ALWAYS_FATAL("Unknown socket type");
- }
+ switch (socketType) {
+ case SocketType::UNIX:
+ if (session->setupUnixDomainClient(addr.c_str())) goto success;
+ break;
+ case SocketType::VSOCK:
+ if (session->setupVsockClient(VMADDR_CID_LOCAL, vsockPort)) goto success;
+ break;
+ case SocketType::INET:
+ if (session->setupInetClient("127.0.0.1", outPort)) goto success;
+ break;
+ default:
+ LOG_ALWAYS_FATAL("Unknown socket type");
}
LOG_ALWAYS_FATAL("Could not connect");
success:
@@ -934,13 +934,42 @@
INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc,
::testing::ValuesIn({
SocketType::UNIX,
+// TODO(b/185269356): working on host
#ifdef __BIONIC__
SocketType::VSOCK,
-#endif // __BIONIC__
+#endif
SocketType::INET,
}),
PrintSocketType);
+class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool>> {};
+
+TEST_P(BinderRpcServerRootObject, WeakRootObject) {
+ using SetFn = std::function<void(RpcServer*, sp<IBinder>)>;
+ auto setRootObject = [](bool isStrong) -> SetFn {
+ return isStrong ? SetFn(&RpcServer::setRootObject) : SetFn(&RpcServer::setRootObjectWeak);
+ };
+
+ auto server = RpcServer::make();
+ auto [isStrong1, isStrong2] = GetParam();
+ auto binder1 = sp<BBinder>::make();
+ IBinder* binderRaw1 = binder1.get();
+ setRootObject(isStrong1)(server.get(), binder1);
+ EXPECT_EQ(binderRaw1, server->getRootObject());
+ binder1.clear();
+ EXPECT_EQ((isStrong1 ? binderRaw1 : nullptr), server->getRootObject());
+
+ auto binder2 = sp<BBinder>::make();
+ IBinder* binderRaw2 = binder2.get();
+ setRootObject(isStrong2)(server.get(), binder2);
+ EXPECT_EQ(binderRaw2, server->getRootObject());
+ binder2.clear();
+ EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject());
+}
+
+INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject,
+ ::testing::Combine(::testing::Bool(), ::testing::Bool()));
+
} // namespace android
int main(int argc, char** argv) {
diff --git a/libs/binder/tests/parcel_fuzzer/binder.cpp b/libs/binder/tests/parcel_fuzzer/binder.cpp
index 394d222..5f2c17c 100644
--- a/libs/binder/tests/parcel_fuzzer/binder.cpp
+++ b/libs/binder/tests/parcel_fuzzer/binder.cpp
@@ -66,6 +66,10 @@
int32_t mValue = 0;
};
+struct BigStruct {
+ uint8_t data[1337];
+};
+
#define PARCEL_READ_WITH_STATUS(T, FUN) \
[] (const ::android::Parcel& p, uint8_t /*data*/) {\
FUZZ_LOG() << "about to read " #T " using " #FUN " with status";\
@@ -158,22 +162,20 @@
PARCEL_READ_WITH_STATUS(android::sp<android::IBinder>, readStrongBinder),
PARCEL_READ_WITH_STATUS(android::sp<android::IBinder>, readNullableStrongBinder),
- // TODO(b/131868573): can force read of arbitrarily sized vector
- // PARCEL_READ_WITH_STATUS(std::vector<ByteEnum>, readEnumVector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<ByteEnum>>, readEnumVector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<ByteEnum>>, readEnumVector),
- // PARCEL_READ_WITH_STATUS(std::vector<IntEnum>, readEnumVector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<IntEnum>>, readEnumVector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<IntEnum>>, readEnumVector),
- // PARCEL_READ_WITH_STATUS(std::vector<LongEnum>, readEnumVector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<LongEnum>>, readEnumVector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<LongEnum>>, readEnumVector),
+ PARCEL_READ_WITH_STATUS(std::vector<ByteEnum>, readEnumVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<ByteEnum>>, readEnumVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<ByteEnum>>, readEnumVector),
+ PARCEL_READ_WITH_STATUS(std::vector<IntEnum>, readEnumVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<IntEnum>>, readEnumVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<IntEnum>>, readEnumVector),
+ PARCEL_READ_WITH_STATUS(std::vector<LongEnum>, readEnumVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<LongEnum>>, readEnumVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<LongEnum>>, readEnumVector),
// only reading one parcelable type for now
- // TODO(b/131868573): can force read of arbitrarily sized vector
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<std::unique_ptr<ExampleParcelable>>>, readParcelableVector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<std::optional<ExampleParcelable>>>, readParcelableVector),
- // PARCEL_READ_WITH_STATUS(std::vector<ExampleParcelable>, readParcelableVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<std::unique_ptr<ExampleParcelable>>>, readParcelableVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<std::optional<ExampleParcelable>>>, readParcelableVector),
+ PARCEL_READ_WITH_STATUS(std::vector<ExampleParcelable>, readParcelableVector),
PARCEL_READ_WITH_STATUS(ExampleParcelable, readParcelable),
PARCEL_READ_WITH_STATUS(std::unique_ptr<ExampleParcelable>, readParcelable),
PARCEL_READ_WITH_STATUS(std::optional<ExampleParcelable>, readParcelable),
@@ -182,45 +184,43 @@
PARCEL_READ_WITH_STATUS(android::sp<android::os::IServiceManager>, readStrongBinder),
PARCEL_READ_WITH_STATUS(android::sp<android::os::IServiceManager>, readNullableStrongBinder),
- // TODO(b/131868573): can force read of arbitrarily sized vector
- // PARCEL_READ_WITH_STATUS(::std::unique_ptr<std::vector<android::sp<android::IBinder>>>, readStrongBinderVector),
- // PARCEL_READ_WITH_STATUS(::std::optional<std::vector<android::sp<android::IBinder>>>, readStrongBinderVector),
- // PARCEL_READ_WITH_STATUS(std::vector<android::sp<android::IBinder>>, readStrongBinderVector),
+ PARCEL_READ_WITH_STATUS(::std::unique_ptr<std::vector<android::sp<android::IBinder>>>, readStrongBinderVector),
+ PARCEL_READ_WITH_STATUS(::std::optional<std::vector<android::sp<android::IBinder>>>, readStrongBinderVector),
+ PARCEL_READ_WITH_STATUS(std::vector<android::sp<android::IBinder>>, readStrongBinderVector),
- // TODO(b/131868573): can force read of arbitrarily sized vector
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<int8_t>>, readByteVector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<int8_t>>, readByteVector),
- // PARCEL_READ_WITH_STATUS(std::vector<int8_t>, readByteVector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<uint8_t>>, readByteVector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<uint8_t>>, readByteVector),
- // PARCEL_READ_WITH_STATUS(std::vector<uint8_t>, readByteVector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<int32_t>>, readInt32Vector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<int32_t>>, readInt32Vector),
- // PARCEL_READ_WITH_STATUS(std::vector<int32_t>, readInt32Vector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<int64_t>>, readInt64Vector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<int64_t>>, readInt64Vector),
- // PARCEL_READ_WITH_STATUS(std::vector<int64_t>, readInt64Vector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<uint64_t>>, readUint64Vector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<uint64_t>>, readUint64Vector),
- // PARCEL_READ_WITH_STATUS(std::vector<uint64_t>, readUint64Vector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<float>>, readFloatVector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<float>>, readFloatVector),
- // PARCEL_READ_WITH_STATUS(std::vector<float>, readFloatVector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<double>>, readDoubleVector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<double>>, readDoubleVector),
- // PARCEL_READ_WITH_STATUS(std::vector<double>, readDoubleVector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<bool>>, readBoolVector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<bool>>, readBoolVector),
- // PARCEL_READ_WITH_STATUS(std::vector<bool>, readBoolVector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<char16_t>>, readCharVector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<char16_t>>, readCharVector),
- // PARCEL_READ_WITH_STATUS(std::vector<char16_t>, readCharVector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<std::unique_ptr<android::String16>>>, readString16Vector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<std::optional<android::String16>>>, readString16Vector),
- // PARCEL_READ_WITH_STATUS(std::vector<android::String16>, readString16Vector),
- // PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<std::unique_ptr<std::string>>>, readUtf8VectorFromUtf16Vector),
- // PARCEL_READ_WITH_STATUS(std::optional<std::vector<std::optional<std::string>>>, readUtf8VectorFromUtf16Vector),
- // PARCEL_READ_WITH_STATUS(std::vector<std::string>, readUtf8VectorFromUtf16Vector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<int8_t>>, readByteVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<int8_t>>, readByteVector),
+ PARCEL_READ_WITH_STATUS(std::vector<int8_t>, readByteVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<uint8_t>>, readByteVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<uint8_t>>, readByteVector),
+ PARCEL_READ_WITH_STATUS(std::vector<uint8_t>, readByteVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<int32_t>>, readInt32Vector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<int32_t>>, readInt32Vector),
+ PARCEL_READ_WITH_STATUS(std::vector<int32_t>, readInt32Vector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<int64_t>>, readInt64Vector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<int64_t>>, readInt64Vector),
+ PARCEL_READ_WITH_STATUS(std::vector<int64_t>, readInt64Vector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<uint64_t>>, readUint64Vector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<uint64_t>>, readUint64Vector),
+ PARCEL_READ_WITH_STATUS(std::vector<uint64_t>, readUint64Vector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<float>>, readFloatVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<float>>, readFloatVector),
+ PARCEL_READ_WITH_STATUS(std::vector<float>, readFloatVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<double>>, readDoubleVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<double>>, readDoubleVector),
+ PARCEL_READ_WITH_STATUS(std::vector<double>, readDoubleVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<bool>>, readBoolVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<bool>>, readBoolVector),
+ PARCEL_READ_WITH_STATUS(std::vector<bool>, readBoolVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<char16_t>>, readCharVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<char16_t>>, readCharVector),
+ PARCEL_READ_WITH_STATUS(std::vector<char16_t>, readCharVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<std::unique_ptr<android::String16>>>, readString16Vector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<std::optional<android::String16>>>, readString16Vector),
+ PARCEL_READ_WITH_STATUS(std::vector<android::String16>, readString16Vector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<std::unique_ptr<std::string>>>, readUtf8VectorFromUtf16Vector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<std::optional<std::string>>>, readUtf8VectorFromUtf16Vector),
+ PARCEL_READ_WITH_STATUS(std::vector<std::string>, readUtf8VectorFromUtf16Vector),
[] (const android::Parcel& p, uint8_t /*len*/) {
FUZZ_LOG() << "about to read flattenable";
@@ -235,8 +235,12 @@
FUZZ_LOG() << "read lite flattenable: " << status;
},
- // TODO(b/131868573): can force read of arbitrarily sized vector
- // TODO: resizeOutVector
+ PARCEL_READ_WITH_STATUS(std::vector<uint8_t>, resizeOutVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<uint8_t>>, resizeOutVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<uint8_t>>, resizeOutVector),
+ PARCEL_READ_WITH_STATUS(std::vector<BigStruct>, resizeOutVector),
+ PARCEL_READ_WITH_STATUS(std::optional<std::vector<BigStruct>>, resizeOutVector),
+ PARCEL_READ_WITH_STATUS(std::unique_ptr<std::vector<BigStruct>>, resizeOutVector),
PARCEL_READ_NO_STATUS(int32_t, readExceptionCode),
[] (const android::Parcel& p, uint8_t /*len*/) {
@@ -254,10 +258,9 @@
PARCEL_READ_NO_STATUS(int, readParcelFileDescriptor),
PARCEL_READ_WITH_STATUS(android::base::unique_fd, readUniqueFileDescriptor),
- // TODO(b/131868573): can force read of arbitrarily sized vector
- // 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<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),
[] (const android::Parcel& p, uint8_t len) {
FUZZ_LOG() << "about to readBlob";
diff --git a/libs/binder/tests/parcel_fuzzer/binder_ndk.cpp b/libs/binder/tests/parcel_fuzzer/binder_ndk.cpp
index 008780c..6b783a4 100644
--- a/libs/binder/tests/parcel_fuzzer/binder_ndk.cpp
+++ b/libs/binder/tests/parcel_fuzzer/binder_ndk.cpp
@@ -91,28 +91,27 @@
PARCEL_READ(ndk::ScopedFileDescriptor, ndk::AParcel_readRequiredParcelFileDescriptor),
PARCEL_READ(std::string, ndk::AParcel_readString),
PARCEL_READ(std::optional<std::string>, ndk::AParcel_readString),
- // TODO(b/131868573): can force process to allocate arbitrary amount of
- // memory
- // PARCEL_READ(std::vector<std::string>, ndk::AParcel_readVector),
- // PARCEL_READ(std::optional<std::vector<std::optional<std::string>>>,
- // ndk::AParcel_readVector), PARCEL_READ(std::vector<SomeParcelable>,
- // ndk::AParcel_readVector), PARCEL_READ(std::vector<int32_t>, ndk::AParcel_readVector),
- // PARCEL_READ(std::optional<std::vector<int32_t>>, ndk::AParcel_readVector),
- // PARCEL_READ(std::vector<uint32_t>, ndk::AParcel_readVector),
- // PARCEL_READ(std::optional<std::vector<uint32_t>>, ndk::AParcel_readVector),
- // PARCEL_READ(std::vector<int64_t>, ndk::AParcel_readVector),
- // PARCEL_READ(std::optional<std::vector<int64_t>>, ndk::AParcel_readVector),
- // PARCEL_READ(std::vector<uint64_t>, ndk::AParcel_readVector),
- // PARCEL_READ(std::optional<std::vector<uint64_t>>, ndk::AParcel_readVector),
- // PARCEL_READ(std::vector<float>, ndk::AParcel_readVector),
- // PARCEL_READ(std::optional<std::vector<float>>, ndk::AParcel_readVector),
- // PARCEL_READ(std::vector<double>, ndk::AParcel_readVector),
- // PARCEL_READ(std::optional<std::vector<double>>, ndk::AParcel_readVector),
- // PARCEL_READ(std::vector<bool>, ndk::AParcel_readVector),
- // PARCEL_READ(std::optional<std::vector<bool>>, ndk::AParcel_readVector),
- // PARCEL_READ(std::vector<char16_t>, ndk::AParcel_readVector),
- // PARCEL_READ(std::optional<std::vector<char16_t>>, ndk::AParcel_readVector),
- // PARCEL_READ(std::vector<int32_t>, ndk::AParcel_resizeVector),
- // PARCEL_READ(std::optional<std::vector<int32_t>>, ndk::AParcel_resizeVector),
+
+ PARCEL_READ(std::vector<std::string>, ndk::AParcel_readVector),
+ PARCEL_READ(std::optional<std::vector<std::optional<std::string>>>, ndk::AParcel_readVector),
+ PARCEL_READ(std::vector<SomeParcelable>, ndk::AParcel_readVector),
+ PARCEL_READ(std::vector<int32_t>, ndk::AParcel_readVector),
+ PARCEL_READ(std::optional<std::vector<int32_t>>, ndk::AParcel_readVector),
+ PARCEL_READ(std::vector<uint32_t>, ndk::AParcel_readVector),
+ PARCEL_READ(std::optional<std::vector<uint32_t>>, ndk::AParcel_readVector),
+ PARCEL_READ(std::vector<int64_t>, ndk::AParcel_readVector),
+ PARCEL_READ(std::optional<std::vector<int64_t>>, ndk::AParcel_readVector),
+ PARCEL_READ(std::vector<uint64_t>, ndk::AParcel_readVector),
+ PARCEL_READ(std::optional<std::vector<uint64_t>>, ndk::AParcel_readVector),
+ PARCEL_READ(std::vector<float>, ndk::AParcel_readVector),
+ PARCEL_READ(std::optional<std::vector<float>>, ndk::AParcel_readVector),
+ PARCEL_READ(std::vector<double>, ndk::AParcel_readVector),
+ PARCEL_READ(std::optional<std::vector<double>>, ndk::AParcel_readVector),
+ PARCEL_READ(std::vector<bool>, ndk::AParcel_readVector),
+ PARCEL_READ(std::optional<std::vector<bool>>, ndk::AParcel_readVector),
+ PARCEL_READ(std::vector<char16_t>, ndk::AParcel_readVector),
+ PARCEL_READ(std::optional<std::vector<char16_t>>, ndk::AParcel_readVector),
+ PARCEL_READ(std::vector<int32_t>, ndk::AParcel_resizeVector),
+ PARCEL_READ(std::optional<std::vector<int32_t>>, ndk::AParcel_resizeVector),
};
// clang-format on
diff --git a/libs/binder/tests/parcel_fuzzer/main.cpp b/libs/binder/tests/parcel_fuzzer/main.cpp
index a47b753..f426fd3 100644
--- a/libs/binder/tests/parcel_fuzzer/main.cpp
+++ b/libs/binder/tests/parcel_fuzzer/main.cpp
@@ -95,25 +95,7 @@
}
}
-size_t getHardMemoryLimit() {
- struct rlimit limit;
- CHECK(0 == getrlimit(RLIMIT_AS, &limit)) << errno;
- return limit.rlim_max;
-}
-
-void setMemoryLimit(size_t cur, size_t max) {
- const struct rlimit kLimit = {
- .rlim_cur = cur,
- .rlim_max = max,
- };
- CHECK(0 == setrlimit(RLIMIT_AS, &kLimit)) << errno;
-}
-
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
- static constexpr size_t kMemLimit = 1 * 1024 * 1024;
- size_t hardLimit = getHardMemoryLimit();
- setMemoryLimit(std::min(kMemLimit, hardLimit), hardLimit);
-
if (size <= 1) return 0; // no use
// avoid timeouts, see b/142617274, b/142473153
@@ -138,7 +120,5 @@
provider.PickValueInArray(fuzzBackend)(std::move(provider));
- setMemoryLimit(hardLimit, hardLimit);
-
return 0;
}
diff --git a/libs/binder/tests/rpc_fuzzer/Android.bp b/libs/binder/tests/rpc_fuzzer/Android.bp
new file mode 100644
index 0000000..1c75306
--- /dev/null
+++ b/libs/binder/tests/rpc_fuzzer/Android.bp
@@ -0,0 +1,40 @@
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "frameworks_native_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["frameworks_native_license"],
+}
+
+cc_fuzz {
+ name: "binder_rpc_fuzzer",
+ host_supported: true,
+
+ fuzz_config: {
+ cc: ["smoreland@google.com"],
+ },
+
+ srcs: [
+ "main.cpp",
+ ],
+ static_libs: [
+ "libbase",
+ "libcutils",
+ "liblog",
+ "libutils",
+ ],
+
+ target: {
+ android: {
+ shared_libs: [
+ "libbinder",
+ ],
+ },
+ host: {
+ static_libs: [
+ "libbinder",
+ ],
+ },
+ },
+}
diff --git a/libs/binder/tests/rpc_fuzzer/main.cpp b/libs/binder/tests/rpc_fuzzer/main.cpp
new file mode 100644
index 0000000..8a12aea
--- /dev/null
+++ b/libs/binder/tests/rpc_fuzzer/main.cpp
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2021 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include <android-base/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>
+#include <binder/RpcSession.h>
+
+#include <sys/resource.h>
+#include <sys/un.h>
+
+namespace android {
+
+static const std::string kSock = std::string(getenv("TMPDIR") ?: "/tmp") +
+ "/binderRpcFuzzerSocket_" + std::to_string(getpid());
+
+class SomeBinder : public BBinder {
+ status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags = 0) {
+ (void)flags;
+
+ if ((code & 1) == 0) {
+ sp<IBinder> binder;
+ (void)data.readStrongBinder(&binder);
+ if (binder != nullptr) {
+ (void)binder->pingBinder();
+ }
+ }
+ if ((code & 2) == 0) {
+ (void)data.readInt32();
+ }
+ if ((code & 4) == 0) {
+ (void)reply->writeStrongBinder(sp<BBinder>::make());
+ }
+
+ return OK;
+ }
+};
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ if (size > 50000) return 0;
+
+ unlink(kSock.c_str());
+
+ sp<RpcServer> server = RpcServer::make();
+ server->setRootObject(sp<SomeBinder>::make());
+ server->iUnderstandThisCodeIsExperimentalAndIWillNotUseItInProduction();
+ CHECK(server->setupUnixDomainServer(kSock.c_str()));
+
+ std::thread serverThread([=] { (void)server->acceptOne(); });
+
+ sockaddr_un addr{
+ .sun_family = AF_UNIX,
+ };
+ CHECK_LT(kSock.size(), sizeof(addr.sun_path));
+ memcpy(&addr.sun_path, kSock.c_str(), kSock.size());
+
+ base::unique_fd clientFd(TEMP_FAILURE_RETRY(socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0)));
+ CHECK_NE(clientFd.get(), -1);
+ CHECK_EQ(0,
+ TEMP_FAILURE_RETRY(
+ connect(clientFd.get(), reinterpret_cast<sockaddr*>(&addr), sizeof(addr))))
+ << strerror(errno);
+
+ serverThread.join();
+
+ // TODO(b/182938024): fuzz multiple sessions, instead of just one
+
+#if 0
+ // make fuzzer more productive locally by forcing it to create a new session
+ int32_t id = -1;
+ CHECK(base::WriteFully(clientFd, &id, sizeof(id)));
+#endif
+
+ CHECK(base::WriteFully(clientFd, data, size));
+
+ clientFd.reset();
+
+ // TODO(b/185167543): better way to force a server to shutdown
+ while (!server->listSessions().empty() && server->numUninitializedSessions()) {
+ usleep(1);
+ }
+
+ return 0;
+}
+
+} // namespace android
diff --git a/libs/binder/vm_sockets.h b/libs/binder/vm_sockets.h
new file mode 100644
index 0000000..7d9732b
--- /dev/null
+++ b/libs/binder/vm_sockets.h
@@ -0,0 +1,54 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ *** This header was automatically generated from a Linux kernel header
+ *** of the same name, to make information necessary for userspace to
+ *** call into the kernel available to libc. It contains only constants,
+ *** structures, and macros generated from the original header, and thus,
+ *** contains no copyrightable information.
+ ***
+ *** Copied and modified from bionic/libc/kernel/uapi/linux/vm_sockets.h
+ ***
+ ****************************************************************************
+ ****************************************************************************/
+#pragma once
+
+#ifdef __BIONIC__
+#include <linux/vm_sockets.h>
+#else
+
+#ifndef _UAPI_VM_SOCKETS_H
+#define _UAPI_VM_SOCKETS_H
+#define SO_VM_SOCKETS_BUFFER_SIZE 0
+#define SO_VM_SOCKETS_BUFFER_MIN_SIZE 1
+#define SO_VM_SOCKETS_BUFFER_MAX_SIZE 2
+#define SO_VM_SOCKETS_PEER_HOST_VM_ID 3
+#define SO_VM_SOCKETS_TRUSTED 5
+#define SO_VM_SOCKETS_CONNECT_TIMEOUT 6
+#define SO_VM_SOCKETS_NONBLOCK_TXRX 7
+#define VMADDR_CID_ANY (-1U)
+#define VMADDR_PORT_ANY (-1U)
+#define VMADDR_CID_HYPERVISOR 0
+#define VMADDR_CID_LOCAL 1
+#define VMADDR_CID_HOST 2
+#define VM_SOCKETS_INVALID_VERSION (-1U)
+#define VM_SOCKETS_VERSION_EPOCH(_v) (((_v)&0xFF000000) >> 24)
+#define VM_SOCKETS_VERSION_MAJOR(_v) (((_v)&0x00FF0000) >> 16)
+#define VM_SOCKETS_VERSION_MINOR(_v) (((_v)&0x0000FFFF))
+struct sockaddr_vm {
+ sa_family_t svm_family;
+ // NOLINTNEXTLINE(google-runtime-int)
+ unsigned short svm_reserved1;
+ unsigned int svm_port;
+ unsigned int svm_cid;
+ // NOLINTNEXTLINE(google-runtime-int)
+ unsigned char svm_zero[sizeof(struct sockaddr) - sizeof(sa_family_t) - sizeof(unsigned short) -
+ sizeof(unsigned int) - sizeof(unsigned int)];
+};
+#define IOCTL_VM_SOCKETS_GET_LOCAL_CID _IO(7, 0xb9)
+#ifndef AF_VSOCK
+#define AF_VSOCK 40
+#endif
+#endif
+
+#endif
diff --git a/services/surfaceflinger/BufferStateLayer.cpp b/services/surfaceflinger/BufferStateLayer.cpp
index 41dd7bf..d94347a 100644
--- a/services/surfaceflinger/BufferStateLayer.cpp
+++ b/services/surfaceflinger/BufferStateLayer.cpp
@@ -66,10 +66,70 @@
}
}
+status_t BufferStateLayer::addReleaseFence(const sp<CallbackHandle>& ch,
+ const sp<Fence>& fence) {
+ if (ch == nullptr) {
+ return OK;
+ }
+ if (!ch->previousReleaseFence.get()) {
+ ch->previousReleaseFence = fence;
+ return OK;
+ }
+
+ // Below logic is lifted from ConsumerBase.cpp:
+ // Check status of fences first because merging is expensive.
+ // Merging an invalid fence with any other fence results in an
+ // invalid fence.
+ auto currentStatus = ch->previousReleaseFence->getStatus();
+ if (currentStatus == Fence::Status::Invalid) {
+ ALOGE("Existing fence has invalid state, layer: %s", mName.c_str());
+ return BAD_VALUE;
+ }
+
+ auto incomingStatus = fence->getStatus();
+ if (incomingStatus == Fence::Status::Invalid) {
+ ALOGE("New fence has invalid state, layer: %s", mName.c_str());
+ ch->previousReleaseFence = fence;
+ return BAD_VALUE;
+ }
+
+ // If both fences are signaled or both are unsignaled, we need to merge
+ // them to get an accurate timestamp.
+ if (currentStatus == incomingStatus) {
+ char fenceName[32] = {};
+ snprintf(fenceName, 32, "%.28s", mName.c_str());
+ sp<Fence> mergedFence = Fence::merge(
+ fenceName, ch->previousReleaseFence, fence);
+ if (!mergedFence.get()) {
+ ALOGE("failed to merge release fences, layer: %s", mName.c_str());
+ // synchronization is broken, the best we can do is hope fences
+ // signal in order so the new fence will act like a union
+ ch->previousReleaseFence = fence;
+ return BAD_VALUE;
+ }
+ ch->previousReleaseFence = mergedFence;
+ } else if (incomingStatus == Fence::Status::Unsignaled) {
+ // If one fence has signaled and the other hasn't, the unsignaled
+ // fence will approximately correspond with the correct timestamp.
+ // There's a small race if both fences signal at about the same time
+ // and their statuses are retrieved with unfortunate timing. However,
+ // by this point, they will have both signaled and only the timestamp
+ // will be slightly off; any dependencies after this point will
+ // already have been met.
+ ch->previousReleaseFence = fence;
+ }
+ // else if (currentStatus == Fence::Status::Unsignaled) is a no-op.
+
+ return OK;
+}
+
// -----------------------------------------------------------------------
// Interface implementation for Layer
// -----------------------------------------------------------------------
void BufferStateLayer::onLayerDisplayed(const sp<Fence>& releaseFence) {
+ if (!releaseFence->isValid()) {
+ return;
+ }
// The previous release fence notifies the client that SurfaceFlinger is done with the previous
// buffer that was presented on this layer. The first transaction that came in this frame that
// replaced the previous buffer on this layer needs this release fence, because the fence will
@@ -86,12 +146,17 @@
// buffer. It replaces the buffer in the second transaction. The buffer in the second
// transaction will now no longer be presented so it is released immediately and the third
// transaction doesn't need a previous release fence.
+ sp<CallbackHandle> ch;
for (auto& handle : mDrawingState.callbackHandles) {
if (handle->releasePreviousBuffer) {
- handle->previousReleaseFence = releaseFence;
+ ch = handle;
break;
}
}
+ auto status = addReleaseFence(ch, releaseFence);
+ if (status != OK) {
+ ALOGE("Failed to add release fence for layer %s", getName().c_str());
+ }
mPreviousReleaseFence = releaseFence;
diff --git a/services/surfaceflinger/BufferStateLayer.h b/services/surfaceflinger/BufferStateLayer.h
index 00fa7f7..2430c4e 100644
--- a/services/surfaceflinger/BufferStateLayer.h
+++ b/services/surfaceflinger/BufferStateLayer.h
@@ -120,6 +120,8 @@
bool updateFrameEventHistory(const sp<Fence>& acquireFence, nsecs_t postedTime,
nsecs_t requestedPresentTime);
+ status_t addReleaseFence(const sp<CallbackHandle>& ch, const sp<Fence>& releaseFence);
+
uint64_t getFrameNumber(nsecs_t expectedPresentTime) const override;
bool getAutoRefresh() const override;