diff options
116 files changed, 2095 insertions, 1186 deletions
diff --git a/cmds/cmd/Android.bp b/cmds/cmd/Android.bp index 27ef78854c..cf27e1974a 100644 --- a/cmds/cmd/Android.bp +++ b/cmds/cmd/Android.bp @@ -27,14 +27,10 @@ cc_library_static { "libselinux", "libbinder", ], - whole_static_libs: [ - "libc++fs", - ], cflags: [ "-Wall", "-Werror", - "-DXP_UNIX", ], } @@ -58,6 +54,5 @@ cc_binary { cflags: [ "-Wall", "-Werror", - "-DXP_UNIX", ], } diff --git a/cmds/cmd/fuzzer/cmd_fuzzer.cpp b/cmds/cmd/fuzzer/cmd_fuzzer.cpp index ab514a1d04..72b295b866 100644 --- a/cmds/cmd/fuzzer/cmd_fuzzer.cpp +++ b/cmds/cmd/fuzzer/cmd_fuzzer.cpp @@ -58,6 +58,12 @@ void CmdFuzzer::process(const uint8_t* data, size_t size) { while (mFDP->remaining_bytes() > 0) { size_t sizestr = mFDP->ConsumeIntegralInRange<size_t>(1, mFDP->remaining_bytes()); string argument = mFDP->ConsumeBytesAsString(sizestr); + /** + * Filtering out strings based on "-w" argument. Since it leads to timeout. + */ + if(strcmp(argument.c_str(), "-w") == 0) { + continue; + } arguments.emplace_back(argument); } } diff --git a/cmds/dumpstate/DumpstateUtil.h b/cmds/dumpstate/DumpstateUtil.h index 9e955e3c04..ae7152a26a 100644 --- a/cmds/dumpstate/DumpstateUtil.h +++ b/cmds/dumpstate/DumpstateUtil.h @@ -18,6 +18,7 @@ #include <cstdint> #include <string> +#include <vector> /* * Converts seconds to milliseconds. diff --git a/cmds/dumpstate/TEST_MAPPING b/cmds/dumpstate/TEST_MAPPING index 649a13ee1e..a24546abb3 100644 --- a/cmds/dumpstate/TEST_MAPPING +++ b/cmds/dumpstate/TEST_MAPPING @@ -10,6 +10,14 @@ }, { "name": "dumpstate_test" + }, + { + "name": "CtsSecurityHostTestCases", + "options": [ + { + "include-filter": "android.security.cts.SELinuxHostTest#testNoBugreportDenials" + } + ] } ], "postsubmit": [ diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp index c501921399..5b817c1877 100644 --- a/cmds/dumpstate/dumpstate.cpp +++ b/cmds/dumpstate/dumpstate.cpp @@ -190,6 +190,7 @@ void add_mountinfo(); #define SDK_EXT_INFO "/apex/com.android.sdkext/bin/derive_sdk" #define DROPBOX_DIR "/data/system/dropbox" #define PRINT_FLAGS "/system/bin/printflags" +#define UWB_LOG_DIR "/data/misc/apexdata/com.android.uwb/log" // TODO(narayan): Since this information has to be kept in sync // with tombstoned, we should just put it in a common header. @@ -1963,6 +1964,9 @@ Dumpstate::RunStatus Dumpstate::DumpstateDefaultAfterCritical() { RunCommand("SDK EXTENSIONS", {SDK_EXT_INFO, "--dump"}, CommandOptions::WithTimeout(10).Always().DropRoot().Build()); + // Dump UWB UCI logs here because apexdata requires root access + ds.AddDir(UWB_LOG_DIR, true); + if (dump_pool_) { RETURN_IF_USER_DENIED_CONSENT(); WaitForTask(std::move(dump_traces)); @@ -2182,6 +2186,74 @@ static void DumpstateOnboardingOnly() { ds.AddDir(LOGPERSIST_DATA_DIR, false); } +static std::string GetTimestamp(const timespec& ts) { + tm tm; + localtime_r(&ts.tv_sec, &tm); + + // Reserve enough space for the entire time string, includes the space + // for the '\0' to make the calculations below easier by using size for + // the total string size. + std::string str(sizeof("1970-01-01 00:00:00.123456789+0830"), '\0'); + size_t n = strftime(str.data(), str.size(), "%F %H:%M", &tm); + if (n == 0) { + return "TIMESTAMP FAILURE"; + } + int num_chars = snprintf(&str[n], str.size() - n, ":%02d.%09ld", tm.tm_sec, ts.tv_nsec); + if (num_chars > str.size() - n) { + return "TIMESTAMP FAILURE"; + } + n += static_cast<size_t>(num_chars); + if (strftime(&str[n], str.size() - n, "%z", &tm) == 0) { + return "TIMESTAMP FAILURE"; + } + return str; +} + +static std::string GetCmdline(pid_t pid) { + std::string cmdline; + if (!android::base::ReadFileToString(android::base::StringPrintf("/proc/%d/cmdline", pid), + &cmdline)) { + return "UNKNOWN"; + } + // There are '\0' terminators between arguments, convert them to spaces. + // But start by skipping all trailing '\0' values. + size_t cur = cmdline.size() - 1; + while (cur != 0 && cmdline[cur] == '\0') { + cur--; + } + if (cur == 0) { + return "UNKNOWN"; + } + while ((cur = cmdline.rfind('\0', cur)) != std::string::npos) { + cmdline[cur] = ' '; + } + return cmdline; +} + +static void DumpPidHeader(int fd, pid_t pid, const timespec& ts) { + // For consistency, the header to this message matches the one + // dumped by debuggerd. + dprintf(fd, "\n----- pid %d at %s -----\n", pid, GetTimestamp(ts).c_str()); + dprintf(fd, "Cmd line: %s\n", GetCmdline(pid).c_str()); +} + +static void DumpPidFooter(int fd, pid_t pid) { + // For consistency, the footer to this message matches the one + // dumped by debuggerd. + dprintf(fd, "----- end %d -----\n", pid); +} + +static bool DumpBacktrace(int fd, pid_t pid, bool is_java_process) { + int ret = dump_backtrace_to_file_timeout( + pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace, 3, fd); + if (ret == -1 && is_java_process) { + // Tried to unwind as a java process, try a native unwind. + dprintf(fd, "Java unwind failed for pid %d, trying a native unwind.\n", pid); + ret = dump_backtrace_to_file_timeout(pid, kDebuggerdNativeBacktrace, 3, fd); + } + return ret != -1; +} + Dumpstate::RunStatus Dumpstate::DumpTraces(const char** path) { const std::string temp_file_pattern = ds.bugreport_internal_dir_ + "/dumptrace_XXXXXX"; const size_t buf_size = temp_file_pattern.length() + 1; @@ -2230,16 +2302,6 @@ Dumpstate::RunStatus Dumpstate::DumpTraces(const char** path) { continue; } - // Skip cached processes. - if (IsCached(pid)) { - // For consistency, the header and footer to this message match those - // dumped by debuggerd in the success case. - dprintf(fd, "\n---- pid %d at [unknown] ----\n", pid); - dprintf(fd, "Dump skipped for cached process.\n"); - dprintf(fd, "---- end %d ----", pid); - continue; - } - const std::string link_name = android::base::StringPrintf("/proc/%d/exe", pid); std::string exe; if (!android::base::Readlink(link_name, &exe)) { @@ -2268,16 +2330,31 @@ Dumpstate::RunStatus Dumpstate::DumpTraces(const char** path) { break; } + timespec start_timespec; + clock_gettime(CLOCK_REALTIME, &start_timespec); + if (IsCached(pid)) { + DumpPidHeader(fd, pid, start_timespec); + dprintf(fd, "Process is cached, skipping backtrace due to high chance of timeout.\n"); + DumpPidFooter(fd, pid); + continue; + } + const uint64_t start = Nanotime(); - const int ret = dump_backtrace_to_file_timeout( - pid, is_java_process ? kDebuggerdJavaBacktrace : kDebuggerdNativeBacktrace, 3, fd); + if (!DumpBacktrace(fd, pid, is_java_process)) { + if (IsCached(pid)) { + DumpPidHeader(fd, pid, start_timespec); + dprintf(fd, "Backtrace failed, but process has become cached.\n"); + DumpPidFooter(fd, pid); + continue; + } - if (ret == -1) { - // For consistency, the header and footer to this message match those - // dumped by debuggerd in the success case. - dprintf(fd, "\n---- pid %d at [unknown] ----\n", pid); - dprintf(fd, "Dump failed, likely due to a timeout.\n"); - dprintf(fd, "---- end %d ----", pid); + DumpPidHeader(fd, pid, start_timespec); + dprintf(fd, "Backtrace gathering failed, likely due to a timeout.\n"); + DumpPidFooter(fd, pid); + + dprintf(fd, "\n[dump %s stack %d: %.3fs elapsed]\n", + is_java_process ? "dalvik" : "native", pid, + (float)(Nanotime() - start) / NANOS_PER_SEC); timeout_failures++; continue; } diff --git a/cmds/installd/file_parsing.h b/cmds/installd/file_parsing.h index 88801ca671..0ec5abbd15 100644 --- a/cmds/installd/file_parsing.h +++ b/cmds/installd/file_parsing.h @@ -51,7 +51,7 @@ bool ParseFile(std::istream& input_stream, Func parse) { } template<typename Func> -bool ParseFile(std::string_view str_file, Func parse) { +bool ParseFile(const std::string& str_file, Func parse) { std::ifstream ifs(str_file); if (!ifs.is_open()) { return false; diff --git a/cmds/installd/otapreopt_script.sh b/cmds/installd/otapreopt_script.sh index ae7d8e04d4..2d889fd80d 100644 --- a/cmds/installd/otapreopt_script.sh +++ b/cmds/installd/otapreopt_script.sh @@ -50,7 +50,27 @@ else exit 1 fi -if pm art on-ota-staged --slot "$TARGET_SLOT_SUFFIX"; then +# A source that infinitely emits arbitrary lines. +# When connected to STDIN of another process, this source keeps STDIN open until +# the consumer process closes STDIN or this script dies. +function infinite_source { + while echo .; do + sleep 1 + done +} + +# Delegate to Pre-reboot Dexopt, a feature of ART Service. +# ART Service decides what to do with this request: +# - If Pre-reboot Dexopt is disabled or unsupported, the command returns +# non-zero. This is always the case if the current system is Android 14 or +# earlier. +# - If Pre-reboot Dexopt is enabled in synchronous mode, the command blocks +# until Pre-reboot Dexopt finishes, and returns zero no matter it succeeds or +# not. This is the default behavior if the current system is Android 15. +# - If Pre-reboot Dexopt is enabled in asynchronous mode, the command schedules +# an asynchronous job and returns 0 immediately. The job will then run by the +# job scheduler when the device is idle and charging. +if infinite_source | pm art on-ota-staged --slot "$TARGET_SLOT_SUFFIX"; then # Handled by Pre-reboot Dexopt. exit 0 fi diff --git a/cmds/installd/tests/Android.bp b/cmds/installd/tests/Android.bp index 61fe316225..f3e024c5dc 100644 --- a/cmds/installd/tests/Android.bp +++ b/cmds/installd/tests/Android.bp @@ -102,7 +102,6 @@ cc_defaults { "libziparchive", "liblog", "liblogwrap", - "libc++fs", ], product_variables: { arc: { diff --git a/cmds/service/Android.bp b/cmds/service/Android.bp index 21ac11b4cf..00fd249f56 100644 --- a/cmds/service/Android.bp +++ b/cmds/service/Android.bp @@ -27,7 +27,6 @@ cc_binary { ], cflags: [ - "-DXP_UNIX", "-Wall", "-Werror", ], @@ -46,7 +45,6 @@ cc_binary { ], cflags: [ - "-DXP_UNIX", "-DVENDORSERVICES", "-Wall", "-Werror", @@ -65,7 +63,6 @@ cc_binary_host { ], cflags: [ - "-DXP_UNIX", "-Wall", "-Werror", ], diff --git a/include/android/choreographer.h b/include/android/choreographer.h index f999708f04..6a91d9836e 100644 --- a/include/android/choreographer.h +++ b/include/android/choreographer.h @@ -17,8 +17,20 @@ /** * @addtogroup Choreographer * - * Choreographer coordinates the timing of frame rendering. This is the C version of the - * android.view.Choreographer object in Java. + * Choreographer coordinates the timing of frame rendering. This is the C + * version of the android.view.Choreographer object in Java. If you do not use + * Choreographer to pace your render loop, you may render too quickly for the + * display, increasing latency between frame submission and presentation. + * + * Input events are guaranteed to be processed before the frame callback is + * called, and will not be run concurrently. Input and sensor events should not + * be handled in the Choregrapher callback. + * + * The frame callback is also the appropriate place to run any per-frame state + * update logic. For example, in a game, the frame callback should be + * responsible for updating things like physics, AI, game state, and rendering + * the frame. Input and sensors should be handled separately via callbacks + * registered with AInputQueue and ASensorManager. * * As of API level 33, apps can follow proper frame pacing and even choose a future frame to render. * The API is used as follows: @@ -38,6 +50,11 @@ * 4. SurfaceFlinger attempts to follow the chosen frame timeline, by not applying transactions or * latching buffers before the desired presentation time. * + * On older devices, AChoreographer_postFrameCallback64 or + * AChoreographer_postFrameCallback can be used to lesser effect. They cannot be + * used to precisely plan your render timeline, but will rate limit to avoid + * overloading the display pipeline and increasing frame latency. + * * @{ */ @@ -119,23 +136,60 @@ typedef void (*AChoreographer_refreshRateCallback)(int64_t vsyncPeriodNanos, voi AChoreographer* AChoreographer_getInstance() __INTRODUCED_IN(24); /** - * Deprecated: Use AChoreographer_postFrameCallback64 instead. + * Post a callback to be run when the application should begin rendering the + * next frame. The data pointer provided will be passed to the callback function + * when it's called. + * + * The callback will only be run for the next frame, not all subsequent frames, + * so to render continuously the callback should itself call + * AChoreographer_postFrameCallback. + * + * \bug The callback receives the frame time in nanoseconds as a long. On 32-bit + * systems, long is 32-bit, so the frame time will roll over roughly every two + * seconds. If your minSdkVersion is 29 or higher, switch to + * AChoreographer_postFrameCallback64, which uses a 64-bit frame time for all + * platforms. For older OS versions, you must combine the argument with the + * upper bits of clock_gettime(CLOCK_MONOTONIC, ...) on 32-bit systems. + * + * \deprecated Use AChoreographer_postFrameCallback64, which does not have the + * bug described above. */ void AChoreographer_postFrameCallback(AChoreographer* choreographer, AChoreographer_frameCallback callback, void* data) - __INTRODUCED_IN(24) __DEPRECATED_IN(29); + __INTRODUCED_IN(24) __DEPRECATED_IN(29, "Use AChoreographer_postFrameCallback64 instead"); /** - * Deprecated: Use AChoreographer_postFrameCallbackDelayed64 instead. + * Post a callback to be run when the application should begin rendering the + * next frame following the specified delay. The data pointer provided will be + * passed to the callback function when it's called. + * + * The callback will only be run for the next frame after the delay, not all + * subsequent frames, so to render continuously the callback should itself call + * AChoreographer_postFrameCallbackDelayed. + * + * \bug The callback receives the frame time in nanoseconds as a long. On 32-bit + * systems, long is 32-bit, so the frame time will roll over roughly every two + * seconds. If your minSdkVersion is 29 or higher, switch to + * AChoreographer_postFrameCallbackDelayed64, which uses a 64-bit frame time for + * all platforms. For older OS versions, you must combine the argument with the + * upper bits of clock_gettime(CLOCK_MONOTONIC, ...) on 32-bit systems. + * + * \deprecated Use AChoreographer_postFrameCallbackDelayed64, which does not + * have the bug described above. */ void AChoreographer_postFrameCallbackDelayed(AChoreographer* choreographer, AChoreographer_frameCallback callback, void* data, long delayMillis) __INTRODUCED_IN(24) - __DEPRECATED_IN(29); + __DEPRECATED_IN(29, "Use AChoreographer_postFrameCallbackDelayed64 instead"); /** - * Post a callback to be run on the next frame. The data pointer provided will - * be passed to the callback function when it's called. + * Post a callback to be run when the application should begin rendering the + * next frame. The data pointer provided will be passed to the callback function + * when it's called. + * + * The callback will only be run on the next frame, not all subsequent frames, + * so to render continuously the callback should itself call + * AChoreographer_postFrameCallback64. * * Available since API level 29. */ @@ -144,9 +198,13 @@ void AChoreographer_postFrameCallback64(AChoreographer* choreographer, __INTRODUCED_IN(29); /** - * Post a callback to be run on the frame following the specified delay. The - * data pointer provided will be passed to the callback function when it's - * called. + * Post a callback to be run when the application should begin rendering the + * next frame following the specified delay. The data pointer provided will be + * passed to the callback function when it's called. + * + * The callback will only be run for the next frame after the delay, not all + * subsequent frames, so to render continuously the callback should itself call + * AChoreographer_postFrameCallbackDelayed64. * * Available since API level 29. */ @@ -155,8 +213,13 @@ void AChoreographer_postFrameCallbackDelayed64(AChoreographer* choreographer, uint32_t delayMillis) __INTRODUCED_IN(29); /** - * Posts a callback to be run on the next frame. The data pointer provided will - * be passed to the callback function when it's called. + * Posts a callback to be run when the application should begin rendering the + * next frame. The data pointer provided will be passed to the callback function + * when it's called. + * + * The callback will only be run for the next frame, not all subsequent frames, + * so to render continuously the callback should itself call + * AChoreographer_postVsyncCallback. * * Available since API level 33. */ diff --git a/include/android/looper.h b/include/android/looper.h index e50730d5c1..d80a3660a6 100644 --- a/include/android/looper.h +++ b/include/android/looper.h @@ -35,7 +35,7 @@ extern "C" { // This file may also be built on glibc or on Windows/MacOS libc's, so // deprecated definitions are provided. #if !defined(__REMOVED_IN) -#define __REMOVED_IN(__api_level) __attribute__((__deprecated__)) +#define __REMOVED_IN(__api_level, msg) __attribute__((__deprecated__(msg))) #endif struct ALooper; @@ -182,23 +182,27 @@ typedef int (*ALooper_callbackFunc)(int fd, int events, void* data); * If the timeout is zero, returns immediately without blocking. * If the timeout is negative, waits indefinitely until an event appears. * - * Returns ALOOPER_POLL_WAKE if the poll was awoken using wake() before + * Returns ALOOPER_POLL_WAKE if the poll was awoken using ALooper_wake() before * the timeout expired and no callbacks were invoked and no other file - * descriptors were ready. + * descriptors were ready. **All return values may also imply + * ALOOPER_POLL_WAKE.** * - * Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked. + * Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked. The poll + * may also have been explicitly woken by ALooper_wake. * - * Returns ALOOPER_POLL_TIMEOUT if there was no data before the given - * timeout expired. + * Returns ALOOPER_POLL_TIMEOUT if there was no data before the given timeout + * expired. The poll may also have been explicitly woken by ALooper_wake. * - * Returns ALOOPER_POLL_ERROR if an error occurred. + * Returns ALOOPER_POLL_ERROR if the calling thread has no associated Looper or + * for unrecoverable internal errors. The poll may also have been explicitly + * woken by ALooper_wake. * - * Returns a value >= 0 containing an identifier (the same identifier - * `ident` passed to ALooper_addFd()) if its file descriptor has data - * and it has no callback function (requiring the caller here to - * handle it). In this (and only this) case outFd, outEvents and - * outData will contain the poll events and data associated with the - * fd, otherwise they will be set to NULL. + * Returns a value >= 0 containing an identifier (the same identifier `ident` + * passed to ALooper_addFd()) if its file descriptor has data and it has no + * callback function (requiring the caller here to handle it). In this (and + * only this) case outFd, outEvents and outData will contain the poll events and + * data associated with the fd, otherwise they will be set to NULL. The poll may + * also have been explicitly woken by ALooper_wake. * * This method does not return until it has finished invoking the appropriate callbacks * for all file descriptors that were signalled. @@ -210,10 +214,21 @@ int ALooper_pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outDa * data has been consumed or a file descriptor is available with no callback. * This function will never return ALOOPER_POLL_CALLBACK. * - * Removed in API 34 as ALooper_pollAll can swallow ALooper_wake calls. - * Use ALooper_pollOnce instead. + * This API cannot be used safely, but a safe alternative exists (see below). As + * such, new builds will not be able to call this API and must migrate to the + * safe API. Binary compatibility is preserved to support already-compiled apps. + * + * \bug ALooper_pollAll will not wake in response to ALooper_wake calls if it + * also handles another event at the same time. + * + * \deprecated Calls to ALooper_pollAll should be replaced with + * ALooper_pollOnce. If you call ALooper_pollOnce in a loop, you *must* treat + * all return values as if they also indicate ALOOPER_POLL_WAKE. */ -int ALooper_pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) __REMOVED_IN(1); +int ALooper_pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData) + __REMOVED_IN(1, + "ALooper_pollAll may ignore wakes. Use ALooper_pollOnce instead. See " + "The API documentation for more information"); /** * Wakes the poll asynchronously. diff --git a/include/android/sensor.h b/include/android/sensor.h index a618393e66..e3c1ccfc6c 100644 --- a/include/android/sensor.h +++ b/include/android/sensor.h @@ -60,7 +60,7 @@ #define __INTRODUCED_IN(__api_level) /* nothing */ #endif #if !defined(__DEPRECATED_IN) -#define __DEPRECATED_IN(__api_level) __attribute__((__deprecated__)) +#define __DEPRECATED_IN(__api_level, msg) __attribute__((__deprecated__(msg))) #endif #ifdef __cplusplus @@ -748,7 +748,8 @@ typedef ASensorRef const* ASensorList; * ASensorManager* sensorManager = ASensorManager_getInstance(); * */ -ASensorManager* ASensorManager_getInstance() __DEPRECATED_IN(26); +ASensorManager* ASensorManager_getInstance() + __DEPRECATED_IN(26, "Use ASensorManager_getInstanceForPackage instead"); /** * Get a reference to the sensor manager. ASensorManager is a singleton diff --git a/include/android/surface_control.h b/include/android/surface_control.h index 443cb7e51f..14167e6467 100644 --- a/include/android/surface_control.h +++ b/include/android/surface_control.h @@ -62,16 +62,18 @@ typedef struct ASurfaceControl ASurfaceControl; * * Available since API level 29. */ -ASurfaceControl* ASurfaceControl_createFromWindow(ANativeWindow* parent, const char* debug_name) - __INTRODUCED_IN(29); +ASurfaceControl* _Nullable ASurfaceControl_createFromWindow(ANativeWindow* _Nonnull parent, + const char* _Nonnull debug_name) + __INTRODUCED_IN(29); /** * See ASurfaceControl_createFromWindow. * * Available since API level 29. */ -ASurfaceControl* ASurfaceControl_create(ASurfaceControl* parent, const char* debug_name) - __INTRODUCED_IN(29); +ASurfaceControl* _Nullable ASurfaceControl_create(ASurfaceControl* _Nonnull parent, + const char* _Nonnull debug_name) + __INTRODUCED_IN(29); /** * Acquires a reference on the given ASurfaceControl object. This prevents the object @@ -81,7 +83,7 @@ ASurfaceControl* ASurfaceControl_create(ASurfaceControl* parent, const char* deb * * Available since API level 31. */ -void ASurfaceControl_acquire(ASurfaceControl* surface_control) __INTRODUCED_IN(31); +void ASurfaceControl_acquire(ASurfaceControl* _Nonnull surface_control) __INTRODUCED_IN(31); /** * Removes a reference that was previously acquired with one of the following functions: @@ -92,7 +94,7 @@ void ASurfaceControl_acquire(ASurfaceControl* surface_control) __INTRODUCED_IN(3 * * Available since API level 29. */ -void ASurfaceControl_release(ASurfaceControl* surface_control) __INTRODUCED_IN(29); +void ASurfaceControl_release(ASurfaceControl* _Nonnull surface_control) __INTRODUCED_IN(29); struct ASurfaceTransaction; @@ -108,14 +110,14 @@ typedef struct ASurfaceTransaction ASurfaceTransaction; * * Available since API level 29. */ -ASurfaceTransaction* ASurfaceTransaction_create() __INTRODUCED_IN(29); +ASurfaceTransaction* _Nonnull ASurfaceTransaction_create() __INTRODUCED_IN(29); /** * Destroys the \a transaction object. * * Available since API level 29. */ -void ASurfaceTransaction_delete(ASurfaceTransaction* transaction) __INTRODUCED_IN(29); +void ASurfaceTransaction_delete(ASurfaceTransaction* _Nullable transaction) __INTRODUCED_IN(29); /** * Applies the updates accumulated in \a transaction. @@ -126,7 +128,7 @@ void ASurfaceTransaction_delete(ASurfaceTransaction* transaction) __INTRODUCED_I * * Available since API level 29. */ -void ASurfaceTransaction_apply(ASurfaceTransaction* transaction) __INTRODUCED_IN(29); +void ASurfaceTransaction_apply(ASurfaceTransaction* _Nonnull transaction) __INTRODUCED_IN(29); /** * An opaque handle returned during a callback that can be used to query general stats and stats for @@ -154,9 +156,9 @@ typedef struct ASurfaceTransactionStats ASurfaceTransactionStats; * * Available since API level 29. */ -typedef void (*ASurfaceTransaction_OnComplete)(void* context, ASurfaceTransactionStats* stats) - __INTRODUCED_IN(29); - +typedef void (*ASurfaceTransaction_OnComplete)(void* _Null_unspecified context, + ASurfaceTransactionStats* _Nonnull stats) + __INTRODUCED_IN(29); /** * The ASurfaceTransaction_OnCommit callback is invoked when transaction is applied and the updates @@ -183,8 +185,9 @@ typedef void (*ASurfaceTransaction_OnComplete)(void* context, ASurfaceTransactio * * Available since API level 31. */ -typedef void (*ASurfaceTransaction_OnCommit)(void* context, ASurfaceTransactionStats* stats) - __INTRODUCED_IN(31); +typedef void (*ASurfaceTransaction_OnCommit)(void* _Null_unspecified context, + ASurfaceTransactionStats* _Nonnull stats) + __INTRODUCED_IN(31); /** * Returns the timestamp of when the frame was latched by the framework. Once a frame is @@ -192,8 +195,8 @@ typedef void (*ASurfaceTransaction_OnCommit)(void* context, ASurfaceTransactionS * * Available since API level 29. */ -int64_t ASurfaceTransactionStats_getLatchTime(ASurfaceTransactionStats* surface_transaction_stats) - __INTRODUCED_IN(29); +int64_t ASurfaceTransactionStats_getLatchTime( + ASurfaceTransactionStats* _Nonnull surface_transaction_stats) __INTRODUCED_IN(29); /** * Returns a sync fence that signals when the transaction has been presented. @@ -204,8 +207,8 @@ int64_t ASurfaceTransactionStats_getLatchTime(ASurfaceTransactionStats* surface_ * * Available since API level 29. */ -int ASurfaceTransactionStats_getPresentFenceFd(ASurfaceTransactionStats* surface_transaction_stats) - __INTRODUCED_IN(29); +int ASurfaceTransactionStats_getPresentFenceFd( + ASurfaceTransactionStats* _Nonnull surface_transaction_stats) __INTRODUCED_IN(29); /** * \a outASurfaceControls returns an array of ASurfaceControl pointers that were updated during the @@ -217,18 +220,18 @@ int ASurfaceTransactionStats_getPresentFenceFd(ASurfaceTransactionStats* surface * * \a outASurfaceControlsSize returns the size of the ASurfaceControls array. */ -void ASurfaceTransactionStats_getASurfaceControls(ASurfaceTransactionStats* surface_transaction_stats, - ASurfaceControl*** outASurfaceControls, - size_t* outASurfaceControlsSize) - __INTRODUCED_IN(29); +void ASurfaceTransactionStats_getASurfaceControls( + ASurfaceTransactionStats* _Nonnull surface_transaction_stats, + ASurfaceControl* _Nullable* _Nullable* _Nonnull outASurfaceControls, + size_t* _Nonnull outASurfaceControlsSize) __INTRODUCED_IN(29); /** * Releases the array of ASurfaceControls that were returned by * ASurfaceTransactionStats_getASurfaceControls(). * * Available since API level 29. */ -void ASurfaceTransactionStats_releaseASurfaceControls(ASurfaceControl** surface_controls) - __INTRODUCED_IN(29); +void ASurfaceTransactionStats_releaseASurfaceControls( + ASurfaceControl* _Nonnull* _Nonnull surface_controls) __INTRODUCED_IN(29); /** * Returns the timestamp of when the CURRENT buffer was acquired. A buffer is considered @@ -237,9 +240,9 @@ void ASurfaceTransactionStats_releaseASurfaceControls(ASurfaceControl** surface_ * * Available since API level 29. */ -int64_t ASurfaceTransactionStats_getAcquireTime(ASurfaceTransactionStats* surface_transaction_stats, - ASurfaceControl* surface_control) - __INTRODUCED_IN(29); +int64_t ASurfaceTransactionStats_getAcquireTime( + ASurfaceTransactionStats* _Nonnull surface_transaction_stats, + ASurfaceControl* _Nonnull surface_control) __INTRODUCED_IN(29); /** * The returns the fence used to signal the release of the PREVIOUS buffer set on @@ -264,9 +267,8 @@ int64_t ASurfaceTransactionStats_getAcquireTime(ASurfaceTransactionStats* surfac * Available since API level 29. */ int ASurfaceTransactionStats_getPreviousReleaseFenceFd( - ASurfaceTransactionStats* surface_transaction_stats, - ASurfaceControl* surface_control) - __INTRODUCED_IN(29); + ASurfaceTransactionStats* _Nonnull surface_transaction_stats, + ASurfaceControl* _Nonnull surface_control) __INTRODUCED_IN(29); /** * Sets the callback that will be invoked when the updates from this transaction @@ -275,8 +277,10 @@ int ASurfaceTransactionStats_getPreviousReleaseFenceFd( * * Available since API level 29. */ -void ASurfaceTransaction_setOnComplete(ASurfaceTransaction* transaction, void* context, - ASurfaceTransaction_OnComplete func) __INTRODUCED_IN(29); +void ASurfaceTransaction_setOnComplete(ASurfaceTransaction* _Nonnull transaction, + void* _Null_unspecified context, + ASurfaceTransaction_OnComplete _Nonnull func) + __INTRODUCED_IN(29); /** * Sets the callback that will be invoked when the updates from this transaction are applied and are @@ -285,8 +289,10 @@ void ASurfaceTransaction_setOnComplete(ASurfaceTransaction* transaction, void* c * * Available since API level 31. */ -void ASurfaceTransaction_setOnCommit(ASurfaceTransaction* transaction, void* context, - ASurfaceTransaction_OnCommit func) __INTRODUCED_IN(31); +void ASurfaceTransaction_setOnCommit(ASurfaceTransaction* _Nonnull transaction, + void* _Null_unspecified context, + ASurfaceTransaction_OnCommit _Nonnull func) + __INTRODUCED_IN(31); /** * Reparents the \a surface_control from its old parent to the \a new_parent surface control. @@ -296,9 +302,9 @@ void ASurfaceTransaction_setOnCommit(ASurfaceTransaction* transaction, void* con * * Available since API level 29. */ -void ASurfaceTransaction_reparent(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, ASurfaceControl* new_parent) - __INTRODUCED_IN(29); +void ASurfaceTransaction_reparent(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, + ASurfaceControl* _Nullable new_parent) __INTRODUCED_IN(29); /** * Parameter for ASurfaceTransaction_setVisibility(). @@ -314,10 +320,10 @@ enum ASurfaceTransactionVisibility : int8_t { * * Available since API level 29. */ -void ASurfaceTransaction_setVisibility(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, +void ASurfaceTransaction_setVisibility(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, enum ASurfaceTransactionVisibility visibility) - __INTRODUCED_IN(29); + __INTRODUCED_IN(29); /** * Updates the z order index for \a surface_control. Note that the z order for a surface @@ -328,9 +334,9 @@ void ASurfaceTransaction_setVisibility(ASurfaceTransaction* transaction, * * Available since API level 29. */ -void ASurfaceTransaction_setZOrder(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, int32_t z_order) - __INTRODUCED_IN(29); +void ASurfaceTransaction_setZOrder(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, int32_t z_order) + __INTRODUCED_IN(29); /** * Updates the AHardwareBuffer displayed for \a surface_control. If not -1, the @@ -345,9 +351,10 @@ void ASurfaceTransaction_setZOrder(ASurfaceTransaction* transaction, * * Available since API level 29. */ -void ASurfaceTransaction_setBuffer(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, AHardwareBuffer* buffer, - int acquire_fence_fd) __INTRODUCED_IN(29); +void ASurfaceTransaction_setBuffer(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, + AHardwareBuffer* _Nonnull buffer, int acquire_fence_fd) + __INTRODUCED_IN(29); /** * Updates the color for \a surface_control. This will make the background color for the @@ -357,23 +364,23 @@ void ASurfaceTransaction_setBuffer(ASurfaceTransaction* transaction, * * Available since API level 29. */ -void ASurfaceTransaction_setColor(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, float r, float g, float b, - float alpha, enum ADataSpace dataspace) - __INTRODUCED_IN(29); +void ASurfaceTransaction_setColor(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, float r, float g, + float b, float alpha, enum ADataSpace dataspace) + __INTRODUCED_IN(29); /** * \param source The sub-rect within the buffer's content to be rendered inside the surface's area * The surface's source rect is clipped by the bounds of its current buffer. The source rect's width * and height must be > 0. * - * \param destination Specifies the rect in the parent's space where this surface will be drawn. The post - * source rect bounds are scaled to fit the destination rect. The surface's destination rect is + * \param destination Specifies the rect in the parent's space where this surface will be drawn. The + * post source rect bounds are scaled to fit the destination rect. The surface's destination rect is * clipped by the bounds of its parent. The destination rect's width and height must be > 0. * - * \param transform The transform applied after the source rect is applied to the buffer. This parameter - * should be set to 0 for no transform. To specify a transfrom use the NATIVE_WINDOW_TRANSFORM_* - * enum. + * \param transform The transform applied after the source rect is applied to the buffer. This + * parameter should be set to 0 for no transform. To specify a transfrom use the + * NATIVE_WINDOW_TRANSFORM_* enum. * * Available since API level 29. * @@ -382,10 +389,10 @@ void ASurfaceTransaction_setColor(ASurfaceTransaction* transaction, * to set different properties at different times, instead of having to specify all the desired * properties at once. */ -void ASurfaceTransaction_setGeometry(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, const ARect& source, +void ASurfaceTransaction_setGeometry(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, const ARect& source, const ARect& destination, int32_t transform) - __INTRODUCED_IN(29); + __INTRODUCED_IN(29); /** * Bounds the surface and its children to the bounds specified. The crop and buffer size will be @@ -396,9 +403,9 @@ void ASurfaceTransaction_setGeometry(ASurfaceTransaction* transaction, * * Available since API level 31. */ -void ASurfaceTransaction_setCrop(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, const ARect& crop) - __INTRODUCED_IN(31); +void ASurfaceTransaction_setCrop(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, const ARect& crop) + __INTRODUCED_IN(31); /** * Specifies the position in the parent's space where the surface will be drawn. @@ -408,9 +415,9 @@ void ASurfaceTransaction_setCrop(ASurfaceTransaction* transaction, * * Available since API level 31. */ -void ASurfaceTransaction_setPosition(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, int32_t x, int32_t y) - __INTRODUCED_IN(31); +void ASurfaceTransaction_setPosition(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, int32_t x, + int32_t y) __INTRODUCED_IN(31); /** * \param transform The transform applied after the source rect is applied to the buffer. This @@ -419,9 +426,9 @@ void ASurfaceTransaction_setPosition(ASurfaceTransaction* transaction, * * Available since API level 31. */ -void ASurfaceTransaction_setBufferTransform(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, int32_t transform) - __INTRODUCED_IN(31); +void ASurfaceTransaction_setBufferTransform(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, + int32_t transform) __INTRODUCED_IN(31); /** * Sets an x and y scale of a surface with (0, 0) as the centerpoint of the scale. @@ -431,9 +438,9 @@ void ASurfaceTransaction_setBufferTransform(ASurfaceTransaction* transaction, * * Available since API level 31. */ -void ASurfaceTransaction_setScale(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, float xScale, float yScale) - __INTRODUCED_IN(31); +void ASurfaceTransaction_setScale(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, float xScale, + float yScale) __INTRODUCED_IN(31); /** * Parameter for ASurfaceTransaction_setBufferTransparency(). */ @@ -449,8 +456,8 @@ enum ASurfaceTransactionTransparency : int8_t { * * Available since API level 29. */ -void ASurfaceTransaction_setBufferTransparency(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, +void ASurfaceTransaction_setBufferTransparency(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, enum ASurfaceTransactionTransparency transparency) __INTRODUCED_IN(29); @@ -460,9 +467,10 @@ void ASurfaceTransaction_setBufferTransparency(ASurfaceTransaction* transaction, * * Available since API level 29. */ -void ASurfaceTransaction_setDamageRegion(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, const ARect rects[], - uint32_t count) __INTRODUCED_IN(29); +void ASurfaceTransaction_setDamageRegion(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, + const ARect* _Nullable rects, uint32_t count) + __INTRODUCED_IN(29); /** * Specifies a desiredPresentTime for the transaction. The framework will try to present @@ -476,7 +484,7 @@ void ASurfaceTransaction_setDamageRegion(ASurfaceTransaction* transaction, * * Available since API level 29. */ -void ASurfaceTransaction_setDesiredPresentTime(ASurfaceTransaction* transaction, +void ASurfaceTransaction_setDesiredPresentTime(ASurfaceTransaction* _Nonnull transaction, int64_t desiredPresentTime) __INTRODUCED_IN(29); /** @@ -486,8 +494,8 @@ void ASurfaceTransaction_setDesiredPresentTime(ASurfaceTransaction* transaction, * * Available since API level 29. */ -void ASurfaceTransaction_setBufferAlpha(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, float alpha) +void ASurfaceTransaction_setBufferAlpha(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, float alpha) __INTRODUCED_IN(29); /** @@ -497,9 +505,9 @@ void ASurfaceTransaction_setBufferAlpha(ASurfaceTransaction* transaction, * * Available since API level 29. */ -void ASurfaceTransaction_setBufferDataSpace(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, enum ADataSpace data_space) - __INTRODUCED_IN(29); +void ASurfaceTransaction_setBufferDataSpace(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, + enum ADataSpace data_space) __INTRODUCED_IN(29); /** * SMPTE ST 2086 "Mastering Display Color Volume" static metadata @@ -509,9 +517,9 @@ void ASurfaceTransaction_setBufferDataSpace(ASurfaceTransaction* transaction, * * Available since API level 29. */ -void ASurfaceTransaction_setHdrMetadata_smpte2086(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, - struct AHdrMetadata_smpte2086* metadata) +void ASurfaceTransaction_setHdrMetadata_smpte2086(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, + struct AHdrMetadata_smpte2086* _Nullable metadata) __INTRODUCED_IN(29); /** @@ -522,9 +530,9 @@ void ASurfaceTransaction_setHdrMetadata_smpte2086(ASurfaceTransaction* transacti * * Available since API level 29. */ -void ASurfaceTransaction_setHdrMetadata_cta861_3(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, - struct AHdrMetadata_cta861_3* metadata) +void ASurfaceTransaction_setHdrMetadata_cta861_3(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, + struct AHdrMetadata_cta861_3* _Nullable metadata) __INTRODUCED_IN(29); /** @@ -569,10 +577,10 @@ void ASurfaceTransaction_setHdrMetadata_cta861_3(ASurfaceTransaction* transactio * * Available since API level 34. */ -void ASurfaceTransaction_setExtendedRangeBrightness(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, - float currentBufferRatio, - float desiredRatio) __INTRODUCED_IN(__ANDROID_API_U__); +void ASurfaceTransaction_setExtendedRangeBrightness(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, + float currentBufferRatio, float desiredRatio) + __INTRODUCED_IN(__ANDROID_API_U__); /** * Same as ASurfaceTransaction_setFrameRateWithChangeStrategy(transaction, surface_control, @@ -582,8 +590,8 @@ void ASurfaceTransaction_setExtendedRangeBrightness(ASurfaceTransaction* transac * * Available since API level 30. */ -void ASurfaceTransaction_setFrameRate(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, float frameRate, +void ASurfaceTransaction_setFrameRate(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, float frameRate, int8_t compatibility) __INTRODUCED_IN(30); /** @@ -618,10 +626,11 @@ void ASurfaceTransaction_setFrameRate(ASurfaceTransaction* transaction, * * Available since API level 31. */ -void ASurfaceTransaction_setFrameRateWithChangeStrategy(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, float frameRate, - int8_t compatibility, int8_t changeFrameRateStrategy) - __INTRODUCED_IN(31); +void ASurfaceTransaction_setFrameRateWithChangeStrategy(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, + float frameRate, int8_t compatibility, + int8_t changeFrameRateStrategy) + __INTRODUCED_IN(31); /** * Clears the frame rate which is set for \a surface_control. @@ -644,8 +653,8 @@ void ASurfaceTransaction_setFrameRateWithChangeStrategy(ASurfaceTransaction* tra * * Available since API level 34. */ -void ASurfaceTransaction_clearFrameRate(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control) +void ASurfaceTransaction_clearFrameRate(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control) __INTRODUCED_IN(__ANDROID_API_U__); /** @@ -674,10 +683,9 @@ void ASurfaceTransaction_clearFrameRate(ASurfaceTransaction* transaction, * \param surface_control The ASurfaceControl on which to control buffer backpressure behavior. * \param enableBackPressure Whether to enable back pressure. */ -void ASurfaceTransaction_setEnableBackPressure(ASurfaceTransaction* transaction, - ASurfaceControl* surface_control, - bool enableBackPressure) - __INTRODUCED_IN(31); +void ASurfaceTransaction_setEnableBackPressure(ASurfaceTransaction* _Nonnull transaction, + ASurfaceControl* _Nonnull surface_control, + bool enableBackPressure) __INTRODUCED_IN(31); /** * Sets the frame timeline to use in SurfaceFlinger. @@ -697,7 +705,7 @@ void ASurfaceTransaction_setEnableBackPressure(ASurfaceTransaction* transaction, * to the corresponding expected presentation time and deadline from the frame to be rendered. A * stale or invalid value will be ignored. */ -void ASurfaceTransaction_setFrameTimeline(ASurfaceTransaction* transaction, +void ASurfaceTransaction_setFrameTimeline(ASurfaceTransaction* _Nonnull transaction, AVsyncId vsyncId) __INTRODUCED_IN(33); __END_DECLS diff --git a/include/binder/Common.h b/include/binder/Common.h new file mode 120000 index 0000000000..940f89d6ec --- /dev/null +++ b/include/binder/Common.h @@ -0,0 +1 @@ +../../libs/binder/include/binder/Common.h
\ No newline at end of file diff --git a/libs/binder/Android.bp b/libs/binder/Android.bp index 090e35bc37..cb1d1143bc 100644 --- a/libs/binder/Android.bp +++ b/libs/binder/Android.bp @@ -28,6 +28,7 @@ cc_library_headers { recovery_available: true, host_supported: true, native_bridge_supported: true, + cmake_snapshot_supported: true, header_libs: [ "libbinder_headers_platform_shared", @@ -83,6 +84,124 @@ cc_library_headers { }, } +cc_cmake_snapshot { + name: "binder_sdk", + modules: [ + "libbinder_sdk", + "libbinder_sdk_single_threaded", + "libbinder_ndk_sdk", + "binderRpcTestNoKernel", + ], + prebuilts: [ + // to enable arm64 host support, build with musl - e.g. on aosp_cf_arm64_phone + "aidl", + "libc++", + ], + include_sources: true, + cflags: [ + "-DNDEBUG", + "-DBINDER_ENABLE_LIBLOG_ASSERT", + "-DBINDER_DISABLE_NATIVE_HANDLE", + "-DBINDER_DISABLE_BLOB", + "-DBINDER_NO_LIBBASE", + "-DBINDER_NO_KERNEL_IPC_TESTING", + + // from Soong's global.go commonGlobalCflags and noOverrideGlobalCflags + "-Wno-c99-designator", + "-Wno-missing-field-initializers", + + // warnings that only pop up on gcc + "-Wno-unknown-pragmas", // "pragma clang" + "-Wno-attributes", // attributes on compound-statements + "-Wno-psabi", // reminders about old ABI changes + ], + cflags_ignored: [ + // gcc requires all header constexprs to be used in all dependent compilatinon units + "-Wunused-const-variable", + ], + library_mapping: [ + { + android_name: "libssl", + mapped_name: "ssl", + package_pregenerated: "external/boringssl", + }, + { + android_name: "libcrypto", + mapped_name: "crypto", + package_pregenerated: "external/boringssl", + }, + { + android_name: "libgtest", + mapped_name: "GTest::gtest", + package_system: "GTest", + }, + { + android_name: "libgtest_main", + mapped_name: "GTest::gtest", + package_system: "GTest", + }, + + // use libbinder_sdk and friends instead of full Android's libbinder + { + android_name: "libbinder_rpc_no_kernel", + mapped_name: "android::libbinder_sdk", + }, + { + android_name: "libbinder_rpc_single_threaded_no_kernel", + mapped_name: "android::libbinder_sdk_single_threaded", + }, + { + android_name: "libbinder_headers", + mapped_name: "android::libbinder_headers_base", + }, + { + android_name: "libbinder", + mapped_name: "android::libbinder_sdk", + }, + { + android_name: "libbinder_ndk", + mapped_name: "android::libbinder_ndk_sdk", + }, + { + android_name: "liblog", + mapped_name: "android::liblog_stub", + }, + + // explicitly included by Binder tests, but not needed outside of Android + { + android_name: "libbase", + }, + { + android_name: "libcutils", + }, + { + android_name: "libutils", + }, + + // disable tests that don't work outside of Android yet + { + android_name: "binder_rpc_test_service", + }, + { + android_name: "binder_rpc_test_service_single_threaded", + }, + + // trusty mocks are artificially triggered and not needed outside of Android build + { + android_name: "libbinder_on_trusty_mock", + }, + { + android_name: "libbinder_ndk_on_trusty_mock", + }, + { + android_name: "binderRpcTestService_on_trusty_mock", + }, + { + android_name: "binderRpcTest_on_trusty_mock", + }, + ], +} + // These interfaces are android-specific implementation unrelated to binder // transport itself and should be moved to AIDL or in domain-specific libs. // @@ -126,6 +245,9 @@ cc_defaults { header_libs: [ "libbinder_headers_base", ], + export_header_lib_headers: [ + "libbinder_headers_base", + ], cflags: [ "-Wextra", @@ -369,6 +491,7 @@ cc_library { double_loadable: true, // TODO(b/153609531): remove when no longer needed. native_bridge_supported: true, + cmake_snapshot_supported: false, // libbinder does not offer a stable wire protocol. // if a second copy of it is installed, then it may break after security @@ -408,16 +531,8 @@ cc_library { afdo: true, } -cc_library_host_shared { - name: "libbinder_sdk", - - defaults: [ - "libbinder_common_defaults", - ], - - shared_libs: [ - "libutils_binder_sdk", - ], +cc_defaults { + name: "binder_sdk_defaults", cflags: [ "-DBINDER_ENABLE_LIBLOG_ASSERT", @@ -429,6 +544,21 @@ cc_library_host_shared { header_libs: [ "liblog_stub", ], +} + +cc_defaults { + name: "libbinder_sdk_defaults", + + cmake_snapshot_supported: true, + + defaults: [ + "libbinder_common_defaults", + "binder_sdk_defaults", + ], + + shared_libs: [ + "libutils_binder_sdk", + ], srcs: [ "OS_non_android_linux.cpp", @@ -446,6 +576,19 @@ cc_library_host_shared { }, } +cc_library_host_shared { + name: "libbinder_sdk", + defaults: ["libbinder_sdk_defaults"], +} + +cc_library_host_shared { + name: "libbinder_sdk_single_threaded", + defaults: ["libbinder_sdk_defaults"], + cflags: [ + "-DBINDER_RPC_SINGLE_THREADED", + ], +} + cc_library { name: "libbinder_rpc_no_kernel", vendor_available: true, @@ -535,6 +678,7 @@ cc_defaults { defaults: ["libbinder_tls_shared_deps"], vendor_available: true, host_supported: true, + cmake_snapshot_supported: true, header_libs: [ "libbinder_headers", diff --git a/libs/binder/BpBinder.cpp b/libs/binder/BpBinder.cpp index 54457fc568..6594aa6309 100644 --- a/libs/binder/BpBinder.cpp +++ b/libs/binder/BpBinder.cpp @@ -23,6 +23,7 @@ #include <binder/IResultReceiver.h> #include <binder/RpcSession.h> #include <binder/Stability.h> +#include <binder/Trace.h> #include <stdio.h> @@ -209,6 +210,7 @@ sp<BpBinder> BpBinder::create(int32_t handle) { sTrackingMap[trackedUid]++; } uint32_t numProxies = sBinderProxyCount.fetch_add(1, std::memory_order_relaxed); + binder::os::trace_int(ATRACE_TAG_AIDL, "binder_proxies", numProxies); uint32_t numLastWarned = sBinderProxyCountWarned.load(std::memory_order_relaxed); uint32_t numNextWarn = numLastWarned + kBinderProxyCountWarnInterval; if (numProxies >= numNextWarn) { @@ -632,8 +634,8 @@ BpBinder::~BpBinder() { } } } - --sBinderProxyCount; - + uint32_t numProxies = --sBinderProxyCount; + binder::os::trace_int(ATRACE_TAG_AIDL, "binder_proxies", numProxies); if (ipc) { ipc->expungeHandle(binderHandle(), this); ipc->decWeakHandle(binderHandle()); diff --git a/libs/binder/BufferedTextOutput.h b/libs/binder/BufferedTextOutput.h index 57e03cb3a6..1c074e65c8 100644 --- a/libs/binder/BufferedTextOutput.h +++ b/libs/binder/BufferedTextOutput.h @@ -24,8 +24,7 @@ // --------------------------------------------------------------------------- namespace android { -class BufferedTextOutput : public TextOutput -{ +class LIBBINDER_INTERNAL_EXPORTED BufferedTextOutput : public TextOutput { public: //** Flags for constructor */ enum { diff --git a/libs/binder/Debug.h b/libs/binder/Debug.h index 262dfbac82..c3d03f8918 100644 --- a/libs/binder/Debug.h +++ b/libs/binder/Debug.h @@ -20,6 +20,8 @@ #include <sys/types.h> #include <string> +#include <binder/Common.h> + namespace android { // --------------------------------------------------------------------------- @@ -35,7 +37,8 @@ void printHexData(int32_t indent, const void *buf, size_t length, size_t alignment=0, bool cArrayStyle=false, debugPrintFunc func = nullptr, void* cookie = nullptr); -extern "C" ssize_t getBinderKernelReferences(size_t count, uintptr_t* buf); +// Used by libmemunreachable. +extern "C" LIBBINDER_EXPORTED ssize_t getBinderKernelReferences(size_t count, uintptr_t* buf); // --------------------------------------------------------------------------- } // namespace android diff --git a/libs/binder/FdTrigger.h b/libs/binder/FdTrigger.h index e4a02839dc..78cdaaa408 100644 --- a/libs/binder/FdTrigger.h +++ b/libs/binder/FdTrigger.h @@ -25,7 +25,7 @@ namespace android { /** This is not a pipe. */ -class FdTrigger { +class LIBBINDER_INTERNAL_EXPORTED FdTrigger { public: /** Returns nullptr for error case */ static std::unique_ptr<FdTrigger> make(); diff --git a/libs/binder/IPCThreadState.cpp b/libs/binder/IPCThreadState.cpp index ef96f803c3..fbc812571a 100644 --- a/libs/binder/IPCThreadState.cpp +++ b/libs/binder/IPCThreadState.cpp @@ -1027,6 +1027,7 @@ status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult) goto finish; case BR_FROZEN_REPLY: + ALOGW("Transaction failed because process frozen."); err = FAILED_TRANSACTION; goto finish; @@ -1578,8 +1579,8 @@ void IPCThreadState::logExtendedError() { } #endif - ALOGE_IF(ee.command != BR_OK, "Binder transaction failure: %d/%d/%d", - ee.id, ee.command, ee.param); + ALOGE_IF(ee.command != BR_OK, "Binder transaction failure. id: %d, BR_*: %d, error: %d (%s)", + ee.id, ee.command, ee.param, strerror(-ee.param)); } void IPCThreadState::freeBuffer(const uint8_t* data, size_t /*dataSize*/, diff --git a/libs/binder/IServiceManager.cpp b/libs/binder/IServiceManager.cpp index 39573ec54d..fbcf823045 100644 --- a/libs/binder/IServiceManager.cpp +++ b/libs/binder/IServiceManager.cpp @@ -20,6 +20,7 @@ #include <inttypes.h> #include <unistd.h> +#include <condition_variable> #include <android-base/properties.h> #include <android/os/BnServiceCallback.h> @@ -642,7 +643,7 @@ public: protected: // Override realGetService for ServiceManagerShim::waitForService. - Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) { + Status realGetService(const std::string& name, sp<IBinder>* _aidl_return) override { *_aidl_return = getDeviceService({"-g", name}, mOptions); return Status::ok(); } diff --git a/libs/binder/OS.h b/libs/binder/OS.h index 0035aeb205..04869a170f 100644 --- a/libs/binder/OS.h +++ b/libs/binder/OS.h @@ -24,8 +24,9 @@ namespace android::binder::os { -void trace_begin(uint64_t tag, const char* name); -void trace_end(uint64_t tag); +LIBBINDER_EXPORTED void trace_begin(uint64_t tag, const char* name); +LIBBINDER_EXPORTED void trace_end(uint64_t tag); +LIBBINDER_EXPORTED void trace_int(uint64_t tag, const char* name, int32_t value); status_t setNonBlocking(borrowed_fd fd); @@ -35,11 +36,13 @@ status_t dupFileDescriptor(int oldFd, int* newFd); std::unique_ptr<RpcTransportCtxFactory> makeDefaultRpcTransportCtxFactory(); -ssize_t sendMessageOnSocket(const RpcTransportFd& socket, iovec* iovs, int niovs, - const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds); +LIBBINDER_INTERNAL_EXPORTED ssize_t +sendMessageOnSocket(const RpcTransportFd& socket, iovec* iovs, int niovs, + const std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds); -ssize_t receiveMessageFromSocket(const RpcTransportFd& socket, iovec* iovs, int niovs, - std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds); +LIBBINDER_INTERNAL_EXPORTED ssize_t +receiveMessageFromSocket(const RpcTransportFd& socket, iovec* iovs, int niovs, + std::vector<std::variant<unique_fd, borrowed_fd>>* ancillaryFds); uint64_t GetThreadId(); diff --git a/libs/binder/OS_android.cpp b/libs/binder/OS_android.cpp index 1eace857fb..893ee15578 100644 --- a/libs/binder/OS_android.cpp +++ b/libs/binder/OS_android.cpp @@ -44,6 +44,10 @@ void trace_end(uint64_t tag) { atrace_end(tag); } +void trace_int(uint64_t tag, const char* name, int32_t value) { + atrace_int(tag, name, value); +} + } // namespace os // Legacy trace symbol. To be removed once all of downstream rebuilds. diff --git a/libs/binder/OS_non_android_linux.cpp b/libs/binder/OS_non_android_linux.cpp index b525d1ac34..0c64eb61c6 100644 --- a/libs/binder/OS_non_android_linux.cpp +++ b/libs/binder/OS_non_android_linux.cpp @@ -21,6 +21,8 @@ #include <syscall.h> #include <cstdarg> +#include <binder/Common.h> + #ifdef __ANDROID__ #error "This module is not intended for Android, just bare Linux" #endif @@ -37,6 +39,8 @@ void trace_begin(uint64_t, const char*) {} void trace_end(uint64_t) {} +void trace_int(uint64_t, const char*, int32_t) {} + uint64_t GetThreadId() { return syscall(__NR_gettid); } @@ -47,7 +51,8 @@ bool report_sysprop_change() { } // namespace android::binder::os -int __android_log_print(int /*prio*/, const char* /*tag*/, const char* fmt, ...) { +LIBBINDER_EXPORTED int __android_log_print(int /*prio*/, const char* /*tag*/, const char* fmt, + ...) { va_list args; va_start(args, fmt); vfprintf(stderr, fmt, args); diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp index 84ef489a6c..77b32753de 100644 --- a/libs/binder/Parcel.cpp +++ b/libs/binder/Parcel.cpp @@ -2768,7 +2768,7 @@ void Parcel::ipcSetDataReference(const uint8_t* data, size_t dataSize, const bin } if (type == BINDER_TYPE_FD) { // FDs from the kernel are always owned - FdTag(flat->handle, 0, this); + FdTag(flat->handle, nullptr, this); } minOffset = offset + sizeof(flat_binder_object); } diff --git a/libs/binder/PersistableBundle.cpp b/libs/binder/PersistableBundle.cpp index 15047152a1..5b157cc7c3 100644 --- a/libs/binder/PersistableBundle.cpp +++ b/libs/binder/PersistableBundle.cpp @@ -82,13 +82,12 @@ namespace os { } \ } -#define RETURN_IF_ENTRY_ERASED(map, key) \ - { \ - size_t num_erased = (map).erase(key); \ - if (num_erased) { \ - ALOGE("Failed at %s:%d (%s)", __FILE__, __LINE__, __func__); \ - return num_erased; \ - } \ +#define RETURN_IF_ENTRY_ERASED(map, key) \ + { \ + size_t num_erased = (map).erase(key); \ + if (num_erased) { \ + return num_erased; \ + } \ } status_t PersistableBundle::writeToParcel(Parcel* parcel) const { diff --git a/libs/binder/ProcessState.cpp b/libs/binder/ProcessState.cpp index fb2781be59..8485ecd835 100644 --- a/libs/binder/ProcessState.cpp +++ b/libs/binder/ProcessState.cpp @@ -516,22 +516,23 @@ String8 ProcessState::getDriverName() { return mDriverName; } -static unique_fd open_driver(const char* driver) { +static unique_fd open_driver(const char* driver, String8* error) { auto fd = unique_fd(open(driver, O_RDWR | O_CLOEXEC)); if (!fd.ok()) { - PLOGE("Opening '%s' failed", driver); + error->appendFormat("%d (%s) Opening '%s' failed", errno, strerror(errno), driver); return {}; } int vers = 0; int result = ioctl(fd.get(), BINDER_VERSION, &vers); if (result == -1) { - PLOGE("Binder ioctl to obtain version failed"); + error->appendFormat("%d (%s) Binder ioctl to obtain version failed", errno, + strerror(errno)); return {}; } if (result != 0 || vers != BINDER_CURRENT_PROTOCOL_VERSION) { - ALOGE("Binder driver protocol(%d) does not match user space protocol(%d)! " - "ioctl() return value: %d", - vers, BINDER_CURRENT_PROTOCOL_VERSION, result); + error->appendFormat("Binder driver protocol(%d) does not match user space protocol(%d)! " + "ioctl() return value: %d", + vers, BINDER_CURRENT_PROTOCOL_VERSION, result); return {}; } size_t maxThreads = DEFAULT_MAX_BINDER_THREADS; @@ -565,7 +566,8 @@ ProcessState::ProcessState(const char* driver) mThreadPoolStarted(false), mThreadPoolSeq(1), mCallRestriction(CallRestriction::NONE) { - unique_fd opened = open_driver(driver); + String8 error; + unique_fd opened = open_driver(driver, &error); if (opened.ok()) { // mmap the binder, providing a chunk of virtual address space to receive transactions. @@ -580,8 +582,9 @@ ProcessState::ProcessState(const char* driver) } #ifdef __ANDROID__ - LOG_ALWAYS_FATAL_IF(!opened.ok(), "Binder driver '%s' could not be opened. Terminating.", - driver); + LOG_ALWAYS_FATAL_IF(!opened.ok(), + "Binder driver '%s' could not be opened. Error: %s. Terminating.", + error.c_str(), driver); #endif if (opened.ok()) { diff --git a/libs/binder/RecordedTransaction.cpp b/libs/binder/RecordedTransaction.cpp index de2a69f7cf..924537e63a 100644 --- a/libs/binder/RecordedTransaction.cpp +++ b/libs/binder/RecordedTransaction.cpp @@ -230,8 +230,8 @@ std::optional<RecordedTransaction> RecordedTransaction::fromFile(const unique_fd } size_t memoryMappedSize = chunkPayloadSize + mmapPayloadStartOffset; - void* mappedMemory = - mmap(NULL, memoryMappedSize, PROT_READ, MAP_SHARED, fd.get(), mmapPageAlignedStart); + void* mappedMemory = mmap(nullptr, memoryMappedSize, PROT_READ, MAP_SHARED, fd.get(), + mmapPageAlignedStart); auto mmap_guard = make_scope_guard( [mappedMemory, memoryMappedSize] { munmap(mappedMemory, memoryMappedSize); }); @@ -382,7 +382,7 @@ android::status_t RecordedTransaction::dumpToFile(const unique_fd& fd) const { return UNKNOWN_ERROR; } - if (NO_ERROR != writeChunk(fd, END_CHUNK, 0, NULL)) { + if (NO_ERROR != writeChunk(fd, END_CHUNK, 0, nullptr)) { ALOGE("Failed to write end chunk to fd %d", fd.get()); return UNKNOWN_ERROR; } diff --git a/libs/binder/RpcState.h b/libs/binder/RpcState.h index 8b84602fee..94013cc952 100644 --- a/libs/binder/RpcState.h +++ b/libs/binder/RpcState.h @@ -149,8 +149,8 @@ public: */ [[nodiscard]] status_t sendObituaries(const sp<RpcSession>& session); - size_t countBinders(); - void dump(); + LIBBINDER_INTERNAL_EXPORTED size_t countBinders(); + LIBBINDER_INTERNAL_EXPORTED void dump(); /** * Called when reading or writing data to a session fails to clean up diff --git a/libs/binder/Stability.cpp b/libs/binder/Stability.cpp index 665dfea456..4fb8fa08bc 100644 --- a/libs/binder/Stability.cpp +++ b/libs/binder/Stability.cpp @@ -70,7 +70,7 @@ bool Stability::requiresVintfDeclaration(const sp<IBinder>& binder) { } void Stability::tryMarkCompilationUnit(IBinder* binder) { - (void)setRepr(binder, getLocalLevel(), REPR_NONE); + std::ignore = setRepr(binder, getLocalLevel(), REPR_NONE); } // after deprecation of the VNDK, these should be aliases. At some point diff --git a/libs/binder/Utils.h b/libs/binder/Utils.h index eec09eb859..df8a4ce1f1 100644 --- a/libs/binder/Utils.h +++ b/libs/binder/Utils.h @@ -21,6 +21,7 @@ #include <cstdint> #include <optional> +#include <binder/Common.h> #include <log/log.h> #include <utils/Errors.h> @@ -111,6 +112,6 @@ struct Span { // // Hex values are printed in order, e.g. 0xDEAD will result in 'adde' because // Android is little-endian. -std::string HexString(const void* bytes, size_t len); +LIBBINDER_INTERNAL_EXPORTED std::string HexString(const void* bytes, size_t len); } // namespace android diff --git a/libs/binder/UtilsHost.h b/libs/binder/UtilsHost.h index d6fe9facde..03af1e72f0 100644 --- a/libs/binder/UtilsHost.h +++ b/libs/binder/UtilsHost.h @@ -24,6 +24,7 @@ #include <vector> #include <android-base/macros.h> +#include <binder/Common.h> #include <binder/unique_fd.h> #include <utils/Errors.h> @@ -40,7 +41,7 @@ namespace android { -struct CommandResult { +struct LIBBINDER_EXPORTED CommandResult { std::optional<int32_t> exitCode; std::optional<int32_t> signal; std::optional<pid_t> pid; @@ -72,7 +73,7 @@ private: void operator=(const CommandResult&) = delete; }; -std::ostream& operator<<(std::ostream& os, const CommandResult& res); +LIBBINDER_EXPORTED std::ostream& operator<<(std::ostream& os, const CommandResult& res); // Execute a command using tokens specified in @a argStringVec. // @@ -96,6 +97,7 @@ std::ostream& operator<<(std::ostream& os, const CommandResult& res); // // If the parent process has encountered any errors for system calls, return ExecuteError with // the proper errno set. -std::optional<CommandResult> execute(std::vector<std::string> argStringVec, - const std::function<bool(const CommandResult&)>& end); +LIBBINDER_EXPORTED std::optional<CommandResult> execute( + std::vector<std::string> argStringVec, + const std::function<bool(const CommandResult&)>& end); } // namespace android diff --git a/libs/binder/include/binder/Binder.h b/libs/binder/include/binder/Binder.h index 7a65ff4e45..135be89c6c 100644 --- a/libs/binder/include/binder/Binder.h +++ b/libs/binder/include/binder/Binder.h @@ -18,6 +18,7 @@ #include <atomic> #include <stdint.h> +#include <binder/Common.h> #include <binder/IBinder.h> // --------------------------------------------------------------------------- @@ -27,50 +28,47 @@ namespace internal { class Stability; } -class BBinder : public IBinder -{ +class BBinder : public IBinder { public: - BBinder(); + LIBBINDER_EXPORTED BBinder(); - virtual const String16& getInterfaceDescriptor() const; - virtual bool isBinderAlive() const; - virtual status_t pingBinder(); - virtual status_t dump(int fd, const Vector<String16>& args); + LIBBINDER_EXPORTED virtual const String16& getInterfaceDescriptor() const; + LIBBINDER_EXPORTED virtual bool isBinderAlive() const; + LIBBINDER_EXPORTED virtual status_t pingBinder(); + LIBBINDER_EXPORTED virtual status_t dump(int fd, const Vector<String16>& args); // NOLINTNEXTLINE(google-default-arguments) - virtual status_t transact( uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0) final; + LIBBINDER_EXPORTED virtual status_t transact(uint32_t code, const Parcel& data, Parcel* reply, + uint32_t flags = 0) final; // NOLINTNEXTLINE(google-default-arguments) - virtual status_t linkToDeath(const sp<DeathRecipient>& recipient, - void* cookie = nullptr, - uint32_t flags = 0); + LIBBINDER_EXPORTED virtual status_t linkToDeath(const sp<DeathRecipient>& recipient, + void* cookie = nullptr, uint32_t flags = 0); // NOLINTNEXTLINE(google-default-arguments) - virtual status_t unlinkToDeath( const wp<DeathRecipient>& recipient, - void* cookie = nullptr, - uint32_t flags = 0, - wp<DeathRecipient>* outRecipient = nullptr); - - virtual void* attachObject(const void* objectID, void* object, void* cleanupCookie, - object_cleanup_func func) final; - virtual void* findObject(const void* objectID) const final; - virtual void* detachObject(const void* objectID) final; - void withLock(const std::function<void()>& doWithLock); - sp<IBinder> lookupOrCreateWeak(const void* objectID, IBinder::object_make_func make, - const void* makeArgs); - - virtual BBinder* localBinder(); - - bool isRequestingSid(); + LIBBINDER_EXPORTED virtual status_t unlinkToDeath(const wp<DeathRecipient>& recipient, + void* cookie = nullptr, uint32_t flags = 0, + wp<DeathRecipient>* outRecipient = nullptr); + + LIBBINDER_EXPORTED virtual void* attachObject(const void* objectID, void* object, + void* cleanupCookie, + object_cleanup_func func) final; + LIBBINDER_EXPORTED virtual void* findObject(const void* objectID) const final; + LIBBINDER_EXPORTED virtual void* detachObject(const void* objectID) final; + LIBBINDER_EXPORTED void withLock(const std::function<void()>& doWithLock); + LIBBINDER_EXPORTED sp<IBinder> lookupOrCreateWeak(const void* objectID, + IBinder::object_make_func make, + const void* makeArgs); + + LIBBINDER_EXPORTED virtual BBinder* localBinder(); + + LIBBINDER_EXPORTED bool isRequestingSid(); // This must be called before the object is sent to another process. Not thread safe. - void setRequestingSid(bool requestSid); + LIBBINDER_EXPORTED void setRequestingSid(bool requestSid); - sp<IBinder> getExtension(); + LIBBINDER_EXPORTED sp<IBinder> getExtension(); // This must be called before the object is sent to another process. Not thread safe. - void setExtension(const sp<IBinder>& extension); + LIBBINDER_EXPORTED void setExtension(const sp<IBinder>& extension); // This must be called before the object is sent to another process. Not thread safe. // @@ -84,35 +82,33 @@ public: // Appropriate values are: // SCHED_NORMAL: -20 <= priority <= 19 // SCHED_RR/SCHED_FIFO: 1 <= priority <= 99 - void setMinSchedulerPolicy(int policy, int priority); - int getMinSchedulerPolicy(); - int getMinSchedulerPriority(); + LIBBINDER_EXPORTED void setMinSchedulerPolicy(int policy, int priority); + LIBBINDER_EXPORTED int getMinSchedulerPolicy(); + LIBBINDER_EXPORTED int getMinSchedulerPriority(); // Whether realtime scheduling policies are inherited. - bool isInheritRt(); + LIBBINDER_EXPORTED bool isInheritRt(); // This must be called before the object is sent to another process. Not thread safe. - void setInheritRt(bool inheritRt); + LIBBINDER_EXPORTED void setInheritRt(bool inheritRt); - pid_t getDebugPid(); + LIBBINDER_EXPORTED pid_t getDebugPid(); // Whether this binder has been sent to another process. - bool wasParceled(); + LIBBINDER_EXPORTED bool wasParceled(); // Consider this binder as parceled (setup/init-related calls should no // longer by called. This is automatically set by when this binder is sent // to another process. - void setParceled(); + LIBBINDER_EXPORTED void setParceled(); - [[nodiscard]] status_t setRpcClientDebug(binder::unique_fd clientFd, - const sp<IBinder>& keepAliveBinder); + [[nodiscard]] LIBBINDER_EXPORTED status_t setRpcClientDebug(binder::unique_fd clientFd, + const sp<IBinder>& keepAliveBinder); protected: - virtual ~BBinder(); + LIBBINDER_EXPORTED virtual ~BBinder(); // NOLINTNEXTLINE(google-default-arguments) - virtual status_t onTransact( uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0); + LIBBINDER_EXPORTED virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, + uint32_t flags = 0); private: BBinder(const BBinder& o); @@ -142,17 +138,18 @@ private: // --------------------------------------------------------------------------- -class BpRefBase : public virtual RefBase -{ +class BpRefBase : public virtual RefBase { protected: - explicit BpRefBase(const sp<IBinder>& o); - virtual ~BpRefBase(); - virtual void onFirstRef(); - virtual void onLastStrongRef(const void* id); - virtual bool onIncStrongAttempted(uint32_t flags, const void* id); - - inline IBinder* remote() const { return mRemote; } - inline sp<IBinder> remoteStrong() const { return sp<IBinder>::fromExisting(mRemote); } + LIBBINDER_EXPORTED explicit BpRefBase(const sp<IBinder>& o); + LIBBINDER_EXPORTED virtual ~BpRefBase(); + LIBBINDER_EXPORTED virtual void onFirstRef(); + LIBBINDER_EXPORTED virtual void onLastStrongRef(const void* id); + LIBBINDER_EXPORTED virtual bool onIncStrongAttempted(uint32_t flags, const void* id); + + LIBBINDER_EXPORTED inline IBinder* remote() const { return mRemote; } + LIBBINDER_EXPORTED inline sp<IBinder> remoteStrong() const { + return sp<IBinder>::fromExisting(mRemote); + } private: BpRefBase(const BpRefBase& o); diff --git a/libs/binder/include/binder/BpBinder.h b/libs/binder/include/binder/BpBinder.h index 9f0390769b..8ac30ba02f 100644 --- a/libs/binder/include/binder/BpBinder.h +++ b/libs/binder/include/binder/BpBinder.h @@ -16,6 +16,7 @@ #pragma once +#include <binder/Common.h> #include <binder/IBinder.h> #include <binder/RpcThreads.h> #include <binder/unique_fd.h> @@ -38,67 +39,64 @@ class ProcessState; using binder_proxy_limit_callback = std::function<void(int)>; using binder_proxy_warning_callback = std::function<void(int)>; -class BpBinder : public IBinder -{ +class BpBinder : public IBinder { public: /** * Return value: * true - this is associated with a socket RpcSession * false - (usual) binder over e.g. /dev/binder */ - bool isRpcBinder() const; + LIBBINDER_EXPORTED bool isRpcBinder() const; - virtual const String16& getInterfaceDescriptor() const; - virtual bool isBinderAlive() const; - virtual status_t pingBinder(); - virtual status_t dump(int fd, const Vector<String16>& args); + LIBBINDER_EXPORTED virtual const String16& getInterfaceDescriptor() const; + LIBBINDER_EXPORTED virtual bool isBinderAlive() const; + LIBBINDER_EXPORTED virtual status_t pingBinder(); + LIBBINDER_EXPORTED virtual status_t dump(int fd, const Vector<String16>& args); // NOLINTNEXTLINE(google-default-arguments) - virtual status_t transact( uint32_t code, - const Parcel& data, - Parcel* reply, - uint32_t flags = 0) final; + LIBBINDER_EXPORTED virtual status_t transact(uint32_t code, const Parcel& data, Parcel* reply, + uint32_t flags = 0) final; // NOLINTNEXTLINE(google-default-arguments) - virtual status_t linkToDeath(const sp<DeathRecipient>& recipient, - void* cookie = nullptr, - uint32_t flags = 0); + LIBBINDER_EXPORTED virtual status_t linkToDeath(const sp<DeathRecipient>& recipient, + void* cookie = nullptr, uint32_t flags = 0); // NOLINTNEXTLINE(google-default-arguments) - virtual status_t unlinkToDeath( const wp<DeathRecipient>& recipient, - void* cookie = nullptr, - uint32_t flags = 0, - wp<DeathRecipient>* outRecipient = nullptr); - - virtual void* attachObject(const void* objectID, void* object, void* cleanupCookie, - object_cleanup_func func) final; - virtual void* findObject(const void* objectID) const final; - virtual void* detachObject(const void* objectID) final; - void withLock(const std::function<void()>& doWithLock); - sp<IBinder> lookupOrCreateWeak(const void* objectID, IBinder::object_make_func make, - const void* makeArgs); - - virtual BpBinder* remoteBinder(); - - void sendObituary(); - - static uint32_t getBinderProxyCount(uint32_t uid); - static void getCountByUid(Vector<uint32_t>& uids, Vector<uint32_t>& counts); - static void enableCountByUid(); - static void disableCountByUid(); - static void setCountByUidEnabled(bool enable); - static void setBinderProxyCountEventCallback(binder_proxy_limit_callback cbl, - binder_proxy_warning_callback cbw); - static void setBinderProxyCountWatermarks(int high, int low, int warning); - static uint32_t getBinderProxyCount(); - - std::optional<int32_t> getDebugBinderHandle() const; + LIBBINDER_EXPORTED virtual status_t unlinkToDeath(const wp<DeathRecipient>& recipient, + void* cookie = nullptr, uint32_t flags = 0, + wp<DeathRecipient>* outRecipient = nullptr); + + LIBBINDER_EXPORTED virtual void* attachObject(const void* objectID, void* object, + void* cleanupCookie, + object_cleanup_func func) final; + LIBBINDER_EXPORTED virtual void* findObject(const void* objectID) const final; + LIBBINDER_EXPORTED virtual void* detachObject(const void* objectID) final; + LIBBINDER_EXPORTED void withLock(const std::function<void()>& doWithLock); + LIBBINDER_EXPORTED sp<IBinder> lookupOrCreateWeak(const void* objectID, + IBinder::object_make_func make, + const void* makeArgs); + + LIBBINDER_EXPORTED virtual BpBinder* remoteBinder(); + + LIBBINDER_EXPORTED void sendObituary(); + + LIBBINDER_EXPORTED static uint32_t getBinderProxyCount(uint32_t uid); + LIBBINDER_EXPORTED static void getCountByUid(Vector<uint32_t>& uids, Vector<uint32_t>& counts); + LIBBINDER_EXPORTED static void enableCountByUid(); + LIBBINDER_EXPORTED static void disableCountByUid(); + LIBBINDER_EXPORTED static void setCountByUidEnabled(bool enable); + LIBBINDER_EXPORTED static void setBinderProxyCountEventCallback( + binder_proxy_limit_callback cbl, binder_proxy_warning_callback cbw); + LIBBINDER_EXPORTED static void setBinderProxyCountWatermarks(int high, int low, int warning); + LIBBINDER_EXPORTED static uint32_t getBinderProxyCount(); + + LIBBINDER_EXPORTED std::optional<int32_t> getDebugBinderHandle() const; // Start recording transactions to the unique_fd. // See RecordedTransaction.h for more details. - status_t startRecordingBinder(const binder::unique_fd& fd); + LIBBINDER_EXPORTED status_t startRecordingBinder(const binder::unique_fd& fd); // Stop the current recording. - status_t stopRecordingBinder(); + LIBBINDER_EXPORTED status_t stopRecordingBinder(); class ObjectManager { public: @@ -150,7 +148,9 @@ public: const BpBinder* mBinder; }; - const PrivateAccessor getPrivateAccessor() const { return PrivateAccessor(this); } + LIBBINDER_EXPORTED const PrivateAccessor getPrivateAccessor() const { + return PrivateAccessor(this); + } private: friend PrivateAccessor; diff --git a/libs/binder/include/binder/Common.h b/libs/binder/include/binder/Common.h new file mode 100644 index 0000000000..ed10154ca1 --- /dev/null +++ b/libs/binder/include/binder/Common.h @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2024 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +// libbinder is built with symbol hidden by default. To add a new symbol to the +// ABI, you must annotate it with this LIBBINDER_EXPORTED macro. When not +// building libbinder (e.g. when another binary includes a libbinder header), +// this macro is a no-op. +// +// Examples: +// +// // Export a function. +// LIBBINDER_EXPORTED void someFunction(); +// +// // Export a subset of the symbols for a class. +// class SomeClassA { +// public: +// LIBBINDER_EXPORTED SomeClassA(); +// +// LIBBINDER_EXPORTED SomeMethod(); +// } +// +// // Export all the symbols for a class, even private symbols. +// class LIBBINDER_EXPORTED SomeClassB {}; +// +// For a more detailed explanation of this strategy, see +// https://www.gnu.org/software/gnulib/manual/html_node/Exported-Symbols-of-Shared-Libraries.html +#if BUILDING_LIBBINDER +#define LIBBINDER_EXPORTED __attribute__((__visibility__("default"))) +#else +#define LIBBINDER_EXPORTED +#endif + +// For stuff that is exported but probably shouldn't be. It behaves the exact +// same way as LIBBINDER_EXPORTED, only exists to help track what we want +// eventually remove. +// +// Needed, at least in part, because the test binaries are using internal +// headers and accessing these symbols directly. +#define LIBBINDER_INTERNAL_EXPORTED LIBBINDER_EXPORTED diff --git a/libs/binder/include/binder/Delegate.h b/libs/binder/include/binder/Delegate.h index ad5a6a3e88..7aaa7a0f54 100644 --- a/libs/binder/include/binder/Delegate.h +++ b/libs/binder/include/binder/Delegate.h @@ -16,6 +16,7 @@ #pragma once +#include <binder/Common.h> #include <binder/IBinder.h> #if !defined(__BIONIC__) && defined(BINDER_ENABLE_LIBLOG_ASSERT) diff --git a/libs/binder/include/binder/IBinder.h b/libs/binder/include/binder/IBinder.h index dad9a1782d..17248ce289 100644 --- a/libs/binder/include/binder/IBinder.h +++ b/libs/binder/include/binder/IBinder.h @@ -16,6 +16,7 @@ #pragma once +#include <binder/Common.h> #include <binder/unique_fd.h> #include <utils/Errors.h> #include <utils/RefBase.h> @@ -48,8 +49,7 @@ class IShellCallback; * (method calls, property get and set) is down through a low-level * protocol implemented on top of the transact() API. */ -class [[clang::lto_visibility_public]] IBinder : public virtual RefBase -{ +class [[clang::lto_visibility_public]] LIBBINDER_EXPORTED IBinder : public virtual RefBase { public: enum { FIRST_CALL_TRANSACTION = 0x00000001, diff --git a/libs/binder/include/binder/IInterface.h b/libs/binder/include/binder/IInterface.h index ac845bc003..30e005c2d2 100644 --- a/libs/binder/include/binder/IInterface.h +++ b/libs/binder/include/binder/IInterface.h @@ -17,6 +17,7 @@ #pragma once #include <binder/Binder.h> +#include <binder/Common.h> #include <assert.h> @@ -24,8 +25,7 @@ namespace android { // ---------------------------------------------------------------------- -class IInterface : public virtual RefBase -{ +class LIBBINDER_EXPORTED IInterface : public virtual RefBase { public: IInterface(); static sp<IBinder> asBinder(const IInterface*); @@ -66,9 +66,8 @@ inline sp<INTERFACE> checked_interface_cast(const sp<IBinder>& obj) // ---------------------------------------------------------------------- -template<typename INTERFACE> -class BnInterface : public INTERFACE, public BBinder -{ +template <typename INTERFACE> +class LIBBINDER_EXPORTED BnInterface : public INTERFACE, public BBinder { public: virtual sp<IInterface> queryLocalInterface(const String16& _descriptor); virtual const String16& getInterfaceDescriptor() const; @@ -80,9 +79,8 @@ protected: // ---------------------------------------------------------------------- -template<typename INTERFACE> -class BpInterface : public INTERFACE, public BpRefBase -{ +template <typename INTERFACE> +class LIBBINDER_EXPORTED BpInterface : public INTERFACE, public BpRefBase { public: explicit BpInterface(const sp<IBinder>& remote); typedef INTERFACE BaseInterface; diff --git a/libs/binder/include/binder/IMemory.h b/libs/binder/include/binder/IMemory.h index d8b7ec1fb7..12c5c61832 100644 --- a/libs/binder/include/binder/IMemory.h +++ b/libs/binder/include/binder/IMemory.h @@ -22,14 +22,14 @@ #include <utils/RefBase.h> #include <utils/Errors.h> +#include <binder/Common.h> #include <binder/IInterface.h> namespace android { // ---------------------------------------------------------------------------- -class IMemoryHeap : public IInterface -{ +class LIBBINDER_EXPORTED IMemoryHeap : public IInterface { public: DECLARE_META_INTERFACE(MemoryHeap) @@ -50,8 +50,7 @@ public: size_t virtualSize() const { return getSize(); } }; -class BnMemoryHeap : public BnInterface<IMemoryHeap> -{ +class LIBBINDER_EXPORTED BnMemoryHeap : public BnInterface<IMemoryHeap> { public: // NOLINTNEXTLINE(google-default-arguments) virtual status_t onTransact( @@ -67,8 +66,7 @@ protected: // ---------------------------------------------------------------------------- -class IMemory : public IInterface -{ +class LIBBINDER_EXPORTED IMemory : public IInterface { public: DECLARE_META_INTERFACE(Memory) @@ -105,8 +103,7 @@ private: void* fastPointer(const sp<IBinder>& heap, ssize_t offset) const; }; -class BnMemory : public BnInterface<IMemory> -{ +class LIBBINDER_EXPORTED BnMemory : public BnInterface<IMemory> { public: // NOLINTNEXTLINE(google-default-arguments) virtual status_t onTransact( diff --git a/libs/binder/include/binder/IPCThreadState.h b/libs/binder/include/binder/IPCThreadState.h index dc5b1a1712..09ab442c7d 100644 --- a/libs/binder/include/binder/IPCThreadState.h +++ b/libs/binder/include/binder/IPCThreadState.h @@ -16,9 +16,10 @@ #pragma once -#include <utils/Errors.h> +#include <binder/Common.h> #include <binder/Parcel.h> #include <binder/ProcessState.h> +#include <utils/Errors.h> #include <utils/Vector.h> #if defined(_WIN32) @@ -32,13 +33,12 @@ namespace android { * Kernel binder thread state. All operations here refer to kernel binder. This * object is allocated per-thread. */ -class IPCThreadState -{ +class IPCThreadState { public: using CallRestriction = ProcessState::CallRestriction; - static IPCThreadState* self(); - static IPCThreadState* selfOrNull(); // self(), but won't instantiate + LIBBINDER_EXPORTED static IPCThreadState* self(); + LIBBINDER_EXPORTED static IPCThreadState* selfOrNull(); // self(), but won't instantiate // Freeze or unfreeze the binder interface to a specific process. When freezing, this method // will block up to timeout_ms to process pending transactions directed to pid. Unfreeze @@ -52,182 +52,175 @@ public: // binder transactions to be processed. // // returns: 0 in case of success, a value < 0 in case of error - static status_t freeze(pid_t pid, bool enabled, uint32_t timeout_ms); + LIBBINDER_EXPORTED static status_t freeze(pid_t pid, bool enabled, uint32_t timeout_ms); // Provide information about the state of a frozen process - static status_t getProcessFreezeInfo(pid_t pid, uint32_t *sync_received, - uint32_t *async_received); - - status_t clearLastError(); - - /** - * Returns the PID of the process which has made the current binder - * call. If not in a binder call, this will return getpid. - * - * Warning: oneway transactions do not receive PID. Even if you expect - * a transaction to be synchronous, a misbehaving client could send it - * as an asynchronous call and result in a 0 PID here. Additionally, if - * there is a race and the calling process dies, the PID may still be - * 0 for a synchronous call. - */ - [[nodiscard]] pid_t getCallingPid() const; - - /** - * Returns the SELinux security identifier of the process which has - * made the current binder call. If not in a binder call this will - * return nullptr. If this isn't requested with - * Binder::setRequestingSid, it will also return nullptr. - * - * This can't be restored once it's cleared, and it does not return the - * context of the current process when not in a binder call. - */ - [[nodiscard]] const char* getCallingSid() const; - - /** - * Returns the UID of the process which has made the current binder - * call. If not in a binder call, this will return 0. - */ - [[nodiscard]] uid_t getCallingUid() const; - - /** - * Make it an abort to rely on getCalling* for a section of - * execution. - * - * Usage: - * IPCThreadState::SpGuard guard { - * .address = __builtin_frame_address(0), - * .context = "...", - * }; - * const auto* orig = pushGetCallingSpGuard(&guard); - * { - * // will abort if you call getCalling*, unless you are - * // serving a nested binder transaction - * } - * restoreCallingSpGuard(orig); - */ - struct SpGuard { - const void* address; - const char* context; - }; - const SpGuard* pushGetCallingSpGuard(const SpGuard* guard); - void restoreGetCallingSpGuard(const SpGuard* guard); - /** - * Used internally by getCalling*. Can also be used to assert that - * you are in a binder context (getCalling* is valid). This is - * intentionally not exposed as a boolean API since code should be - * written to know its environment. - */ - void checkContextIsBinderForUse(const char* use) const; - - void setStrictModePolicy(int32_t policy); - int32_t getStrictModePolicy() const; - - // See Binder#setCallingWorkSourceUid in Binder.java. - int64_t setCallingWorkSourceUid(uid_t uid); - // Internal only. Use setCallingWorkSourceUid(uid) instead. - int64_t setCallingWorkSourceUidWithoutPropagation(uid_t uid); - // See Binder#getCallingWorkSourceUid in Binder.java. - uid_t getCallingWorkSourceUid() const; - // See Binder#clearCallingWorkSource in Binder.java. - int64_t clearCallingWorkSource(); - // See Binder#restoreCallingWorkSource in Binder.java. - void restoreCallingWorkSource(int64_t token); - void clearPropagateWorkSource(); - bool shouldPropagateWorkSource() const; - - void setLastTransactionBinderFlags(int32_t flags); - int32_t getLastTransactionBinderFlags() const; - - void setCallRestriction(CallRestriction restriction); - CallRestriction getCallRestriction() const; - - int64_t clearCallingIdentity(); - // Restores PID/UID (not SID) - void restoreCallingIdentity(int64_t token); - bool hasExplicitIdentity(); - - // For main functions - dangerous for libraries to use - status_t setupPolling(int* fd); - status_t handlePolledCommands(); - void flushCommands(); - bool flushIfNeeded(); - - // Adds the current thread into the binder threadpool. - // - // This is in addition to any threads which are started - // with startThreadPool. Libraries should not call this - // function, as they may be loaded into processes which - // try to configure the threadpool differently. - void joinThreadPool(bool isMain = true); - - // Stop the local process. - void stopProcess(bool immediate = true); - - status_t transact(int32_t handle, - uint32_t code, const Parcel& data, + LIBBINDER_EXPORTED static status_t getProcessFreezeInfo(pid_t pid, uint32_t* sync_received, + uint32_t* async_received); + + LIBBINDER_EXPORTED status_t clearLastError(); + + /** + * Returns the PID of the process which has made the current binder + * call. If not in a binder call, this will return getpid. + * + * Warning: oneway transactions do not receive PID. Even if you expect + * a transaction to be synchronous, a misbehaving client could send it + * as an asynchronous call and result in a 0 PID here. Additionally, if + * there is a race and the calling process dies, the PID may still be + * 0 for a synchronous call. + */ + [[nodiscard]] LIBBINDER_EXPORTED pid_t getCallingPid() const; + + /** + * Returns the SELinux security identifier of the process which has + * made the current binder call. If not in a binder call this will + * return nullptr. If this isn't requested with + * Binder::setRequestingSid, it will also return nullptr. + * + * This can't be restored once it's cleared, and it does not return the + * context of the current process when not in a binder call. + */ + [[nodiscard]] LIBBINDER_EXPORTED const char* getCallingSid() const; + + /** + * Returns the UID of the process which has made the current binder + * call. If not in a binder call, this will return 0. + */ + [[nodiscard]] LIBBINDER_EXPORTED uid_t getCallingUid() const; + + /** + * Make it an abort to rely on getCalling* for a section of + * execution. + * + * Usage: + * IPCThreadState::SpGuard guard { + * .address = __builtin_frame_address(0), + * .context = "...", + * }; + * const auto* orig = pushGetCallingSpGuard(&guard); + * { + * // will abort if you call getCalling*, unless you are + * // serving a nested binder transaction + * } + * restoreCallingSpGuard(orig); + */ + struct SpGuard { + const void* address; + const char* context; + }; + LIBBINDER_EXPORTED const SpGuard* pushGetCallingSpGuard(const SpGuard* guard); + LIBBINDER_EXPORTED void restoreGetCallingSpGuard(const SpGuard* guard); + /** + * Used internally by getCalling*. Can also be used to assert that + * you are in a binder context (getCalling* is valid). This is + * intentionally not exposed as a boolean API since code should be + * written to know its environment. + */ + LIBBINDER_EXPORTED void checkContextIsBinderForUse(const char* use) const; + + LIBBINDER_EXPORTED void setStrictModePolicy(int32_t policy); + LIBBINDER_EXPORTED int32_t getStrictModePolicy() const; + + // See Binder#setCallingWorkSourceUid in Binder.java. + LIBBINDER_EXPORTED int64_t setCallingWorkSourceUid(uid_t uid); + // Internal only. Use setCallingWorkSourceUid(uid) instead. + LIBBINDER_EXPORTED int64_t setCallingWorkSourceUidWithoutPropagation(uid_t uid); + // See Binder#getCallingWorkSourceUid in Binder.java. + LIBBINDER_EXPORTED uid_t getCallingWorkSourceUid() const; + // See Binder#clearCallingWorkSource in Binder.java. + LIBBINDER_EXPORTED int64_t clearCallingWorkSource(); + // See Binder#restoreCallingWorkSource in Binder.java. + LIBBINDER_EXPORTED void restoreCallingWorkSource(int64_t token); + LIBBINDER_EXPORTED void clearPropagateWorkSource(); + LIBBINDER_EXPORTED bool shouldPropagateWorkSource() const; + + LIBBINDER_EXPORTED void setLastTransactionBinderFlags(int32_t flags); + LIBBINDER_EXPORTED int32_t getLastTransactionBinderFlags() const; + + LIBBINDER_EXPORTED void setCallRestriction(CallRestriction restriction); + LIBBINDER_EXPORTED CallRestriction getCallRestriction() const; + + LIBBINDER_EXPORTED int64_t clearCallingIdentity(); + // Restores PID/UID (not SID) + LIBBINDER_EXPORTED void restoreCallingIdentity(int64_t token); + LIBBINDER_EXPORTED bool hasExplicitIdentity(); + + // For main functions - dangerous for libraries to use + LIBBINDER_EXPORTED status_t setupPolling(int* fd); + LIBBINDER_EXPORTED status_t handlePolledCommands(); + LIBBINDER_EXPORTED void flushCommands(); + LIBBINDER_EXPORTED bool flushIfNeeded(); + + // Adds the current thread into the binder threadpool. + // + // This is in addition to any threads which are started + // with startThreadPool. Libraries should not call this + // function, as they may be loaded into processes which + // try to configure the threadpool differently. + LIBBINDER_EXPORTED void joinThreadPool(bool isMain = true); + + // Stop the local process. + LIBBINDER_EXPORTED void stopProcess(bool immediate = true); + + LIBBINDER_EXPORTED status_t transact(int32_t handle, uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); - void incStrongHandle(int32_t handle, BpBinder *proxy); - void decStrongHandle(int32_t handle); - void incWeakHandle(int32_t handle, BpBinder *proxy); - void decWeakHandle(int32_t handle); - status_t attemptIncStrongHandle(int32_t handle); - static void expungeHandle(int32_t handle, IBinder* binder); - status_t requestDeathNotification( int32_t handle, - BpBinder* proxy); - status_t clearDeathNotification( int32_t handle, - BpBinder* proxy); + LIBBINDER_EXPORTED void incStrongHandle(int32_t handle, BpBinder* proxy); + LIBBINDER_EXPORTED void decStrongHandle(int32_t handle); + LIBBINDER_EXPORTED void incWeakHandle(int32_t handle, BpBinder* proxy); + LIBBINDER_EXPORTED void decWeakHandle(int32_t handle); + LIBBINDER_EXPORTED status_t attemptIncStrongHandle(int32_t handle); + LIBBINDER_EXPORTED static void expungeHandle(int32_t handle, IBinder* binder); + LIBBINDER_EXPORTED status_t requestDeathNotification(int32_t handle, BpBinder* proxy); + LIBBINDER_EXPORTED status_t clearDeathNotification(int32_t handle, BpBinder* proxy); - static void shutdown(); + LIBBINDER_EXPORTED static void shutdown(); // Call this to disable switching threads to background scheduling when // receiving incoming IPC calls. This is specifically here for the // Android system process, since it expects to have background apps calling // in to it but doesn't want to acquire locks in its services while in // the background. - static void disableBackgroundScheduling(bool disable); - bool backgroundSchedulingDisabled(); - - // Call blocks until the number of executing binder threads is less than - // the maximum number of binder threads threads allowed for this process. - void blockUntilThreadAvailable(); - - // Service manager registration - void setTheContextObject(const sp<BBinder>& obj); - - // WARNING: DO NOT USE THIS API - // - // Returns a pointer to the stack from the last time a transaction - // was initiated by the kernel. Used to compare when making nested - // calls between multiple different transports. - const void* getServingStackPointer() const; - - // The work source represents the UID of the process we should attribute the transaction - // to. We use -1 to specify that the work source was not set using #setWorkSource. - // - // This constant needs to be kept in sync with Binder.UNSET_WORKSOURCE from the Java - // side. - static const int32_t kUnsetWorkSource = -1; + LIBBINDER_EXPORTED static void disableBackgroundScheduling(bool disable); + LIBBINDER_EXPORTED bool backgroundSchedulingDisabled(); + + // Call blocks until the number of executing binder threads is less than + // the maximum number of binder threads threads allowed for this process. + LIBBINDER_EXPORTED void blockUntilThreadAvailable(); + + // Service manager registration + LIBBINDER_EXPORTED void setTheContextObject(const sp<BBinder>& obj); + + // WARNING: DO NOT USE THIS API + // + // Returns a pointer to the stack from the last time a transaction + // was initiated by the kernel. Used to compare when making nested + // calls between multiple different transports. + LIBBINDER_EXPORTED const void* getServingStackPointer() const; + + // The work source represents the UID of the process we should attribute the transaction + // to. We use -1 to specify that the work source was not set using #setWorkSource. + // + // This constant needs to be kept in sync with Binder.UNSET_WORKSOURCE from the Java + // side. + LIBBINDER_EXPORTED static const int32_t kUnsetWorkSource = -1; + private: - IPCThreadState(); - ~IPCThreadState(); - - status_t sendReply(const Parcel& reply, uint32_t flags); - status_t waitForResponse(Parcel *reply, - status_t *acquireResult=nullptr); - status_t talkWithDriver(bool doReceive=true); - status_t writeTransactionData(int32_t cmd, - uint32_t binderFlags, - int32_t handle, - uint32_t code, - const Parcel& data, - status_t* statusBuffer); - status_t getAndExecuteCommand(); - status_t executeCommand(int32_t command); - void processPendingDerefs(); - void processPostWriteDerefs(); - - void clearCaller(); + IPCThreadState(); + ~IPCThreadState(); + + status_t sendReply(const Parcel& reply, uint32_t flags); + status_t waitForResponse(Parcel* reply, status_t* acquireResult = nullptr); + status_t talkWithDriver(bool doReceive = true); + status_t writeTransactionData(int32_t cmd, uint32_t binderFlags, int32_t handle, uint32_t code, + const Parcel& data, status_t* statusBuffer); + status_t getAndExecuteCommand(); + status_t executeCommand(int32_t command); + void processPendingDerefs(); + void processPostWriteDerefs(); + + void clearCaller(); static void threadDestructor(void *st); static void freeBuffer(const uint8_t* data, size_t dataSize, const binder_size_t* objects, diff --git a/libs/binder/include/binder/IPermissionController.h b/libs/binder/include/binder/IPermissionController.h index a4f93d9b56..2bf9e71275 100644 --- a/libs/binder/include/binder/IPermissionController.h +++ b/libs/binder/include/binder/IPermissionController.h @@ -18,6 +18,7 @@ #ifndef __ANDROID_VNDK__ +#include <binder/Common.h> #include <binder/IInterface.h> #include <stdlib.h> @@ -25,8 +26,7 @@ namespace android { // ---------------------------------------------------------------------- -class IPermissionController : public IInterface -{ +class LIBBINDER_EXPORTED IPermissionController : public IInterface { public: DECLARE_META_INTERFACE(PermissionController) @@ -51,8 +51,7 @@ public: // ---------------------------------------------------------------------- -class BnPermissionController : public BnInterface<IPermissionController> -{ +class LIBBINDER_EXPORTED BnPermissionController : public BnInterface<IPermissionController> { public: // NOLINTNEXTLINE(google-default-arguments) virtual status_t onTransact( uint32_t code, diff --git a/libs/binder/include/binder/IResultReceiver.h b/libs/binder/include/binder/IResultReceiver.h index 5434445cf8..b72cf11831 100644 --- a/libs/binder/include/binder/IResultReceiver.h +++ b/libs/binder/include/binder/IResultReceiver.h @@ -16,14 +16,14 @@ #pragma once +#include <binder/Common.h> #include <binder/IInterface.h> namespace android { // ---------------------------------------------------------------------- -class IResultReceiver : public IInterface -{ +class LIBBINDER_EXPORTED IResultReceiver : public IInterface { public: DECLARE_META_INTERFACE(ResultReceiver) @@ -36,8 +36,7 @@ public: // ---------------------------------------------------------------------- -class BnResultReceiver : public BnInterface<IResultReceiver> -{ +class LIBBINDER_EXPORTED BnResultReceiver : public BnInterface<IResultReceiver> { public: // NOLINTNEXTLINE(google-default-arguments) virtual status_t onTransact( uint32_t code, diff --git a/libs/binder/include/binder/IServiceManager.h b/libs/binder/include/binder/IServiceManager.h index 486bdfba78..5fb73079cb 100644 --- a/libs/binder/include/binder/IServiceManager.h +++ b/libs/binder/include/binder/IServiceManager.h @@ -15,6 +15,7 @@ */ #pragma once +#include <binder/Common.h> #include <binder/IInterface.h> #include <utils/Vector.h> #include <utils/String16.h> @@ -29,8 +30,7 @@ namespace android { * * IInterface is only for legacy ABI compatibility */ -class IServiceManager : public IInterface -{ +class LIBBINDER_EXPORTED IServiceManager : public IInterface { public: // for ABI compatibility virtual const String16& getInterfaceDescriptor() const; @@ -149,7 +149,7 @@ public: virtual std::vector<ServiceDebugInfo> getServiceDebugInfo() = 0; }; -sp<IServiceManager> defaultServiceManager(); +LIBBINDER_EXPORTED sp<IServiceManager> defaultServiceManager(); /** * Directly set the default service manager. Only used for testing. @@ -157,7 +157,7 @@ sp<IServiceManager> defaultServiceManager(); * *before* any call to defaultServiceManager(); if the latter is * called first, setDefaultServiceManager() will abort. */ -void setDefaultServiceManager(const sp<IServiceManager>& sm); +LIBBINDER_EXPORTED void setDefaultServiceManager(const sp<IServiceManager>& sm); template<typename INTERFACE> sp<INTERFACE> waitForService(const String16& name) { @@ -207,13 +207,14 @@ status_t getService(const String16& name, sp<INTERFACE>* outService) return NAME_NOT_FOUND; } -void* openDeclaredPassthroughHal(const String16& interface, const String16& instance, int flag); +LIBBINDER_EXPORTED void* openDeclaredPassthroughHal(const String16& interface, + const String16& instance, int flag); -bool checkCallingPermission(const String16& permission); -bool checkCallingPermission(const String16& permission, - int32_t* outPid, int32_t* outUid); -bool checkPermission(const String16& permission, pid_t pid, uid_t uid, - bool logPermissionFailure = true); +LIBBINDER_EXPORTED bool checkCallingPermission(const String16& permission); +LIBBINDER_EXPORTED bool checkCallingPermission(const String16& permission, int32_t* outPid, + int32_t* outUid); +LIBBINDER_EXPORTED bool checkPermission(const String16& permission, pid_t pid, uid_t uid, + bool logPermissionFailure = true); #ifndef __ANDROID__ // Create an IServiceManager that delegates the service manager on the device via adb. @@ -233,7 +234,7 @@ bool checkPermission(const String16& permission, pid_t pid, uid_t uid, struct RpcDelegateServiceManagerOptions { std::optional<size_t> maxOutgoingConnections; }; -sp<IServiceManager> createRpcDelegateServiceManager( +LIBBINDER_EXPORTED sp<IServiceManager> createRpcDelegateServiceManager( const RpcDelegateServiceManagerOptions& options); #endif diff --git a/libs/binder/include/binder/IShellCallback.h b/libs/binder/include/binder/IShellCallback.h index 6d3fe4a13e..4324afc4d0 100644 --- a/libs/binder/include/binder/IShellCallback.h +++ b/libs/binder/include/binder/IShellCallback.h @@ -16,14 +16,14 @@ #pragma once +#include <binder/Common.h> #include <binder/IInterface.h> namespace android { // ---------------------------------------------------------------------- -class IShellCallback : public IInterface -{ +class LIBBINDER_EXPORTED IShellCallback : public IInterface { public: DECLARE_META_INTERFACE(ShellCallback) @@ -37,8 +37,7 @@ public: // ---------------------------------------------------------------------- -class BnShellCallback : public BnInterface<IShellCallback> -{ +class LIBBINDER_EXPORTED BnShellCallback : public BnInterface<IShellCallback> { public: // NOLINTNEXTLINE(google-default-arguments) virtual status_t onTransact( uint32_t code, diff --git a/libs/binder/include/binder/LazyServiceRegistrar.h b/libs/binder/include/binder/LazyServiceRegistrar.h index bda3d19ee1..3436b11bd1 100644 --- a/libs/binder/include/binder/LazyServiceRegistrar.h +++ b/libs/binder/include/binder/LazyServiceRegistrar.h @@ -18,6 +18,7 @@ #include <functional> +#include <binder/Common.h> #include <binder/IServiceManager.h> #include <binder/Status.h> #include <utils/StrongPointer.h> @@ -42,70 +43,71 @@ class ClientCounterCallback; * For more information on init .rc configuration, see system/core/init/README.md **/ class LazyServiceRegistrar { - public: - static LazyServiceRegistrar& getInstance(); - status_t registerService(const sp<IBinder>& service, - const std::string& name = "default", - bool allowIsolated = false, - 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. - * - * 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); +public: + LIBBINDER_EXPORTED static LazyServiceRegistrar& getInstance(); + LIBBINDER_EXPORTED status_t + registerService(const sp<IBinder>& service, const std::string& name = "default", + bool allowIsolated = false, + 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. + * + * 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. + */ + LIBBINDER_EXPORTED void forcePersist(bool persist); - /** - * Set a callback that is invoked when the active service count (i.e. services with clients) - * registered with this process drops to zero (or becomes nonzero). - * The callback takes a boolean argument, which is 'true' if there is - * at least one service with clients. - * - * Callback return value: - * - false: Default behavior for lazy services (shut down the process if there - * are no clients). - * - true: Don't shut down the process even if there are no clients. - * - * This callback gives a chance to: - * 1 - Perform some additional operations before exiting; - * 2 - Prevent the process from exiting by returning "true" from the - * callback. - * - * This method should be called before 'registerService' to avoid races. - */ - void setActiveServicesCallback(const std::function<bool(bool)>& activeServicesCallback); + /** + * Set a callback that is invoked when the active service count (i.e. services with clients) + * registered with this process drops to zero (or becomes nonzero). + * The callback takes a boolean argument, which is 'true' if there is + * at least one service with clients. + * + * Callback return value: + * - false: Default behavior for lazy services (shut down the process if there + * are no clients). + * - true: Don't shut down the process even if there are no clients. + * + * This callback gives a chance to: + * 1 - Perform some additional operations before exiting; + * 2 - Prevent the process from exiting by returning "true" from the + * callback. + * + * This method should be called before 'registerService' to avoid races. + */ + LIBBINDER_EXPORTED void setActiveServicesCallback( + const std::function<bool(bool)>& activeServicesCallback); - /** - * Try to unregister all services previously registered with 'registerService'. - * Returns 'true' if successful. This should only be called within the callback registered by - * setActiveServicesCallback. - */ - bool tryUnregister(); + /** + * Try to unregister all services previously registered with 'registerService'. + * Returns 'true' if successful. This should only be called within the callback registered by + * setActiveServicesCallback. + */ + LIBBINDER_EXPORTED bool tryUnregister(); - /** - * Re-register services that were unregistered by 'tryUnregister'. - * This method should be called in the case 'tryUnregister' fails - * (and should be called on the same thread). - */ - void reRegister(); + /** + * Re-register services that were unregistered by 'tryUnregister'. + * This method should be called in the case 'tryUnregister' fails + * (and should be called on the same thread). + */ + LIBBINDER_EXPORTED void reRegister(); - /** - * Create a second instance of lazy service registrar. - * - * WARNING: dangerous! DO NOT USE THIS - LazyServiceRegistrar - * should be single-instanced, so that the service will only - * shut down when all services are unused. A separate instance - * is only used to test race conditions. - */ - static LazyServiceRegistrar createExtraTestInstance(); + /** + * Create a second instance of lazy service registrar. + * + * WARNING: dangerous! DO NOT USE THIS - LazyServiceRegistrar + * should be single-instanced, so that the service will only + * shut down when all services are unused. A separate instance + * is only used to test race conditions. + */ + LIBBINDER_EXPORTED static LazyServiceRegistrar createExtraTestInstance(); - private: - std::shared_ptr<internal::ClientCounterCallback> mClientCC; - LazyServiceRegistrar(); +private: + std::shared_ptr<internal::ClientCounterCallback> mClientCC; + LazyServiceRegistrar(); }; } // namespace binder diff --git a/libs/binder/include/binder/MemoryBase.h b/libs/binder/include/binder/MemoryBase.h index 61a029cd1d..04cd1a43e0 100644 --- a/libs/binder/include/binder/MemoryBase.h +++ b/libs/binder/include/binder/MemoryBase.h @@ -19,6 +19,7 @@ #include <stdlib.h> #include <stdint.h> +#include <binder/Common.h> #include <binder/IMemory.h> @@ -26,8 +27,7 @@ namespace android { // --------------------------------------------------------------------------- -class MemoryBase : public BnMemory -{ +class LIBBINDER_EXPORTED MemoryBase : public BnMemory { public: MemoryBase(const sp<IMemoryHeap>& heap, ssize_t offset, size_t size); virtual ~MemoryBase(); diff --git a/libs/binder/include/binder/MemoryDealer.h b/libs/binder/include/binder/MemoryDealer.h index 3f7dd11933..b979da52cf 100644 --- a/libs/binder/include/binder/MemoryDealer.h +++ b/libs/binder/include/binder/MemoryDealer.h @@ -19,6 +19,7 @@ #include <stdint.h> #include <sys/types.h> +#include <binder/Common.h> #include <binder/IMemory.h> #include <binder/MemoryHeapBase.h> @@ -29,33 +30,32 @@ class SimpleBestFitAllocator; // ---------------------------------------------------------------------------- -class MemoryDealer : public RefBase -{ +class MemoryDealer : public RefBase { public: - explicit MemoryDealer(size_t size, const char* name = nullptr, - uint32_t flags = 0 /* or bits such as MemoryHeapBase::READ_ONLY */ ); + LIBBINDER_EXPORTED explicit MemoryDealer( + size_t size, const char* name = nullptr, + uint32_t flags = 0 /* or bits such as MemoryHeapBase::READ_ONLY */); - virtual sp<IMemory> allocate(size_t size); - virtual void dump(const char* what) const; + LIBBINDER_EXPORTED virtual sp<IMemory> allocate(size_t size); + LIBBINDER_EXPORTED virtual void dump(const char* what) const; // allocations are aligned to some value. return that value so clients can account for it. - static size_t getAllocationAlignment(); + LIBBINDER_EXPORTED static size_t getAllocationAlignment(); sp<IMemoryHeap> getMemoryHeap() const { return heap(); } protected: - virtual ~MemoryDealer(); + LIBBINDER_EXPORTED virtual ~MemoryDealer(); private: friend class Allocation; virtual void deallocate(size_t offset); - const sp<IMemoryHeap>& heap() const; + LIBBINDER_EXPORTED const sp<IMemoryHeap>& heap() const; SimpleBestFitAllocator* allocator() const; sp<IMemoryHeap> mHeap; SimpleBestFitAllocator* mAllocator; }; - // ---------------------------------------------------------------------------- } // namespace android diff --git a/libs/binder/include/binder/MemoryHeapBase.h b/libs/binder/include/binder/MemoryHeapBase.h index c7177bd8eb..ff2d09fc2b 100644 --- a/libs/binder/include/binder/MemoryHeapBase.h +++ b/libs/binder/include/binder/MemoryHeapBase.h @@ -19,6 +19,7 @@ #include <stdlib.h> #include <stdint.h> +#include <binder/Common.h> #include <binder/IMemory.h> @@ -26,8 +27,7 @@ namespace android { // --------------------------------------------------------------------------- -class MemoryHeapBase : public BnMemoryHeap -{ +class MemoryHeapBase : public BnMemoryHeap { public: static constexpr auto MEMFD_ALLOW_SEALING_FLAG = 0x00000800; enum { @@ -56,42 +56,44 @@ public: * maps the memory referenced by fd. but DOESN'T take ownership * of the filedescriptor (it makes a copy with dup() */ - MemoryHeapBase(int fd, size_t size, uint32_t flags = 0, off_t offset = 0); + LIBBINDER_EXPORTED MemoryHeapBase(int fd, size_t size, uint32_t flags = 0, off_t offset = 0); /* * maps memory from the given device */ - explicit MemoryHeapBase(const char* device, size_t size = 0, uint32_t flags = 0); + LIBBINDER_EXPORTED explicit MemoryHeapBase(const char* device, size_t size = 0, + uint32_t flags = 0); /* * maps memory from ashmem, with the given name for debugging * if the READ_ONLY flag is set, the memory will be writeable by the calling process, * but not by others. this is NOT the case with the other ctors. */ - explicit MemoryHeapBase(size_t size, uint32_t flags = 0, char const* name = nullptr); + LIBBINDER_EXPORTED explicit MemoryHeapBase(size_t size, uint32_t flags = 0, + char const* name = nullptr); - virtual ~MemoryHeapBase(); + LIBBINDER_EXPORTED virtual ~MemoryHeapBase(); /* implement IMemoryHeap interface */ - int getHeapID() const override; + LIBBINDER_EXPORTED int getHeapID() const override; /* virtual address of the heap. returns MAP_FAILED in case of error */ - void* getBase() const override; + LIBBINDER_EXPORTED void* getBase() const override; - size_t getSize() const override; - uint32_t getFlags() const override; - off_t getOffset() const override; + LIBBINDER_EXPORTED size_t getSize() const override; + LIBBINDER_EXPORTED uint32_t getFlags() const override; + LIBBINDER_EXPORTED off_t getOffset() const override; - const char* getDevice() const; + LIBBINDER_EXPORTED const char* getDevice() const; /* this closes this heap -- use carefully */ - void dispose(); + LIBBINDER_EXPORTED void dispose(); protected: - MemoryHeapBase(); + LIBBINDER_EXPORTED MemoryHeapBase(); // init() takes ownership of fd - status_t init(int fd, void *base, size_t size, - int flags = 0, const char* device = nullptr); + LIBBINDER_EXPORTED status_t init(int fd, void* base, size_t size, int flags = 0, + const char* device = nullptr); private: status_t mapfd(int fd, bool writeableByCaller, size_t size, off_t offset = 0); diff --git a/libs/binder/include/binder/Parcel.h b/libs/binder/include/binder/Parcel.h index 5e18b9197d..5cc0830c88 100644 --- a/libs/binder/include/binder/Parcel.h +++ b/libs/binder/include/binder/Parcel.h @@ -34,6 +34,7 @@ #include <utils/String16.h> #include <utils/Vector.h> +#include <binder/Common.h> #include <binder/IInterface.h> #include <binder/Parcelable.h> @@ -68,73 +69,74 @@ public: class ReadableBlob; class WritableBlob; - Parcel(); - ~Parcel(); - - const uint8_t* data() const; - size_t dataSize() const; - size_t dataAvail() const; - size_t dataPosition() const; - size_t dataCapacity() const; - size_t dataBufferSize() const; + LIBBINDER_EXPORTED Parcel(); + LIBBINDER_EXPORTED ~Parcel(); - status_t setDataSize(size_t size); + LIBBINDER_EXPORTED const uint8_t* data() const; + LIBBINDER_EXPORTED size_t dataSize() const; + LIBBINDER_EXPORTED size_t dataAvail() const; + LIBBINDER_EXPORTED size_t dataPosition() const; + LIBBINDER_EXPORTED size_t dataCapacity() const; + LIBBINDER_EXPORTED size_t dataBufferSize() const; + + LIBBINDER_EXPORTED status_t setDataSize(size_t size); // this must only be used to set a data position that was previously returned from // dataPosition(). If writes are made, the exact same types of writes must be made (e.g. // auto i = p.dataPosition(); p.writeInt32(0); p.setDataPosition(i); p.writeInt32(1);). // Writing over objects, such as file descriptors and binders, is not supported. - void setDataPosition(size_t pos) const; - status_t setDataCapacity(size_t size); + LIBBINDER_EXPORTED void setDataPosition(size_t pos) const; + LIBBINDER_EXPORTED status_t setDataCapacity(size_t size); - status_t setData(const uint8_t* buffer, size_t len); + LIBBINDER_EXPORTED status_t setData(const uint8_t* buffer, size_t len); - status_t appendFrom(const Parcel *parcel, - size_t start, size_t len); + LIBBINDER_EXPORTED status_t appendFrom(const Parcel* parcel, size_t start, size_t len); - int compareData(const Parcel& other); - status_t compareDataInRange(size_t thisOffset, const Parcel& other, size_t otherOffset, - size_t length, int* result) const; + LIBBINDER_EXPORTED int compareData(const Parcel& other); + LIBBINDER_EXPORTED status_t compareDataInRange(size_t thisOffset, const Parcel& other, + size_t otherOffset, size_t length, + int* result) const; - bool allowFds() const; - bool pushAllowFds(bool allowFds); - void restoreAllowFds(bool lastValue); + LIBBINDER_EXPORTED bool allowFds() const; + LIBBINDER_EXPORTED bool pushAllowFds(bool allowFds); + LIBBINDER_EXPORTED void restoreAllowFds(bool lastValue); - bool hasFileDescriptors() const; - status_t hasBinders(bool* result) const; - status_t hasFileDescriptorsInRange(size_t offset, size_t length, bool* result) const; - status_t hasBindersInRange(size_t offset, size_t length, bool* result) const; + LIBBINDER_EXPORTED bool hasFileDescriptors() const; + LIBBINDER_EXPORTED status_t hasBinders(bool* result) const; + LIBBINDER_EXPORTED status_t hasFileDescriptorsInRange(size_t offset, size_t length, + bool* result) const; + LIBBINDER_EXPORTED status_t hasBindersInRange(size_t offset, size_t length, bool* result) const; // returns all binder objects in the Parcel - std::vector<sp<IBinder>> debugReadAllStrongBinders() const; + LIBBINDER_EXPORTED std::vector<sp<IBinder>> debugReadAllStrongBinders() const; // returns all file descriptors in the Parcel // does not dup - std::vector<int> debugReadAllFileDescriptors() const; + LIBBINDER_EXPORTED std::vector<int> debugReadAllFileDescriptors() const; // Zeros data when reallocating. Other mitigations may be added // in the future. // // WARNING: some read methods may make additional copies of data. // In order to verify this, heap dumps should be used. - void markSensitive() const; + LIBBINDER_EXPORTED void markSensitive() const; // For a 'data' Parcel, this should mark the Parcel as being prepared for a // transaction on this specific binder object. Based on this, the format of // the wire binder protocol may change (data is written differently when it // is for an RPC transaction). - void markForBinder(const sp<IBinder>& binder); + LIBBINDER_EXPORTED void markForBinder(const sp<IBinder>& binder); // Whenever possible, markForBinder should be preferred. This method is // called automatically on reply Parcels for RPC transactions. - void markForRpc(const sp<RpcSession>& session); + LIBBINDER_EXPORTED void markForRpc(const sp<RpcSession>& session); // Whether this Parcel is written for RPC transactions (after calls to // markForBinder or markForRpc). - bool isForRpc() const; + LIBBINDER_EXPORTED bool isForRpc() const; // Writes the IPC/RPC header. - status_t writeInterfaceToken(const String16& interface); - status_t writeInterfaceToken(const char16_t* str, size_t len); + LIBBINDER_EXPORTED status_t writeInterfaceToken(const String16& interface); + LIBBINDER_EXPORTED status_t writeInterfaceToken(const char16_t* str, size_t len); // Parses the RPC header, returning true if the interface name // in the header matches the expected interface from the caller. @@ -143,101 +145,116 @@ public: // propagating the StrictMode policy mask, populating the current // IPCThreadState, which as an optimization may optionally be // passed in. - bool enforceInterface(const String16& interface, - IPCThreadState* threadState = nullptr) const; - bool enforceInterface(const char16_t* interface, - size_t len, - IPCThreadState* threadState = nullptr) const; - bool checkInterface(IBinder*) const; + LIBBINDER_EXPORTED bool enforceInterface(const String16& interface, + IPCThreadState* threadState = nullptr) const; + LIBBINDER_EXPORTED bool enforceInterface(const char16_t* interface, size_t len, + IPCThreadState* threadState = nullptr) const; + LIBBINDER_EXPORTED bool checkInterface(IBinder*) const; // Verify there are no bytes left to be read on the Parcel. // Returns Status(EX_BAD_PARCELABLE) when the Parcel is not consumed. - binder::Status enforceNoDataAvail() const; + LIBBINDER_EXPORTED binder::Status enforceNoDataAvail() const; // This Api is used by fuzzers to skip dataAvail checks. - void setEnforceNoDataAvail(bool enforceNoDataAvail); + LIBBINDER_EXPORTED void setEnforceNoDataAvail(bool enforceNoDataAvail); // When fuzzing, we want to remove certain ABI checks that cause significant // lost coverage, and we also want to avoid logs that cost too much to write. - void setServiceFuzzing(); - bool isServiceFuzzing() const; - - void freeData(); - - size_t objectsCount() const; - - status_t errorCheck() const; - void setError(status_t err); - - status_t write(const void* data, size_t len); - void* writeInplace(size_t len); - status_t writeUnpadded(const void* data, size_t len); - status_t writeInt32(int32_t val); - status_t writeUint32(uint32_t val); - status_t writeInt64(int64_t val); - status_t writeUint64(uint64_t val); - status_t writeFloat(float val); - status_t writeDouble(double val); - status_t writeCString(const char* str); - status_t writeString8(const String8& str); - status_t writeString8(const char* str, size_t len); - status_t writeString16(const String16& str); - status_t writeString16(const std::optional<String16>& str); - status_t writeString16(const std::unique_ptr<String16>& str) __attribute__((deprecated("use std::optional version instead"))); - status_t writeString16(const char16_t* str, size_t len); - status_t writeStrongBinder(const sp<IBinder>& val); - status_t writeInt32Array(size_t len, const int32_t *val); - status_t writeByteArray(size_t len, const uint8_t *val); - status_t writeBool(bool val); - status_t writeChar(char16_t val); - status_t writeByte(int8_t val); + LIBBINDER_EXPORTED void setServiceFuzzing(); + LIBBINDER_EXPORTED bool isServiceFuzzing() const; + + LIBBINDER_EXPORTED void freeData(); + + LIBBINDER_EXPORTED size_t objectsCount() const; + + LIBBINDER_EXPORTED status_t errorCheck() const; + LIBBINDER_EXPORTED void setError(status_t err); + + LIBBINDER_EXPORTED status_t write(const void* data, size_t len); + LIBBINDER_EXPORTED void* writeInplace(size_t len); + LIBBINDER_EXPORTED status_t writeUnpadded(const void* data, size_t len); + LIBBINDER_EXPORTED status_t writeInt32(int32_t val); + LIBBINDER_EXPORTED status_t writeUint32(uint32_t val); + LIBBINDER_EXPORTED status_t writeInt64(int64_t val); + LIBBINDER_EXPORTED status_t writeUint64(uint64_t val); + LIBBINDER_EXPORTED status_t writeFloat(float val); + LIBBINDER_EXPORTED status_t writeDouble(double val); + LIBBINDER_EXPORTED status_t writeCString(const char* str); + LIBBINDER_EXPORTED status_t writeString8(const String8& str); + LIBBINDER_EXPORTED status_t writeString8(const char* str, size_t len); + LIBBINDER_EXPORTED status_t writeString16(const String16& str); + LIBBINDER_EXPORTED status_t writeString16(const std::optional<String16>& str); + LIBBINDER_EXPORTED status_t writeString16(const std::unique_ptr<String16>& str) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeString16(const char16_t* str, size_t len); + LIBBINDER_EXPORTED status_t writeStrongBinder(const sp<IBinder>& val); + LIBBINDER_EXPORTED status_t writeInt32Array(size_t len, const int32_t* val); + LIBBINDER_EXPORTED status_t writeByteArray(size_t len, const uint8_t* val); + LIBBINDER_EXPORTED status_t writeBool(bool val); + LIBBINDER_EXPORTED status_t writeChar(char16_t val); + LIBBINDER_EXPORTED status_t writeByte(int8_t val); // Take a UTF8 encoded string, convert to UTF16, write it to the parcel. - status_t writeUtf8AsUtf16(const std::string& str); - status_t writeUtf8AsUtf16(const std::optional<std::string>& str); - status_t writeUtf8AsUtf16(const std::unique_ptr<std::string>& str) __attribute__((deprecated("use std::optional version instead"))); - - status_t writeByteVector(const std::optional<std::vector<int8_t>>& val); - status_t writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeByteVector(const std::vector<int8_t>& val); - status_t writeByteVector(const std::optional<std::vector<uint8_t>>& val); - status_t writeByteVector(const std::unique_ptr<std::vector<uint8_t>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeByteVector(const std::vector<uint8_t>& val); - status_t writeInt32Vector(const std::optional<std::vector<int32_t>>& val); - status_t writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeInt32Vector(const std::vector<int32_t>& val); - status_t writeInt64Vector(const std::optional<std::vector<int64_t>>& val); - status_t writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeInt64Vector(const std::vector<int64_t>& val); - status_t writeUint64Vector(const std::optional<std::vector<uint64_t>>& val); - status_t writeUint64Vector(const std::unique_ptr<std::vector<uint64_t>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeUint64Vector(const std::vector<uint64_t>& val); - status_t writeFloatVector(const std::optional<std::vector<float>>& val); - status_t writeFloatVector(const std::unique_ptr<std::vector<float>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeFloatVector(const std::vector<float>& val); - status_t writeDoubleVector(const std::optional<std::vector<double>>& val); - status_t writeDoubleVector(const std::unique_ptr<std::vector<double>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeDoubleVector(const std::vector<double>& val); - status_t writeBoolVector(const std::optional<std::vector<bool>>& val); - status_t writeBoolVector(const std::unique_ptr<std::vector<bool>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeBoolVector(const std::vector<bool>& val); - status_t writeCharVector(const std::optional<std::vector<char16_t>>& val); - status_t writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeCharVector(const std::vector<char16_t>& val); - status_t writeString16Vector( - const std::optional<std::vector<std::optional<String16>>>& val); - status_t writeString16Vector( - const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeString16Vector(const std::vector<String16>& val); - status_t writeUtf8VectorAsUtf16Vector( - const std::optional<std::vector<std::optional<std::string>>>& val); - status_t writeUtf8VectorAsUtf16Vector( - const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val); - - status_t writeStrongBinderVector(const std::optional<std::vector<sp<IBinder>>>& val); - status_t writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeStrongBinderVector(const std::vector<sp<IBinder>>& val); + LIBBINDER_EXPORTED status_t writeUtf8AsUtf16(const std::string& str); + LIBBINDER_EXPORTED status_t writeUtf8AsUtf16(const std::optional<std::string>& str); + LIBBINDER_EXPORTED status_t writeUtf8AsUtf16(const std::unique_ptr<std::string>& str) + __attribute__((deprecated("use std::optional version instead"))); + + LIBBINDER_EXPORTED status_t writeByteVector(const std::optional<std::vector<int8_t>>& val); + LIBBINDER_EXPORTED status_t writeByteVector(const std::unique_ptr<std::vector<int8_t>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeByteVector(const std::vector<int8_t>& val); + LIBBINDER_EXPORTED status_t writeByteVector(const std::optional<std::vector<uint8_t>>& val); + LIBBINDER_EXPORTED status_t writeByteVector(const std::unique_ptr<std::vector<uint8_t>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeByteVector(const std::vector<uint8_t>& val); + LIBBINDER_EXPORTED status_t writeInt32Vector(const std::optional<std::vector<int32_t>>& val); + LIBBINDER_EXPORTED status_t writeInt32Vector(const std::unique_ptr<std::vector<int32_t>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeInt32Vector(const std::vector<int32_t>& val); + LIBBINDER_EXPORTED status_t writeInt64Vector(const std::optional<std::vector<int64_t>>& val); + LIBBINDER_EXPORTED status_t writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeInt64Vector(const std::vector<int64_t>& val); + LIBBINDER_EXPORTED status_t writeUint64Vector(const std::optional<std::vector<uint64_t>>& val); + LIBBINDER_EXPORTED status_t writeUint64Vector(const std::unique_ptr<std::vector<uint64_t>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeUint64Vector(const std::vector<uint64_t>& val); + LIBBINDER_EXPORTED status_t writeFloatVector(const std::optional<std::vector<float>>& val); + LIBBINDER_EXPORTED status_t writeFloatVector(const std::unique_ptr<std::vector<float>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeFloatVector(const std::vector<float>& val); + LIBBINDER_EXPORTED status_t writeDoubleVector(const std::optional<std::vector<double>>& val); + LIBBINDER_EXPORTED status_t writeDoubleVector(const std::unique_ptr<std::vector<double>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeDoubleVector(const std::vector<double>& val); + LIBBINDER_EXPORTED status_t writeBoolVector(const std::optional<std::vector<bool>>& val); + LIBBINDER_EXPORTED status_t writeBoolVector(const std::unique_ptr<std::vector<bool>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeBoolVector(const std::vector<bool>& val); + LIBBINDER_EXPORTED status_t writeCharVector(const std::optional<std::vector<char16_t>>& val); + LIBBINDER_EXPORTED status_t writeCharVector(const std::unique_ptr<std::vector<char16_t>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeCharVector(const std::vector<char16_t>& val); + LIBBINDER_EXPORTED status_t + writeString16Vector(const std::optional<std::vector<std::optional<String16>>>& val); + LIBBINDER_EXPORTED status_t + writeString16Vector(const std::unique_ptr<std::vector<std::unique_ptr<String16>>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeString16Vector(const std::vector<String16>& val); + LIBBINDER_EXPORTED status_t + writeUtf8VectorAsUtf16Vector(const std::optional<std::vector<std::optional<std::string>>>& val); + LIBBINDER_EXPORTED status_t writeUtf8VectorAsUtf16Vector( + const std::unique_ptr<std::vector<std::unique_ptr<std::string>>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeUtf8VectorAsUtf16Vector(const std::vector<std::string>& val); + + LIBBINDER_EXPORTED status_t + writeStrongBinderVector(const std::optional<std::vector<sp<IBinder>>>& val); + LIBBINDER_EXPORTED status_t + writeStrongBinderVector(const std::unique_ptr<std::vector<sp<IBinder>>>& val) + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t writeStrongBinderVector(const std::vector<sp<IBinder>>& val); // Write an IInterface or a vector of IInterface's template <typename T, @@ -315,7 +332,7 @@ public: return writeData(parcelable); } - status_t writeParcelable(const Parcelable& parcelable); + LIBBINDER_EXPORTED status_t writeParcelable(const Parcelable& parcelable); template<typename T> status_t write(const Flattenable<T>& val); @@ -335,40 +352,41 @@ public: // descriptors are dup'ed, so it is safe to delete the native_handle // when this function returns). // Doesn't take ownership of the native_handle. - status_t writeNativeHandle(const native_handle* handle); + LIBBINDER_EXPORTED status_t writeNativeHandle(const native_handle* handle); #endif // Place a file descriptor into the parcel. The given fd must remain // valid for the lifetime of the parcel. // The Parcel does not take ownership of the given fd unless you ask it to. - status_t writeFileDescriptor(int fd, bool takeOwnership = false); + LIBBINDER_EXPORTED status_t writeFileDescriptor(int fd, bool takeOwnership = false); // Place a file descriptor into the parcel. A dup of the fd is made, which // will be closed once the parcel is destroyed. - status_t writeDupFileDescriptor(int fd); + LIBBINDER_EXPORTED status_t writeDupFileDescriptor(int fd); // Place a Java "parcel file descriptor" into the parcel. The given fd must remain // valid for the lifetime of the parcel. // The Parcel does not take ownership of the given fd unless you ask it to. - status_t writeParcelFileDescriptor(int fd, bool takeOwnership = false); + LIBBINDER_EXPORTED status_t writeParcelFileDescriptor(int fd, bool takeOwnership = false); // Place a Java "parcel file descriptor" into the parcel. A dup of the fd is made, which will // be closed once the parcel is destroyed. - status_t writeDupParcelFileDescriptor(int fd); + LIBBINDER_EXPORTED status_t writeDupParcelFileDescriptor(int fd); // Place a file descriptor into the parcel. This will not affect the // semantics of the smart file descriptor. A new descriptor will be // created, and will be closed when the parcel is destroyed. - status_t writeUniqueFileDescriptor(const binder::unique_fd& fd); + LIBBINDER_EXPORTED status_t writeUniqueFileDescriptor(const binder::unique_fd& fd); // Place a vector of file desciptors into the parcel. Each descriptor is // dup'd as in writeDupFileDescriptor - status_t writeUniqueFileDescriptorVector( - const std::optional<std::vector<binder::unique_fd>>& val); - status_t writeUniqueFileDescriptorVector( - const std::unique_ptr<std::vector<binder::unique_fd>>& val) + LIBBINDER_EXPORTED status_t + writeUniqueFileDescriptorVector(const std::optional<std::vector<binder::unique_fd>>& val); + LIBBINDER_EXPORTED status_t + writeUniqueFileDescriptorVector(const std::unique_ptr<std::vector<binder::unique_fd>>& val) __attribute__((deprecated("use std::optional version instead"))); - status_t writeUniqueFileDescriptorVector(const std::vector<binder::unique_fd>& val); + LIBBINDER_EXPORTED status_t + writeUniqueFileDescriptorVector(const std::vector<binder::unique_fd>& val); // Writes a blob to the parcel. // If the blob is small, then it is stored in-place, otherwise it is @@ -376,58 +394,60 @@ public: // immutable blobs if possible since they may be subsequently transferred between // processes without further copying whereas mutable blobs always need to be copied. // The caller should call release() on the blob after writing its contents. - status_t writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob); + LIBBINDER_EXPORTED status_t writeBlob(size_t len, bool mutableCopy, WritableBlob* outBlob); // Write an existing immutable blob file descriptor to the parcel. // This allows the client to send the same blob to multiple processes // as long as it keeps a dup of the blob file descriptor handy for later. - status_t writeDupImmutableBlobFileDescriptor(int fd); + LIBBINDER_EXPORTED status_t writeDupImmutableBlobFileDescriptor(int fd); - status_t writeObject(const flat_binder_object& val, bool nullMetaData); + LIBBINDER_EXPORTED status_t writeObject(const flat_binder_object& val, bool nullMetaData); // Like Parcel.java's writeNoException(). Just writes a zero int32. // Currently the native implementation doesn't do any of the StrictMode // stack gathering and serialization that the Java implementation does. - status_t writeNoException(); - - status_t read(void* outData, size_t len) const; - const void* readInplace(size_t len) const; - int32_t readInt32() const; - status_t readInt32(int32_t *pArg) const; - uint32_t readUint32() const; - status_t readUint32(uint32_t *pArg) const; - int64_t readInt64() const; - status_t readInt64(int64_t *pArg) const; - uint64_t readUint64() const; - status_t readUint64(uint64_t *pArg) const; - float readFloat() const; - status_t readFloat(float *pArg) const; - double readDouble() const; - status_t readDouble(double *pArg) const; - bool readBool() const; - status_t readBool(bool *pArg) const; - char16_t readChar() const; - status_t readChar(char16_t *pArg) const; - int8_t readByte() const; - status_t readByte(int8_t *pArg) const; + LIBBINDER_EXPORTED status_t writeNoException(); + + LIBBINDER_EXPORTED status_t read(void* outData, size_t len) const; + LIBBINDER_EXPORTED const void* readInplace(size_t len) const; + LIBBINDER_EXPORTED int32_t readInt32() const; + LIBBINDER_EXPORTED status_t readInt32(int32_t* pArg) const; + LIBBINDER_EXPORTED uint32_t readUint32() const; + LIBBINDER_EXPORTED status_t readUint32(uint32_t* pArg) const; + LIBBINDER_EXPORTED int64_t readInt64() const; + LIBBINDER_EXPORTED status_t readInt64(int64_t* pArg) const; + LIBBINDER_EXPORTED uint64_t readUint64() const; + LIBBINDER_EXPORTED status_t readUint64(uint64_t* pArg) const; + LIBBINDER_EXPORTED float readFloat() const; + LIBBINDER_EXPORTED status_t readFloat(float* pArg) const; + LIBBINDER_EXPORTED double readDouble() const; + LIBBINDER_EXPORTED status_t readDouble(double* pArg) const; + LIBBINDER_EXPORTED bool readBool() const; + LIBBINDER_EXPORTED status_t readBool(bool* pArg) const; + LIBBINDER_EXPORTED char16_t readChar() const; + LIBBINDER_EXPORTED status_t readChar(char16_t* pArg) const; + LIBBINDER_EXPORTED int8_t readByte() const; + LIBBINDER_EXPORTED status_t readByte(int8_t* pArg) const; // Read a UTF16 encoded string, convert to UTF8 - status_t readUtf8FromUtf16(std::string* str) const; - status_t readUtf8FromUtf16(std::optional<std::string>* str) const; - status_t readUtf8FromUtf16(std::unique_ptr<std::string>* str) const __attribute__((deprecated("use std::optional version instead"))); - - const char* readCString() const; - String8 readString8() const; - status_t readString8(String8* pArg) const; - const char* readString8Inplace(size_t* outLen) const; - String16 readString16() const; - status_t readString16(String16* pArg) const; - status_t readString16(std::optional<String16>* pArg) const; - status_t readString16(std::unique_ptr<String16>* pArg) const __attribute__((deprecated("use std::optional version instead"))); - const char16_t* readString16Inplace(size_t* outLen) const; - sp<IBinder> readStrongBinder() const; - status_t readStrongBinder(sp<IBinder>* val) const; - status_t readNullableStrongBinder(sp<IBinder>* val) const; + LIBBINDER_EXPORTED status_t readUtf8FromUtf16(std::string* str) const; + LIBBINDER_EXPORTED status_t readUtf8FromUtf16(std::optional<std::string>* str) const; + LIBBINDER_EXPORTED status_t readUtf8FromUtf16(std::unique_ptr<std::string>* str) const + __attribute__((deprecated("use std::optional version instead"))); + + LIBBINDER_EXPORTED const char* readCString() const; + LIBBINDER_EXPORTED String8 readString8() const; + LIBBINDER_EXPORTED status_t readString8(String8* pArg) const; + LIBBINDER_EXPORTED const char* readString8Inplace(size_t* outLen) const; + LIBBINDER_EXPORTED String16 readString16() const; + LIBBINDER_EXPORTED status_t readString16(String16* pArg) const; + LIBBINDER_EXPORTED status_t readString16(std::optional<String16>* pArg) const; + LIBBINDER_EXPORTED status_t readString16(std::unique_ptr<String16>* pArg) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED const char16_t* readString16Inplace(size_t* outLen) const; + LIBBINDER_EXPORTED sp<IBinder> readStrongBinder() const; + LIBBINDER_EXPORTED status_t readStrongBinder(sp<IBinder>* val) const; + LIBBINDER_EXPORTED status_t readNullableStrongBinder(sp<IBinder>* val) const; // Read an Enum vector with underlying type int8_t. // Does not use padding; each byte is contiguous. @@ -466,7 +486,7 @@ public: status_t readParcelableVector(std::vector<T>* val) const { return readData(val); } - status_t readParcelable(Parcelable* parcelable) const; + LIBBINDER_EXPORTED status_t readParcelable(Parcelable* parcelable) const; template<typename T> status_t readParcelable(std::optional<T>* parcelable) const @@ -484,9 +504,12 @@ public: template<typename T> status_t readNullableStrongBinder(sp<T>* val) const; - status_t readStrongBinderVector(std::optional<std::vector<sp<IBinder>>>* val) const; - status_t readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readStrongBinderVector(std::vector<sp<IBinder>>* val) const; + LIBBINDER_EXPORTED status_t + readStrongBinderVector(std::optional<std::vector<sp<IBinder>>>* val) const; + LIBBINDER_EXPORTED status_t + readStrongBinderVector(std::unique_ptr<std::vector<sp<IBinder>>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readStrongBinderVector(std::vector<sp<IBinder>>* val) const; template <typename T, std::enable_if_t<std::is_base_of_v<::android::IInterface, T>, bool> = true> status_t readStrongBinderVector(std::vector<sp<T>>* val) const { @@ -498,43 +521,54 @@ public: return readData(val); } - status_t readByteVector(std::optional<std::vector<int8_t>>* val) const; - status_t readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readByteVector(std::vector<int8_t>* val) const; - status_t readByteVector(std::optional<std::vector<uint8_t>>* val) const; - status_t readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readByteVector(std::vector<uint8_t>* val) const; - status_t readInt32Vector(std::optional<std::vector<int32_t>>* val) const; - status_t readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readInt32Vector(std::vector<int32_t>* val) const; - status_t readInt64Vector(std::optional<std::vector<int64_t>>* val) const; - status_t readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readInt64Vector(std::vector<int64_t>* val) const; - status_t readUint64Vector(std::optional<std::vector<uint64_t>>* val) const; - status_t readUint64Vector(std::unique_ptr<std::vector<uint64_t>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readUint64Vector(std::vector<uint64_t>* val) const; - status_t readFloatVector(std::optional<std::vector<float>>* val) const; - status_t readFloatVector(std::unique_ptr<std::vector<float>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readFloatVector(std::vector<float>* val) const; - status_t readDoubleVector(std::optional<std::vector<double>>* val) const; - status_t readDoubleVector(std::unique_ptr<std::vector<double>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readDoubleVector(std::vector<double>* val) const; - status_t readBoolVector(std::optional<std::vector<bool>>* val) const; - status_t readBoolVector(std::unique_ptr<std::vector<bool>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readBoolVector(std::vector<bool>* val) const; - status_t readCharVector(std::optional<std::vector<char16_t>>* val) const; - status_t readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readCharVector(std::vector<char16_t>* val) const; - status_t readString16Vector( - std::optional<std::vector<std::optional<String16>>>* val) const; - status_t readString16Vector( - std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readString16Vector(std::vector<String16>* val) const; - status_t readUtf8VectorFromUtf16Vector( - std::optional<std::vector<std::optional<std::string>>>* val) const; - status_t readUtf8VectorFromUtf16Vector( - std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const __attribute__((deprecated("use std::optional version instead"))); - status_t readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const; + LIBBINDER_EXPORTED status_t readByteVector(std::optional<std::vector<int8_t>>* val) const; + LIBBINDER_EXPORTED status_t readByteVector(std::unique_ptr<std::vector<int8_t>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readByteVector(std::vector<int8_t>* val) const; + LIBBINDER_EXPORTED status_t readByteVector(std::optional<std::vector<uint8_t>>* val) const; + LIBBINDER_EXPORTED status_t readByteVector(std::unique_ptr<std::vector<uint8_t>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readByteVector(std::vector<uint8_t>* val) const; + LIBBINDER_EXPORTED status_t readInt32Vector(std::optional<std::vector<int32_t>>* val) const; + LIBBINDER_EXPORTED status_t readInt32Vector(std::unique_ptr<std::vector<int32_t>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readInt32Vector(std::vector<int32_t>* val) const; + LIBBINDER_EXPORTED status_t readInt64Vector(std::optional<std::vector<int64_t>>* val) const; + LIBBINDER_EXPORTED status_t readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readInt64Vector(std::vector<int64_t>* val) const; + LIBBINDER_EXPORTED status_t readUint64Vector(std::optional<std::vector<uint64_t>>* val) const; + LIBBINDER_EXPORTED status_t readUint64Vector(std::unique_ptr<std::vector<uint64_t>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readUint64Vector(std::vector<uint64_t>* val) const; + LIBBINDER_EXPORTED status_t readFloatVector(std::optional<std::vector<float>>* val) const; + LIBBINDER_EXPORTED status_t readFloatVector(std::unique_ptr<std::vector<float>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readFloatVector(std::vector<float>* val) const; + LIBBINDER_EXPORTED status_t readDoubleVector(std::optional<std::vector<double>>* val) const; + LIBBINDER_EXPORTED status_t readDoubleVector(std::unique_ptr<std::vector<double>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readDoubleVector(std::vector<double>* val) const; + LIBBINDER_EXPORTED status_t readBoolVector(std::optional<std::vector<bool>>* val) const; + LIBBINDER_EXPORTED status_t readBoolVector(std::unique_ptr<std::vector<bool>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readBoolVector(std::vector<bool>* val) const; + LIBBINDER_EXPORTED status_t readCharVector(std::optional<std::vector<char16_t>>* val) const; + LIBBINDER_EXPORTED status_t readCharVector(std::unique_ptr<std::vector<char16_t>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readCharVector(std::vector<char16_t>* val) const; + LIBBINDER_EXPORTED status_t + readString16Vector(std::optional<std::vector<std::optional<String16>>>* val) const; + LIBBINDER_EXPORTED status_t + readString16Vector(std::unique_ptr<std::vector<std::unique_ptr<String16>>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readString16Vector(std::vector<String16>* val) const; + LIBBINDER_EXPORTED status_t readUtf8VectorFromUtf16Vector( + std::optional<std::vector<std::optional<std::string>>>* val) const; + LIBBINDER_EXPORTED status_t readUtf8VectorFromUtf16Vector( + std::unique_ptr<std::vector<std::unique_ptr<std::string>>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t readUtf8VectorFromUtf16Vector(std::vector<std::string>* val) const; template <typename T, size_t N> status_t readFixedArray(std::array<T, N>* val) const { @@ -564,56 +598,58 @@ public: // code on exceptions, but also deals with skipping over rich // response headers. Callers should use this to read & parse the // response headers rather than doing it by hand. - int32_t readExceptionCode() const; + LIBBINDER_EXPORTED int32_t readExceptionCode() const; #ifndef BINDER_DISABLE_NATIVE_HANDLE // Retrieve native_handle from the parcel. This returns a copy of the // parcel's native_handle (the caller takes ownership). The caller // must free the native_handle with native_handle_close() and // native_handle_delete(). - native_handle* readNativeHandle() const; + LIBBINDER_EXPORTED native_handle* readNativeHandle() const; #endif // Retrieve a file descriptor from the parcel. This returns the raw fd // in the parcel, which you do not own -- use dup() to get your own copy. - int readFileDescriptor() const; + LIBBINDER_EXPORTED int readFileDescriptor() const; // Retrieve a Java "parcel file descriptor" from the parcel. This returns the raw fd // in the parcel, which you do not own -- use dup() to get your own copy. - int readParcelFileDescriptor() const; + LIBBINDER_EXPORTED int readParcelFileDescriptor() const; // Retrieve a smart file descriptor from the parcel. - status_t readUniqueFileDescriptor(binder::unique_fd* val) const; + LIBBINDER_EXPORTED status_t readUniqueFileDescriptor(binder::unique_fd* val) const; // Retrieve a Java "parcel file descriptor" from the parcel. - status_t readUniqueParcelFileDescriptor(binder::unique_fd* val) const; + LIBBINDER_EXPORTED status_t readUniqueParcelFileDescriptor(binder::unique_fd* val) const; // Retrieve a vector of smart file descriptors from the parcel. - status_t readUniqueFileDescriptorVector( - std::optional<std::vector<binder::unique_fd>>* val) const; - status_t readUniqueFileDescriptorVector(std::unique_ptr<std::vector<binder::unique_fd>>* val) - const __attribute__((deprecated("use std::optional version instead"))); - status_t readUniqueFileDescriptorVector(std::vector<binder::unique_fd>* val) const; + LIBBINDER_EXPORTED status_t + readUniqueFileDescriptorVector(std::optional<std::vector<binder::unique_fd>>* val) const; + LIBBINDER_EXPORTED status_t + readUniqueFileDescriptorVector(std::unique_ptr<std::vector<binder::unique_fd>>* val) const + __attribute__((deprecated("use std::optional version instead"))); + LIBBINDER_EXPORTED status_t + readUniqueFileDescriptorVector(std::vector<binder::unique_fd>* val) const; // Reads a blob from the parcel. // The caller should call release() on the blob after reading its contents. - status_t readBlob(size_t len, ReadableBlob* outBlob) const; + LIBBINDER_EXPORTED status_t readBlob(size_t len, ReadableBlob* outBlob) const; - const flat_binder_object* readObject(bool nullMetaData) const; + LIBBINDER_EXPORTED const flat_binder_object* readObject(bool nullMetaData) const; // Explicitly close all file descriptors in the parcel. - void closeFileDescriptors(); + LIBBINDER_EXPORTED void closeFileDescriptors(); // Debugging: get metrics on current allocations. - static size_t getGlobalAllocSize(); - static size_t getGlobalAllocCount(); + LIBBINDER_EXPORTED static size_t getGlobalAllocSize(); + LIBBINDER_EXPORTED static size_t getGlobalAllocCount(); - bool replaceCallingWorkSourceUid(uid_t uid); + LIBBINDER_EXPORTED bool replaceCallingWorkSourceUid(uid_t uid); // Returns the work source provided by the caller. This can only be trusted for trusted calling // uid. - uid_t readCallingWorkSourceUid() const; + LIBBINDER_EXPORTED uid_t readCallingWorkSourceUid() const; - void print(std::ostream& to, uint32_t flags = 0) const; + LIBBINDER_EXPORTED void print(std::ostream& to, uint32_t flags = 0) const; private: // `objects` and `objectsSize` always 0 for RPC Parcels. @@ -660,7 +696,7 @@ private: status_t flattenBinder(const sp<IBinder>& binder); status_t unflattenBinder(sp<IBinder>* out) const; - status_t readOutVectorSizeWithCheck(size_t elmSize, int32_t* size) const; + LIBBINDER_EXPORTED status_t readOutVectorSizeWithCheck(size_t elmSize, int32_t* size) const; template<class T> status_t readAligned(T *pArg) const; @@ -1009,7 +1045,7 @@ private: typename std::enable_if_t<is_specialization_v<CT, std::vector>, bool> = true> status_t writeData(const CT& c) { using T = first_template_type_t<CT>; // The T in CT == C<T, ...> - if (c.size() > std::numeric_limits<int32_t>::max()) return BAD_VALUE; + if (c.size() > static_cast<size_t>(std::numeric_limits<int32_t>::max())) return BAD_VALUE; const auto size = static_cast<int32_t>(c.size()); writeData(size); if constexpr (is_pointer_equivalent_array_v<T>) { @@ -1356,14 +1392,14 @@ private: class Blob { public: - Blob(); - ~Blob(); + LIBBINDER_EXPORTED Blob(); + LIBBINDER_EXPORTED ~Blob(); - void clear(); - void release(); - inline size_t size() const { return mSize; } - inline int fd() const { return mFd; } - inline bool isMutable() const { return mMutable; } + LIBBINDER_EXPORTED void clear(); + LIBBINDER_EXPORTED void release(); + LIBBINDER_EXPORTED inline size_t size() const { return mSize; } + LIBBINDER_EXPORTED inline int fd() const { return mFd; } + LIBBINDER_EXPORTED inline bool isMutable() const { return mMutable; } protected: void init(int fd, void* data, size_t size, bool isMutable); @@ -1381,7 +1417,7 @@ private: // FlattenableHelperInterface and FlattenableHelper avoid generating a vtable entry in objects // following Flattenable template/protocol. - class FlattenableHelperInterface { + class LIBBINDER_EXPORTED FlattenableHelperInterface { protected: ~FlattenableHelperInterface() { } public: @@ -1420,21 +1456,21 @@ private: return const_cast<Flattenable<T>&>(val).unflatten(buffer, size, fds, count); } }; - status_t write(const FlattenableHelperInterface& val); - status_t read(FlattenableHelperInterface& val) const; + LIBBINDER_EXPORTED status_t write(const FlattenableHelperInterface& val); + LIBBINDER_EXPORTED status_t read(FlattenableHelperInterface& val) const; public: class ReadableBlob : public Blob { friend class Parcel; public: - inline const void* data() const { return mData; } - inline void* mutableData() { return isMutable() ? mData : nullptr; } + LIBBINDER_EXPORTED inline const void* data() const { return mData; } + LIBBINDER_EXPORTED inline void* mutableData() { return isMutable() ? mData : nullptr; } }; class WritableBlob : public Blob { friend class Parcel; public: - inline void* data() { return mData; } + LIBBINDER_EXPORTED inline void* data() { return mData; } }; /** @@ -1444,12 +1480,12 @@ public: * is referenced by this Parcel, but which this parcel doesn't own (e.g. * writeFileDescriptor is called without 'takeOwnership' true). */ - size_t getOpenAshmemSize() const; + LIBBINDER_EXPORTED size_t getOpenAshmemSize() const; private: // TODO(b/202029388): Remove 'getBlobAshmemSize' once no prebuilts reference // this - size_t getBlobAshmemSize() const; + LIBBINDER_EXPORTED size_t getBlobAshmemSize() const; // Needed so that we can save object metadata to the disk friend class android::binder::debug::RecordedTransaction; diff --git a/libs/binder/include/binder/ParcelFileDescriptor.h b/libs/binder/include/binder/ParcelFileDescriptor.h index c4ef3547e9..50a1d399ac 100644 --- a/libs/binder/include/binder/ParcelFileDescriptor.h +++ b/libs/binder/include/binder/ParcelFileDescriptor.h @@ -16,6 +16,7 @@ #pragma once +#include <binder/Common.h> #include <binder/Parcel.h> #include <binder/Parcelable.h> #include <binder/unique_fd.h> @@ -26,7 +27,7 @@ namespace os { /* * C++ implementation of the Java class android.os.ParcelFileDescriptor */ -class ParcelFileDescriptor : public android::Parcelable { +class LIBBINDER_EXPORTED ParcelFileDescriptor : public android::Parcelable { public: ParcelFileDescriptor(); explicit ParcelFileDescriptor(binder::unique_fd fd); diff --git a/libs/binder/include/binder/Parcelable.h b/libs/binder/include/binder/Parcelable.h index 2c652be0e9..0b707b35d4 100644 --- a/libs/binder/include/binder/Parcelable.h +++ b/libs/binder/include/binder/Parcelable.h @@ -21,6 +21,8 @@ #include <utils/Errors.h> #include <utils/String16.h> +#include <binder/Common.h> + namespace android { class Parcel; @@ -31,7 +33,7 @@ class Parcel; #endif // Abstract interface of all parcelables. -class Parcelable { +class LIBBINDER_EXPORTED Parcelable { public: virtual ~Parcelable() = default; diff --git a/libs/binder/include/binder/ParcelableHolder.h b/libs/binder/include/binder/ParcelableHolder.h index 40fd30ae3f..965d0970a2 100644 --- a/libs/binder/include/binder/ParcelableHolder.h +++ b/libs/binder/include/binder/ParcelableHolder.h @@ -16,6 +16,7 @@ #pragma once +#include <binder/Common.h> #include <binder/Parcel.h> #include <binder/Parcelable.h> #include <utils/String16.h> @@ -28,7 +29,7 @@ namespace os { /* * C++ implementation of the Java class android.os.ParcelableHolder */ -class ParcelableHolder : public android::Parcelable { +class LIBBINDER_EXPORTED ParcelableHolder : public android::Parcelable { public: ParcelableHolder() = delete; explicit ParcelableHolder(Stability stability) : mStability(stability){} diff --git a/libs/binder/include/binder/PermissionCache.h b/libs/binder/include/binder/PermissionCache.h index 21aa705ff7..9c08016af8 100644 --- a/libs/binder/include/binder/PermissionCache.h +++ b/libs/binder/include/binder/PermissionCache.h @@ -24,6 +24,7 @@ #include <utils/String16.h> #include <utils/Singleton.h> #include <utils/SortedVector.h> +#include <binder/Common.h> namespace android { // --------------------------------------------------------------------------- @@ -64,17 +65,17 @@ class PermissionCache : Singleton<PermissionCache> { void cache(const String16& permission, uid_t uid, bool granted); public: - PermissionCache(); + LIBBINDER_EXPORTED PermissionCache(); - static bool checkCallingPermission(const String16& permission); + LIBBINDER_EXPORTED static bool checkCallingPermission(const String16& permission); - static bool checkCallingPermission(const String16& permission, - int32_t* outPid, int32_t* outUid); + LIBBINDER_EXPORTED static bool checkCallingPermission(const String16& permission, + int32_t* outPid, int32_t* outUid); - static bool checkPermission(const String16& permission, - pid_t pid, uid_t uid); + LIBBINDER_EXPORTED static bool checkPermission(const String16& permission, pid_t pid, + uid_t uid); - static void purgeCache(); + LIBBINDER_EXPORTED static void purgeCache(); }; // --------------------------------------------------------------------------- diff --git a/libs/binder/include/binder/PermissionController.h b/libs/binder/include/binder/PermissionController.h index 6f9eb5e4b9..0cf0b701fe 100644 --- a/libs/binder/include/binder/PermissionController.h +++ b/libs/binder/include/binder/PermissionController.h @@ -18,14 +18,14 @@ #ifndef __ANDROID_VNDK__ +#include <binder/Common.h> #include <binder/IPermissionController.h> #include <utils/Mutex.h> // --------------------------------------------------------------------------- namespace android { -class PermissionController -{ +class PermissionController { public: enum { @@ -42,13 +42,13 @@ public: MODE_DEFAULT = 3, }; - PermissionController(); + LIBBINDER_EXPORTED PermissionController(); - bool checkPermission(const String16& permission, int32_t pid, int32_t uid); - int32_t noteOp(const String16& op, int32_t uid, const String16& packageName); - void getPackagesForUid(const uid_t uid, Vector<String16>& packages); - bool isRuntimePermission(const String16& permission); - int getPackageUid(const String16& package, int flags); + LIBBINDER_EXPORTED bool checkPermission(const String16& permission, int32_t pid, int32_t uid); + LIBBINDER_EXPORTED int32_t noteOp(const String16& op, int32_t uid, const String16& packageName); + LIBBINDER_EXPORTED void getPackagesForUid(const uid_t uid, Vector<String16>& packages); + LIBBINDER_EXPORTED bool isRuntimePermission(const String16& permission); + LIBBINDER_EXPORTED int getPackageUid(const String16& package, int flags); private: Mutex mLock; diff --git a/libs/binder/include/binder/PersistableBundle.h b/libs/binder/include/binder/PersistableBundle.h index 4517cf290e..7c3b625872 100644 --- a/libs/binder/include/binder/PersistableBundle.h +++ b/libs/binder/include/binder/PersistableBundle.h @@ -20,6 +20,7 @@ #include <set> #include <vector> +#include <binder/Common.h> #include <binder/Parcelable.h> #include <utils/String16.h> #include <utils/StrongPointer.h> @@ -32,7 +33,7 @@ namespace os { * C++ implementation of PersistableBundle, a mapping from String values to * various types that can be saved to persistent and later restored. */ -class PersistableBundle : public Parcelable { +class LIBBINDER_EXPORTED PersistableBundle : public Parcelable { public: PersistableBundle() = default; virtual ~PersistableBundle() = default; diff --git a/libs/binder/include/binder/ProcessState.h b/libs/binder/include/binder/ProcessState.h index 3672702fe1..a46663867c 100644 --- a/libs/binder/include/binder/ProcessState.h +++ b/libs/binder/include/binder/ProcessState.h @@ -16,6 +16,7 @@ #pragma once +#include <binder/Common.h> #include <binder/IBinder.h> #include <utils/String16.h> #include <utils/String8.h> @@ -35,10 +36,10 @@ class IPCThreadState; */ class ProcessState : public virtual RefBase { public: - static sp<ProcessState> self(); - static sp<ProcessState> selfOrNull(); + LIBBINDER_EXPORTED static sp<ProcessState> self(); + LIBBINDER_EXPORTED static sp<ProcessState> selfOrNull(); - static bool isVndservicemanagerEnabled(); + LIBBINDER_EXPORTED static bool isVndservicemanagerEnabled(); /* initWithDriver() can be used to configure libbinder to use * a different binder driver dev node. It must be called *before* @@ -48,9 +49,9 @@ public: * * If this is called with nullptr, the behavior is the same as selfOrNull. */ - static sp<ProcessState> initWithDriver(const char* driver); + LIBBINDER_EXPORTED static sp<ProcessState> initWithDriver(const char* driver); - sp<IBinder> getContextObject(const sp<IBinder>& caller); + LIBBINDER_EXPORTED sp<IBinder> getContextObject(const sp<IBinder>& caller); // This should be called before startThreadPool at the beginning // of a program, and libraries should never call it because programs @@ -60,7 +61,7 @@ public: // The 'maxThreads' value refers to the total number of threads // that will be started by the kernel. This is in addition to any // threads started by 'startThreadPool' or 'joinRpcThreadpool'. - status_t setThreadPoolMaxThreadCount(size_t maxThreads); + LIBBINDER_EXPORTED status_t setThreadPoolMaxThreadCount(size_t maxThreads); // Libraries should not call this, as processes should configure // threadpools themselves. Should be called in the main function @@ -72,27 +73,27 @@ public: // For instance, if setThreadPoolMaxCount(3) is called and // startThreadpPool (+1 thread) and joinThreadPool (+1 thread) // are all called, then up to 5 threads can be started. - void startThreadPool(); + LIBBINDER_EXPORTED void startThreadPool(); - [[nodiscard]] bool becomeContextManager(); + [[nodiscard]] LIBBINDER_EXPORTED bool becomeContextManager(); - sp<IBinder> getStrongProxyForHandle(int32_t handle); - void expungeHandle(int32_t handle, IBinder* binder); + LIBBINDER_EXPORTED sp<IBinder> getStrongProxyForHandle(int32_t handle); + LIBBINDER_EXPORTED void expungeHandle(int32_t handle, IBinder* binder); // TODO: deprecate. - void spawnPooledThread(bool isMain); + LIBBINDER_EXPORTED void spawnPooledThread(bool isMain); - status_t enableOnewaySpamDetection(bool enable); + LIBBINDER_EXPORTED status_t enableOnewaySpamDetection(bool enable); // Set the name of the current thread to look like a threadpool // thread. Typically this is called before joinThreadPool. // // TODO: remove this API, and automatically set it intelligently. - void giveThreadPoolName(); + LIBBINDER_EXPORTED void giveThreadPoolName(); - String8 getDriverName(); + LIBBINDER_EXPORTED String8 getDriverName(); - ssize_t getKernelReferences(size_t count, uintptr_t* buf); + LIBBINDER_EXPORTED ssize_t getKernelReferences(size_t count, uintptr_t* buf); // Only usable by the context manager. // This refcount includes: @@ -100,7 +101,7 @@ public: // 2. Temporary strong references held by the kernel during a // transaction on the node. // It does NOT include local strong references to the node - ssize_t getStrongRefCountForNode(const sp<BpBinder>& binder); + LIBBINDER_EXPORTED ssize_t getStrongRefCountForNode(const sp<BpBinder>& binder); enum class CallRestriction { // all calls okay @@ -112,26 +113,26 @@ public: }; // Sets calling restrictions for all transactions in this process. This must be called // before any threads are spawned. - void setCallRestriction(CallRestriction restriction); + LIBBINDER_EXPORTED void setCallRestriction(CallRestriction restriction); /** * Get the max number of threads that have joined the thread pool. * This includes kernel started threads, user joined threads and polling * threads if used. */ - size_t getThreadPoolMaxTotalThreadCount() const; + LIBBINDER_EXPORTED size_t getThreadPoolMaxTotalThreadCount() const; /** * Check to see if the thread pool has started. */ - bool isThreadPoolStarted() const; + LIBBINDER_EXPORTED bool isThreadPoolStarted() const; enum class DriverFeature { ONEWAY_SPAM_DETECTION, EXTENDED_ERROR, }; // Determine whether a feature is supported by the binder driver. - static bool isDriverFeatureEnabled(const DriverFeature feature); + LIBBINDER_EXPORTED static bool isDriverFeatureEnabled(const DriverFeature feature); private: static sp<ProcessState> init(const char* defaultDriver, bool requireDefault); diff --git a/libs/binder/include/binder/RecordedTransaction.h b/libs/binder/include/binder/RecordedTransaction.h index f0bee7f39e..ed75e43487 100644 --- a/libs/binder/include/binder/RecordedTransaction.h +++ b/libs/binder/include/binder/RecordedTransaction.h @@ -16,6 +16,7 @@ #pragma once +#include <binder/Common.h> #include <binder/Parcel.h> #include <binder/unique_fd.h> #include <mutex> @@ -32,25 +33,25 @@ class RecordedTransaction { public: // Filled with the first transaction from fd. - static std::optional<RecordedTransaction> fromFile(const binder::unique_fd& fd); + LIBBINDER_EXPORTED static std::optional<RecordedTransaction> fromFile( + const binder::unique_fd& fd); // Filled with the arguments. - static std::optional<RecordedTransaction> fromDetails(const String16& interfaceName, - uint32_t code, uint32_t flags, - timespec timestamp, const Parcel& data, - const Parcel& reply, status_t err); - RecordedTransaction(RecordedTransaction&& t) noexcept; + LIBBINDER_EXPORTED static std::optional<RecordedTransaction> fromDetails( + const String16& interfaceName, uint32_t code, uint32_t flags, timespec timestamp, + const Parcel& data, const Parcel& reply, status_t err); + LIBBINDER_EXPORTED RecordedTransaction(RecordedTransaction&& t) noexcept; - [[nodiscard]] status_t dumpToFile(const binder::unique_fd& fd) const; + [[nodiscard]] LIBBINDER_EXPORTED status_t dumpToFile(const binder::unique_fd& fd) const; - const std::string& getInterfaceName() const; - uint32_t getCode() const; - uint32_t getFlags() const; - int32_t getReturnedStatus() const; - timespec getTimestamp() const; - uint32_t getVersion() const; - const Parcel& getDataParcel() const; - const Parcel& getReplyParcel() const; - const std::vector<uint64_t>& getObjectOffsets() const; + LIBBINDER_EXPORTED const std::string& getInterfaceName() const; + LIBBINDER_EXPORTED uint32_t getCode() const; + LIBBINDER_EXPORTED uint32_t getFlags() const; + LIBBINDER_EXPORTED int32_t getReturnedStatus() const; + LIBBINDER_EXPORTED timespec getTimestamp() const; + LIBBINDER_EXPORTED uint32_t getVersion() const; + LIBBINDER_EXPORTED const Parcel& getDataParcel() const; + LIBBINDER_EXPORTED const Parcel& getReplyParcel() const; + LIBBINDER_EXPORTED const std::vector<uint64_t>& getObjectOffsets() const; private: RecordedTransaction() = default; diff --git a/libs/binder/include/binder/RpcServer.h b/libs/binder/include/binder/RpcServer.h index a07880dd65..abea0fb40c 100644 --- a/libs/binder/include/binder/RpcServer.h +++ b/libs/binder/include/binder/RpcServer.h @@ -15,6 +15,7 @@ */ #pragma once +#include <binder/Common.h> #include <binder/IBinder.h> #include <binder/RpcSession.h> #include <binder/RpcThreads.h> @@ -47,7 +48,7 @@ class RpcSocketAddress; */ class RpcServer final : public virtual RefBase, private RpcSession::EventListener { public: - static sp<RpcServer> make( + LIBBINDER_EXPORTED static sp<RpcServer> make( std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory = nullptr); /** @@ -59,7 +60,8 @@ public: * to RpcSession::setupUnixDomainSocketBootstrapClient. Multiple client * session can be created from the client end of the pair. */ - [[nodiscard]] status_t setupUnixDomainSocketBootstrapServer(binder::unique_fd serverFd); + [[nodiscard]] LIBBINDER_EXPORTED status_t + setupUnixDomainSocketBootstrapServer(binder::unique_fd serverFd); /** * This represents a session for responses, e.g.: @@ -69,7 +71,7 @@ public: * process B makes binder b and sends it to A * A uses this 'back session' to send things back to B */ - [[nodiscard]] status_t setupUnixDomainServer(const char* path); + [[nodiscard]] LIBBINDER_EXPORTED status_t setupUnixDomainServer(const char* path); /** * Sets up an RPC server with a raw socket file descriptor. @@ -79,12 +81,13 @@ public: * This method is used in the libbinder_rpc_unstable API * RunInitUnixDomainRpcServer(). */ - [[nodiscard]] status_t setupRawSocketServer(binder::unique_fd socket_fd); + [[nodiscard]] LIBBINDER_EXPORTED status_t setupRawSocketServer(binder::unique_fd socket_fd); /** * Creates an RPC server binding to the given CID at the given port. */ - [[nodiscard]] status_t setupVsockServer(unsigned int bindCid, unsigned int port); + [[nodiscard]] LIBBINDER_EXPORTED status_t setupVsockServer(unsigned int bindCid, + unsigned int port); /** * Creates an RPC server at the current port using IPv4. @@ -100,24 +103,25 @@ public: * "0.0.0.0" allows for connections on any IP address that the device may * have */ - [[nodiscard]] status_t setupInetServer(const char* address, unsigned int port, - unsigned int* assignedPort = nullptr); + [[nodiscard]] LIBBINDER_EXPORTED status_t setupInetServer(const char* address, + unsigned int port, + unsigned int* assignedPort = nullptr); /** * If setup*Server has been successful, return true. Otherwise return false. */ - [[nodiscard]] bool hasServer(); + [[nodiscard]] LIBBINDER_EXPORTED bool hasServer(); /** * If hasServer(), return the server FD. Otherwise return invalid FD. */ - [[nodiscard]] binder::unique_fd releaseServer(); + [[nodiscard]] LIBBINDER_EXPORTED binder::unique_fd releaseServer(); /** * Set up server using an external FD previously set up by releaseServer(). * Return false if there's already a server. */ - [[nodiscard]] status_t setupExternalServer(binder::unique_fd serverFd); + [[nodiscard]] LIBBINDER_EXPORTED status_t setupExternalServer(binder::unique_fd serverFd); /** * This must be called before adding a client session. This corresponds @@ -130,15 +134,15 @@ public: * TODO(b/167966510): these are currently created per client, but these * should be shared. */ - void setMaxThreads(size_t threads); - size_t getMaxThreads(); + LIBBINDER_EXPORTED void setMaxThreads(size_t threads); + LIBBINDER_EXPORTED size_t getMaxThreads(); /** * By default, the latest protocol version which is supported by a client is * used. However, this can be used in order to prevent newer protocol * versions from ever being used. This is expected to be useful for testing. */ - [[nodiscard]] bool setProtocolVersion(uint32_t version); + [[nodiscard]] LIBBINDER_EXPORTED bool setProtocolVersion(uint32_t version); /** * Set the supported transports for sending and receiving file descriptors. @@ -146,7 +150,7 @@ public: * Clients will propose a mode when connecting. If the mode is not in the * provided list, the connection will be rejected. */ - void setSupportedFileDescriptorTransportModes( + LIBBINDER_EXPORTED void setSupportedFileDescriptorTransportModes( const std::vector<RpcSession::FileDescriptorTransportMode>& modes); /** @@ -155,11 +159,11 @@ public: * * Holds a strong reference to the root object. */ - void setRootObject(const sp<IBinder>& binder); + LIBBINDER_EXPORTED void setRootObject(const sp<IBinder>& binder); /** * Holds a weak reference to the root object. */ - void setRootObjectWeak(const wp<IBinder>& binder); + LIBBINDER_EXPORTED void setRootObjectWeak(const wp<IBinder>& binder); /** * Allows a root object to be created for each session. * @@ -174,9 +178,9 @@ public: * validate the size, then cast the type-erased pointer to a pointer to the actual type of the * address, e.g., const void* to const sockaddr_vm*. */ - void setPerSessionRootObject( + LIBBINDER_EXPORTED void setPerSessionRootObject( std::function<sp<IBinder>(wp<RpcSession> session, const void*, size_t)>&& object); - sp<IBinder> getRootObject(); + LIBBINDER_EXPORTED sp<IBinder> getRootObject(); /** * Set optional filter of incoming connections based on the peer's address. @@ -186,24 +190,25 @@ public: * See the description of setPerSessionRootObject() for details about * the callable's arguments. */ - void setConnectionFilter(std::function<bool(const void*, size_t)>&& filter); + LIBBINDER_EXPORTED void setConnectionFilter(std::function<bool(const void*, size_t)>&& filter); /** * Set optional modifier of each newly created server socket. * * The only argument is a successfully created file descriptor, not bound to an address yet. */ - void setServerSocketModifier(std::function<void(binder::borrowed_fd)>&& modifier); + LIBBINDER_EXPORTED void setServerSocketModifier( + std::function<void(binder::borrowed_fd)>&& modifier); /** * See RpcTransportCtx::getCertificate */ - std::vector<uint8_t> getCertificate(RpcCertificateFormat); + LIBBINDER_EXPORTED std::vector<uint8_t> getCertificate(RpcCertificateFormat); /** * Runs join() in a background thread. Immediately returns. */ - void start(); + LIBBINDER_EXPORTED void start(); /** * You must have at least one client session before calling this. @@ -216,7 +221,7 @@ public: * still occurring. To ensure that the service is fully shutdown, you might * want to call shutdown after 'join' returns. */ - void join(); + LIBBINDER_EXPORTED void join(); /** * Shut down any existing join(). Return true if successfully shut down, false otherwise @@ -225,20 +230,20 @@ public: * * Warning: this will hang if it is called from its own thread. */ - [[nodiscard]] bool shutdown(); + [[nodiscard]] LIBBINDER_EXPORTED bool shutdown(); /** * For debugging! */ - std::vector<sp<RpcSession>> listSessions(); - size_t numUninitializedSessions(); + LIBBINDER_EXPORTED std::vector<sp<RpcSession>> listSessions(); + LIBBINDER_EXPORTED size_t numUninitializedSessions(); /** * Whether any requests are currently being processed. */ - bool hasActiveRequests(); + LIBBINDER_EXPORTED bool hasActiveRequests(); - ~RpcServer(); + LIBBINDER_EXPORTED ~RpcServer(); private: friend RpcServerTrusty; diff --git a/libs/binder/include/binder/RpcSession.h b/libs/binder/include/binder/RpcSession.h index 11fbde9ace..40102bb9f0 100644 --- a/libs/binder/include/binder/RpcSession.h +++ b/libs/binder/include/binder/RpcSession.h @@ -15,6 +15,7 @@ */ #pragma once +#include <binder/Common.h> #include <binder/IBinder.h> #include <binder/RpcThreads.h> #include <binder/RpcTransport.h> @@ -57,12 +58,13 @@ constexpr uint32_t RPC_WIRE_PROTOCOL_VERSION_RPC_HEADER_FEATURE_EXPLICIT_PARCEL_ class RpcSession final : public virtual RefBase { public: // Create an RpcSession with default configuration (raw sockets). - static sp<RpcSession> make(); + LIBBINDER_EXPORTED static sp<RpcSession> make(); // Create an RpcSession with the given configuration. |serverRpcCertificateFormat| and // |serverCertificate| must have values or be nullopt simultaneously. If they have values, set // server certificate. - static sp<RpcSession> make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory); + LIBBINDER_EXPORTED static sp<RpcSession> make( + std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory); /** * Set the maximum number of incoming threads allowed to be made (for things like callbacks). @@ -75,8 +77,8 @@ public: * * TODO(b/189955605): start these lazily - currently all are started */ - void setMaxIncomingThreads(size_t threads); - size_t getMaxIncomingThreads(); + LIBBINDER_EXPORTED void setMaxIncomingThreads(size_t threads); + LIBBINDER_EXPORTED size_t getMaxIncomingThreads(); /** * Set the maximum number of outgoing connections allowed to be made. @@ -90,15 +92,15 @@ public: * created. This API is used to limit the amount of resources a server can request you * create. */ - void setMaxOutgoingConnections(size_t connections); - size_t getMaxOutgoingThreads(); + LIBBINDER_EXPORTED void setMaxOutgoingConnections(size_t connections); + LIBBINDER_EXPORTED size_t getMaxOutgoingThreads(); /** * By default, the minimum of the supported versions of the client and the * server will be used. Usually, this API should only be used for debugging. */ - [[nodiscard]] bool setProtocolVersion(uint32_t version); - std::optional<uint32_t> getProtocolVersion(); + [[nodiscard]] LIBBINDER_EXPORTED bool setProtocolVersion(uint32_t version); + LIBBINDER_EXPORTED std::optional<uint32_t> getProtocolVersion(); enum class FileDescriptorTransportMode : uint8_t { NONE = 0, @@ -111,29 +113,30 @@ public: /** * Set the transport for sending and receiving file descriptors. */ - void setFileDescriptorTransportMode(FileDescriptorTransportMode mode); - FileDescriptorTransportMode getFileDescriptorTransportMode(); + LIBBINDER_EXPORTED void setFileDescriptorTransportMode(FileDescriptorTransportMode mode); + LIBBINDER_EXPORTED FileDescriptorTransportMode getFileDescriptorTransportMode(); /** * This should be called once per thread, matching 'join' in the remote * process. */ - [[nodiscard]] status_t setupUnixDomainClient(const char* path); + [[nodiscard]] LIBBINDER_EXPORTED status_t setupUnixDomainClient(const char* path); /** * Connects to an RPC server over a nameless Unix domain socket pair. */ - [[nodiscard]] status_t setupUnixDomainSocketBootstrapClient(binder::unique_fd bootstrap); + [[nodiscard]] LIBBINDER_EXPORTED status_t + setupUnixDomainSocketBootstrapClient(binder::unique_fd bootstrap); /** - * Connects to an RPC server at the CVD & port. + * Connects to an RPC server at the CID & port. */ - [[nodiscard]] status_t setupVsockClient(unsigned int cvd, unsigned int port); + [[nodiscard]] LIBBINDER_EXPORTED status_t setupVsockClient(unsigned int cid, unsigned int port); /** * Connects to an RPC server at the given address and port. */ - [[nodiscard]] status_t setupInetClient(const char* addr, unsigned int port); + [[nodiscard]] LIBBINDER_EXPORTED status_t setupInetClient(const char* addr, unsigned int port); /** * Starts talking to an RPC server which has already been connected to. This @@ -145,8 +148,8 @@ public: * * For future compatibility, 'request' should not reference any stack data. */ - [[nodiscard]] status_t setupPreconnectedClient(binder::unique_fd fd, - std::function<binder::unique_fd()>&& request); + [[nodiscard]] LIBBINDER_EXPORTED status_t + setupPreconnectedClient(binder::unique_fd fd, std::function<binder::unique_fd()>&& request); /** * For debugging! @@ -155,24 +158,24 @@ public: * response will never be satisfied. All data sent here will be * unceremoniously cast down the bottomless pit, /dev/null. */ - [[nodiscard]] status_t addNullDebuggingClient(); + [[nodiscard]] LIBBINDER_EXPORTED status_t addNullDebuggingClient(); /** * Query the other side of the session for the root object hosted by that * process's RpcServer (if one exists) */ - sp<IBinder> getRootObject(); + LIBBINDER_EXPORTED sp<IBinder> getRootObject(); /** * Query the other side of the session for the maximum number of threads * it supports (maximum number of concurrent non-nested synchronous transactions) */ - [[nodiscard]] status_t getRemoteMaxThreads(size_t* maxThreads); + [[nodiscard]] LIBBINDER_EXPORTED status_t getRemoteMaxThreads(size_t* maxThreads); /** * See RpcTransportCtx::getCertificate */ - std::vector<uint8_t> getCertificate(RpcCertificateFormat); + LIBBINDER_EXPORTED std::vector<uint8_t> getCertificate(RpcCertificateFormat); /** * Shuts down the service. @@ -188,33 +191,34 @@ public: * complete before returning. This will hang if it is called from the * session threadpool (when processing received calls). */ - [[nodiscard]] bool shutdownAndWait(bool wait); + [[nodiscard]] LIBBINDER_EXPORTED bool shutdownAndWait(bool wait); - [[nodiscard]] status_t transact(const sp<IBinder>& binder, uint32_t code, const Parcel& data, - Parcel* reply, uint32_t flags); + [[nodiscard]] LIBBINDER_EXPORTED status_t transact(const sp<IBinder>& binder, uint32_t code, + const Parcel& data, Parcel* reply, + uint32_t flags); /** * Generally, you should not call this, unless you are testing error * conditions, as this is called automatically by BpBinders when they are * deleted (this is also why a raw pointer is used here) */ - [[nodiscard]] status_t sendDecStrong(const BpBinder* binder); + [[nodiscard]] LIBBINDER_EXPORTED status_t sendDecStrong(const BpBinder* binder); /** * Whether any requests are currently being processed. */ - bool hasActiveRequests(); + LIBBINDER_EXPORTED bool hasActiveRequests(); - ~RpcSession(); + LIBBINDER_EXPORTED ~RpcSession(); /** * Server if this session is created as part of a server (symmetrical to * client servers). Otherwise, nullptr. */ - sp<RpcServer> server(); + LIBBINDER_EXPORTED sp<RpcServer> server(); // internal only - const std::unique_ptr<RpcState>& state() { return mRpcBinderState; } + LIBBINDER_EXPORTED const std::unique_ptr<RpcState>& state() { return mRpcBinderState; } private: friend sp<RpcSession>; diff --git a/libs/binder/include/binder/RpcThreads.h b/libs/binder/include/binder/RpcThreads.h index d25f29277c..99fa6b8b29 100644 --- a/libs/binder/include/binder/RpcThreads.h +++ b/libs/binder/include/binder/RpcThreads.h @@ -22,27 +22,29 @@ #include <memory> #include <thread> +#include <binder/Common.h> + namespace android { #ifdef BINDER_RPC_SINGLE_THREADED -class RpcMutex { +class LIBBINDER_EXPORTED RpcMutex { public: void lock() {} void unlock() {} }; -class RpcMutexUniqueLock { +class LIBBINDER_EXPORTED RpcMutexUniqueLock { public: RpcMutexUniqueLock(RpcMutex&) {} void unlock() {} }; -class RpcMutexLockGuard { +class LIBBINDER_EXPORTED RpcMutexLockGuard { public: RpcMutexLockGuard(RpcMutex&) {} }; -class RpcConditionVariable { +class LIBBINDER_EXPORTED RpcConditionVariable { public: void notify_one() {} void notify_all() {} @@ -65,7 +67,7 @@ public: } }; -class RpcMaybeThread { +class LIBBINDER_EXPORTED RpcMaybeThread { public: RpcMaybeThread() = default; diff --git a/libs/binder/include/binder/RpcTransport.h b/libs/binder/include/binder/RpcTransport.h index a50cdc1db0..843c4bf32f 100644 --- a/libs/binder/include/binder/RpcTransport.h +++ b/libs/binder/include/binder/RpcTransport.h @@ -27,6 +27,7 @@ #include <utils/Errors.h> +#include <binder/Common.h> #include <binder/Functional.h> #include <binder/RpcCertificateFormat.h> #include <binder/RpcThreads.h> @@ -51,7 +52,7 @@ class RpcTransportCtxTipcTrusty; // Represents a socket connection. // No thread-safety is guaranteed for these APIs. -class RpcTransport { +class LIBBINDER_EXPORTED RpcTransport { public: virtual ~RpcTransport() = default; @@ -123,7 +124,7 @@ private: // Represents the context that generates the socket connection. // All APIs are thread-safe. See RpcTransportCtxRaw and RpcTransportCtxTls for details. -class RpcTransportCtx { +class LIBBINDER_EXPORTED RpcTransportCtx { public: virtual ~RpcTransportCtx() = default; @@ -154,7 +155,7 @@ private: // A factory class that generates RpcTransportCtx. // All APIs are thread-safe. -class RpcTransportCtxFactory { +class LIBBINDER_EXPORTED RpcTransportCtxFactory { public: virtual ~RpcTransportCtxFactory() = default; // Creates server context. @@ -171,7 +172,7 @@ protected: RpcTransportCtxFactory() = default; }; -struct RpcTransportFd final { +struct LIBBINDER_EXPORTED RpcTransportFd final { private: mutable bool isPolling{false}; diff --git a/libs/binder/include/binder/RpcTransportRaw.h b/libs/binder/include/binder/RpcTransportRaw.h index 6fb1f92aab..bfa73ead3a 100644 --- a/libs/binder/include/binder/RpcTransportRaw.h +++ b/libs/binder/include/binder/RpcTransportRaw.h @@ -21,6 +21,7 @@ #include <memory> +#include <binder/Common.h> #include <binder/RpcTransport.h> namespace android { @@ -28,11 +29,11 @@ namespace android { // RpcTransportCtxFactory with TLS disabled. class RpcTransportCtxFactoryRaw : public RpcTransportCtxFactory { public: - static std::unique_ptr<RpcTransportCtxFactory> make(); + LIBBINDER_EXPORTED static std::unique_ptr<RpcTransportCtxFactory> make(); - std::unique_ptr<RpcTransportCtx> newServerCtx() const override; - std::unique_ptr<RpcTransportCtx> newClientCtx() const override; - const char* toCString() const override; + LIBBINDER_EXPORTED std::unique_ptr<RpcTransportCtx> newServerCtx() const override; + LIBBINDER_EXPORTED std::unique_ptr<RpcTransportCtx> newClientCtx() const override; + LIBBINDER_EXPORTED const char* toCString() const override; private: RpcTransportCtxFactoryRaw() = default; diff --git a/libs/binder/include/binder/SafeInterface.h b/libs/binder/include/binder/SafeInterface.h index 96b9733c94..c671eed039 100644 --- a/libs/binder/include/binder/SafeInterface.h +++ b/libs/binder/include/binder/SafeInterface.h @@ -16,6 +16,7 @@ #pragma once +#include <binder/Common.h> #include <binder/IInterface.h> #include <binder/Parcel.h> @@ -34,7 +35,7 @@ namespace android { namespace SafeInterface { // ParcelHandler is responsible for writing/reading various types to/from a Parcel in a generic way -class ParcelHandler { +class LIBBINDER_EXPORTED ParcelHandler { public: explicit ParcelHandler(const char* logTag) : mLogTag(logTag) {} @@ -243,7 +244,7 @@ struct ParamExtractor<Return (Class::*)(Params...) const> { } // namespace SafeInterface template <typename Interface> -class SafeBpInterface : public BpInterface<Interface> { +class LIBBINDER_EXPORTED SafeBpInterface : public BpInterface<Interface> { protected: SafeBpInterface(const sp<IBinder>& impl, const char* logTag) : BpInterface<Interface>(impl), mLogTag(logTag) {} @@ -438,7 +439,7 @@ private: }; template <typename Interface> -class SafeBnInterface : public BnInterface<Interface> { +class LIBBINDER_EXPORTED SafeBnInterface : public BnInterface<Interface> { public: explicit SafeBnInterface(const char* logTag) : mLogTag(logTag) {} diff --git a/libs/binder/include/binder/Stability.h b/libs/binder/include/binder/Stability.h index ce4362f763..cafb8aa04b 100644 --- a/libs/binder/include/binder/Stability.h +++ b/libs/binder/include/binder/Stability.h @@ -16,6 +16,7 @@ #pragma once +#include <binder/Common.h> #include <binder/IBinder.h> #include <string> @@ -54,7 +55,7 @@ public: // requirements associated with that higher stability level. For instance, a // VINTF stability binder is required to be in the VINTF manifest. This API // can be called to use that same interface within the local partition. - static void forceDowngradeToLocalStability(const sp<IBinder>& binder); + LIBBINDER_EXPORTED static void forceDowngradeToLocalStability(const sp<IBinder>& binder); // WARNING: Below APIs are only ever expected to be called by auto-generated code. // Instead of calling them, you should set the stability of a .aidl interface @@ -76,30 +77,30 @@ public: // requirements associated with that higher stability level. For instance, a // VINTF stability binder is required to be in the VINTF manifest. This API // can be called to use that same interface within the vendor partition. - static void forceDowngradeToVendorStability(const sp<IBinder>& binder); + LIBBINDER_EXPORTED static void forceDowngradeToVendorStability(const sp<IBinder>& binder); // Given a binder interface at a certain stability, there may be some // requirements associated with that higher stability level. For instance, a // VINTF stability binder is required to be in the VINTF manifest. This API // can be called to use that same interface within the system partition. - static void forceDowngradeToSystemStability(const sp<IBinder>& binder); + LIBBINDER_EXPORTED static void forceDowngradeToSystemStability(const sp<IBinder>& binder); // WARNING: This is only ever expected to be called by auto-generated code. You likely want to // change or modify the stability class of the interface you are using. // This must be called as soon as the binder in question is constructed. No thread safety // is provided. // E.g. stability is according to libbinder compilation unit - static void markCompilationUnit(IBinder* binder); + LIBBINDER_EXPORTED static void markCompilationUnit(IBinder* binder); // WARNING: This is only ever expected to be called by auto-generated code. You likely want to // change or modify the stability class of the interface you are using. // This must be called as soon as the binder in question is constructed. No thread safety // is provided. // E.g. stability is according to libbinder_ndk or Java SDK AND the interface // expressed here is guaranteed to be stable for multiple years (Stable AIDL) - static void markVintf(IBinder* binder); + LIBBINDER_EXPORTED static void markVintf(IBinder* binder); // WARNING: for debugging only - static std::string debugToString(const sp<IBinder>& binder); + LIBBINDER_EXPORTED static std::string debugToString(const sp<IBinder>& binder); // WARNING: This is only ever expected to be called by auto-generated code or tests. // You likely want to change or modify the stability of the interface you are using. @@ -109,11 +110,12 @@ public: // expressed here is guaranteed to be stable for multiple years (Stable AIDL) // If this is called when __ANDROID_VNDK__ is not defined, then it is UB and will likely // break the device during GSI or other tests. - static void markVndk(IBinder* binder); + LIBBINDER_EXPORTED static void markVndk(IBinder* binder); // Returns true if the binder needs to be declared in the VINTF manifest or // else false if the binder is local to the current partition. - static bool requiresVintfDeclaration(const sp<IBinder>& binder); + LIBBINDER_EXPORTED static bool requiresVintfDeclaration(const sp<IBinder>& binder); + private: // Parcel needs to read/write stability level in an unstable format. friend ::android::Parcel; diff --git a/libs/binder/include/binder/Status.h b/libs/binder/include/binder/Status.h index af34695875..49ccf7c36c 100644 --- a/libs/binder/include/binder/Status.h +++ b/libs/binder/include/binder/Status.h @@ -21,6 +21,7 @@ #include <sstream> // historical #include <ostream> +#include <binder/Common.h> #include <binder/Parcel.h> #include <utils/String8.h> #include <string> @@ -51,7 +52,7 @@ namespace binder { // // exception during handling. // } // -class Status final { +class LIBBINDER_EXPORTED Status final { public: // Keep the exception codes in sync with android/os/Parcel.java. enum Exception { diff --git a/libs/binder/include/binder/TextOutput.h b/libs/binder/include/binder/TextOutput.h index 50158c3072..0527eeb0c0 100644 --- a/libs/binder/include/binder/TextOutput.h +++ b/libs/binder/include/binder/TextOutput.h @@ -16,6 +16,7 @@ #pragma once +#include <binder/Common.h> #include <utils/Errors.h> #include <utils/String8.h> @@ -26,8 +27,7 @@ // --------------------------------------------------------------------------- namespace android { -class TextOutput -{ +class LIBBINDER_EXPORTED TextOutput { public: TextOutput(); virtual ~TextOutput(); @@ -52,17 +52,17 @@ public: // DO NOT USE: prefer libutils/libbase logs, which don't require static data to // be allocated. // Text output stream for printing to the log (via utils/Log.h). -extern TextOutput& alog; +extern LIBBINDER_EXPORTED TextOutput& alog; // DO NOT USE: prefer libutils/libbase logs, which don't require static data to // be allocated. // Text output stream for printing to stdout. -extern TextOutput& aout; +extern LIBBINDER_EXPORTED TextOutput& aout; // DO NOT USE: prefer libutils/libbase logs, which don't require static data to // be allocated. // Text output stream for printing to stderr. -extern TextOutput& aerr; +extern LIBBINDER_EXPORTED TextOutput& aerr; typedef TextOutput& (*TextOutputManipFunc)(TextOutput&); @@ -80,10 +80,9 @@ TextOutput& operator<<(TextOutput& to, const T& val) return to; } -TextOutput& operator<<(TextOutput& to, TextOutputManipFunc func); +LIBBINDER_EXPORTED TextOutput& operator<<(TextOutput& to, TextOutputManipFunc func); -class TypeCode -{ +class LIBBINDER_EXPORTED TypeCode { public: inline explicit TypeCode(uint32_t code); inline ~TypeCode(); @@ -94,10 +93,9 @@ private: uint32_t mCode; }; -std::ostream& operator<<(std::ostream& to, const TypeCode& val); +LIBBINDER_EXPORTED std::ostream& operator<<(std::ostream& to, const TypeCode& val); -class HexDump -{ +class LIBBINDER_EXPORTED HexDump { public: HexDump(const void *buf, size_t size, size_t bytesPerLine=16); inline ~HexDump(); @@ -123,7 +121,7 @@ private: bool mCArrayStyle; }; -std::ostream& operator<<(std::ostream& to, const HexDump& val); +LIBBINDER_EXPORTED std::ostream& operator<<(std::ostream& to, const HexDump& val); inline TextOutput& operator<<(TextOutput& to, decltype(std::endl<char, std::char_traits<char>>) diff --git a/libs/binder/include/binder/Trace.h b/libs/binder/include/binder/Trace.h index 95318b2bf6..2f450cb36b 100644 --- a/libs/binder/include/binder/Trace.h +++ b/libs/binder/include/binder/Trace.h @@ -22,6 +22,8 @@ #include <cutils/trace.h> #endif +#include <binder/Common.h> + #ifdef ATRACE_TAG_AIDL #if ATRACE_TAG_AIDL != (1 << 24) #error "Mismatched ATRACE_TAG_AIDL definitions" @@ -39,9 +41,10 @@ namespace os { // libcutils/libutils void trace_begin(uint64_t tag, const char* name); void trace_end(uint64_t tag); +void trace_int(uint64_t tag, const char* name, int32_t value); } // namespace os -class ScopedTrace { +class LIBBINDER_EXPORTED ScopedTrace { public: inline ScopedTrace(uint64_t tag, const char* name) : mTag(tag) { os::trace_begin(mTag, name); } diff --git a/libs/binder/include/binder/unique_fd.h b/libs/binder/include/binder/unique_fd.h index 439b8a2e4e..3de4149328 100644 --- a/libs/binder/include/binder/unique_fd.h +++ b/libs/binder/include/binder/unique_fd.h @@ -16,6 +16,8 @@ #pragma once +#include <binder/Common.h> + #ifndef BINDER_NO_LIBBASE #include <android-base/unique_fd.h> @@ -43,7 +45,7 @@ namespace android::binder { // // return 0; // Descriptor is closed for you. // -class unique_fd final { +class LIBBINDER_EXPORTED unique_fd final { public: unique_fd() {} @@ -99,7 +101,7 @@ private: // If you think of unique_fd as being like std::string in that represents // ownership, borrowed_fd is like std::string_view (and int is like const // char*). -struct borrowed_fd { +struct LIBBINDER_EXPORTED borrowed_fd { /* implicit */ borrowed_fd(int fd) : fd_(fd) {} // NOLINT /* implicit */ borrowed_fd(const unique_fd& ufd) : fd_(ufd.get()) {} // NOLINT diff --git a/libs/binder/liblog_stub/Android.bp b/libs/binder/liblog_stub/Android.bp index f2ca22fdb0..2de6658419 100644 --- a/libs/binder/liblog_stub/Android.bp +++ b/libs/binder/liblog_stub/Android.bp @@ -30,6 +30,7 @@ cc_library_headers { product_available: true, recovery_available: true, vendor_available: true, + cmake_snapshot_supported: true, target: { windows: { diff --git a/libs/binder/ndk/Android.bp b/libs/binder/ndk/Android.bp index 9a2d14af32..26c228d9a4 100644 --- a/libs/binder/ndk/Android.bp +++ b/libs/binder/ndk/Android.bp @@ -32,17 +32,11 @@ license { ], } -cc_library { - name: "libbinder_ndk", - +cc_defaults { + name: "libbinder_ndk_common_defaults", host_supported: true, recovery_available: true, - llndk: { - symbol_file: "libbinder_ndk.map.txt", - export_llndk_headers: ["libvendorsupport_llndk_headers"], - }, - export_include_dirs: [ "include_cpp", "include_ndk", @@ -50,7 +44,6 @@ cc_library { ], cflags: [ - "-DBINDER_WITH_KERNEL_IPC", "-Wall", "-Wextra", "-Wextra-semi", @@ -59,14 +52,48 @@ cc_library { srcs: [ "ibinder.cpp", - "ibinder_jni.cpp", "libbinder.cpp", "parcel.cpp", + "stability.cpp", + "status.cpp", + ], +} + +cc_library_host_shared { + name: "libbinder_ndk_sdk", + + defaults: [ + "libbinder_ndk_common_defaults", + "binder_sdk_defaults", + ], + cmake_snapshot_supported: true, + + shared_libs: [ + "libbinder_sdk", + "libutils_binder_sdk", + ], +} + +cc_library { + name: "libbinder_ndk", + + defaults: ["libbinder_ndk_common_defaults"], + cmake_snapshot_supported: false, + + llndk: { + symbol_file: "libbinder_ndk.map.txt", + export_llndk_headers: ["libvendorsupport_llndk_headers"], + }, + + cflags: [ + "-DBINDER_WITH_KERNEL_IPC", + ], + + srcs: [ + "ibinder_jni.cpp", "parcel_jni.cpp", "persistable_bundle.cpp", "process.cpp", - "stability.cpp", - "status.cpp", "service_manager.cpp", ], @@ -195,6 +222,7 @@ cc_library_headers { host_supported: true, // TODO(b/153609531): remove when no longer needed. native_bridge_supported: true, + cmake_snapshot_supported: true, target: { darwin: { enabled: false, diff --git a/libs/binder/ndk/include_cpp/android/binder_auto_utils.h b/libs/binder/ndk/include_cpp/android/binder_auto_utils.h index 18769b1454..8c62924beb 100644 --- a/libs/binder/ndk/include_cpp/android/binder_auto_utils.h +++ b/libs/binder/ndk/include_cpp/android/binder_auto_utils.h @@ -377,7 +377,7 @@ class ScopedAIBinder_Weak namespace internal { -static void closeWithError(int fd) { +inline void closeWithError(int fd) { if (fd == -1) return; int ret = close(fd); if (ret != 0) { diff --git a/libs/binder/ndk/include_ndk/android/binder_ibinder.h b/libs/binder/ndk/include_ndk/android/binder_ibinder.h index b1ab7b0f9a..2929bce897 100644 --- a/libs/binder/ndk/include_ndk/android/binder_ibinder.h +++ b/libs/binder/ndk/include_ndk/android/binder_ibinder.h @@ -718,9 +718,17 @@ binder_status_t AIBinder_getExtension(AIBinder* binder, AIBinder** outExt) __INT * When registering the interface, add: * std::shared_ptr<MyFoo> foo = new MyFoo; // class in AOSP codebase * std::shared_ptr<MyBar> bar = new MyBar; // custom extension class - * ... = AIBinder_setExtension(foo->asBinder().get(), bar->asBinder().get()); + * SpAIBinder binder = foo->asBinder(); // target binder to extend + * ... = AIBinder_setExtension(binder.get(), bar->asBinder().get()); + * ... = AServiceManager_addService(binder.get(), instanceName); * // handle error * + * Do not use foo->asBinder().get() as the target binder argument to + * AIBinder_setExtensions because asBinder it creates a new binder + * object that will be destroyed after the function is called. The same + * binder object must be used for AIBinder_setExtension and + * AServiceManager_addService to register the service with an extension. + * * Then, clients of IFoo can get this extension: * SpAIBinder binder = ...; * std::shared_ptr<IFoo> foo = IFoo::fromBinder(binder); // handle if null diff --git a/libs/binder/ndk/include_platform/android/binder_manager.h b/libs/binder/ndk/include_platform/android/binder_manager.h index c665ad82ad..41b30a0a0f 100644 --- a/libs/binder/ndk/include_platform/android/binder_manager.h +++ b/libs/binder/ndk/include_platform/android/binder_manager.h @@ -18,11 +18,8 @@ #include <android/binder_ibinder.h> #include <android/binder_status.h> -#include <sys/cdefs.h> - -#ifndef __TRUSTY__ #include <android/llndk-versioning.h> -#endif +#include <sys/cdefs.h> __BEGIN_DECLS @@ -33,7 +30,11 @@ enum AServiceManager_AddServiceFlag : uint32_t { * Services with methods that perform file IO, web socket creation or ways to egress data must * not be added with this flag for privacy concerns. */ - ADD_SERVICE_ALLOW_ISOLATED = 1, + ADD_SERVICE_ALLOW_ISOLATED = 1 << 0, + ADD_SERVICE_DUMP_FLAG_PRIORITY_CRITICAL = 1 << 1, + ADD_SERVICE_DUMP_FLAG_PRIORITY_HIGH = 1 << 2, + ADD_SERVICE_DUMP_FLAG_PRIORITY_NORMAL = 1 << 3, + ADD_SERVICE_DUMP_FLAG_PRIORITY_DEFAULT = 1 << 4, }; /** diff --git a/libs/binder/ndk/service_manager.cpp b/libs/binder/ndk/service_manager.cpp index 5529455cc6..4436dbeed7 100644 --- a/libs/binder/ndk/service_manager.cpp +++ b/libs/binder/ndk/service_manager.cpp @@ -49,7 +49,25 @@ binder_exception_t AServiceManager_addServiceWithFlags(AIBinder* binder, const c sp<IServiceManager> sm = defaultServiceManager(); bool allowIsolated = flags & AServiceManager_AddServiceFlag::ADD_SERVICE_ALLOW_ISOLATED; - status_t exception = sm->addService(String16(instance), binder->getBinder(), allowIsolated); + int dumpFlags = 0; + if (flags & AServiceManager_AddServiceFlag::ADD_SERVICE_DUMP_FLAG_PRIORITY_CRITICAL) { + dumpFlags |= IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL; + } + if (flags & AServiceManager_AddServiceFlag::ADD_SERVICE_DUMP_FLAG_PRIORITY_HIGH) { + dumpFlags |= IServiceManager::DUMP_FLAG_PRIORITY_HIGH; + } + if (flags & AServiceManager_AddServiceFlag::ADD_SERVICE_DUMP_FLAG_PRIORITY_NORMAL) { + dumpFlags |= IServiceManager::DUMP_FLAG_PRIORITY_NORMAL; + } + if (flags & AServiceManager_AddServiceFlag::ADD_SERVICE_DUMP_FLAG_PRIORITY_DEFAULT) { + dumpFlags |= IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT; + } + if (dumpFlags == 0) { + dumpFlags = IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT; + } + status_t exception = + sm->addService(String16(instance), binder->getBinder(), allowIsolated, dumpFlags); + return PruneException(exception); } diff --git a/libs/binder/rust/Android.bp b/libs/binder/rust/Android.bp index ef556d7f5f..2deb25457e 100644 --- a/libs/binder/rust/Android.bp +++ b/libs/binder/rust/Android.bp @@ -26,10 +26,7 @@ rust_library { }, apex_available: [ "//apex_available:platform", - "com.android.compos", - "com.android.rkpd", - "com.android.uwb", - "com.android.virt", + "//apex_available:anyapex", ], min_sdk_version: "Tiramisu", } @@ -59,6 +56,7 @@ rust_library { ], host_supported: true, vendor_available: true, + product_available: true, target: { darwin: { enabled: false, @@ -66,9 +64,7 @@ rust_library { }, apex_available: [ "//apex_available:platform", - "com.android.compos", - "com.android.uwb", - "com.android.virt", + "//apex_available:anyapex", ], min_sdk_version: "Tiramisu", } @@ -93,10 +89,7 @@ rust_library { }, apex_available: [ "//apex_available:platform", - "com.android.compos", - "com.android.rkpd", - "com.android.uwb", - "com.android.virt", + "//apex_available:anyapex", ], min_sdk_version: "Tiramisu", lints: "none", @@ -152,10 +145,7 @@ rust_bindgen { }, apex_available: [ "//apex_available:platform", - "com.android.compos", - "com.android.rkpd", - "com.android.uwb", - "com.android.virt", + "//apex_available:anyapex", ], min_sdk_version: "Tiramisu", } diff --git a/libs/binder/rust/binder_tokio/lib.rs b/libs/binder/rust/binder_tokio/lib.rs index 1dc0b2471d..71bb95bc0e 100644 --- a/libs/binder/rust/binder_tokio/lib.rs +++ b/libs/binder/rust/binder_tokio/lib.rs @@ -34,6 +34,7 @@ use std::future::Future; /// Retrieve an existing service for a particular interface, sleeping for a few /// seconds if it doesn't yet exist. +#[deprecated = "this polls 5s, use wait_for_interface or check_interface"] pub async fn get_interface<T: FromIBinder + ?Sized + 'static>( name: &str, ) -> Result<Strong<T>, StatusCode> { @@ -56,6 +57,32 @@ pub async fn get_interface<T: FromIBinder + ?Sized + 'static>( } } +/// Retrieve an existing service for a particular interface. Returns +/// `Err(StatusCode::NAME_NOT_FOUND)` immediately if the service is not available. +/// +/// NOTE: "immediately" above does not mean the future will complete the first time it is polled. +pub async fn check_interface<T: FromIBinder + ?Sized + 'static>( + name: &str, +) -> Result<Strong<T>, StatusCode> { + if binder::is_handling_transaction() { + // See comment in the BinderAsyncPool impl. + return binder::check_interface::<T>(name); + } + + let name = name.to_string(); + let res = tokio::task::spawn_blocking(move || binder::check_interface::<T>(&name)).await; + + // The `is_panic` branch is not actually reachable in Android as we compile + // with `panic = abort`. + match res { + Ok(Ok(service)) => Ok(service), + Ok(Err(err)) => Err(err), + Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()), + Err(e) if e.is_cancelled() => Err(StatusCode::FAILED_TRANSACTION), + Err(_) => Err(StatusCode::UNKNOWN_ERROR), + } +} + /// Retrieve an existing service for a particular interface, or start it if it /// is configured as a dynamic service and isn't yet started. pub async fn wait_for_interface<T: FromIBinder + ?Sized + 'static>( diff --git a/libs/binder/rust/src/lib.rs b/libs/binder/rust/src/lib.rs index 0f9c58c0a2..e70f4f0232 100644 --- a/libs/binder/rust/src/lib.rs +++ b/libs/binder/rust/src/lib.rs @@ -114,9 +114,9 @@ pub use parcel::{ParcelFileDescriptor, Parcelable, ParcelableHolder}; pub use proxy::{DeathRecipient, SpIBinder, WpIBinder}; #[cfg(not(trusty))] pub use service::{ - add_service, force_lazy_services_persist, get_declared_instances, get_interface, get_service, - is_declared, is_handling_transaction, register_lazy_service, wait_for_interface, - wait_for_service, LazyServiceGuard, + add_service, check_interface, check_service, force_lazy_services_persist, + get_declared_instances, get_interface, get_service, is_declared, is_handling_transaction, + register_lazy_service, wait_for_interface, wait_for_service, LazyServiceGuard, }; #[cfg(not(trusty))] pub use state::{ProcessState, ThreadState}; diff --git a/libs/binder/rust/src/service.rs b/libs/binder/rust/src/service.rs index 3ca3b540c4..29dd8e1f58 100644 --- a/libs/binder/rust/src/service.rs +++ b/libs/binder/rust/src/service.rs @@ -144,6 +144,7 @@ fn interface_cast<T: FromIBinder + ?Sized>(service: Option<SpIBinder>) -> Result /// Retrieve an existing service, blocking for a few seconds if it doesn't yet /// exist. +#[deprecated = "this polls 5s, use wait_for_service or check_service"] pub fn get_service(name: &str) -> Option<SpIBinder> { let name = CString::new(name).ok()?; // Safety: `AServiceManager_getService` returns either a null pointer or a @@ -152,6 +153,15 @@ pub fn get_service(name: &str) -> Option<SpIBinder> { unsafe { SpIBinder::from_raw(sys::AServiceManager_getService(name.as_ptr())) } } +/// Retrieve an existing service. Returns `None` immediately if the service is not available. +pub fn check_service(name: &str) -> Option<SpIBinder> { + let name = CString::new(name).ok()?; + // Safety: `AServiceManager_checkService` returns either a null pointer or + // a valid pointer to an owned `AIBinder`. Either of these values is safe to + // pass to `SpIBinder::from_raw`. + unsafe { SpIBinder::from_raw(sys::AServiceManager_checkService(name.as_ptr())) } +} + /// Retrieve an existing service, or start it if it is configured as a dynamic /// service and isn't yet started. pub fn wait_for_service(name: &str) -> Option<SpIBinder> { @@ -164,10 +174,17 @@ pub fn wait_for_service(name: &str) -> Option<SpIBinder> { /// Retrieve an existing service for a particular interface, blocking for a few /// seconds if it doesn't yet exist. +#[deprecated = "this polls 5s, use wait_for_interface or check_interface"] pub fn get_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> { interface_cast(get_service(name)) } +/// Retrieve an existing service for a particular interface. Returns +/// `Err(StatusCode::NAME_NOT_FOUND)` immediately if the service is not available. +pub fn check_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> { + interface_cast(check_service(name)) +} + /// Retrieve an existing service for a particular interface, or start it if it /// is configured as a dynamic service and isn't yet started. pub fn wait_for_interface<T: FromIBinder + ?Sized>(name: &str) -> Result<Strong<T>> { diff --git a/libs/binder/rust/tests/Android.bp b/libs/binder/rust/tests/Android.bp index 2d1175be75..f5b00718ee 100644 --- a/libs/binder/rust/tests/Android.bp +++ b/libs/binder/rust/tests/Android.bp @@ -114,7 +114,6 @@ rust_bindgen { crate_name: "binder_rs_serialization_bindgen", wrapper_src: "serialization.hpp", source_stem: "bindings", - cpp_std: "gnu++17", bindgen_flags: [ "--allowlist-type", "Transaction", "--allowlist-var", "TESTDATA_.*", diff --git a/libs/binder/rust/tests/integration.rs b/libs/binder/rust/tests/integration.rs index c87fa89756..15ae56fdd7 100644 --- a/libs/binder/rust/tests/integration.rs +++ b/libs/binder/rust/tests/integration.rs @@ -421,7 +421,7 @@ mod tests { } #[test] - fn check_services() { + fn check_get_service() { let mut sm = binder::get_service("manager").expect("Did not get manager binder service"); assert!(sm.is_binder_alive()); assert!(sm.ping_binder().is_ok()); @@ -445,7 +445,7 @@ mod tests { } #[tokio::test] - async fn check_services_async() { + async fn check_get_service_async() { let mut sm = binder::get_service("manager").expect("Did not get manager binder service"); assert!(sm.is_binder_alive()); assert!(sm.ping_binder().is_ok()); @@ -474,6 +474,62 @@ mod tests { } #[test] + fn check_check_service() { + let mut sm = binder::check_service("manager").expect("Did not find manager binder service"); + assert!(sm.is_binder_alive()); + assert!(sm.ping_binder().is_ok()); + + assert!(binder::check_service("this_service_does_not_exist").is_none()); + assert_eq!( + binder::check_interface::<dyn ITest>("this_service_does_not_exist").err(), + Some(StatusCode::NAME_NOT_FOUND) + ); + assert_eq!( + binder::check_interface::<dyn IATest<Tokio>>("this_service_does_not_exist").err(), + Some(StatusCode::NAME_NOT_FOUND) + ); + + // The service manager service isn't an ITest, so this must fail. + assert_eq!( + binder::check_interface::<dyn ITest>("manager").err(), + Some(StatusCode::BAD_TYPE) + ); + assert_eq!( + binder::check_interface::<dyn IATest<Tokio>>("manager").err(), + Some(StatusCode::BAD_TYPE) + ); + } + + #[tokio::test] + async fn check_check_service_async() { + let mut sm = binder::check_service("manager").expect("Did not find manager binder service"); + assert!(sm.is_binder_alive()); + assert!(sm.ping_binder().is_ok()); + + assert!(binder::check_service("this_service_does_not_exist").is_none()); + assert_eq!( + binder_tokio::check_interface::<dyn ITest>("this_service_does_not_exist").await.err(), + Some(StatusCode::NAME_NOT_FOUND) + ); + assert_eq!( + binder_tokio::check_interface::<dyn IATest<Tokio>>("this_service_does_not_exist") + .await + .err(), + Some(StatusCode::NAME_NOT_FOUND) + ); + + // The service manager service isn't an ITest, so this must fail. + assert_eq!( + binder_tokio::check_interface::<dyn ITest>("manager").await.err(), + Some(StatusCode::BAD_TYPE) + ); + assert_eq!( + binder_tokio::check_interface::<dyn IATest<Tokio>>("manager").await.err(), + Some(StatusCode::BAD_TYPE) + ); + } + + #[test] fn check_wait_for_service() { let mut sm = binder::wait_for_service("manager").expect("Did not get manager binder service"); diff --git a/libs/binder/tests/Android.bp b/libs/binder/tests/Android.bp index 6800a8d36c..4c7684ccb7 100644 --- a/libs/binder/tests/Android.bp +++ b/libs/binder/tests/Android.bp @@ -25,9 +25,15 @@ package { cc_defaults { name: "binder_test_defaults", + cmake_snapshot_supported: true, cflags: [ "-Wall", "-Werror", + "-Wformat", + "-Wpessimizing-move", + "-Wsign-compare", + "-Wunused-result", + "-Wzero-as-null-pointer-constant", ], } @@ -57,6 +63,7 @@ cc_test { "binderStatusUnitTest.cpp", "binderMemoryHeapBaseUnitTest.cpp", "binderRecordedTransactionTest.cpp", + "binderPersistableBundleTest.cpp", ], shared_libs: [ "libbinder", @@ -136,6 +143,7 @@ aidl_interface { name: "binderRpcTestIface", vendor_available: true, host_supported: true, + cmake_snapshot_supported: true, unstable: true, srcs: [ "BinderRpcTestClientInfo.aidl", @@ -217,6 +225,7 @@ cc_library_static { cc_defaults { name: "binderRpcTest_common_defaults", host_supported: true, + cmake_snapshot_supported: true, target: { darwin: { enabled: false, @@ -258,6 +267,7 @@ cc_defaults { defaults: [ "binderRpcTest_common_defaults", ], + compile_multilib: "first", srcs: [ "binderRpcTest.cpp", @@ -327,7 +337,7 @@ cc_defaults { ], } -cc_test { +cc_binary { // The module name cannot start with "binderRpcTest" because // then atest tries to execute it as part of binderRpcTest name: "binder_rpc_test_service", @@ -338,7 +348,7 @@ cc_test { ], } -cc_test { +cc_binary { name: "binder_rpc_test_service_no_kernel", defaults: [ "binderRpcTest_service_defaults", @@ -349,7 +359,7 @@ cc_test { ], } -cc_test { +cc_binary { name: "binder_rpc_test_service_single_threaded", defaults: [ "binderRpcTest_service_defaults", @@ -364,7 +374,7 @@ cc_test { ], } -cc_test { +cc_binary { name: "binder_rpc_test_service_single_threaded_no_kernel", defaults: [ "binderRpcTest_service_defaults", @@ -376,6 +386,9 @@ cc_test { static_libs: [ "libbinder_rpc_single_threaded_no_kernel", ], + shared_libs: [ + "libbinder_ndk", + ], } cc_binary { @@ -456,6 +469,20 @@ cc_test { } cc_test { + name: "binderRpcTestNoKernelAtAll", + defaults: [ + "binderRpcTest_defaults", + "binderRpcTest_static_defaults", + ], + static_libs: [ + "libbinder_rpc_no_kernel", + ], + cflags: [ + "-DBINDER_NO_KERNEL_IPC_TESTING", + ], +} + +cc_test { name: "binderRpcTestSingleThreaded", defaults: [ "binderRpcTest_defaults", @@ -482,6 +509,9 @@ cc_test { static_libs: [ "libbinder_rpc_single_threaded_no_kernel", ], + shared_libs: [ + "libbinder_ndk", + ], } cc_test { diff --git a/libs/binder/tests/RpcTlsUtilsTest.cpp b/libs/binder/tests/RpcTlsUtilsTest.cpp index 530606c44a..48e3345ed1 100644 --- a/libs/binder/tests/RpcTlsUtilsTest.cpp +++ b/libs/binder/tests/RpcTlsUtilsTest.cpp @@ -52,9 +52,9 @@ TEST_P(RpcTlsUtilsKeyTest, Test) { << "\nactual: " << toDebugString(deserializedPkey.get()); } -INSTANTIATE_TEST_CASE_P(RpcTlsUtilsTest, RpcTlsUtilsKeyTest, - testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER), - RpcTlsUtilsKeyTest::PrintParamInfo); +INSTANTIATE_TEST_SUITE_P(RpcTlsUtilsTest, RpcTlsUtilsKeyTest, + testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER), + RpcTlsUtilsKeyTest::PrintParamInfo); class RpcTlsUtilsCertTest : public testing::TestWithParam<RpcCertificateFormat> { public: @@ -75,9 +75,9 @@ TEST_P(RpcTlsUtilsCertTest, Test) { EXPECT_EQ(0, X509_cmp(cert.get(), deserializedCert.get())); } -INSTANTIATE_TEST_CASE_P(RpcTlsUtilsTest, RpcTlsUtilsCertTest, - testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER), - RpcTlsUtilsCertTest::PrintParamInfo); +INSTANTIATE_TEST_SUITE_P(RpcTlsUtilsTest, RpcTlsUtilsCertTest, + testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER), + RpcTlsUtilsCertTest::PrintParamInfo); class RpcTlsUtilsKeyAndCertTest : public testing::TestWithParam<std::tuple<RpcKeyFormat, RpcCertificateFormat>> { @@ -105,10 +105,10 @@ TEST_P(RpcTlsUtilsKeyAndCertTest, TestCertFromDeserializedKey) { EXPECT_EQ(0, X509_cmp(cert.get(), deserializedCert.get())); } -INSTANTIATE_TEST_CASE_P(RpcTlsUtilsTest, RpcTlsUtilsKeyAndCertTest, - testing::Combine(testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER), - testing::Values(RpcCertificateFormat::PEM, - RpcCertificateFormat::DER)), - RpcTlsUtilsKeyAndCertTest::PrintParamInfo); +INSTANTIATE_TEST_SUITE_P(RpcTlsUtilsTest, RpcTlsUtilsKeyAndCertTest, + testing::Combine(testing::Values(RpcKeyFormat::PEM, RpcKeyFormat::DER), + testing::Values(RpcCertificateFormat::PEM, + RpcCertificateFormat::DER)), + RpcTlsUtilsKeyAndCertTest::PrintParamInfo); } // namespace android diff --git a/libs/binder/tests/binderAllocationLimits.cpp b/libs/binder/tests/binderAllocationLimits.cpp index 7e0b59463a..c0c0aae80b 100644 --- a/libs/binder/tests/binderAllocationLimits.cpp +++ b/libs/binder/tests/binderAllocationLimits.cpp @@ -114,12 +114,12 @@ TEST(TestTheTest, OnMalloc) { { const auto on_malloc = OnMalloc([&](size_t bytes) { mallocs++; - EXPECT_EQ(bytes, 40); + EXPECT_EQ(bytes, 40u); }); imaginary_use = new int[10]; } - EXPECT_EQ(mallocs, 1); + EXPECT_EQ(mallocs, 1u); } @@ -196,9 +196,9 @@ TEST(BinderAllocation, InterfaceDescriptorTransaction) { // Happens to be SM package length. We could switch to forking // and registering our own service if it became an issue. #if defined(__LP64__) - EXPECT_EQ(bytes, 78); + EXPECT_EQ(bytes, 78u); #else - EXPECT_EQ(bytes, 70); + EXPECT_EQ(bytes, 70u); #endif }); @@ -206,7 +206,7 @@ TEST(BinderAllocation, InterfaceDescriptorTransaction) { a_binder->getInterfaceDescriptor(); a_binder->getInterfaceDescriptor(); - EXPECT_EQ(mallocs, 1); + EXPECT_EQ(mallocs, 1u); } TEST(BinderAllocation, SmallTransaction) { @@ -217,11 +217,11 @@ TEST(BinderAllocation, SmallTransaction) { const auto on_malloc = OnMalloc([&](size_t bytes) { mallocs++; // Parcel should allocate a small amount by default - EXPECT_EQ(bytes, 128); + EXPECT_EQ(bytes, 128u); }); manager->checkService(empty_descriptor); - EXPECT_EQ(mallocs, 1); + EXPECT_EQ(mallocs, 1u); } TEST(RpcBinderAllocation, SetupRpcServer) { @@ -250,8 +250,8 @@ TEST(RpcBinderAllocation, SetupRpcServer) { }); ASSERT_EQ(OK, remoteBinder->pingBinder()); } - EXPECT_EQ(mallocs, 1); - EXPECT_EQ(totalBytes, 40); + EXPECT_EQ(mallocs, 1u); + EXPECT_EQ(totalBytes, 40u); } int main(int argc, char** argv) { diff --git a/libs/binder/tests/binderClearBufTest.cpp b/libs/binder/tests/binderClearBufTest.cpp index e43ee5fcf5..3230a3f904 100644 --- a/libs/binder/tests/binderClearBufTest.cpp +++ b/libs/binder/tests/binderClearBufTest.cpp @@ -88,7 +88,7 @@ TEST(BinderClearBuf, ClearKernelBuffer) { // the buffer must have at least some length for the string, but we will // just check it has some length, to avoid assuming anything about the // format - EXPECT_GT(replyBuffer.size(), 0); + EXPECT_GT(replyBuffer.size(), 0u); for (size_t i = 0; i < replyBuffer.size(); i++) { EXPECT_EQ(replyBuffer[i], '0') << "reply buffer at " << i; diff --git a/libs/binder/tests/binderLibTest.cpp b/libs/binder/tests/binderLibTest.cpp index 1f61f1852a..00406edcf2 100644 --- a/libs/binder/tests/binderLibTest.cpp +++ b/libs/binder/tests/binderLibTest.cpp @@ -38,6 +38,7 @@ #include <binder/IServiceManager.h> #include <binder/RpcServer.h> #include <binder/RpcSession.h> +#include <binder/Status.h> #include <binder/unique_fd.h> #include <utils/Flattenable.h> @@ -57,6 +58,7 @@ using namespace std::string_literals; using namespace std::chrono_literals; using android::base::testing::HasValue; using android::base::testing::Ok; +using android::binder::Status; using android::binder::unique_fd; using testing::ExplainMatchResult; using testing::Matcher; @@ -253,7 +255,7 @@ class BinderLibTest : public ::testing::Test { public: virtual void SetUp() { m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer(); - IPCThreadState::self()->restoreCallingWorkSource(0); + IPCThreadState::self()->restoreCallingWorkSource(0); } virtual void TearDown() { } @@ -461,6 +463,35 @@ TEST_F(BinderLibTest, AddManagerToManager) { EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder)); } +TEST_F(BinderLibTest, RegisterForNotificationsFailure) { + auto sm = defaultServiceManager(); + using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback; + class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback { + void onServiceRegistration(const String16&, const sp<IBinder>&) override {} + virtual ~LocalRegistrationCallbackImpl() {} + }; + sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make(); + + EXPECT_EQ(BAD_VALUE, sm->registerForNotifications(String16("ValidName"), nullptr)); + EXPECT_EQ(UNKNOWN_ERROR, sm->registerForNotifications(String16("InvalidName!$"), cb)); +} + +TEST_F(BinderLibTest, UnregisterForNotificationsFailure) { + auto sm = defaultServiceManager(); + using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback; + class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback { + void onServiceRegistration(const String16&, const sp<IBinder>&) override {} + virtual ~LocalRegistrationCallbackImpl() {} + }; + sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make(); + + EXPECT_EQ(OK, sm->registerForNotifications(String16("ValidName"), cb)); + + EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("ValidName"), nullptr)); + EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("AnotherValidName"), cb)); + EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("InvalidName!!!"), cb)); +} + TEST_F(BinderLibTest, WasParceled) { auto binder = sp<BBinder>::make(); EXPECT_FALSE(binder->wasParceled()); @@ -528,8 +559,8 @@ TEST_F(BinderLibTest, Freeze) { EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received, &async_received)); - EXPECT_EQ(sync_received, 1); - EXPECT_EQ(async_received, 0); + EXPECT_EQ(sync_received, 1u); + EXPECT_EQ(async_received, 0u); EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0)); EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply)); @@ -1238,13 +1269,13 @@ TEST_F(BinderLibTest, BufRejected) { data.setDataCapacity(1024); // Write a bogus object at offset 0 to get an entry in the offset table data.writeFileDescriptor(0); - EXPECT_EQ(data.objectsCount(), 1); + EXPECT_EQ(data.objectsCount(), 1u); uint8_t *parcelData = const_cast<uint8_t*>(data.data()); // And now, overwrite it with the buffer object memcpy(parcelData, &obj, sizeof(obj)); data.setDataSize(sizeof(obj)); - EXPECT_EQ(data.objectsCount(), 1); + EXPECT_EQ(data.objectsCount(), 1u); // 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 @@ -1269,7 +1300,7 @@ TEST_F(BinderLibTest, WeakRejected) { data.setDataCapacity(1024); // Write a bogus object at offset 0 to get an entry in the offset table data.writeFileDescriptor(0); - EXPECT_EQ(data.objectsCount(), 1); + EXPECT_EQ(data.objectsCount(), 1u); uint8_t *parcelData = const_cast<uint8_t *>(data.data()); // And now, overwrite it with the weak binder memcpy(parcelData, &obj, sizeof(obj)); @@ -1279,7 +1310,7 @@ TEST_F(BinderLibTest, WeakRejected) { // test with an object that libbinder will actually try to release EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make())); - EXPECT_EQ(data.objectsCount(), 2); + EXPECT_EQ(data.objectsCount(), 2u); // send it many times, since previous error was memory corruption, make it // more likely that the server crashes @@ -1648,8 +1679,8 @@ TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) { EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr), Debuggable(StatusEq(UNEXPECTED_NULL))); } -INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(), - BinderLibRpcTestP::ParamToString); +INSTANTIATE_TEST_SUITE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(), + BinderLibRpcTestP::ParamToString); class BinderLibTestService : public BBinder { public: diff --git a/libs/binder/tests/binderPersistableBundleTest.cpp b/libs/binder/tests/binderPersistableBundleTest.cpp new file mode 100644 index 0000000000..392e018735 --- /dev/null +++ b/libs/binder/tests/binderPersistableBundleTest.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2024 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 <binder/Parcel.h> +#include <binder/PersistableBundle.h> +#include <gtest/gtest.h> +#include <numeric> + +using android::OK; +using android::Parcel; +using android::status_t; +using android::String16; +using android::String8; +using android::os::PersistableBundle; + +namespace android { + +inline std::string to_string(String16 const& str) { + return String8{str}.c_str(); +} + +namespace os { + +template <typename T> +inline std::ostream& operator<<(std::ostream& out, std::vector<T> const& vec) { + using std::to_string; + auto str = + std::accumulate(vec.begin(), vec.end(), std::string{}, + [](std::string const& a, auto const& b) { return a + to_string(b); }); + return out << str; +} + +inline std::ostream& operator<<(std::ostream& out, PersistableBundle const& pb) { +#define PRINT(TYPENAME, TYPE) \ + for (auto const& key : pb.get##TYPENAME##Keys()) { \ + TYPE val{}; \ + pb.get##TYPENAME(key, &val); \ + out << #TYPE " " << key << ": " << val << std::endl; \ + } + + out << "size: " << pb.size() << std::endl; + PRINT(Boolean, bool); + PRINT(Int, int); + PRINT(Long, int64_t); + PRINT(Double, double); + PRINT(String, String16); + PRINT(BooleanVector, std::vector<bool>); + PRINT(IntVector, std::vector<int32_t>); + PRINT(LongVector, std::vector<int64_t>); + PRINT(DoubleVector, std::vector<double>); + PRINT(StringVector, std::vector<String16>); + PRINT(PersistableBundle, PersistableBundle); + +#undef PRINT + + return out; +} + +} // namespace os +} // namespace android + +static const String16 kKey{"key"}; + +static PersistableBundle createSimplePersistableBundle() { + PersistableBundle pb{}; + pb.putInt(kKey, 64); + return pb; +} + +#define TEST_PUT_AND_GET(TYPENAME, TYPE, ...) \ + TEST(PersistableBundle, PutAndGet##TYPENAME) { \ + TYPE const expected{__VA_ARGS__}; \ + PersistableBundle pb{}; \ + \ + pb.put##TYPENAME(kKey, expected); \ + \ + std::set<String16> expectedKeys{kKey}; \ + EXPECT_EQ(pb.get##TYPENAME##Keys(), expectedKeys); \ + \ + TYPE val{}; \ + EXPECT_TRUE(pb.get##TYPENAME(kKey, &val)); \ + EXPECT_EQ(val, expected); \ + } + +TEST_PUT_AND_GET(Boolean, bool, true); +TEST_PUT_AND_GET(Int, int, 64); +TEST_PUT_AND_GET(Long, int64_t, 42); +TEST_PUT_AND_GET(Double, double, 42.64); +TEST_PUT_AND_GET(String, String16, String16{"foo"}); +TEST_PUT_AND_GET(BooleanVector, std::vector<bool>, true, true); +TEST_PUT_AND_GET(IntVector, std::vector<int32_t>, 1, 2); +TEST_PUT_AND_GET(LongVector, std::vector<int64_t>, 1, 2); +TEST_PUT_AND_GET(DoubleVector, std::vector<double>, 4.2, 5.9); +TEST_PUT_AND_GET(StringVector, std::vector<String16>, String16{"foo"}, String16{"bar"}); +TEST_PUT_AND_GET(PersistableBundle, PersistableBundle, createSimplePersistableBundle()); + +TEST(PersistableBundle, ParcelAndUnparcel) { + PersistableBundle expected = createSimplePersistableBundle(); + PersistableBundle out{}; + + Parcel p{}; + EXPECT_EQ(expected.writeToParcel(&p), 0); + p.setDataPosition(0); + EXPECT_EQ(out.readFromParcel(&p), 0); + + EXPECT_EQ(expected, out); +} + +TEST(PersistableBundle, OverwriteKey) { + PersistableBundle pb{}; + + pb.putInt(kKey, 64); + pb.putDouble(kKey, 0.5); + + EXPECT_EQ(pb.getIntKeys().size(), 0); + EXPECT_EQ(pb.getDoubleKeys().size(), 1); + + double out; + EXPECT_TRUE(pb.getDouble(kKey, &out)); + EXPECT_EQ(out, 0.5); +} diff --git a/libs/binder/tests/binderRpcBenchmark.cpp b/libs/binder/tests/binderRpcBenchmark.cpp index 4f10d7417f..865f0ec9a4 100644 --- a/libs/binder/tests/binderRpcBenchmark.cpp +++ b/libs/binder/tests/binderRpcBenchmark.cpp @@ -216,7 +216,7 @@ void BM_repeatTwoPageString(benchmark::State& state) { // by how many binder calls work together (and by factors like the scheduler, // thermal throttling, core choice, etc..). std::string str = std::string(getpagesize() * 2, 'a'); - CHECK_EQ(str.size(), getpagesize() * 2); + CHECK_EQ(static_cast<ssize_t>(str.size()), getpagesize() * 2); while (state.KeepRunning()) { std::string out; diff --git a/libs/binder/tests/binderRpcTest.cpp b/libs/binder/tests/binderRpcTest.cpp index 2769a88342..19882ea1a9 100644 --- a/libs/binder/tests/binderRpcTest.cpp +++ b/libs/binder/tests/binderRpcTest.cpp @@ -64,12 +64,12 @@ constexpr char kTrustyIpcDevice[] = "/dev/trusty-ipc-dev0"; static std::string WaitStatusToString(int wstatus) { if (WIFEXITED(wstatus)) { - return std::format("exit status {}", WEXITSTATUS(wstatus)); + return "exit status " + std::to_string(WEXITSTATUS(wstatus)); } if (WIFSIGNALED(wstatus)) { - return std::format("term signal {}", WTERMSIG(wstatus)); + return "term signal " + std::to_string(WTERMSIG(wstatus)); } - return std::format("unexpected state {}", wstatus); + return "unexpected state " + std::to_string(wstatus); } static void debugBacktrace(pid_t pid) { @@ -177,7 +177,7 @@ public: EXPECT_NE(nullptr, session); EXPECT_NE(nullptr, session->state()); - EXPECT_EQ(0, session->state()->countBinders()) << (session->state()->dump(), "dump:"); + EXPECT_EQ(0u, session->state()->countBinders()) << (session->state()->dump(), "dump:"); wp<RpcSession> weakSession = session; session = nullptr; @@ -235,7 +235,7 @@ static unique_fd connectToUnixBootstrap(const RpcTransportFd& transportFd) { if (binder::os::sendMessageOnSocket(transportFd, &iov, 1, &fds) < 0) { PLOGF("Failed sendMessageOnSocket"); } - return std::move(sockClient); + return sockClient; } #endif // BINDER_RPC_TO_TRUSTY_TEST @@ -263,9 +263,8 @@ std::unique_ptr<ProcessSession> BinderRpc::createRpcTestSocketServerProcessEtc( bool noKernel = GetParam().noKernel; std::string path = GetExecutableDirectory(); - auto servicePath = - std::format("{}/binder_rpc_test_service{}{}", path, - singleThreaded ? "_single_threaded" : "", noKernel ? "_no_kernel" : ""); + auto servicePath = path + "/binder_rpc_test_service" + + (singleThreaded ? "_single_threaded" : "") + (noKernel ? "_no_kernel" : ""); unique_fd bootstrapClientFd, socketFd; @@ -623,7 +622,7 @@ TEST_P(BinderRpc, OnewayCallQueueing) { for (size_t i = 0; i + 1 < kNumQueued; i++) { int n; proc.rootIface->blockingRecvInt(&n); - EXPECT_EQ(n, i); + EXPECT_EQ(n, static_cast<ssize_t>(i)); } saturateThreadPool(1 + kNumExtraServerThreads, proc.rootIface); @@ -1148,8 +1147,8 @@ static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() { return ret; } -INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()), - BinderRpc::PrintParamInfo); +INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()), + BinderRpc::PrintParamInfo); #else // BINDER_RPC_TO_TRUSTY_TEST bool testSupportVsockLoopback() { // We don't need to enable TLS to know if vsock is supported. @@ -1279,7 +1278,7 @@ static std::vector<BinderRpc::ParamType> getBinderRpcParams() { for (const auto& clientVersion : testVersions()) { for (const auto& serverVersion : testVersions()) { for (bool singleThreaded : {false, true}) { - for (bool noKernel : {false, true}) { + for (bool noKernel : noKernelValues()) { ret.push_back(BinderRpc::ParamType{ .type = type, .security = security, @@ -1300,7 +1299,7 @@ static std::vector<BinderRpc::ParamType> getBinderRpcParams() { .clientVersion = RPC_WIRE_PROTOCOL_VERSION, .serverVersion = RPC_WIRE_PROTOCOL_VERSION, .singleThreaded = false, - .noKernel = false, + .noKernel = !kEnableKernelIpcTesting, }); } } @@ -1308,8 +1307,8 @@ static std::vector<BinderRpc::ParamType> getBinderRpcParams() { return ret; } -INSTANTIATE_TEST_CASE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()), - BinderRpc::PrintParamInfo); +INSTANTIATE_TEST_SUITE_P(PerSocket, BinderRpc, ::testing::ValuesIn(getBinderRpcParams()), + BinderRpc::PrintParamInfo); class BinderRpcServerRootObject : public ::testing::TestWithParam<std::tuple<bool, bool, RpcSecurity>> {}; @@ -1337,9 +1336,9 @@ TEST_P(BinderRpcServerRootObject, WeakRootObject) { EXPECT_EQ((isStrong2 ? binderRaw2 : nullptr), server->getRootObject()); } -INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerRootObject, - ::testing::Combine(::testing::Bool(), ::testing::Bool(), - ::testing::ValuesIn(RpcSecurityValues()))); +INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerRootObject, + ::testing::Combine(::testing::Bool(), ::testing::Bool(), + ::testing::ValuesIn(RpcSecurityValues()))); class OneOffSignal { public: @@ -1384,7 +1383,7 @@ TEST(BinderRpc, Java) { auto binder = sm->checkService(String16("batteryproperties")); ASSERT_NE(nullptr, binder); auto descriptor = binder->getInterfaceDescriptor(); - ASSERT_GE(descriptor.size(), 0); + ASSERT_GE(descriptor.size(), 0u); ASSERT_EQ(OK, binder->pingBinder()); auto rpcServer = RpcServer::make(); @@ -1468,10 +1467,10 @@ TEST_P(BinderRpcServerOnly, Shutdown) { << "After server->shutdown() returns true, join() did not stop after 2s"; } -INSTANTIATE_TEST_CASE_P(BinderRpc, BinderRpcServerOnly, - ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()), - ::testing::ValuesIn(testVersions())), - BinderRpcServerOnly::PrintTestParam); +INSTANTIATE_TEST_SUITE_P(BinderRpc, BinderRpcServerOnly, + ::testing::Combine(::testing::ValuesIn(RpcSecurityValues()), + ::testing::ValuesIn(testVersions())), + BinderRpcServerOnly::PrintTestParam); class RpcTransportTestUtils { public: @@ -2018,9 +2017,9 @@ TEST_P(RpcTransportTest, CheckWaitingForRead) { server->shutdown(); } -INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest, - ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()), - RpcTransportTest::PrintParamInfo); +INSTANTIATE_TEST_SUITE_P(BinderRpc, RpcTransportTest, + ::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()), + RpcTransportTest::PrintParamInfo); class RpcTransportTlsKeyTest : public testing::TestWithParam< @@ -2075,7 +2074,7 @@ TEST_P(RpcTransportTlsKeyTest, PreSignedCertificate) { client.run(); } -INSTANTIATE_TEST_CASE_P( +INSTANTIATE_TEST_SUITE_P( BinderRpc, RpcTransportTlsKeyTest, testing::Combine(testing::ValuesIn(testSocketTypes(false /* hasPreconnected*/)), testing::Values(RpcCertificateFormat::PEM, RpcCertificateFormat::DER), diff --git a/libs/binder/tests/binderRpcTestCommon.h b/libs/binder/tests/binderRpcTestCommon.h index 8832f1a6ba..dc22647b85 100644 --- a/libs/binder/tests/binderRpcTestCommon.h +++ b/libs/binder/tests/binderRpcTestCommon.h @@ -60,11 +60,16 @@ #include "../FdUtils.h" #include "../RpcState.h" // for debugging #include "FileUtils.h" -#include "format.h" #include "utils/Errors.h" namespace android { +#ifdef BINDER_NO_KERNEL_IPC_TESTING +constexpr bool kEnableKernelIpcTesting = false; +#else +constexpr bool kEnableKernelIpcTesting = true; +#endif + constexpr char kLocalInetAddress[] = "127.0.0.1"; enum class RpcSecurity { RAW, TLS }; @@ -73,6 +78,14 @@ static inline std::vector<RpcSecurity> RpcSecurityValues() { return {RpcSecurity::RAW, RpcSecurity::TLS}; } +static inline std::vector<bool> noKernelValues() { + std::vector<bool> values = {true}; + if (kEnableKernelIpcTesting) { + values.push_back(false); + } + return values; +} + static inline bool hasExperimentalRpc() { #ifdef BINDER_RPC_TO_TRUSTY_TEST // Trusty services do not support the experimental version, @@ -99,7 +112,7 @@ static inline std::vector<uint32_t> testVersions() { } static inline std::string trustyIpcPort(uint32_t serverVersion) { - return std::format("com.android.trusty.binderRpcTestService.V{}", serverVersion); + return "com.android.trusty.binderRpcTestService.V" + std::to_string(serverVersion); } enum class SocketType { @@ -210,7 +223,7 @@ static inline std::unique_ptr<RpcTransportCtxFactory> newTlsFactory( return RpcTransportCtxFactoryTls::make(std::move(verifier), std::move(auth)); } default: - LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity); + LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", static_cast<int>(rpcSecurity)); } } @@ -256,7 +269,7 @@ public: mValue.reset(); lock.unlock(); mCvEmpty.notify_all(); - return std::move(v); + return v; } private: diff --git a/libs/binder/tests/binderRpcTestTrusty.cpp b/libs/binder/tests/binderRpcTestTrusty.cpp index 18751cc089..31c0eba1c1 100644 --- a/libs/binder/tests/binderRpcTestTrusty.cpp +++ b/libs/binder/tests/binderRpcTestTrusty.cpp @@ -45,7 +45,7 @@ std::unique_ptr<RpcTransportCtxFactory> BinderRpc::newFactory(RpcSecurity rpcSec case RpcSecurity::RAW: return RpcTransportCtxFactoryTipcTrusty::make(); default: - LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", rpcSecurity); + LOG_ALWAYS_FATAL("Unknown RpcSecurity %d", static_cast<int>(rpcSecurity)); } } @@ -110,8 +110,8 @@ static std::vector<BinderRpc::ParamType> getTrustyBinderRpcParams() { return ret; } -INSTANTIATE_TEST_CASE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()), - BinderRpc::PrintParamInfo); +INSTANTIATE_TEST_SUITE_P(Trusty, BinderRpc, ::testing::ValuesIn(getTrustyBinderRpcParams()), + BinderRpc::PrintParamInfo); } // namespace android diff --git a/libs/binder/tests/binderRpcWireProtocolTest.cpp b/libs/binder/tests/binderRpcWireProtocolTest.cpp index e59dc82b2b..91145f0c13 100644 --- a/libs/binder/tests/binderRpcWireProtocolTest.cpp +++ b/libs/binder/tests/binderRpcWireProtocolTest.cpp @@ -14,14 +14,15 @@ * limitations under the License. */ -#include <android-base/logging.h> -#include <android-base/properties.h> -#include <android-base/strings.h> #include <binder/Parcel.h> #include <binder/RpcSession.h> #include <binder/Status.h> #include <gtest/gtest.h> +#ifdef __ANDROID__ +#include <android-base/properties.h> +#endif + #include "../Debug.h" #include "../Utils.h" @@ -69,8 +70,8 @@ static const std::vector<std::function<void(Parcel* p)>> kFillFuns { [](Parcel* p) { ASSERT_EQ(OK, p->writeString16(String16(u"a"))); }, [](Parcel* p) { ASSERT_EQ(OK, p->writeString16(String16(u"baba"))); }, [](Parcel* p) { ASSERT_EQ(OK, p->writeStrongBinder(nullptr)); }, - [](Parcel* p) { ASSERT_EQ(OK, p->writeInt32Array(arraysize(kInt32Array), kInt32Array)); }, - [](Parcel* p) { ASSERT_EQ(OK, p->writeByteArray(arraysize(kByteArray), kByteArray)); }, + [](Parcel* p) { ASSERT_EQ(OK, p->writeInt32Array(countof(kInt32Array), kInt32Array)); }, + [](Parcel* p) { ASSERT_EQ(OK, p->writeByteArray(countof(kByteArray), kByteArray)); }, [](Parcel* p) { ASSERT_EQ(OK, p->writeBool(true)); }, [](Parcel* p) { ASSERT_EQ(OK, p->writeBool(false)); }, [](Parcel* p) { ASSERT_EQ(OK, p->writeChar('a')); }, @@ -162,8 +163,8 @@ static const std::vector<std::function<void(Parcel* p)>> kFillFuns { static void setParcelForRpc(Parcel* p, uint32_t version) { auto session = RpcSession::make(); - CHECK(session->setProtocolVersion(version)); - CHECK_EQ(OK, session->addNullDebuggingClient()); + EXPECT_TRUE(session->setProtocolVersion(version)); + EXPECT_EQ(OK, session->addNullDebuggingClient()); p->markForRpc(session); } @@ -180,13 +181,25 @@ static std::string buildRepr(uint32_t version) { return result; } +// To be replaced with std::views::split (and std::views::zip) once C++ compilers catch up. +static std::vector<std::string> split(std::string_view s, char delimiter) { + std::vector<std::string> result; + size_t pos = 0; + while (true) { + const auto found = s.find(delimiter, pos); + result.emplace_back(s.substr(pos, found - pos)); + if (found == s.npos) return result; + pos = found + 1; + } +} + static void checkRepr(const std::string& repr, uint32_t version) { const std::string actualRepr = buildRepr(version); - auto expected = base::Split(repr, "|"); + auto expected = split(repr, '|'); ASSERT_EQ(expected.size(), kFillFuns.size()); - auto actual = base::Split(actualRepr, "|"); + auto actual = split(actualRepr, '|'); ASSERT_EQ(actual.size(), kFillFuns.size()); for (size_t i = 0; i < kFillFuns.size(); i++) { @@ -257,8 +270,13 @@ TEST(RpcWire, NextIsPlusOneReminder) { TEST(RpcWire, ReleaseBranchHasFrozenRpcWireProtocol) { if (RPC_WIRE_PROTOCOL_VERSION == RPC_WIRE_PROTOCOL_VERSION_EXPERIMENTAL) { - EXPECT_FALSE(base::GetProperty("ro.build.version.codename", "") == "REL") - << "Binder RPC wire protocol must be frozen on a release branch!"; +#ifdef __ANDROID__ + bool isRelease = base::GetProperty("ro.build.version.codename", "") == "REL"; +#else + bool isRelease = true; +#endif + EXPECT_FALSE(isRelease) + << "Binder RPC wire protocol must be frozen in release configuration!"; } } diff --git a/libs/binder/tests/binderSafeInterfaceTest.cpp b/libs/binder/tests/binderSafeInterfaceTest.cpp index 41cb552e4c..0aa678dd65 100644 --- a/libs/binder/tests/binderSafeInterfaceTest.cpp +++ b/libs/binder/tests/binderSafeInterfaceTest.cpp @@ -723,7 +723,7 @@ TEST_F(SafeInterfaceTest, TestIncrementNoCopyNoMove) { ASSERT_EQ(a.getValue() + 1, aPlusOne.getValue()); } -TEST_F(SafeInterfaceTest, TestIncremementParcelableVector) { +TEST_F(SafeInterfaceTest, TestIncrementParcelableVector) { const std::vector<TestParcelable> a{TestParcelable{1}, TestParcelable{2}}; std::vector<TestParcelable> aPlusOne; status_t result = mSafeInterfaceTest->increment(a, &aPlusOne); diff --git a/libs/binder/trusty/OS.cpp b/libs/binder/trusty/OS.cpp index a8dabc3a1d..157ab3c85d 100644 --- a/libs/binder/trusty/OS.cpp +++ b/libs/binder/trusty/OS.cpp @@ -21,6 +21,7 @@ #include <lib/rand/rand.h> #endif +#include <binder/Common.h> #include <binder/RpcTransportTipcTrusty.h> #include <log/log.h> #include <trusty_log.h> @@ -39,6 +40,8 @@ void trace_begin(uint64_t, const char*) {} void trace_end(uint64_t) {} +void trace_int(uint64_t, const char*, int32_t) {} + uint64_t GetThreadId() { return 0; } @@ -92,7 +95,8 @@ ssize_t receiveMessageFromSocket( } // namespace android::binder::os -int __android_log_print(int prio [[maybe_unused]], const char* tag, const char* fmt, ...) { +LIBBINDER_EXPORTED int __android_log_print(int prio [[maybe_unused]], const char* tag, + const char* fmt, ...) { #ifdef TRUSTY_USERSPACE #define trusty_tlog _tlog #define trusty_vtlog _vtlog diff --git a/libs/binder/trusty/include/binder/RpcTransportTipcTrusty.h b/libs/binder/trusty/include/binder/RpcTransportTipcTrusty.h index 8eae8c2ec1..91c6008fcd 100644 --- a/libs/binder/trusty/include/binder/RpcTransportTipcTrusty.h +++ b/libs/binder/trusty/include/binder/RpcTransportTipcTrusty.h @@ -26,7 +26,7 @@ namespace android { // RpcTransportCtxFactory with TLS disabled. -class RpcTransportCtxFactoryTipcTrusty : public RpcTransportCtxFactory { +class LIBBINDER_EXPORTED RpcTransportCtxFactoryTipcTrusty : public RpcTransportCtxFactory { public: static std::unique_ptr<RpcTransportCtxFactory> make(); diff --git a/libs/binder/tests/format.h b/libs/binder/trusty/ndk/include/android/llndk-versioning.h index c588de70bd..3ae3d8f577 100644 --- a/libs/binder/tests/format.h +++ b/libs/binder/trusty/ndk/include/android/llndk-versioning.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2023 The Android Open Source Project + * Copyright (C) 2024 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. @@ -13,17 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#pragma once -// TODO(b/302723053): remove this header and replace with <format> once b/175635923 is done -// ETA for this blocker is 2023-10-27~2023-11-10. -// Also, remember to remove fmtlib's format.cc from trusty makefiles. - -#if __has_include(<format>) && !defined(_LIBCPP_HAS_NO_INCOMPLETE_FORMAT) -#include <format> -#else -#include <fmt/format.h> - -namespace std { -using fmt::format; -} -#endif
\ No newline at end of file +#define __INTRODUCED_IN_LLNDK(x) /* nothing on Trusty */ diff --git a/libs/binder/trusty/ndk/include/sys/cdefs.h b/libs/binder/trusty/ndk/include/sys/cdefs.h index 7528f2bb45..4e9b0e83c6 100644 --- a/libs/binder/trusty/ndk/include/sys/cdefs.h +++ b/libs/binder/trusty/ndk/include/sys/cdefs.h @@ -27,4 +27,3 @@ #endif #define __INTRODUCED_IN(x) /* nothing on Trusty */ -#define __INTRODUCED_IN_LLNDK(x) /* nothing on Trusty */ diff --git a/libs/bufferstreams/Android.bp b/libs/bufferstreams/Android.bp index 365fc457d1..6c2a980f71 100644 --- a/libs/bufferstreams/Android.bp +++ b/libs/bufferstreams/Android.bp @@ -19,6 +19,7 @@ package { aconfig_declarations { name: "bufferstreams_flags", package: "com.android.graphics.bufferstreams.flags", + container: "system", srcs: [ "aconfig/bufferstreams_flags.aconfig", ], diff --git a/libs/bufferstreams/aconfig/bufferstreams_flags.aconfig b/libs/bufferstreams/aconfig/bufferstreams_flags.aconfig index e258725e3d..d0f7812d21 100644 --- a/libs/bufferstreams/aconfig/bufferstreams_flags.aconfig +++ b/libs/bufferstreams/aconfig/bufferstreams_flags.aconfig @@ -1,4 +1,5 @@ package: "com.android.graphics.bufferstreams.flags" +container: "system" flag { name: "bufferstreams_steel_thread" diff --git a/libs/bufferstreams/rust/src/publishers/buffer_pool_publisher.rs b/libs/bufferstreams/rust/src/publishers/buffer_pool_publisher.rs index 846105dacd..c5c1fd37c1 100644 --- a/libs/bufferstreams/rust/src/publishers/buffer_pool_publisher.rs +++ b/libs/bufferstreams/rust/src/publishers/buffer_pool_publisher.rs @@ -12,8 +12,6 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! - use std::time::Instant; use crate::{ diff --git a/libs/cputimeinstate/testtimeinstate.cpp b/libs/cputimeinstate/testtimeinstate.cpp index 6ccc6cafb6..81f6a585ab 100644 --- a/libs/cputimeinstate/testtimeinstate.cpp +++ b/libs/cputimeinstate/testtimeinstate.cpp @@ -40,6 +40,9 @@ namespace bpf { static constexpr uint64_t NSEC_PER_SEC = 1000000000; static constexpr uint64_t NSEC_PER_YEAR = NSEC_PER_SEC * 60 * 60 * 24 * 365; +// Declare busy loop variable globally to prevent removal during optimization +static long sum __attribute__((used)) = 0; + using std::vector; class TimeInStateTest : public testing::Test { @@ -576,7 +579,7 @@ uint64_t timeNanos() { // Keeps CPU busy with some number crunching void useCpu() { - long sum = 0; + sum = 0; for (int i = 0; i < 100000; i++) { sum *= i; } diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp index 86431484d6..059e19ebb8 100644 --- a/libs/gui/Android.bp +++ b/libs/gui/Android.bp @@ -23,6 +23,7 @@ package { aconfig_declarations { name: "libgui_flags", package: "com.android.graphics.libgui.flags", + container: "system", srcs: ["libgui_flags.aconfig"], } diff --git a/libs/gui/libgui_flags.aconfig b/libs/gui/libgui_flags.aconfig index b081030c9f..38646992da 100644 --- a/libs/gui/libgui_flags.aconfig +++ b/libs/gui/libgui_flags.aconfig @@ -1,4 +1,5 @@ package: "com.android.graphics.libgui.flags" +container: "system" flag { name: "bq_setframerate" diff --git a/libs/input/Android.bp b/libs/input/Android.bp index 252040d1b0..400ca9fa7d 100644 --- a/libs/input/Android.bp +++ b/libs/input/Android.bp @@ -39,6 +39,7 @@ filegroup { aconfig_declarations { name: "com.android.input.flags-aconfig", package: "com.android.input.flags", + container: "system", srcs: ["input_flags.aconfig"], } @@ -79,10 +80,6 @@ rust_bindgen { visibility: ["//frameworks/native/services/inputflinger"], wrapper_src: "InputWrapper.hpp", - include_dirs: [ - "frameworks/native/include", - ], - source_stem: "bindings", bindgen_flags: [ diff --git a/libs/input/input_flags.aconfig b/libs/input/input_flags.aconfig index 54eeb39935..dbc002ccb3 100644 --- a/libs/input/input_flags.aconfig +++ b/libs/input/input_flags.aconfig @@ -1,4 +1,5 @@ package: "com.android.input.flags" +container: "system" flag { name: "enable_outbound_event_verification" diff --git a/libs/ui/DisplayIdentification.cpp b/libs/ui/DisplayIdentification.cpp index 82e5427317..ed7f1930aa 100644 --- a/libs/ui/DisplayIdentification.cpp +++ b/libs/ui/DisplayIdentification.cpp @@ -374,6 +374,11 @@ std::optional<PnpId> getPnpId(PhysicalDisplayId displayId) { std::optional<DisplayIdentificationInfo> parseDisplayIdentificationData( uint8_t port, const DisplayIdentificationData& data) { + if (data.empty()) { + ALOGI("Display identification data is empty."); + return {}; + } + if (!isEdid(data)) { ALOGE("Display identification data has unknown format."); return {}; diff --git a/libs/ui/GraphicBufferMapper.cpp b/libs/ui/GraphicBufferMapper.cpp index 7086e0470c..dc026d2a57 100644 --- a/libs/ui/GraphicBufferMapper.cpp +++ b/libs/ui/GraphicBufferMapper.cpp @@ -171,8 +171,8 @@ status_t GraphicBufferMapper::lockAsync(buffer_handle_t handle, uint64_t produce int32_t* outBytesPerStride) { ATRACE_CALL(); - const uint64_t usage = static_cast<uint64_t>( - android_convertGralloc1To0Usage(producerUsage, consumerUsage)); + const uint64_t usage = static_cast<uint64_t>(ANDROID_NATIVE_UNSIGNED_CAST( + android_convertGralloc1To0Usage(producerUsage, consumerUsage))); return mMapper->lock(handle, usage, bounds, fenceFd, vaddr, outBytesPerPixel, outBytesPerStride); } diff --git a/opengl/libs/EGL/egl_display.cpp b/opengl/libs/EGL/egl_display.cpp index 1ada33ed6e..5b5afd33c6 100644 --- a/opengl/libs/EGL/egl_display.cpp +++ b/opengl/libs/EGL/egl_display.cpp @@ -254,6 +254,7 @@ EGLBoolean egl_display_t::initialize(EGLint* major, EGLint* minor) { } } + std::vector<std::string> extensionStrings; { // scope for lock std::lock_guard<std::mutex> _l(lock); @@ -315,16 +316,14 @@ EGLBoolean egl_display_t::initialize(EGLint* major, EGLint* minor) { } mClientApiString = sClientApiString; - mExtensionString = gBuiltinExtensionString; - // b/269060366 Conditionally enabled EGL_ANDROID_get_frame_timestamps extension if the // device's present timestamps are reliable (which may not be the case on emulators). if (cnx->angleLoaded) { if (android::base::GetBoolProperty("service.sf.present_timestamp", false)) { - mExtensionString.append("EGL_ANDROID_get_frame_timestamps "); + extensionStrings.push_back("EGL_ANDROID_get_frame_timestamps"); } } else { - mExtensionString.append("EGL_ANDROID_get_frame_timestamps "); + extensionStrings.push_back("EGL_ANDROID_get_frame_timestamps"); } hasColorSpaceSupport = findExtension(disp.queryString.extensions, "EGL_KHR_gl_colorspace"); @@ -335,10 +334,12 @@ EGLBoolean egl_display_t::initialize(EGLint* major, EGLint* minor) { // Add wide-color extensions if device can support wide-color if (wideColorBoardConfig && hasColorSpaceSupport) { - mExtensionString.append( - "EGL_EXT_gl_colorspace_scrgb EGL_EXT_gl_colorspace_scrgb_linear " - "EGL_EXT_gl_colorspace_display_p3_linear EGL_EXT_gl_colorspace_display_p3 " - "EGL_EXT_gl_colorspace_display_p3_passthrough "); + std::vector<std::string> wideColorExtensions = + {"EGL_EXT_gl_colorspace_scrgb", "EGL_EXT_gl_colorspace_scrgb_linear", + "EGL_EXT_gl_colorspace_display_p3_linear", "EGL_EXT_gl_colorspace_display_p3", + "EGL_EXT_gl_colorspace_display_p3_passthrough"}; + extensionStrings.insert(extensionStrings.end(), wideColorExtensions.begin(), + wideColorExtensions.end()); } bool hasHdrBoardConfig = android::sysprop::has_HDR_display(false); @@ -348,9 +349,11 @@ EGLBoolean egl_display_t::initialize(EGLint* major, EGLint* minor) { // Typically that means there is an HDR capable display attached, but could be // support for attaching an HDR display. In either case, advertise support for // HDR color spaces. - mExtensionString.append("EGL_EXT_gl_colorspace_bt2020_hlg " - "EGL_EXT_gl_colorspace_bt2020_linear " - "EGL_EXT_gl_colorspace_bt2020_pq "); + std::vector<std::string> hdrExtensions = {"EGL_EXT_gl_colorspace_bt2020_hlg", + "EGL_EXT_gl_colorspace_bt2020_linear", + "EGL_EXT_gl_colorspace_bt2020_pq"}; + extensionStrings.insert(extensionStrings.end(), hdrExtensions.begin(), + hdrExtensions.end()); } char const* start = gExtensionString; @@ -361,7 +364,7 @@ EGLBoolean egl_display_t::initialize(EGLint* major, EGLint* minor) { // NOTE: we could avoid the copy if we had strnstr. const std::string ext(start, len); if (findExtension(disp.queryString.extensions, ext.c_str(), len)) { - mExtensionString.append(ext + " "); + extensionStrings.push_back(ext); } // advance to the next extension name, skipping the space. start += len; @@ -388,6 +391,14 @@ EGLBoolean egl_display_t::initialize(EGLint* major, EGLint* minor) { refCond.notify_all(); } + auto mergeExtensionStrings = [](const std::vector<std::string>& strings) { + std::ostringstream combinedStringStream; + std::copy(strings.begin(), strings.end(), + std::ostream_iterator<std::string>(combinedStringStream, " ")); + // gBuiltinExtensionString already has a trailing space so is added here + return gBuiltinExtensionString + combinedStringStream.str(); + }; + mExtensionString = mergeExtensionStrings(extensionStrings); return EGL_TRUE; } diff --git a/opengl/tests/EGLTest/Android.bp b/opengl/tests/EGLTest/Android.bp index d96a89564d..aebd3f2bf2 100644 --- a/opengl/tests/EGLTest/Android.bp +++ b/opengl/tests/EGLTest/Android.bp @@ -37,6 +37,11 @@ cc_test { "libSurfaceFlingerProp", ], + static_libs: [ + "libgmock", + "libgtest", + ], + include_dirs: [ "frameworks/native/opengl/libs", "frameworks/native/opengl/libs/EGL", diff --git a/opengl/tests/EGLTest/EGL_test.cpp b/opengl/tests/EGLTest/EGL_test.cpp index cbe4ef9c40..503d7dffdb 100644 --- a/opengl/tests/EGLTest/EGL_test.cpp +++ b/opengl/tests/EGLTest/EGL_test.cpp @@ -15,6 +15,7 @@ */ #include <gtest/gtest.h> +#include <gmock/gmock.h> #include <SurfaceFlingerProperties.h> #include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h> @@ -29,6 +30,8 @@ #include <gui/IGraphicBufferConsumer.h> #include <gui/BufferQueue.h> +#include "egl_display.h" + bool hasEglExtension(EGLDisplay dpy, const char* extensionName) { const char* exts = eglQueryString(dpy, EGL_EXTENSIONS); size_t cropExtLen = strlen(extensionName); @@ -1011,4 +1014,57 @@ TEST_F(EGLTest, EGLCreateWindowTwoColorspaces) { EXPECT_TRUE(eglDestroySurface(mEglDisplay, eglSurface)); } + +TEST_F(EGLTest, EGLCheckExtensionString) { + // check that the format of the extension string is correct + + egl_display_t* display = egl_display_t::get(mEglDisplay); + ASSERT_NE(display, nullptr); + + std::string extensionStrRegex = "((EGL_ANDROID_front_buffer_auto_refresh|" + "EGL_ANDROID_get_native_client_buffer|" + "EGL_ANDROID_presentation_time|" + "EGL_EXT_surface_CTA861_3_metadata|" + "EGL_EXT_surface_SMPTE2086_metadata|" + "EGL_KHR_get_all_proc_addresses|" + "EGL_KHR_swap_buffers_with_damage|" + "EGL_ANDROID_get_frame_timestamps|" + "EGL_EXT_gl_colorspace_scrgb|" + "EGL_EXT_gl_colorspace_scrgb_linear|" + "EGL_EXT_gl_colorspace_display_p3_linear|" + "EGL_EXT_gl_colorspace_display_p3|" + "EGL_EXT_gl_colorspace_display_p3_passthrough|" + "EGL_EXT_gl_colorspace_bt2020_hlg|" + "EGL_EXT_gl_colorspace_bt2020_linear|" + "EGL_EXT_gl_colorspace_bt2020_pq|" + "EGL_ANDROID_image_native_buffer|" + "EGL_ANDROID_native_fence_sync|" + "EGL_ANDROID_recordable|" + "EGL_EXT_create_context_robustness|" + "EGL_EXT_image_gl_colorspace|" + "EGL_EXT_pixel_format_float|" + "EGL_EXT_protected_content|" + "EGL_EXT_yuv_surface|" + "EGL_IMG_context_priority|" + "EGL_KHR_config_attribs|" + "EGL_KHR_create_context|" + "EGL_KHR_fence_sync|" + "EGL_KHR_gl_colorspace|" + "EGL_KHR_gl_renderbuffer_image|" + "EGL_KHR_gl_texture_2D_image|" + "EGL_KHR_gl_texture_3D_image|" + "EGL_KHR_gl_texture_cubemap_image|" + "EGL_KHR_image|" + "EGL_KHR_image_base|" + "EGL_KHR_mutable_render_buffer|" + "EGL_KHR_no_config_context|" + "EGL_KHR_partial_update|" + "EGL_KHR_surfaceless_context|" + "EGL_KHR_wait_sync|" + "EGL_EXT_buffer_age|" + "EGL_KHR_reusable_sync|" + "EGL_NV_context_priority_realtime) )+"; + EXPECT_THAT(display->getExtensionString(), testing::MatchesRegex(extensionStrRegex)); +} + } diff --git a/services/inputflinger/reader/Android.bp b/services/inputflinger/reader/Android.bp index f954370928..ce034488e5 100644 --- a/services/inputflinger/reader/Android.bp +++ b/services/inputflinger/reader/Android.bp @@ -90,7 +90,6 @@ cc_defaults { "libutils", ], static_libs: [ - "libc++fs", "libchrome-gestures", "libui-types", ], @@ -155,7 +154,6 @@ cc_library_shared { }, }, static_libs: [ - "libc++fs", "libchrome-gestures", ], } diff --git a/services/inputflinger/reader/mapper/MultiTouchInputMapper.cpp b/services/inputflinger/reader/mapper/MultiTouchInputMapper.cpp index 5a74a42446..82f92767d9 100644 --- a/services/inputflinger/reader/mapper/MultiTouchInputMapper.cpp +++ b/services/inputflinger/reader/mapper/MultiTouchInputMapper.cpp @@ -140,13 +140,14 @@ void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) { // Assign pointer id using tracking id if available. if (mHavePointerIds) { - int32_t trackingId = inSlot.getTrackingId(); + const int32_t trackingId = inSlot.getTrackingId(); int32_t id = -1; if (trackingId >= 0) { for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty();) { uint32_t n = idBits.clearFirstMarkedBit(); if (mPointerTrackingIdMap[n] == trackingId) { id = n; + break; } } diff --git a/services/inputflinger/tests/Android.bp b/services/inputflinger/tests/Android.bp index 9c9f643656..159632dd27 100644 --- a/services/inputflinger/tests/Android.bp +++ b/services/inputflinger/tests/Android.bp @@ -95,7 +95,6 @@ cc_test { }, static_libs: [ "libflagtest", - "libc++fs", "libgmock", ], require_root: true, diff --git a/services/sensorservice/OWNERS b/services/sensorservice/OWNERS index 90c233030e..7347ac74e6 100644 --- a/services/sensorservice/OWNERS +++ b/services/sensorservice/OWNERS @@ -1,3 +1 @@ -arthuri@google.com bduddie@google.com -stange@google.com diff --git a/services/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp index 0989863b7d..dcef9a3775 100644 --- a/services/surfaceflinger/Android.bp +++ b/services/surfaceflinger/Android.bp @@ -10,6 +10,7 @@ package { aconfig_declarations { name: "surfaceflinger_flags", package: "com.android.graphics.surfaceflinger.flags", + container: "system", srcs: ["surfaceflinger_flags.aconfig"], } diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index b980a65255..ab0598d90b 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -6270,12 +6270,17 @@ void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const { uint8_t port; DisplayIdentificationData data; if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) { - result.append("no identification data\n"); + result.append("no display identification data\n"); + continue; + } + + if (data.empty()) { + result.append("empty display identification data\n"); continue; } if (!isEdid(data)) { - result.append("unknown identification data\n"); + result.append("unknown format for display identification data\n"); continue; } diff --git a/services/surfaceflinger/surfaceflinger_flags.aconfig b/services/surfaceflinger/surfaceflinger_flags.aconfig index 1a28b81483..abe7ec708f 100644 --- a/services/surfaceflinger/surfaceflinger_flags.aconfig +++ b/services/surfaceflinger/surfaceflinger_flags.aconfig @@ -1,4 +1,5 @@ package: "com.android.graphics.surfaceflinger.flags" +container: "system" flag { name: "misc1" |